{"nl": {"description": "The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: \u00ab[date:time]: message\u00bb, where for each \u00ab[date:time]\u00bb value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer \u2014 Alex \u2014 managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format \u00ab[time]: message\u00bb. So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written.So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications).We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day.", "input_spec": "The first input line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). The following n lines contain recordings in format \u00ab[time]: message\u00bb, where time is given in format \u00abhh:mm x.m.\u00bb. For hh two-digit numbers from 01 to 12 are used, for mm two-digit numbers from 00 to 59 are used, and x is either character \u00aba\u00bb or character \u00abp\u00bb. A message is a non-empty sequence of Latin letters and/or spaces, it doesn't start or end with a space. The length of each message doesn't exceed 20.", "output_spec": "Output one number \u2014 the minimum amount of days covered by the log.", "sample_inputs": ["5\n[05:00 a.m.]: Server is started\n[05:00 a.m.]: Rescan initialized\n[01:13 p.m.]: Request processed\n[01:10 p.m.]: Request processed\n[11:40 p.m.]: Rescan completed", "3\n[09:00 a.m.]: User logged in\n[08:00 a.m.]: User logged in\n[07:00 a.m.]: User logged in"], "sample_outputs": ["2", "3"], "notes": "NoteFormally the 12-hour time format is described at: http://en.wikipedia.org/wiki/12-hour_clock. The problem authors recommend you to look through these descriptions before you start with the problem."}, "positive_code": [{"source_code": "let (|>) x f = f x\nlet flip f x y = f y x\n\nlet () =\n let re = Str.regexp \"^\\\\[\\\\([0-9][0-9]\\\\):\\\\([0-9][0-9]\\\\) \\\\([ap]\\\\)\" in\n let last = ref max_int in\n let cnt = ref 0 in\n let ans = ref 0 in\n for i = 1 to read_int () do\n let s = read_line () in\n Str.string_match re s 0 |> ignore;\n let hh = Str.matched_group 1 s |> int_of_string |> flip (mod) 12 in\n let mm = Str.matched_group 2 s |> int_of_string in\n let pm = if Str.matched_group 3 s = \"p\" then 12*3600 else 0 in\n let time = hh*60+mm+pm in\n if time = !last then\n incr cnt\n else\n cnt := 1;\n if time < !last || !cnt > 10 then (\n incr ans;\n cnt := 1\n );\n last := time\n done;\n Printf.printf \"%d\\n\" !ans\n"}], "negative_code": [], "src_uid": "54f8b8e6711ff5c69e0bc38a6e2f4999"} {"nl": {"description": "The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.", "input_spec": "The first line contains three integers n, m, and k (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105, n\u2009-\u20091\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105, 1\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n)\u00a0\u2014 indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.", "output_spec": "You should print k lines. i-th of these lines must start with an integer ci ()\u00a0\u2014 the number of vertices visited by i-th clone, followed by ci integers\u00a0\u2014 indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.", "sample_inputs": ["3 2 1\n2 1\n3 1", "5 4 2\n1 2\n1 3\n1 4\n1 5"], "sample_outputs": ["3 2 1 3", "3 2 1 3\n3 4 1 5"], "notes": "NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x-1,y-1))\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n \nlet () = \n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n \n let graph = Array.make n [] in\n\n let add_edge (i,j) =\n graph.(i) <- j::graph.(i);\n graph.(j) <- i::graph.(j)\n in\n\n for i=1 to m do add_edge (read_pair ()) done;\n\n let visited = Array.make n false in\n\n let rec dfs v ac =\n (* only get here if v not yet visited *)\n visited.(v) <- true;\n let ac = v::ac in\n List.fold_left (fun ac w ->\n if visited.(w) then ac else v::(dfs w ac)\n ) ac graph.(v)\n in\n \n let path = dfs 0 [] in\n\n (* List.iter (fun v -> printf \"%d \" (v+1)) path; *)\n\n let len = List.length path in\n\n let path = Array.of_list path in\n\n let remain = ref len in\n let nblocks = ref 0 in\n\n let block = (len+k-1) / k in\n \n for i=0 to len-1 do\n if i mod block = 0 then (\n nblocks := !nblocks +1;\n if i<>0 then print_newline();\n printf \"%d \" (min block !remain);\n remain := !remain - block\n );\n printf \"%d \" (path.(i) + 1)\n done;\n print_newline();\n for i=1 to k - !nblocks do printf \"1 1\\n\" done\n\n\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x-1,y-1))\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n \nlet () = \n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n \n let graph = Array.make n [] in\n\n let add_edge (i,j) =\n graph.(i) <- j::graph.(i);\n graph.(j) <- i::graph.(j)\n in\n\n for i=1 to m do add_edge (read_pair ()) done;\n\n let visited = Array.make n false in\n\n let rec dfs v ac =\n (* only get here if v not yet visited *)\n visited.(v) <- true;\n let ac = v::ac in\n List.fold_left (fun ac w ->\n if visited.(w) then ac else v::(dfs w ac)\n ) ac graph.(v)\n in\n \n let path = dfs 0 [] in\n\n (* List.iter (fun v -> printf \"%d \" (v+1)) path; *)\n\n let len = List.length path in\n\n let path = Array.of_list path in\n\n let remain = ref len in\n\n let block = (len+k-1) / k in\n \n for i=0 to len-1 do\n if i mod block = 0 then (\n if i<>0 then print_newline();\n printf \"%d \" (min block !remain);\n remain := !remain - block\n );\n printf \"%d \" (path.(i) + 1)\n done;\n\n print_newline()\n"}], "src_uid": "d32d638e5f90f0bfb7b7cec8e541cf7d"} {"nl": {"description": "Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1,\u2009x2,\u2009...,\u2009xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi\u2009-\u2009hi,\u2009xi] or [xi;xi\u2009+\u2009hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. ", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of trees. Next n lines contain pairs of integers xi,\u2009hi (1\u2009\u2264\u2009xi,\u2009hi\u2009\u2264\u2009109) \u2014 the coordinate and the height of the \u0456-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.", "output_spec": "Print a single number \u2014 the maximum number of trees that you can cut down by the given rules.", "sample_inputs": ["5\n1 2\n2 1\n5 10\n10 9\n19 1", "5\n1 2\n2 1\n5 10\n10 9\n20 1"], "sample_outputs": ["3", "4"], "notes": "NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left \u2014 now it occupies segment [\u2009-\u20091;1] fell the 2-nd tree to the right \u2014 now it occupies segment [2;3] leave the 3-rd tree \u2014 it occupies point 5 leave the 4-th tree \u2014 it occupies point 10 fell the 5-th tree to the right \u2014 now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]."}, "positive_code": [{"source_code": "\nopen Num\n\nlet ni = num_of_int\n\nlet solve l =\n let update (total_fall, left_fall, left_pos, left_high) (pos, high) =\n if left_fall\n then\n begin\n (* Printf.printf\n \"true: pos - left_pos = %d, high = %d\\n\"\n (pos - left_pos)\n high; *)\n if ni pos -/ ni left_pos >/ ni high\n then (total_fall + 1, true, pos, high)\n else (total_fall, false, pos, high)\n end\n else\n begin\n (* Printf.printf\n \"false: pos - left_pos = %d, high = %d, left_high = %d\\n\"\n (pos - left_pos)\n high\n left_high; *)\n\n if ni pos -/ ni left_pos >/ ni left_high +/ ni high\n then (total_fall + 2, true, pos, high)\n\n else if ni pos -/ ni left_pos >/ ni left_high\n then (total_fall + 1, false, pos, high)\n\n else if ni pos -/ ni left_pos >/ ni high\n then (total_fall + 1, true, pos, high)\n else (total_fall, false, pos, high)\n end\n in \n let (ans, last, _, _) = List.fold_left update (0, true, -1000000001, 0) l in\n (* Printf.printf \"last: %b\\n\" last; *)\n if last then ans\n else ans + 1\n\nlet _ =\n let n = read_int () in\n\n let rec read_pairs acc = function\n | 0 -> List.rev acc\n | n ->\n let pair =\n begin\n match Str.split (Str.regexp \" \") (read_line ()) with\n | x :: y :: [] -> int_of_string x, int_of_string y\n | _ -> failwith \"mulformed input\"\n end\n in\n read_pairs (pair :: acc) (n - 1)\n in\n\n let ans = solve (read_pairs [] n) in\n print_endline (string_of_int ans)\n"}, {"source_code": "let rec f lim = function\n\t|(a,b)::(c,d)::q -> if a - b > lim\n\t\t\t\tthen 1 + f a ((c,d)::q)\n\t\t\t\telse if c - a > b\n\t\t\t\t\tthen 1+f (a+b) ((c,d)::q)\n\t\t\t\t\telse f a ((c,d)::q)\n\t| _\t\t -> 1\n\nlet _ =\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) and l = ref [] in\n\tfor i = 1 to n do\n\t\tScanf.scanf \" %d %d\" (fun i j -> l := (i,j)::!l);\n\tdone;\n\tPrintf.printf \"%d\" (f min_int (List.rev !l))\n"}], "negative_code": [{"source_code": "\nlet solve l =\n let update (total_fall, left_fall, left_pos, left_high) (pos, high) =\n if left_fall\n then\n begin\n (* Printf.printf \"true: pos - left_pos = %d, high = %d\\n\" (pos - left_pos) high; *)\n if pos - left_pos > high then (total_fall + 1, true, pos, high)\n else (total_fall, false, pos, high)\n end\n else\n begin\n (* Printf.printf \"false: pos - left_pos = %d, high = %d, left_high = %d\\n\" (pos - left_pos) high left_high; *)\n if pos - left_pos > left_high + high then (total_fall + 2, true, pos, high)\n else if pos - left_pos > left_high then (total_fall + 1, false, pos, high)\n else if pos - left_pos > high then (total_fall + 1, true, pos, high)\n else (total_fall, false, pos, high)\n end\n in \n let (ans, last, _, _) = List.fold_left update (0, true, -1000000001, 0) l in\n (* Printf.printf \"last: %b\\n\" last; *)\n if last then ans\n else ans + 1\n\nlet _ =\n let n = read_int () in\n\n let rec read_pairs acc = function\n | 0 -> List.rev acc\n | n ->\n let pair =\n begin\n match Str.split (Str.regexp \" \") (read_line ()) with\n | x :: y :: [] -> int_of_string x, int_of_string y\n | _ -> failwith \"mulformed input\"\n end\n in\n read_pairs (pair :: acc) (n - 1)\n in\n\n let ans = solve (read_pairs [] n) in\n print_endline (string_of_int ans)\n"}], "src_uid": "a850dd88a67a6295823e70e2c5c857c9"} {"nl": {"description": "Because of budget cuts one IT company established new non-financial reward system instead of bonuses.Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets \"I fixed a critical bug\" pennant on his table. A man who suggested a new interesting feature gets \"I suggested a new feature\" pennant on his table.Because of the limited budget of the new reward system only 5 \"I fixed a critical bug\" pennants and 3 \"I suggested a new feature\" pennants were bought.In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded \"I fixed a critical bug\" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded \"I suggested a new feature\" pennants is passed on to his table.One man can have several pennants of one type and of course he can have pennants of both types on his table. There are n tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.", "input_spec": "The only line of the input contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500) \u2014 the number of tables in the IT company.", "output_spec": "Output one integer \u2014 the amount of ways to place the pennants on n tables.", "sample_inputs": ["2"], "sample_outputs": ["24"], "notes": null}, "positive_code": [{"source_code": "open Big_int\n\nlet (+|) = add_big_int\nlet (-|) = sub_big_int\nlet ( *| ) = mult_big_int\nlet (/|) = div_big_int\nlet bmod = mod_big_int\nlet (=|) = eq_big_int\nlet (/=|) a b = not (a =| b)\nlet (>|) = gt_big_int\nlet (<|) = lt_big_int\nlet (>=|) = ge_big_int\nlet (<=|) = le_big_int\n\nlet n0 = zero_big_int\nlet n1 = unit_big_int\nlet n2 = big_int_of_int 2\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = big_int_of_int n in\n let sqr x = x *| x in\n let res =\n (n +| big_int_of_int 4) *|\n\t(n +| big_int_of_int 3) *|\n\t sqr (n +| big_int_of_int 2) *|\n\t\tsqr (n +| big_int_of_int 1) *|\n\t\t sqr n /|\n\t\t\tbig_int_of_int 720\n in\n Printf.printf \"%s\\n\" (string_of_big_int res)\n"}], "negative_code": [], "src_uid": "d41aebacfd5d16046db7c5d339478115"} {"nl": {"description": "You are given an array of integers $$$a_1, a_2, \\ldots, a_n$$$ and an integer $$$x$$$.You need to select the maximum number of elements in the array, such that for every subsegment $$$a_l, a_{l + 1}, \\ldots, a_r$$$ containing strictly more than one element $$$(l < r)$$$, either: At least one element on this subsegment is not selected, or $$$a_l + a_{l+1} + \\ldots + a_r \\geq x \\cdot (r - l + 1)$$$. ", "input_spec": "The first line of input contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10$$$): the number of test cases. The descriptions of $$$t$$$ test cases follow, three lines per test case. In the first line you are given one integer $$$n$$$ ($$$1 \\leq n \\leq 50\\,000$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-100\\,000 \\leq a_i \\leq 100\\,000$$$). The third line contains one integer $$$x$$$ ($$$-100\\,000 \\leq x \\leq 100\\,000$$$).", "output_spec": "For each test case, print one integer: the maximum number of elements that you can select.", "sample_inputs": ["4\n5\n1 2 3 4 5\n2\n10\n2 4 2 4 2 4 2 4 2 4\n3\n3\n-10 -5 -10\n-8\n3\n9 9 -3\n5"], "sample_outputs": ["4\n8\n2\n2"], "notes": "NoteIn the first example, one valid way to select the elements is $$$[\\underline{1}, 2, \\underline{3}, \\underline{4}, \\underline{5}]$$$. All subsegments satisfy at least one of the criteria. For example, for the subsegment $$$l = 1$$$, $$$r = 2$$$ we have that the element $$$2$$$ is not selected, satisfying the first criterion. For the subsegment $$$l = 3$$$, $$$r = 5$$$ we have $$$3 + 4 + 5 = 12 \\ge 2 \\cdot 3$$$, satisfying the second criterion.We can't select all elements, because in this case for $$$l = 1$$$, $$$r = 2$$$ all elements are selected and we have $$$a_1 + a_2 = 3 < 2 \\cdot 2$$$. Thus, the maximum number of selected elements is $$$4$$$.In the second example, one valid solution is $$$[\\underline{2}, \\underline{4}, 2, \\underline{4}, \\underline{2}, \\underline{4}, 2, \\underline{4}, \\underline{2}, \\underline{4}]$$$.In the third example, one valid solution is $$$[\\underline{-10}, -5, \\underline{-10}]$$$.In the fourth example, one valid solution is $$$[\\underline{9}, \\underline{9}, -3]$$$."}, "positive_code": [{"source_code": "(* The key theorem is that if all contiguous groups of 2 and 3 in a region\n are good, then the whole region is good (all contiguous blocks are good).\n The proof is simply that you can partition any contiguous block into\n disjoint blocks of size 2 and 3, and if those are all good then so\n is the whole thing.\n\n Thus, the question becomes what is the fewest number of things to eliminate\n that eliminate all bad blocks of 2 and 3. This can be done by a linear time\n DP.\n *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet rec bitcount a = if a=0 then 0 else (a land 1) + (bitcount (a lsr 1))\n\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let a = Array.init n read_int in\n let x = read_int () in\n if n=1 then printf \"1\\n\"\n else if n=2 then\n let answer = if a.(0) + a.(1) >= 2*x then 2 else 1 in\n printf \"%d\\n\" answer\n else\n let infty = n+1 in\n let dp = Array.make_matrix n 8 infty in\n let bad2 = Array.make n false in\n let bad3 = Array.make n false in\n for i=1 to n-1 do\n\tbad2.(i) <- a.(i-1) + a.(i) < 2*x;\n\tif i>1 then bad3.(i) <- a.(i-2) + a.(i-1) + a.(i) < 3*x;\n done;\n\n for pat = 0 to 3 do\n\tdp.(1).(pat) <- if bad2.(1) && pat = 0 then infty else bitcount pat\n done;\n\n for i=2 to n-1 do\n\tfor pat = 0 to 7 do\n\t let pat' = pat lsr 1 in\n\t let pat'' = pat land 3 in\n\t dp.(i).(pat'') <- min dp.(i).(pat'') (\n\t if pat'' = 0 && bad2.(i) then infty\n\t else if pat = 0 && bad3.(i) then infty\n\t else dp.(i-1).(pat') + (pat land 1)\n\t )\n\tdone\n done;\n\n let answer = minf 0 7 (fun pat -> dp.(n-1).(pat)) in\n printf \"%d\\n\" (n - answer)\n done\n"}], "negative_code": [], "src_uid": "79ecf771f4a54c2c9f988e069f7bfceb"} {"nl": {"description": "We have a point $$$A$$$ with coordinate $$$x = n$$$ on $$$OX$$$-axis. We'd like to find an integer point $$$B$$$ (also on $$$OX$$$-axis), such that the absolute difference between the distance from $$$O$$$ to $$$B$$$ and the distance from $$$A$$$ to $$$B$$$ is equal to $$$k$$$. The description of the first test case. Since sometimes it's impossible to find such point $$$B$$$, we can, in one step, increase or decrease the coordinate of $$$A$$$ by $$$1$$$. What is the minimum number of steps we should do to make such point $$$B$$$ exist?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 6000$$$)\u00a0\u2014 the number of test cases. The only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$0 \\le n, k \\le 10^6$$$)\u00a0\u2014 the initial position of point $$$A$$$ and desirable absolute difference.", "output_spec": "For each test case, print the minimum number of steps to make point $$$B$$$ exist.", "sample_inputs": ["6\n4 0\n5 8\n0 1000000\n0 0\n1 0\n1000000 1000000"], "sample_outputs": ["0\n3\n1000000\n0\n1\n0"], "notes": "NoteIn the first test case (picture above), if we set the coordinate of $$$B$$$ as $$$2$$$ then the absolute difference will be equal to $$$|(2 - 0) - (4 - 2)| = 0$$$ and we don't have to move $$$A$$$. So the answer is $$$0$$$.In the second test case, we can increase the coordinate of $$$A$$$ by $$$3$$$ and set the coordinate of $$$B$$$ as $$$0$$$ or $$$8$$$. The absolute difference will be equal to $$$|8 - 0| = 8$$$, so the answer is $$$3$$$. "}, "positive_code": [{"source_code": "(* Codeforces 1401 A Distance and Axis train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\n\nlet min_steps n k =\n\t\tif n < k then (k - n)\n\t\telse if ((n - k) mod 2) == 1 then 1\n\t\telse 0;;\n \nlet do_one () = \n let k,n = gr(),gr() in\n\t\tlet min_st = min_steps n k in\n\t\tbegin\n\t\t\tprint_int min_st;\n\t\t\tprint_string \"\\n\"\n\t\tend;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [], "src_uid": "f98d1d426f68241bad437eb221f617f4"} {"nl": {"description": "Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is $$$n$$$. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains $$$2$$$ apartments, every other floor contains $$$x$$$ apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers $$$1$$$ and $$$2$$$, apartments on the second floor have numbers from $$$3$$$ to $$$(x + 2)$$$, apartments on the third floor have numbers from $$$(x + 3)$$$ to $$$(2 \\cdot x + 2)$$$, and so on.Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least $$$n$$$ apartments.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n, x \\le 1000$$$) \u2014 the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).", "output_spec": "For each test case, print the answer: the number of floor on which Petya lives.", "sample_inputs": ["4\n7 3\n1 5\n22 5\n987 13"], "sample_outputs": ["3\n1\n5\n77"], "notes": "NoteConsider the first test case of the example: the first floor contains apartments with numbers $$$1$$$ and $$$2$$$, the second one contains apartments with numbers $$$3$$$, $$$4$$$ and $$$5$$$, the third one contains apartments with numbers $$$6$$$, $$$7$$$ and $$$8$$$. Therefore, Petya lives on the third floor.In the second test case of the example, Petya lives in the apartment $$$1$$$ which is on the first floor."}, "positive_code": [{"source_code": "let rec case t =\n if t > 0 then\n let solve n x = \n if n <= 2 then 1 \n else let rec calc acc n x = \n if n <= x then acc + 1 else calc (acc + 1) (n - x) x\n in calc 1 (n - 2) x\n in Scanf.scanf \"%i %i\\n\" (fun n x -> Printf.printf \"%d\\n\" (solve n x); case (t - 1))\nin Scanf.scanf \"%d\\n\" (fun t -> case t)"}, {"source_code": "let read_int () =\n Scanf.scanf \" %d\" (fun x -> x)\n\nlet rec read_ints n =\n match n with\n | 0 -> []\n | x -> read_int () :: (read_ints (n-1))\n\n(* let read_ints () =\n * let line = read_line () in\n * let ints = Str.split (Str.regexp \" *\") line in\n * List.map int_of_string ints *)\n\nlet rec print_list = function \n [] -> ()\n | e::l -> print_int e ; print_string \" \" ; print_list l\n\n\n\nlet solve () =\n let n = read_int () in\n let x = read_int () in\n let k = int_of_float\n (ceil ((float_of_int (x + n - 2)) /. (float_of_int x))) in\n print_int (if n <= 2 then 1 else k);\n print_endline \"\"\n(**)\n \nlet () =\n let x = read_int () in\n let rec loop n =\n match n with\n | 0 -> ()\n | x -> solve (); loop (n-1) in\n loop x\n"}], "negative_code": [{"source_code": "let read_int () =\n Scanf.scanf \" %d\" (fun x -> x)\n\nlet rec read_ints n =\n match n with\n | 0 -> []\n | x -> read_int () :: (read_ints (n-1))\n\n(* let read_ints () =\n * let line = read_line () in\n * let ints = Str.split (Str.regexp \" *\") line in\n * List.map int_of_string ints *)\n\nlet rec print_list = function \n [] -> ()\n | e::l -> print_int e ; print_string \" \" ; print_list l\n\n\n\nlet solve () =\n let n = float_of_int (read_int ()) in\n let x = float_of_int (read_int ()) in\n let k = int_of_float (ceil (1.0 +. (n -. 2.0) /. x)) in\n print_int k;\n print_endline \"\"\n(**)\n \nlet () =\n let x = read_int () in\n let rec loop n =\n match n with\n | 0 -> ()\n | x -> solve (); loop (n-1) in\n loop x\n"}], "src_uid": "8b50a0eb2e1c425455b132683d3e6047"} {"nl": {"description": "3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#\u03a6\u03c9\u03a6 has just got a new maze game on her PC!The game's main puzzle is a maze, in the forms of a $$$2 \\times n$$$ rectangle grid. NEKO's task is to lead a Nekomimi girl from cell $$$(1, 1)$$$ to the gate at $$$(2, n)$$$ and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only $$$q$$$ such moments: the $$$i$$$-th moment toggles the state of cell $$$(r_i, c_i)$$$ (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the $$$q$$$ moments, whether it is still possible to move from cell $$$(1, 1)$$$ to cell $$$(2, n)$$$ without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?", "input_spec": "The first line contains integers $$$n$$$, $$$q$$$ ($$$2 \\le n \\le 10^5$$$, $$$1 \\le q \\le 10^5$$$). The $$$i$$$-th of $$$q$$$ following lines contains two integers $$$r_i$$$, $$$c_i$$$ ($$$1 \\le r_i \\le 2$$$, $$$1 \\le c_i \\le n$$$), denoting the coordinates of the cell to be flipped at the $$$i$$$-th moment. It is guaranteed that cells $$$(1, 1)$$$ and $$$(2, n)$$$ never appear in the query list.", "output_spec": "For each moment, if it is possible to travel from cell $$$(1, 1)$$$ to cell $$$(2, n)$$$, print \"Yes\", otherwise print \"No\". There should be exactly $$$q$$$ answers, one after every update. You can print the words in any case (either lowercase, uppercase or mixed).", "sample_inputs": ["5 5\n2 3\n1 4\n2 4\n2 3\n1 4"], "sample_outputs": ["Yes\nNo\nNo\nNo\nYes"], "notes": "NoteWe'll crack down the example test here: After the first query, the girl still able to reach the goal. One of the shortest path ways should be: $$$(1,1) \\to (1,2) \\to (1,3) \\to (1,4) \\to (1,5) \\to (2,5)$$$. After the second query, it's impossible to move to the goal, since the farthest cell she could reach is $$$(1, 3)$$$. After the fourth query, the $$$(2, 3)$$$ is not blocked, but now all the $$$4$$$-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let q = read_int() in\n let arr = Array.init n\n (fun _ -> Array.make 2 false)\n in\n let sum = ref 0 in\n for i=0 to q-1 do\n let r = read_int() in\n let c = read_int() in\n let r3 = r lxor 3 in\n let count = [-1; 0; 1]\n |> List.map (fun (x: int) -> (r3, c + x))\n |> List.filter (fun (x: int * int) -> 1 <= (snd x) && (snd x) <= n)\n |> List.filter (fun (x: int * int) -> arr.((snd x) - 1).(r3 - 1))\n |> List.length in\n if arr.(c - 1).(r - 1) then (\n arr.(c - 1).(r - 1) <- false;\n sum := !sum - count\n ) else (\n arr.(c - 1).(r - 1) <- true;\n sum := !sum + count\n );\n printf (if !sum > 0 then \"No\\n\" else \"Yes\\n\");\n done;\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let q = read_int() in\n let arr = Array.init n\n (fun _ -> Array.make 2 false)\n in\n let sum = ref 0 in\n for i=0 to q-1 do\n let r = read_int() - 1 in\n let c = read_int() - 1 in\n let r3 = r lxor 1 in\n let count = [-1; 0; 1]\n |> List.map (fun (x: int) -> (r3, c + x))\n |> List.filter (fun (x: int * int) -> 0 <= (snd x) && (snd x) < n)\n |> List.filter (fun (x: int * int) -> arr.(snd x).(r3))\n |> List.length in\n if arr.(c).(r) then (\n arr.(c).(r) <- false;\n sum := !sum - count\n ) else (\n arr.(c).(r) <- true;\n sum := !sum + count\n );\n printf (if !sum > 0 then \"No\\n\" else \"Yes\\n\");\n done;\n\n"}], "negative_code": [], "src_uid": "af036416721694d1843368988ca78e8e"} {"nl": {"description": "You are given two circles. Find the area of their intersection.", "input_spec": "The first line contains three integers x1,\u2009y1,\u2009r1 (\u2009-\u2009109\u2009\u2264\u2009x1,\u2009y1\u2009\u2264\u2009109,\u20091\u2009\u2264\u2009r1\u2009\u2264\u2009109) \u2014 the position of the center and the radius of the first circle. The second line contains three integers x2,\u2009y2,\u2009r2 (\u2009-\u2009109\u2009\u2264\u2009x2,\u2009y2\u2009\u2264\u2009109,\u20091\u2009\u2264\u2009r2\u2009\u2264\u2009109) \u2014 the position of the center and the radius of the second circle.", "output_spec": "Print the area of the intersection of the circles. The answer will be considered correct if the absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["0 0 4\n6 0 4", "0 0 5\n11 0 5"], "sample_outputs": ["7.25298806364175601379", "0.00000000000000000000"], "notes": null}, "positive_code": [{"source_code": "open Big_int\n\nlet (+|) = add_big_int\nlet (-|) = sub_big_int\nlet ( *| ) = mult_big_int\nlet (/|) = div_big_int\nlet bmod = mod_big_int\nlet (=|) = eq_big_int\nlet (/=|) a b = not (a =| b)\nlet (>|) = gt_big_int\nlet (<|) = lt_big_int\nlet (>=|) = ge_big_int\nlet (<=|) = le_big_int\n\nlet n0 = zero_big_int\nlet n1 = unit_big_int\nlet n2 = big_int_of_int 2\n\nlet precision = 100\nlet base = power_int_positive_int 10 precision\n\nlet atan z =\n let z2 = z *| z in\n let base2 = base *| base in\n let r = ref n0 in\n let p = ref base in\n for n = 0 to 1000 do\n if n > 0 then (\n\tp := !p *| big_int_of_int (2 * n) *| z2 /|\n\t (big_int_of_int (2 * n + 1) *| (base2 +| z2));\n );\n r := !r +| !p;\n done;\n (!r *| z *| base) /| (base2 +| z2)\n\nlet pi = atan base *| big_int_of_int 4\n\nlet atan z =\n if z >| base\n then pi /| n2 -| atan (base *| base /| z)\n else atan z\n\nlet atan z =\n if z <| n0\n then minus_big_int (atan (minus_big_int z))\n else atan z\n\nlet atan2 y x =\n if x >| n0\n then atan (y *| base /| x)\n else if x =| n0\n then (\n if y >| n0\n then pi /| n2\n else if y <| n0\n then minus_big_int (pi /| n2)\n else assert false\n ) else (\n if y >=| n0\n then atan (y *| base /| x) +| pi\n else atan (y *| base /| x) -| pi\n )\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let x1 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y1 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r1 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x2 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y2 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r2 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let sqr x = x *| x in\n let x1 = big_int_of_int x1 *| base in\n let y1 = big_int_of_int y1 *| base in\n let r1 = big_int_of_int r1 *| base in\n let x2 = big_int_of_int x2 *| base in\n let y2 = big_int_of_int y2 *| base in\n let r2 = big_int_of_int r2 *| base in\n let d2 = sqr (x1 -| x2) +| sqr (y1 -| y2) in\n let d = sqrt_big_int d2 in\n let res =\n if d <=| r2 -| r1 +| n1\n then pi *| sqr r1 /| (base *| base)\n else if d <=| r1 -| r2 +| n1\n then pi *| sqr r2 /| (base *| base)\n else if d >=| r1 +| r2 -| n1\n then n0\n else (\n let intersect r1 r2 =\n\tlet a = (d2 +| sqr r1 -| sqr r2) /| (n2 *| d) in\n\tlet h = sqrt_big_int (max_big_int n0 (sqr r1 -| sqr a)) in\n\tlet alpha = atan2 h a in\n\t alpha *| sqr r1 /| (base *| base) -| a *| h /| base\n in\n\tintersect r1 r2 +| intersect r2 r1\n )\n in\n (*Printf.printf \"%s\\n\" (string_of_big_int res)*)\n Num.(\n let res = num_of_big_int res // num_of_big_int base in\n let s = approx_num_fix 100 res in\n let _ = assert (s.[0] = '+') in\n let s = String.sub s 1 (String.length s - 1) in\n\tPrintf.printf \"%s\\n\" s\n )\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let x1 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y1 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r1 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let x2 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y2 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r2 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let pi = 4.0 *. atan 1.0 in\n let sqr x = x *. x in\n let d2 = sqr (x1 -. x2) +. sqr (y1 -. y2) in\n let d = sqrt d2 in\n let res =\n if d <= r2 -. r1 +. 1e-11\n then pi *. sqr r1\n else if d <= r1 -. r2 +. 1e-11\n then pi *. sqr r2\n else if d >= r1 +. r2 -. 1e-11\n then 0.0\n else (\n let a1 = sqr r1 *. acos ((d2 +. sqr r1 -. sqr r2) /. (2.0 *. d *. r1)) in\n let a2 = sqr r2 *. acos ((d2 +. sqr r2 -. sqr r1) /. (2.0 *. d *. r2)) in\n let a3 =\n\tsqrt ((-.d +. r1 +. r2) *. (d -. r1 +. r2) *. (d +. r1 -. r2) *.\n\t\t(d +. r1 +. r2))\n in\n\ta1 +. a2 -. a3 /. 2.0\n )\n in\n Printf.printf \"%.9f\\n\" res\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let x1 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y1 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r1 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let x2 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y2 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r2 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let sqr x = x *. x in\n let d2 = sqr (x1 -. x2) +. sqr (y1 -. y2) in\n let d = sqrt d2 in\n let res =\n if d >= r1 +. r2\n then 0.0\n else (\n let a1 = sqr r1 *. acos ((d2 +. sqr r1 -. sqr r2) /. (2.0 *. d *. r1)) in\n let a2 = sqr r2 *. acos ((d2 +. sqr r2 -. sqr r1) /. (2.0 *. d *. r2)) in\n let a3 =\n\tsqrt ((-.d +. r1 +. r2) *. (d -. r1 +. r2) *. (d +. r1 -. r2) *.\n\t\t(d +. r1 +. r2))\n in\n\ta1 +. a2 -. a3 /. 2.0\n )\n in\n Printf.printf \"%.9f\\n\" res\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let x1 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y1 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r1 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let x2 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y2 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r2 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let pi = 4.0 *. atan 1.0 in\n let sqr x = x *. x in\n let d2 = sqr (x1 -. x2) +. sqr (y1 -. y2) in\n let d = sqrt d2 in\n let res =\n if d <= r2 -. r1 +. 1e-11\n then pi *. sqr r1\n else if d <= r1 -. r2 +. 1e-11\n then pi *. sqr r2\n else if d >= r1 +. r2 -. 1e-11\n then 0.0\n else (\n let intersect r1 r2 =\n\tlet a = (d2 +. sqr r1 -. sqr r2) /. (2.0 *. d) in\n\tlet h = sqrt (max 0.0 (sqr r1 -. sqr a)) in\n\tlet alpha = atan2 h a in\n\t alpha *. sqr r1 -. a *. h\n in\n (*let a1 = sqr r1 *. acos ((d2 +. sqr r1 -. sqr r2) /. (2.0 *. d *. r1)) in\n let a2 = sqr r2 *. acos ((d2 +. sqr r2 -. sqr r1) /. (2.0 *. d *. r2)) in\n let a3 =\n\tsqrt ((-.d +. r1 +. r2) *. (d -. r1 +. r2) *. (d +. r1 -. r2) *.\n\t\t(d +. r1 +. r2))\n in\n\ta1 +. a2 -. a3 /. 2.0\n *)\n\tintersect r1 r2 +. intersect r2 r1\n )\n in\n Printf.printf \"%.9f\\n\" res\n"}], "src_uid": "94d98a05741019f648693085d2f08872"} {"nl": {"description": "You are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met: There are y elements in F, and all of them are integer numbers; . You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two arrays A and B are considered different iff there exists at least one index i (1\u2009\u2264\u2009i\u2009\u2264\u2009y) such that Ai\u2009\u2260\u2009Bi. Since the answer can be very large, print it modulo 109\u2009+\u20097.", "input_spec": "The first line contains one integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009105) \u2014 the number of testcases to solve. Then q lines follow, each containing two integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009106). Each of these lines represents a testcase.", "output_spec": "Print q integers. i-th integer has to be equal to the number of yi-factorizations of xi modulo 109\u2009+\u20097.", "sample_inputs": ["2\n6 3\n4 2"], "sample_outputs": ["36\n6"], "notes": "NoteIn the second testcase of the example there are six y-factorizations: {\u2009-\u20094,\u2009\u2009-\u20091}; {\u2009-\u20092,\u2009\u2009-\u20092}; {\u2009-\u20091,\u2009\u2009-\u20094}; {1,\u20094}; {2,\u20092}; {4,\u20091}. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet factor n = (* the list of prime powers that occur when we factor n *)\n let rec loop n p pow ac =\n let ac' = if pow>0 then (pow::ac) else ac in\n if n=1 then ac'\n else if n mod p = 0 then loop (n/p) p (pow+1) ac\n else loop n (p+1) 0 ac'\n in\n List.rev (loop n 2 0 [])\n\nlet rec power_in p j = if p>j || j mod p <> 0 then 0 else 1 + power_in p (j/p)\n \nlet compute_prime_powers n =\n let sieve = Array.make (n+1) [] in\n let rec loop i = if i <= n then (\n if sieve.(i) = [] then ( (* i is a prime *)\n let rec pass j = if j<=n then (\n\tsieve.(j) <- (power_in i j)::sieve.(j);\n\tpass (j+i)\n ) in\n pass i;\n );\n loop (i+1)\n )\n in\n loop 2;\n sieve\n\nlet mm = 1_000_000_007L\n\nlet ( ** ) a b = (Int64.rem (Int64.mul a b) mm)\nlet ( // ) a b = Int64.div a b (* non mod division *)\nlet ( %% ) a b = Int64.rem a b\nlet ( -- ) a b = Int64.sub a b (* non mod subtraction *)\nlet ( ++ ) a b = let c = Int64.add a b in\n\t\t if c >= mm then (c -- mm) else c\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec powermod a b = (* a^b mod m *)\n if b=0 then 1L else\n let r = powermod a (b lsr 1) in\n let r2 = r**r in\n if b land 1 = 0 then r2 else r2**a\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet product i j f = fold i j (fun i a -> (f i) ** a) 1L\n\nlet inverse a =\n let rec egcd a b =\n (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g *)\n if a = 0 then (0,1,b) else \n let (x,y,g) = egcd (b mod a) a in \n (y-(b/a)*x, x, g)\n in\n let (x,_,_) = egcd (short a) (short mm) in\n long (if x >= 0 then x else x+(short mm))\n \nlet init_factorial n =\n let f = Array.make (n+1) 1L in\n for i=1 to n do\n f.(i) <- (long i) ** f.(i-1)\n done;\n f\n\nlet binom n k f = (* n choose k (f is the factoral table) *)\n if k < 0 || n < k then 0L else\n f.(n) ** (inverse f.(k)) ** (inverse f.(n-k))\n\nlet () =\n\n let maxy = 1_000_000 in\n let maxx = 1_000_000 in \n let maxk = 20 in\n let fact = init_factorial (maxy+maxk-1) in\n let prime_powers = compute_prime_powers maxx in\n\n let q = read_int() in\n for i=1 to q do\n let x = read_int() in\n let y = read_int() in\n\n(* let prime_powers = Array.of_list (factor x) in *)\n let npp = List.length prime_powers.(x) in\n let pparray = Array.of_list prime_powers.(x) in\n\n let combs = product 0 (npp-1) (fun i ->\n let k = pparray.(i) in\n binom (y+k-1) k fact\n ) in\n \n let answer = (powermod 2L (y-1)) ** combs in\n\n printf \"%Ld\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "6b7a083225f0dd895cc48ca68af695f4"} {"nl": {"description": "HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1\u2009\u2264\u2009fi\u2009\u2264\u2009n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |a\u2009-\u2009b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of fragments. The second line contains n different integers fi (1\u2009\u2264\u2009fi\u2009\u2264\u2009n) \u2014 the number of the fragment written in the i-th sector.", "output_spec": "Print the only integer \u2014 the number of time units needed to read the file.", "sample_inputs": ["3\n3 1 2", "5\n1 3 5 4 2"], "sample_outputs": ["3", "10"], "notes": "NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4\u2009+\u20093\u2009+\u20092\u2009+\u20091\u2009=\u200910."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n for i = 1 to n do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(k - 1) <- i\n done;\n let pos = ref a.(0) in\n let res = ref 0L in\n for i = 0 to n - 1 do\n\tres := !res +| Int64.of_int (abs (a.(i) - !pos));\n\tpos := a.(i);\n done;\n Printf.printf \"%Ld\\n\" !res\n"}], "negative_code": [], "src_uid": "54e2b6bea0dc6ee68366405945af50c6"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, and an array $$$b$$$, with length $$$n$$$. Initially $$$b_i=0$$$ for each $$$1 \\leq i \\leq n$$$.In one move you can choose an integer $$$i$$$ ($$$1 \\leq i \\leq n$$$), and add $$$a_i$$$ to $$$b_i$$$ or subtract $$$a_i$$$ from $$$b_i$$$. What is the minimum number of moves needed to make $$$b$$$ increasing (that is, every element is strictly greater than every element before it)?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 5000$$$). The second line contains $$$n$$$ integers, $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) \u2014 the elements of the array $$$a$$$.", "output_spec": "Print a single integer, the minimum number of moves to make $$$b$$$ increasing.", "sample_inputs": ["5\n1 2 3 4 5", "7\n1 2 1 2 1 2 1", "8\n1 8 2 7 3 6 4 5"], "sample_outputs": ["4", "10", "16"], "notes": "NoteExample $$$1$$$: you can subtract $$$a_1$$$ from $$$b_1$$$, and add $$$a_3$$$, $$$a_4$$$, and $$$a_5$$$ to $$$b_3$$$, $$$b_4$$$, and $$$b_5$$$ respectively. The final array will be [$$$-1$$$, $$$0$$$, $$$3$$$, $$$4$$$, $$$5$$$] after $$$4$$$ moves.Example $$$2$$$: you can reach [$$$-3$$$, $$$-2$$$, $$$-1$$$, $$$0$$$, $$$1$$$, $$$2$$$, $$$3$$$] in $$$10$$$ moves."}, "positive_code": [{"source_code": "let _ = read_line ()\r\nlet nums_str = read_line ()\r\n\r\nlet rec split str len n acc nums =\r\n if n = len then nums @ [Int64.of_string acc]\r\n else if str.[n] = ' ' then split str len (n + 1) \"\" (nums @ [Int64.of_string acc])\r\n else split str len (n + 1) (acc ^ String.make 1 str.[n]) nums\r\n\r\nlet nums = split nums_str (String.length nums_str) 0 \"\" []\r\n\r\nlet rec add lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t ->\r\n let o = Int64.div (Int64.add prev h) h in\r\n add t\r\n (Int64.mul h o)\r\n (Int64.add moves o)\r\n\r\nlet rec sub lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t ->\r\n let o = Int64.abs (Int64.div (Int64.sub prev h) h) in\r\n sub t\r\n (Int64.mul (Int64.neg h) o)\r\n (Int64.add moves o)\r\n\r\nlet rec attempt lst rev ans =\r\n match lst with\r\n | [] -> ans\r\n | h :: t -> attempt t (h :: rev) (min ans (Int64.add (sub rev 0L 0L) (add t 0L 0L)))\r\n\r\nlet ans = attempt nums [] Int64.max_int;;\r\n\r\nPrintf.printf \"%Ld\\n\" ans "}, {"source_code": "let _ = read_line ()\r\nlet nums_str = read_line ()\r\n\r\nlet rec split str len n acc nums =\r\n if n = len then nums @ [Int64.of_string acc]\r\n else if str.[n] = ' ' then split str len (n + 1) \"\" (nums @ [Int64.of_string acc])\r\n else split str len (n + 1) (acc ^ String.make 1 str.[n]) nums\r\n\r\nlet nums = split nums_str (String.length nums_str) 0 \"\" []\r\n\r\nlet rec add lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t ->\r\n let o = Int64.div (Int64.add prev h) h in\r\n add t\r\n (Int64.mul h o)\r\n (Int64.add moves o)\r\n\r\nlet rec sub lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t ->\r\n let o = Int64.abs (Int64.div (Int64.sub prev h) h) in\r\n sub t\r\n (Int64.mul (Int64.neg h) o)\r\n (Int64.add moves o)\r\n\r\nlet rec attempt lst rev ans =\r\n match lst with\r\n | [] -> ans\r\n | h :: t -> attempt t (h :: rev) (min ans (Int64.add (sub rev 0L 0L) (add t 0L 0L)))\r\n\r\nlet ans = attempt nums [] Int64.max_int;;\r\n\r\nPrintf.printf \"%Ld\\n\" ans"}], "negative_code": [{"source_code": "let _ = read_line ()\r\nlet nums_str = read_line ()\r\n\r\nlet rec split str len n acc =\r\n if n = len then [ int_of_string acc ]\r\n else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) \"\"\r\n else split str len (n + 1) (acc ^ String.make 1 str.[n])\r\n\r\nlet nums = split nums_str (String.length nums_str) 0 \"\"\r\n\r\nlet rec add lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> add t (h * ((prev + h) / h)) (moves + ((prev + h) / h))\r\n\r\nlet rec sub lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t ->\r\n if abs (prev - h) < 0 then -1\r\n else sub t (-h * (abs (prev - h) / h)) (moves + (abs (prev - h) / h))\r\n\r\nlet rec attempt lst rev ans =\r\n match lst with\r\n | [] -> ans\r\n | h :: t -> attempt t (h :: rev) (min ans (sub rev 0 0 + add t 0 0))\r\n\r\nlet ans = attempt nums [] max_int;;\r\n\r\nPrintf.printf \"%d\\n\" ans"}, {"source_code": "let _ = read_line ()\r\nlet nums_str = read_line ()\r\n\r\nlet rec split str len n acc =\r\n if n = len then [ int_of_string acc ]\r\n else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) \"\"\r\n else split str len (n + 1) (acc ^ String.make 1 str.[n])\r\n\r\nlet nums = split nums_str (String.length nums_str) 0 \"\"\r\n\r\nlet rec add lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> add t (h * ((prev + h) / h)) (moves + ((prev + h) / h))\r\n\r\nlet rec sub lst prev moves = \r\n match lst with\r\n | [] -> moves\r\n | h :: t -> sub t (-h * (abs (prev - h) / h)) (moves + (abs (prev - h) / h))\r\n\r\nlet rec attempt lst rev i ans =\r\n match lst with\r\n | [] -> ans\r\n | h :: t -> attempt t (h :: rev) (i + 1) (min ans (sub rev 0 0 + add t 0 0))\r\n\r\nlet ans = attempt nums [] 0 max_int;;\r\n\r\nPrintf.printf \"%d\\n\" ans"}, {"source_code": "let _ = read_line ()\r\nlet nums_str = read_line ()\r\n\r\nlet rec split str len n acc =\r\n if n = len then [ int_of_string acc ]\r\n else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) \"\"\r\n else split str len (n + 1) (acc ^ String.make 1 str.[n])\r\n\r\nlet nums = split nums_str (String.length nums_str) 0 \"\"\r\n\r\nlet rec add lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> add t (h * (abs (prev + h) / h)) (moves + (abs (prev + h) / h))\r\n\r\nlet rec sub lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> sub t (-h * (abs (prev - h) / h)) (moves + (abs (prev - h) / h))\r\n\r\nlet rec attempt lst rev i ans =\r\n match lst with\r\n | [] -> ans\r\n | h :: t -> attempt t (h :: rev) (i + 1) (min ans (sub rev 0 0 + add t 0 0))\r\n\r\nlet ans = attempt nums [] 0 max_int;;\r\n\r\nPrintf.printf \"%d\\n\" ans"}, {"source_code": "let _ = read_line ()\r\nlet nums_str = read_line ()\r\n\r\nlet rec split str len n acc =\r\n if n = len then [ int_of_string acc ]\r\n else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) \"\"\r\n else split str len (n + 1) (acc ^ String.make 1 str.[n])\r\n\r\nlet nums = split nums_str (String.length nums_str) 0 \"\"\r\n\r\nlet rec add lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> add t (h * ((prev + h) / h)) (moves + ((prev + h) / h))\r\n\r\nlet rec sub lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> sub t (-h * (abs (prev - h) / h)) (moves + (abs (prev - h) / h))\r\n\r\nlet rec attempt lst rev i ans =\r\n match lst with\r\n | [] -> ans\r\n | h :: t -> attempt t (h :: rev) (i + 1) (min ans (sub rev 0 0 + add t 0 0))\r\n\r\nlet ans = attempt nums [] 0 max_int;;\r\n\r\nPrintf.printf \"%d\\n\" ans"}, {"source_code": "let _ = read_line ()\r\nlet nums_str = read_line ()\r\n\r\nlet rec split str len n acc =\r\n if n = len then [ int_of_string acc ]\r\n else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) \"\"\r\n else split str len (n + 1) (acc ^ String.make 1 str.[n])\r\n\r\nlet nums = split nums_str (String.length nums_str) 0 \"\"\r\n\r\nlet rec get_rev lst i =\r\n match lst with\r\n | [] -> []\r\n | h :: t -> if i = 0 then [] else get_rev t (i - 1) @ [ h ]\r\n\r\nlet rec add lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> add t (h * abs ((prev + h) / h)) (moves + ((prev + h) / h))\r\n\r\nlet rec sub lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> sub t (-h * abs ((prev - h) / h)) (moves + (abs (prev - h) / h))\r\n\r\nlet rec attempt lst rev i ans =\r\n match lst with\r\n | [] -> ans\r\n | h :: t -> attempt t (h :: rev) (i + 1) (min ans (sub rev 0 0 + add t 0 0))\r\n\r\nlet ans = attempt nums [] 0 max_int;;\r\n\r\nPrintf.printf \"%d\\n\" ans"}, {"source_code": "let _ = read_line ()\r\nlet nums_str = read_line ()\r\n\r\nlet rec split str len n acc =\r\n if n = len then [ int_of_string acc ]\r\n else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) \"\"\r\n else split str len (n + 1) (acc ^ String.make 1 str.[n])\r\n\r\nlet nums = split nums_str (String.length nums_str) 0 \"\"\r\n\r\nlet rec loop lst =\r\n match lst with\r\n | [] -> print_newline ()\r\n | h :: t ->\r\n print_string (string_of_int h ^ \" \");\r\n loop t\r\n\r\nlet () = loop nums\r\n\r\nlet rec get_rev lst i =\r\n match lst with\r\n | [] -> []\r\n | h :: t -> if i = 0 then [] else get_rev t (i - 1) @ [ h ]\r\n\r\nlet rec add lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> add t (h * abs ((prev + h) / h)) (moves + ((prev + h) / h))\r\n\r\nlet rec sub lst prev moves =\r\n match lst with\r\n | [] -> moves\r\n | h :: t -> sub t (-h * abs ((prev - h) / h)) (moves + (abs (prev - h) / h))\r\n\r\nlet rec attempt lst i len ans =\r\n match lst with\r\n | [] -> ans\r\n | h :: t ->\r\n attempt t (i + 1) len (min ans (sub (get_rev nums i) 0 0 + add t 0 0))\r\n\r\nlet ans = attempt nums 0 (List.length nums) max_int;;\r\n\r\nPrintf.printf \"%d\\n\" ans"}], "src_uid": "da2fb0ea61808905a133021223f6148d"} {"nl": {"description": "A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.", "input_spec": "The first line of input contains n \u2014 a positive integer number without leading zeroes (1\u2009\u2264\u2009n\u2009<\u200910100000).", "output_spec": "Print one number \u2014 any beautiful number obtained by erasing as few as possible digits. If there is no answer, print \u2009-\u20091.", "sample_inputs": ["1033", "10", "11"], "sample_outputs": ["33", "0", "-1"], "notes": "NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let c2i c = Char.code c - Char.code '0' in\n let t =\n let t = ref 0 in\n for i = 0 to n - 1 do\n\tt := !t + c2i s.[i]\n done;\n !t mod 3\n in\n if t = 0\n then Printf.printf \"%s\\n\" s\n else (\n let b = ref 1000000000 in\n let bs = ref \"\" in\n\tfor i = n - 1 downto 0 do\n\t if c2i s.[i] mod 3 = t then (\n\t if i > 0 then (\n\t if !b > 1 then (\n\t\tb := 1;\n\t\tbs := String.sub s 0 i ^ String.sub s (i + 1) (n - i - 1)\n\t )\n\t ) else (\n\t let j = ref (n - 1) in\n\t\tfor i = n - 1 downto 1 do\n\t\t if c2i s.[i] <> 0 then (\n\t\t j := i\n\t\t )\n\t\tdone;\n\t\tif !j > 0 then (\n\t\t if !b > !j then (\n\t\t b := !j;\n\t\t bs := String.sub s !j (n - !j)\n\t\t )\n\t\t)\n\t )\n\t )\n\tdone;\n\t(let p1 = ref (-1) in\n\t let p2 = ref (-1) in\n\t let _ =\n\t for i = n - 1 downto 0 do\n\t if c2i s.[i] mod 3 = 3 - t then (\n\t if !p2 < 0\n\t then p2 := i\n\t else if !p1 < 0\n\t then p1 := i\n\t )\n\t done;\n\t in\n\t let p1 = !p1\n\t and p2 = !p2 in\n\t if p1 >= 0 then (\n\t if p1 > 0 then (\n\t if !b > 2 then (\n\t\t b := 2;\n\t\t bs := String.sub s 0 p1 ^ String.sub s (p1 + 1) (p2 - p1 - 1) ^\n\t\t String.sub s (p2 + 1) (n - p2 - 1)\n\t )\n\t ) else (\n\t let j = ref 1 in\n\t\t while !j < n && (c2i s.[!j] = 0 || !j = p2) do\n\t\t incr j\n\t\t done;\n\t\t if !j < n then (\n\t\t if !j < p2 then (\n\t\t if !b > !j + 1 then (\n\t\t b := !j + 1;\n\t\t bs := String.sub s !j (p2 - !j) ^\n\t\t\t String.sub s (p2 + 1) (n - p2 - 1)\n\t\t )\n\t\t ) else (\n\t\t if !b > !j then (\n\t\t b := !j;\n\t\t bs := String.sub s !j (n - !j)\n\t\t )\n\t\t )\n\t\t ) else if n > 2 then (\n\t\t if !b > n - 1 then (\n\t\t b := n - 1;\n\t\t bs := \"0\"\n\t\t )\n\t\t )\n\t )\n\t )\n\t);\n\tif !bs <> \"\"\n\tthen Printf.printf \"%s\\n\" !bs\n\telse Printf.printf \"-1\\n\"\n )\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let c2i c = Char.code c - Char.code '0' in\n let t =\n let t = ref 0 in\n for i = 0 to n - 1 do\n\tt := !t + c2i s.[i]\n done;\n !t mod 3\n in\n if t = 0\n then Printf.printf \"%s\\n\" s\n else (\n let b = ref 1000000000 in\n let bs = ref \"\" in\n\tfor i = n - 1 downto 0 do\n\t if c2i s.[i] mod 3 = t then (\n\t if i > 0 then (\n\t if !b > 1 then (\n\t\tb := 1;\n\t\tbs := String.sub s 0 i ^ String.sub s (i + 1) (n - i - 1)\n\t )\n\t ) else (\n\t let j = ref (n - 1) in\n\t\tfor i = n - 1 downto 1 do\n\t\t if c2i s.[i] <> 0 then (\n\t\t j := i\n\t\t )\n\t\tdone;\n\t\tif !j > 0 then (\n\t\t if !b > !j then (\n\t\t b := !j;\n\t\t bs := String.sub s !j (n - !j)\n\t\t )\n\t\t)\n\t )\n\t )\n\tdone;\n\t(let p1 = ref (-1) in\n\t let p2 = ref (-1) in\n\t let _ =\n\t for i = n - 1 downto 0 do\n\t if c2i s.[i] mod 3 = 3 - t then (\n\t if !p2 < 0\n\t then p2 := i\n\t else if !p1 < 0\n\t then p1 := i\n\t )\n\t done;\n\t in\n\t let p1 = !p1\n\t and p2 = !p2 in\n\t if p1 >= 0 then (\n\t if p1 > 0 then (\n\t if !b > 2 then (\n\t\t b := 2;\n\t\t bs := String.sub s 0 p1 ^ String.sub s (p1 + 1) (p2 - p1 - 1) ^\n\t\t String.sub s (p2 + 1) (n - p2 - 1)\n\t )\n\t ) else (\n\t let j = ref 1 in\n\t\t while !j < n && (c2i s.[!j] = 0 || !j = p2) do\n\t\t incr j\n\t\t done;\n\t\t if !j < n then (\n\t\t if !j < p2 then (\n\t\t if !b > !j + 1 then (\n\t\t b := !j + 1;\n\t\t bs := String.sub s !j (p2 - !j) ^\n\t\t\t String.sub s (p2 + 1) (n - p2 - 1)\n\t\t )\n\t\t ) else (\n\t\t if !b > !j then (\n\t\t b := !j;\n\t\t bs := String.sub s !j (n - !j)\n\t\t )\n\t\t )\n\t\t ) else if s.[n - 1] = '0' then (\n\t\t if !b > n - 1 then (\n\t\t b := n - 1;\n\t\t bs := String.sub s (n - 1) 1\n\t\t )\n\t\t )\n\t )\n\t )\n\t);\n\tif !bs <> \"\"\n\tthen Printf.printf \"%s\\n\" !bs\n\telse Printf.printf \"-1\\n\"\n )\n"}], "src_uid": "df9942d1eb66b1f3b5c6b665b446cd3e"} {"nl": {"description": "Little Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help.The sequence a is called non-decreasing if a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009aN holds, where N is the length of the sequence.", "input_spec": "The first line of the input contains single integer N (1\u2009\u2264\u2009N\u2009\u2264\u20095000) \u2014 the length of the initial sequence. The following N lines contain one integer each \u2014 elements of the sequence. These numbers do not exceed 109 by absolute value.", "output_spec": "Output one integer \u2014 minimum number of steps required to achieve the goal.", "sample_inputs": ["5\n3 2 -1 2 11", "5\n2 1 1 1 1"], "sample_outputs": ["4", "1"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\ntype node = {key: int; child: node; sibling: node}\n\nlet rec nil = {key = min_int; child = nil; sibling = nil}\nlet is_nil a = a.key = min_int\n\nlet merge a b =\n if a.key > b.key then\n {a with child = {b with sibling = a.child}}\n else\n {b with child = {a with sibling = b.child}}\n\nlet merge_list x =\n let rec go acc x =\n if is_nil x then\n acc\n else\n if is_nil x.sibling then\n x::acc\n else\n go (merge x x.sibling::acc) x.sibling.sibling\n in\n match go [] x with\n | [] -> nil\n | u::us -> List.fold_left (fun u v -> merge u v) u us\n\nlet pop x = merge_list x.child\n\nlet singleton k = {key = k; child = nil; sibling = nil}\n\nlet print x =\n let rec go d x =\n if not (is_nil x) then (\n go (d+1) x.sibling;\n for i = 1 to d do print_string \" \" done;\n Printf.printf \"%d\\n\" x.key;\n go (d+1) x.child;\n )\n in go 0 x\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let rec go st i =\n if i >= n then\n st\n else\n let rec f = function\n | (y,yi)::(x,xi)::xs when x.key > y.key ->\n let z = merge x y in\n let z = if (xi-(if xs=[] then -1 else (List.hd xs |> snd))) land 1 <> 0 &&\n (yi-xi) land 1 <> 0 then pop z else z in\n f ((z,yi)::xs)\n | st -> st\n in\n go ((singleton a.(i),i) :: st |> f) (i+1)\n in\n\n go [] 0\n |> List.rev\n |> List.fold_left (fun (ans,l) (x,xi) ->\n let rec go ans i =\n if i > xi then\n ans\n else\n let open Int64 in\n go (abs (sub (of_int a.(i)) (of_int x.key)) |> add ans) (i+1)\n in\n go ans (l+1), xi\n ) (0L,-1)\n |> fst |> Printf.printf \"%Ld\\n\""}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\ntype node = {key: int; child: node; sibling: node}\n\nlet rec nil = {key = min_int; child = nil; sibling = nil}\nlet is_nil a = a.key = min_int\n\nlet merge a b =\n if a.key > b.key then\n {a with child = {b with sibling = a.child}}\n else\n {b with child = {a with sibling = b.child}}\n\nlet merge_list x =\n let rec go acc x =\n if is_nil x then\n acc\n else\n let y = {x with sibling = nil} in\n if is_nil x.sibling then\n y::acc\n else\n let z = {x.sibling with sibling = nil} in\n go (merge y z::acc) x.sibling.sibling\n in\n match go [] x with\n | [] -> nil\n | u::us -> List.fold_left (fun u v -> merge u v) u us\n\nlet pop x = merge_list x.child\n\nlet singleton k = {key = k; child = nil; sibling = nil}\n\nlet push x k = merge x {key = k; child = nil; sibling = nil}\n\nlet print x =\n let rec go d x =\n if not (is_nil x) then (\n go (d+1) x.sibling;\n for i = 1 to d do print_string \" \" done;\n Printf.printf \"%d\\n\" x.key;\n go (d+1) x.child;\n )\n in go 0 x\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let rec go st i =\n if i >= n then\n st\n else\n let rec f = function\n | (y,yi)::(x,xi)::xs when x.key > y.key ->\n let z = merge x y in\n let z = if (xi-(if xs=[] then -1 else (List.hd xs |> snd))) land 1 <> 0 &&\n (yi-xi) land 1 <> 0 then pop z else z in\n f ((z,yi)::xs)\n | st -> st\n in\n go ((singleton a.(i),i) :: st |> f) (i+1)\n in\n\n (*let st = go [] 0 in*)\n (*Printf.printf \"+ len: %d\\n\" (List.length st);*)\n (*Printf.printf \"+++++++++\\n\";*)\n (*List.nth st 0 |> snd |> Printf.printf \"%d\\n\";*)\n (*List.nth st 0 |> fst |> print;*)\n (*Printf.printf \"+++++++++\\n\";*)\n (*List.nth st 1 |> snd |> Printf.printf \"%d\\n\";*)\n (*List.nth st 1 |> fst |> print;*)\n go [] 0\n |> List.rev\n |> List.fold_left (fun (ans,l) (x,xi) ->\n let rec go ans i =\n if i > xi then\n ans\n else\n let open Int64 in\n go (abs (sub (of_int a.(i)) (of_int x.key)) |> add ans) (i+1)\n in\n go ans (l+1), xi\n ) (0L,-1)\n |> fst |> Printf.printf \"%Ld\\n\"\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet lbound a n x =\n let rec go l h =\n if l >= h then\n l\n else\n let m = (l+h)/2 in\n if a.(m) < x then\n go (m+1) h\n else\n go l m\n in go 0 n\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let b = Array.copy a in\n Array.sort compare b;\n for i = 0 to n-1 do\n a.(i) <- lbound b n a.(i)\n done;\n\n let s = Array.make_matrix 2 n 0L in\n for i = 0 to n-1 do\n s.(0).(i) <- if a.(0) <= i then 0L else b.(a.(0))-b.(i) |> Int64.of_int\n done;\n for i = 1 to n-1 do\n let cur = i land 1 in\n let pre = 1-cur in\n for j = 0 to n-1 do\n s.(cur).(j) <- Int64.add s.(pre).(j) (b.(a.(i))-b.(j) |> abs |> Int64.of_int)\n done;\n for j = 1 to n-1 do\n s.(cur).(j) <- min s.(cur).(j) s.(cur).(j-1)\n done\n done;\n Printf.printf \"%Ld\\n\" s.((n-1) land 1).(n-1)\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet lbound a n x =\n let rec go l h =\n if l >= h then\n l\n else\n let m = (l+h)/2 in\n if a.(m) < x then\n go (m+1) h\n else\n go l m\n in go 0 n\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let b = Array.copy a in\n Array.sort compare b;\n for i = 0 to n-1 do\n a.(i) <- lbound b n a.(i)\n done;\n\n let s = Array.make_matrix 2 n 0 in\n for i = 0 to n-1 do\n s.(0).(i) <- if a.(0) <= i then 0 else b.(a.(0))-b.(i)\n done;\n for i = 1 to n-1 do\n let cur = i land 1 in\n let pre = 1-cur in\n for j = 0 to n-1 do\n s.(cur).(j) <- s.(pre).(j) + abs (b.(a.(i))-b.(j))\n done;\n for j = 1 to n-1 do\n s.(cur).(j) <- min s.(cur).(j) s.(cur).(j-1)\n done\n done;\n Printf.printf \"%d\\n\" s.((n-1) land 1).(n-1)\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\ntype node = {key: int; child: node; sibling: node}\n\nlet rec nil = {key = min_int; child = nil; sibling = nil}\nlet is_nil a = a.key = min_int\n\nlet merge a b =\n if a.key > b.key then\n {a with child = {b with sibling = a.child}}\n else\n {b with child = {a with sibling = b.child}}\n\nlet merge_list x =\n let rec go acc x =\n if is_nil x then\n acc\n else\n let y = {x with sibling = nil} in\n if is_nil x.sibling then\n y::acc\n else\n let z = {x.sibling with sibling = nil} in\n go (merge y z::acc) x.sibling.sibling\n in\n match go [] x with\n | [] -> nil\n | u::us -> List.fold_left (fun u v -> merge u v) u us\n\nlet pop x = merge_list x.child\n\nlet singleton k = {key = k; child = nil; sibling = nil}\n\nlet push x k = merge x {key = k; child = nil; sibling = nil}\n\nlet print x =\n let rec go d x =\n if not (is_nil x) then (\n go (d+1) x.sibling;\n for i = 1 to d do print_string \" \" done;\n Printf.printf \"%d\\n\" x.key;\n go (d+1) x.child;\n )\n in go 0 x\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let rec go st i =\n if i >= n then\n st\n else\n let rec f = function\n | (y,yi)::(x,xi)::xs when x.key > y.key ->\n let z = merge x y in\n let z = if (xi-(if xs=[] then -1 else (List.hd xs |> snd))) land 1 <> 0 &&\n (yi-xi) land 1 <> 0 then pop z else z in\n f ((z,yi)::xs)\n | st -> st\n in\n let st' = f st in\n go ((singleton a.(i),i) :: st') (i+1)\n in\n\n (*Printf.printf \"+ len: %d\\n\" (List.length st);*)\n (*Printf.printf \"+++++++++\\n\";*)\n (*List.nth st 0 |> snd |> Printf.printf \"%d\\n\";*)\n (*Printf.printf \"+++++++++\\n\";*)\n (*List.nth st 1 |> snd |> Printf.printf \"%d\\n\";*)\n (*Printf.printf \"+++++++++\\n\";*)\n (*List.nth st 2 |> snd |> Printf.printf \"%d\\n\";*)\n go [] 0\n |> List.rev\n |> List.fold_left (fun (ans,l) (x,xi) ->\n let rec go ans i =\n if i > xi then\n ans\n else\n let open Int64 in\n go (abs (sub (of_int a.(i)) (of_int x.key)) |> add ans) (i+1)\n in\n go ans (l+1), xi\n ) (0L,-1)\n |> fst |> Printf.printf \"%Ld\\n\"\n"}], "src_uid": "5f4d01b17b9669a00c0f1a8b3a373abf"} {"nl": {"description": "Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: the graph contains exactly 2n\u2009+\u2009p edges; the graph doesn't contain self-loops and multiple edges; for any integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009n), any subgraph consisting of k vertices contains at most 2k\u2009+\u2009p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices.", "input_spec": "The first line contains a single integer t (1\u2009\u2264\u2009t\u2009\u2264\u20095) \u2014 the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5\u2009\u2264\u2009n\u2009\u2264\u200924; p\u2009\u2265\u20090; ) \u2014 the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists.", "output_spec": "For each of the t tests print 2n\u2009+\u2009p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi) \u2014 two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.", "sample_inputs": ["1\n6 0"], "sample_outputs": ["1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet solve n p =\n let m = 2*n + p in\n let a = Array.make m (0,0) in\n let k = ref 0 in\n let add_edge e =\n a.(!k) <- e;\n k := !k + 1\n in\n for i=0 to n-1 do\n add_edge (i, (i+1) mod n);\n add_edge (i, (i+2) mod n);\n done;\n\n let delta = ref 3 in\n for i=0 to p-1 do\n add_edge (i mod n, (i + !delta) mod n);\n if (i+1) mod n = 0 then delta := !delta+1\n done;\n a\n\nlet () = \n let t = read_int () in\n for case = 1 to t do \n let n = read_int() in\n let p = read_int() in\n let a = solve n p in\n for i=0 to 2*n+p-1 do\n let (a,b) = a.(i) in\n printf \"%d %d\\n\" (a+1) (b+1)\n done\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet solve n p =\n let m = 2*n + p in\n let a = Array.make m (0,0) in\n let k = ref 0 in\n let add_edge e =\n a.(!k) <- e;\n k := !k + 1\n in\n for i=0 to n-1 do\n add_edge (i, (i+1) mod n);\n add_edge (i, (i+2) mod n);\n done;\n\n let delta = ref 3 in\n for i=0 to p-1 do\n add_edge (i mod n, (i + !delta) mod n);\n if i mod n = 0 then delta := !delta+1\n done;\n a\n\nlet () = \n let t = read_int () in\n for case = 1 to t do \n let n = read_int() in\n let p = read_int() in\n let a = solve n p in\n for i=0 to 2*n+p-1 do\n let (a,b) = a.(i) in\n printf \"%d %d\\n\" (a+1) (b+1)\n done\n done\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet solve n p =\n let m = 2*n + p in\n let a = Array.make m (0,0) in\n let k = ref 0 in\n let add_edge e =\n a.(!k) <- e;\n k := !k + 1\n in\n for i=0 to n-1 do\n add_edge (i, (i+1) mod n);\n add_edge (i, (i+2) mod n);\n done;\n\n for i=0 to p-1 do\n add_edge (i, (i+3) mod n);\n done;\n a\n\nlet () = \n let t = read_int () in\n for case = 1 to t do \n let n = read_int() in\n let p = read_int() in\n let a = solve n p in\n for i=0 to 2*n+p-1 do\n let (a,b) = a.(i) in\n printf \"%d %d\\n\" (a+1) (b+1)\n done\n done\n"}], "src_uid": "ddbac4053bd07eada84bc44275367ae2"} {"nl": {"description": "You are given a directed graph G with n vertices and m arcs (multiple arcs and self-loops are allowed). You have to paint each vertex of the graph into one of the k (k\u2009\u2264\u2009n) colors in such way that for all arcs of the graph leading from a vertex u to vertex v, vertex v is painted with the next color of the color used to paint vertex u.The colors are numbered cyclically 1 through k. This means that for each color i (i\u2009<\u2009k) its next color is color i\u2009+\u20091. In addition, the next color of color k is color 1. Note, that if k\u2009=\u20091, then the next color for color 1 is again color 1.Your task is to find and print the largest possible value of k (k\u2009\u2264\u2009n) such that it's possible to color G as described above with k colors. Note that you don't necessarily use all the k colors (that is, for each color i there does not necessarily exist a vertex that is colored with color i).", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105), denoting the number of vertices and the number of arcs of the given digraph, respectively. Then m lines follow, each line will contain two space-separated integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n), which means that the i-th arc goes from vertex ai to vertex bi. Multiple arcs and self-loops are allowed.", "output_spec": "Print a single integer \u2014 the maximum possible number of the colors that can be used to paint the digraph (i.e. k, as described in the problem statement). Note that the desired value of k must satisfy the inequality 1\u2009\u2264\u2009k\u2009\u2264\u2009n.", "sample_inputs": ["4 4\n1 2\n2 1\n3 4\n4 3", "5 2\n1 4\n2 5", "4 5\n1 2\n2 3\n3 1\n2 4\n4 1", "4 4\n1 1\n1 2\n2 1\n1 2"], "sample_outputs": ["2", "5", "3", "1"], "notes": "NoteFor the first example, with k\u2009=\u20092, this picture depicts the two colors (arrows denote the next color of that color). With k\u2009=\u20092 a possible way to paint the graph is as follows. It can be proven that no larger value for k exists for this test case.For the second example, here's the picture of the k\u2009=\u20095 colors. A possible coloring of the graph is: For the third example, here's the picture of the k\u2009=\u20093 colors. A possible coloring of the graph is: "}, "positive_code": [{"source_code": "let rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let () =\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- (v, 1) :: es.(u);\n\tes.(v) <- (u, -1) :: es.(v);\n done;\n in\n let es = Array.map Array.of_list es in\n let used = Array.make n false in\n let a = Array.make n (-1) in\n let res = ref 0 in\n let rec dfs u =\n used.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n let (v, d) = es.(u).(i) in\n\tif not used.(v) then (\n\t a.(v) <- a.(u) + d;\n\t dfs v\n\t) else (\n\t res := gcd !res (abs ((a.(u) + d) - a.(v)))\n\t)\n done;\n in\n for i = 0 to n - 1 do\n if not used.(i) then (\n\ta.(i) <- 0;\n\tdfs i\n )\n done;\n if !res = 0\n then res := n;\n Printf.printf \"%d\\n\" !res\n "}, {"source_code": "let rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let () =\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- (v, 1) :: es.(u);\n\tes.(v) <- (u, -1) :: es.(v);\n done;\n in\n let es = Array.map Array.of_list es in\n let used = Array.make n false in\n let a = Array.make n (-1) in\n let res = ref 0 in\n let pos = ref 0 in\n let stack = Array.make n 0 in\n let rec dfs u =\n used.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n let (v, d) = es.(u).(i) in\n\tif not used.(v) then (\n\t a.(v) <- a.(u) + d;\n\t dfs v\n\t) else (\n\t res := gcd !res (abs ((a.(u) + d) - a.(v)))\n\t)\n done;\n in\n let rec dfs () =\n if !pos > 0 then (\n decr pos;\n let u = stack.(!pos) in\n\tfor i = 0 to Array.length es.(u) - 1 do\n\t let (v, d) = es.(u).(i) in\n\t if not used.(v) then (\n\t a.(v) <- a.(u) + d;\n\t stack.(!pos) <- v;\n\t incr pos;\n\t used.(v) <- true;\n\t ) else (\n\t res := gcd !res (abs ((a.(u) + d) - a.(v)))\n\t )\n\tdone;\n\tdfs ()\n )\n in\n for i = 0 to n - 1 do\n if not used.(i) then (\n\ta.(i) <- 0;\n\tpos := 0;\n\tstack.(!pos) <- i;\n\tincr pos;\n\tused.(i) <- true;\n\tdfs ()\n )\n done;\n if !res = 0\n then res := n;\n Printf.printf \"%d\\n\" !res\n\n\n"}], "negative_code": [], "src_uid": "339e8062fa7935c146e87404e67ee021"} {"nl": {"description": "You are given a graph with $$$n$$$ nodes and $$$m$$$ directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are \"abaca\", then the value of that path is $$$3$$$. Your task is find a path whose value is the largest.", "input_spec": "The first line contains two positive integers $$$n, m$$$ ($$$1 \\leq n, m \\leq 300\\,000$$$), denoting that the graph has $$$n$$$ nodes and $$$m$$$ directed edges. The second line contains a string $$$s$$$ with only lowercase English letters. The $$$i$$$-th character is the letter assigned to the $$$i$$$-th node. Then $$$m$$$ lines follow. Each line contains two integers $$$x, y$$$ ($$$1 \\leq x, y \\leq n$$$), describing a directed edge from $$$x$$$ to $$$y$$$. Note that $$$x$$$ can be equal to $$$y$$$ and there can be multiple edges between $$$x$$$ and $$$y$$$. Also the graph can be not connected.", "output_spec": "Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.", "sample_inputs": ["5 4\nabaca\n1 2\n1 3\n3 4\n4 5", "6 6\nxzyabc\n1 2\n3 1\n2 3\n5 4\n4 3\n6 4", "10 14\nxzyzyzyzqx\n1 2\n2 4\n3 5\n4 5\n2 6\n6 8\n6 5\n2 10\n3 9\n10 9\n4 6\n1 10\n2 8\n3 7"], "sample_outputs": ["3", "-1", "4"], "notes": "NoteIn the first sample, the path with largest value is $$$1 \\to 3 \\to 4 \\to 5$$$. The value is $$$3$$$ because the letter 'a' appears $$$3$$$ times."}, "positive_code": [{"source_code": "let n, m = Scanf.scanf \" %d %d\" (fun x y -> x, y);;\nlet node = Scanf.scanf \" %s\" (fun x -> x);;\nlet adjs = Array.make (n + 1) [];;\nlet etat = Array.make (n + 1) 0;;\nlet maxi = Array.make_matrix (n + 1) 26 0;;\n\nfor i = 1 to m do\n let u, v = Scanf.scanf \" %d %d\" (fun x y -> x, y) in\n adjs.(u) <- v :: adjs.(u);\ndone;;\n\nlet rec cycle u =\n match etat.(u) with\n | 1 -> true\n | 2 -> false\n | _ ->\n etat.(u) <- 1;\n let x = List.fold_left (fun x v -> x || cycle v) false adjs.(u) in\n etat.(u) <- 2;\n x;;\n\nlet rec calculer u =\n let aux v =\n calculer v;\n let f i x =\n maxi.(u).(i) <- max maxi.(u).(i) x in\n Array.iteri f maxi.(v) in\n if etat.(u) = 0 then (\n etat.(u) <- 1;\n List.iter aux adjs.(u);\n let i = int_of_char node.[u - 1] - int_of_char 'a' in\n maxi.(u).(i) <- maxi.(u).(i) + 1\n );;\n\nlet cyclique = ref false in\nfor u = 1 to n do\n cyclique := !cyclique || cycle u;\ndone;\nif !cyclique then\n print_int (-1)\nelse (\n Array.fill etat 0 (Array.length etat) 0;\n let r = ref 0 in\n for u = 1 to n do\n calculer u;\n r := max !r (Array.fold_left max 0 maxi.(u));\n done;\n print_int !r\n);;\n"}, {"source_code": "let n, m = Scanf.scanf \" %d %d\" (fun x y -> x, y);;\nlet label = Scanf.scanf \" %s\" (fun x -> x);;\nlet adjs = Array.make (n + 1) [];;\nlet etat = Array.make (n + 1) 0;;\nlet maxi = Array.make_matrix (n + 1) 26 0;;\n\nfor i = 1 to m do\n let u, v = Scanf.scanf \" %d %d\" (fun x y -> x, y) in\n adjs.(u) <- v :: adjs.(u);\ndone;;\n\nlet rec cycle u =\n match etat.(u) with\n | 1 -> true\n | 2 -> false\n | _ ->\n etat.(u) <- 1;\n let x = List.fold_left (fun x v -> x || cycle v) false adjs.(u) in\n etat.(u) <- 2;\n x;;\n\nlet rec calculer u =\n let aux v =\n calculer v;\n let f i x =\n maxi.(u).(i) <- max maxi.(u).(i) x in\n Array.iteri f maxi.(v) in\n if etat.(u) = 0 then (\n etat.(u) <- 1;\n List.iter aux adjs.(u);\n let i = int_of_char label.[u - 1] - int_of_char 'a' in\n maxi.(u).(i) <- maxi.(u).(i) + 1\n );;\n\nlet cyclique = ref false in\nfor u = 1 to n do\n cyclique := !cyclique || cycle u;\ndone;\nif !cyclique then\n print_int (-1)\nelse (\n Array.fill etat 0 (Array.length etat) 0;\n let r = ref 0 in\n for u = 1 to n do\n calculer u;\n r := max !r (Array.fold_left max 0 maxi.(u));\n done;\n print_int !r\n);;\n"}], "negative_code": [], "src_uid": "db5a99701dabe3516f97fd172118807e"} {"nl": {"description": "Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn\u2009=\u2009sn\u2009-\u20092\u2009+\u2009sn\u2009-\u20091, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa. Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him \u043ef accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.", "input_spec": "The first line contains four integers k,\u2009x,\u2009n,\u2009m (3\u2009\u2264\u2009k\u2009\u2264\u200950;\u00a00\u2009\u2264\u2009x\u2009\u2264\u2009109;\u00a01\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100).", "output_spec": "In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them. If the required pair of strings doesn't exist, print \"Happy new year!\" without the quotes.", "sample_inputs": ["3 2 2 2", "3 3 2 2", "3 0 2 2", "4 3 2 1", "4 2 2 1"], "sample_outputs": ["AC\nAC", "Happy new year!", "AA\nAA", "Happy new year!", "Happy new year!"], "notes": null}, "positive_code": [{"source_code": "(* Okay, never mind coding this up. But here's how you do it.\n \n WLOG There are only three choices for the beginning and ending of\n s1 and s2. Namely A, C, or X. So there are 81 possibilities for\n these. We run through each of these.\n \n Given the above choices, we compute for s1 the maximum number of\n ACs that can occur inside of s1. (The minimum number can be zero.)\n Call this number A. A is bounded by 50.\n\n Now we simulate computing the recurrence for k iterations. I say\n \"simulate\" because for each string s_i we compute, we need to know\n what the 3 options for the first char, the 3 options for the last\n char, and the number of ACs that occur inside of it. This can be\n done in O(1) time per iteration.\n\n Actually we're going to keep track of the number of ACs that occur\n in s_k in terms of A, the number of ACs inside of s1 and B the\n number of ACs inside of s2. So in order for there to be the right\n number of ACs we have an equation like this: k*A + l*B = c. The\n upper case letters are variables, the lower case letters are\n constants. In order to test if this has a solution we can simply\n run through all the values of, say, A, and for each see in O(1) time\n if there's an appropriate B.\n\n Anyway, at the end of the day, the running time is going to be\n something on the order of 81*50. So it's very fast.\n\n*)\n\nopen Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( ** ) a b = Int64.mul a b\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let k = read_int () in\n let x = Int64.of_int (read_int ()) in\n let len1 = read_int () in\n let len2 = read_int () in\n\n let cat (s1,a1,b1,c1,e1) (s2,a2,b2,c2,e2) =\n (* concatenate string1 to string2 *)\n let inc = if (e1,s2) = ('A','C') then 1L else 0L in\n (s1, a1++a2, b1++b2, c1++c2++inc, e2)\n in\n\n let rec iterate k s1 s2 = if k=0 then s1\n else iterate (k-1) s2 (cat s1 s2)\n in\n\n let sk s1 s2 = iterate (k-1) s1 s2 in\n\n let solvable (_,a,b,c,_) lo1 hi1 lo2 hi2 = \n let works = ref None in\n for i=lo1 to hi1 do\n for j=lo2 to hi2 do\n\tlet (i',j') = (Int64.of_int i, Int64.of_int j) in\n\tif x = a**i' ++ b**j' ++ c then works := Some (i,j) \n done\n done;\n !works\n in\n\n let rec make_options i = if i=4 then [[]] else\n let prepend x = List.map (fun li -> x::li) (make_options (i+1)) in\n (prepend 'A') @ (prepend 'C') @ (prepend 'X')\n in\n\n (* make_options 0 is [['A'; 'A'; 'A'; 'A']; ['A'; 'A'; 'A'; 'C']; ['A'; 'A'; 'A'; 'X']; ... *)\n\n let bounds (s,_,_,_,e) len = \n match (len,s,e) with\n | (0,_,_) -> failwith \"illegal length\"\n | (1,_,_) -> (0,0)\n | (2,'A','C') -> (1, 1)\n | (2, _ , _ ) -> (0, 0)\n | (_,'A','C') -> (0, len/2)\n | (_, _ ,'C') -> (0, (len-1)/2)\n | (_,'A', _ ) -> (0, (len-1)/2)\n | (_, _ , _ ) -> (0, (len-2)/2)\n in\n\n let solve_options options = \n let o i = List.nth options i in\n let s1 = (o 0, 1L, 0L, 0L, o 1) in\n let s2 = (o 2, 0L, 1L, 0L, o 3) in\n\n if (len1=1 && o 0 <> o 1) || (len2=1 && o 2 <> o 3) then None else\n let s = sk s1 s2 in\n let (lo1,hi1) = bounds s1 len1 in\n let (lo2,hi2) = bounds s2 len2 in\n solvable s lo1 hi1 lo2 hi2\n in\n\n let rec find_option = function \n | [] -> None\n | h::t ->\n match solve_options h with \n\t| None -> find_option t \n\t| Some (i,j) -> Some (h,i,j)\n in\n\n let gen_string (s,len,ac_count,e) =\n let str = String.make len 'X' in\n str.[0] <- s;\n str.[len-1] <- e;\n let st = if s = 'A' then 0 else 1 in\n for i = 0 to 2*ac_count-1 do\n str.[i+st] <- if i land 1 = 0 then 'A' else 'C'\n done;\n str\n in\n\n match find_option (make_options 0) with \n | None -> printf \"Happy new year!\\n\"\n | Some (options,i,j) ->\n let o i = List.nth options i in\n printf \"%s\\n\" (gen_string (o 0, len1, i, o 1));\n printf \"%s\\n\" (gen_string (o 2, len2, j, o 3));\n"}], "negative_code": [], "src_uid": "1d55d31320368ddb1439ee086d40b57c"} {"nl": {"description": "Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors. Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.", "input_spec": "First line of input consists of one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000). Next line consists of n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009n), which stand for coolness factor of each badge.", "output_spec": "Output single integer \u2014 minimum amount of coins the colonel has to pay.", "sample_inputs": ["4\n1 3 1 4", "5\n1 2 3 2 5"], "sample_outputs": ["1", "2"], "notes": "NoteIn first sample test we can increase factor of first badge by 1.In second sample test we can increase factors of the second and the third badge by 1."}, "positive_code": [{"source_code": "\nlet (|>) x f = f x\nlet ($) f g = fun x -> f (g x)\n\nlet solve a =\n let arr = Array.make 10000 0 in\n List.iter\n (fun x -> arr.(x) <- arr.(x) + 1)\n a;\n let res = ref 0 in\n Array.iteri\n (fun i x ->\n if x > 1 then\n (res := !res + x - 1;\n arr.(i + 1) <- arr.(i + 1) + x - 1))\n arr;\n !res\n\nlet _ =\n ignore (read_int ());\n let a =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string\n in\n print_endline (string_of_int (solve a))\n"}, {"source_code": "let f tab =\n\tlet res = ref 0 in\n\tfor i=0 to Array.length tab - 2 do\n\t\tif tab.(i) > 1\n\t\t\tthen begin\n\t\t\t\tlet trop = tab.(i) - 1 in\n\t\t\t\t\ttab.(i) <- 1;\n\t\t\t\t\ttab.(i+1) <- tab.(i+1) + trop;\n\t\t\t\t\tres := trop + !res;\n\t\t\t end\n\t\t\t\t\n\tdone;\n\t!res\n\nlet _ =\n\tlet tab = Array.make 6015 0 and n = Scanf.scanf \"%d\" (fun i -> i) in\n\tfor i=1 to n do\n\t\tScanf.scanf \" %d\" (fun j -> tab.(j) <- tab.(j) + 1);\n\tdone;\n\tPrintf.printf \"%d\" (f tab)\n"}], "negative_code": [], "src_uid": "53ae714f04fd29721b8bbf77576b7ccf"} {"nl": {"description": "SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.", "input_spec": "A single line contains four integers .", "output_spec": "Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["1 2 1 2"], "sample_outputs": ["0.666666666667"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces contest 300D - Draw Squares - Too slow *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet rec readlist n acc = match n with | 0 -> List.rev acc | _ -> readlist (n -1) (gr() :: acc);;\nlet rec readpairs n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readpairs\n\t\t\t\t(n -1)\n\t\t\t\t(\n\t\t\t\t\tlet a = gr() in\n\t\t\t\t\tlet b = gr() in\n\t\t\t\t\t(* let _ = Printf.printf \"a,b = %d %d\\n\" a b in *)\n\t\t\t\t\t(a, b) :: acc\n\t\t\t\t);;\nlet debug = false;;\n\nlet a = gr();; (* number of test data *)\nlet b = gr();; (* number of test data *)\nlet c = gr();; (* number of test data *)\nlet d = gr();; (* number of test data *)\n\nlet main() =\n let af = float_of_int a in\n let bf = float_of_int b in\n let cf = float_of_int c in\n let df = float_of_int d in\n \n\tlet adf = af *. df in\n\tlet acaf = (af *. df) +. (cf *. bf) -. (af *. cf) in\n\tlet pp = adf /. acaf in\n\tPrintf.printf \"%18.12f\" pp;;\t\n\nmain();;\n"}, {"source_code": "(* For the first archer to win, the possibilities are\n * win(a) - lose(a) & lose(b) & win(a)...*)\n\nlet main = \n let (a, b, c, d) = Scanf.scanf \"%f %f %f %f\\n\" (fun a b c d -> (a,b,c,d)) in\n let p_win = a /. b in\n let p_retry = (1. -. p_win) *. (1. -. (c /. d)) in\n let result = p_win /. (1. -. p_retry) in\n Printf.printf \"%f\\n\" result\n"}], "negative_code": [], "src_uid": "7b932b2d3ab65a353b18d81cf533a54e"} {"nl": {"description": "Igor is in the museum and he wants to see as many pictures as possible.Museum can be represented as a rectangular field of n\u2009\u00d7\u2009m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.", "input_spec": "First line of the input contains three integers n, m and k (3\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009min(n\u00b7m,\u2009100\u2009000))\u00a0\u2014 the museum dimensions and the number of starting positions to process. Each of the next n lines contains m symbols '.', '*' \u2014 the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum. Each of the last k lines contains two integers x and y (1\u2009\u2264\u2009x\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009m)\u00a0\u2014 the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns \u2014 from left to right. It is guaranteed that all starting positions are empty cells.", "output_spec": "Print k integers\u00a0\u2014 the maximum number of pictures, that Igor can see if he starts in corresponding position.", "sample_inputs": ["5 6 3\n******\n*..*.*\n******\n*....*\n******\n2 2\n2 5\n4 3", "4 4 1\n****\n*..*\n*.**\n****\n3 2"], "sample_outputs": ["6\n4\n10", "8"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m false in\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tfor j = 0 to m - 1 do\n\t a.(i).(j) <- s.[j] = '.'\n\tdone\n done;\n let res = Array.make (n * m) (-1) in\n let cnt = ref 0 in\n let c = Array.make_matrix n m (-1) in\n let color = ref 0 in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n\tlet (x, y) = q1.(i) in\n\t for i = 0 to 3 do\n\t let (dx, dy) = d.(i) in\n\t let x = x + dx\n\t and y = y + dy in\n\t if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (\n\t\tif c.(y).(x) < 0 then (\n\t\t c.(y).(x) <- !color;\n\t\t q2.(!l2) <- (x, y);\n\t\t incr l2\n\t\t);\n\t ) else incr cnt;\n\t done\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n for y = 0 to n - 1 do\n\tfor x = 0 to m - 1 do\n\t if a.(y).(x) && c.(y).(x) < 0 then (\n\t cnt := 0;\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t res.(!color) <- !cnt;\n\t incr color;\n\t )\n\tdone\n done;\n\tfor i = 1 to k do\n\t let y = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\t let x = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\t Printf.printf \"%d\\n\" res.(c.(y).(x))\n\tdone;\n"}], "negative_code": [], "src_uid": "cfdcfe449868ed50516f0895bf6a66e1"} {"nl": {"description": "Vanya plays a game of balloons on the field of size n\u2009\u00d7\u2009n, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:**o****o**ooooo**o****o**oro***o*o*o***o***o*o*o***oFormally, the cross is given by three integers r, c and d, such that d\u2009\u2264\u2009r,\u2009c\u2009\u2264\u2009n\u2009-\u2009d\u2009+\u20091. The normal cross consists of balloons located in cells (x,\u2009y) (where x stay for the number of the row and y for the number of the column), such that |x\u2009-\u2009r|\u00b7|y\u2009-\u2009c|\u2009=\u20090 and |x\u2009-\u2009r|\u2009+\u2009|y\u2009-\u2009c|\u2009<\u2009d. Rotated cross consists of balloons located in cells (x,\u2009y), such that |x\u2009-\u2009r|\u2009=\u2009|y\u2009-\u2009c| and |x\u2009-\u2009r|\u2009<\u2009d.Vanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo 109\u2009+\u20097.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of rows and columns in the table with balloons. The each of the following n lines contains n characters '0', '1', '2' or '3'\u00a0\u2014 the description of the values in balloons.", "output_spec": "Print the maximum possible product modulo 109\u2009+\u20097. Note, that you are not asked to maximize the remainder modulo 109\u2009+\u20097, but to find the maximum value and print it this modulo.", "sample_inputs": ["4\n1233\n0213\n2020\n0303", "5\n00300\n00300\n33333\n00300\n00300", "5\n00003\n02030\n00300\n03020\n30000", "5\n21312\n10003\n10002\n10003\n23231", "5\n12131\n12111\n12112\n21311\n21212"], "sample_outputs": ["108", "19683", "108", "3", "24"], "notes": "NoteIn the first sample, the maximum product is achieved for a rotated cross with a center in the cell (3,\u20093) and radius 1: 2\u00b72\u00b73\u00b73\u00b73\u2009=\u2009108."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let min (x : int) y = if x < y then x else y in\n let max (x : int) y = if x > y then x else y in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n \"\" in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%s \" (fun s -> s)\n done;\n in\n let make dx dy =\n let b = Array.make_matrix n n 0 in\n let rec fill y x =\n if x >= 0 && y >= 0 && x < n && y < n then (\n\tlet x' = x - dx\n\tand y' = y - dy in\n\t if a.(y).[x] = '0' then (\n\t b.(y).(x) <- 0;\n\t ) else (\n\t let d =\n\t if x' >= 0 && y' >= 0 && x' < n && y' < n\n\t then b.(y').(x') + 1\n\t else 1\n\t in\n\t if b.(y).(x) < d\n\t then b.(y).(x) <- d;\n\t );\n\t fill (y + dy) (x + dx)\n )\n in\n for i = 0 to n - 1 do\n\tfill 0 i;\n\tfill i 0;\n\tfill (n - 1) i;\n\tfill i (n - 1);\n done;\n b\n in\n let al = make 1 0 in\n let ar = make (-1) 0 in\n let au = make 0 1 in\n let ad = make 0 (-1) in\n let aul = make 1 1 in\n let aur = make (-1) 1 in\n let adl = make 1 (-1) in\n let adr = make (-1) (-1) in\n let f = Array.make_matrix n n 0.0 in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet x =\n\t match a.(i).[j] with\n\t | '0' -> -1.0;\n\t | '1' -> 0.0;\n\t | '2' -> log 2.0;\n\t | '3' -> log 3.0;\n\t | _ -> assert false\n\tin\n\t f.(i).(j) <- x\n done;\n done;\n in\n let get y x = Char.code a.(y).[x] - Char.code '0' in\n let fh = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let fv = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let fd1 = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let fd2 = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfh.(i + 1).(j + 1) <- fh.(i + 1).(j) +. f.(i).(j)\n done\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfv.(i + 1).(j + 1) <- fv.(i).(j + 1) +. f.(i).(j)\n done\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfd1.(i + 1).(j + 1) <- fd1.(i).(j) +. f.(i).(j)\n done\n done;\n for i = 0 to n - 1 do\n for j = n - 1 downto 0 do\n\tfd2.(i + 1).(j + 1) <- fd2.(i).(j + 2) +. f.(i).(j)\n done\n done;\n in\n let b = ref (-1000000.0) in\n let br = ref 0 in\n let bc = ref 0 in\n let bd = ref 0 in\n let bt = ref false in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif a.(i).[j] <> '0' then (\n\t let d =\n\t min (min aul.(i).(j) aur.(i).(j)) (min adl.(i).(j) adr.(i).(j))\n\t in\n\t let s =\n\t fd1.(i + d).(j + d) -. fd1.(i - d + 1).(j - d + 1) +.\n\t fd2.(i + d).(j - d + 2) -. fd2.(i - d + 1).(j + d + 1) -. f.(i).(j)\n\t in\n(*Printf.printf \"asd %d %d %d %d %d %d %f\\n\" i j aul.(i).(j) aur.(i).(j)\nadl.(i).(j) adr.(i).(j) s;*)\n\t if !b < s then (\n\t b := s;\n\t br := i;\n\t bc := j;\n\t bd := d;\n\t bt := true;\n\t )\n\t)\n done\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif a.(i).[j] <> '0' then (\n\t let d =\n\t min (min al.(i).(j) ar.(i).(j)) (min au.(i).(j) ad.(i).(j))\n\t in\n\t let s =\n\t fh.(i + 1).(j + d) -. fh.(i + 1).(j - d + 1) +.\n\t fv.(i + d).(j + 1) -. fv.(i - d + 1).(j + 1) -. f.(i).(j)\n\t in\n(*Printf.printf \"asd %d %d %d %d %d %d %f\\n\" i j al.(i).(j) ar.(i).(j)\nau.(i).(j) ad.(i).(j) s;\nPrintf.printf \"qwe %f %f %f %f %f\\n\"\nfh.(i + 1).(j + d) fh.(i + 1).(j - d + 1)\n fv.(i + d).(j + 1) fv.(i - d + 1).(j + 1) f.(i).(j);*)\n\t if !b < s then (\n\t b := s;\n\t br := i;\n\t bc := j;\n\t bd := d;\n\t bt := false;\n\t )\n\t)\n done\n done;\n in\n let res = ref 1L in\n(*Printf.printf \"zxc %f %d %d %d %b\\n\" !b !br !bc !bd !bt;*)\n if not !bt then (\n for i = !br - !bd + 1 to !br + !bd - 1 do\n\tres := mmod (!res *| Int64.of_int (get i !bc));\n done;\n for j = !bc - !bd + 1 to !bc + !bd - 1 do\n\tif j <> !bc\n\tthen res := mmod (!res *| Int64.of_int (get !br j));\n done;\n ) else (\n for i = - !bd + 1 to !bd - 1 do\n\tres := mmod (!res *| Int64.of_int (get (!br + i) (!bc + i)));\n done;\n for i = - !bd + 1 to !bd - 1 do\n\tif i <> 0\n\tthen res := mmod (!res *| Int64.of_int (get (!br + i) (!bc - i)));\n done;\n );\n if !bd = 0\n then res := 0L;\n Printf.printf \"%Ld\\n\" !res\n\n"}], "negative_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let min (x : int) y = if x < y then x else y in\n let max (x : int) y = if x > y then x else y in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n \"\" in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%s \" (fun s -> s)\n done;\n in\n let make dx dy =\n let b = Array.make_matrix n n 0 in\n let rec fill y x =\n if x >= 0 && y >= 0 && x < n && y < n then (\n\tlet x' = x - dx\n\tand y' = y - dy in\n\t if a.(y).[x] = '0' then (\n\t b.(y).(x) <- 0;\n\t ) else (\n\t let d =\n\t if x' >= 0 && y' >= 0 && x' < n && y' < n\n\t then b.(y').(x') + 1\n\t else 1\n\t in\n\t if b.(y).(x) < d\n\t then b.(y).(x) <- d;\n\t );\n\t fill (y + dy) (x + dx)\n )\n in\n for i = 0 to n - 1 do\n\tfill 0 i;\n\tfill i 0;\n\tfill (n - 1) i;\n\tfill i (n - 1);\n done;\n b\n in\n let al = make 1 0 in\n let ar = make (-1) 0 in\n let au = make 0 1 in\n let ad = make 0 (-1) in\n let aul = make 1 1 in\n let aur = make (-1) 1 in\n let adl = make 1 (-1) in\n let adr = make (-1) (-1) in\n let f = Array.make_matrix n n 0.0 in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet x =\n\t match a.(i).[j] with\n\t | '0' -> -1.0;\n\t | '1' -> 0.0;\n\t | '2' -> log 2.0;\n\t | '3' -> log 3.0;\n\t | _ -> assert false\n\tin\n\t f.(i).(j) <- x\n done;\n done;\n in\n let get y x = Char.code a.(y).[x] - Char.code '0' in\n let fh = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let fv = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let fd1 = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let fd2 = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfh.(i + 1).(j + 1) <- fh.(i + 1).(j) +. f.(i).(j)\n done\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfv.(i + 1).(j + 1) <- fv.(i).(j + 1) +. f.(i).(j)\n done\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfd1.(i + 1).(j + 1) <- fd1.(i).(j) +. f.(i).(j)\n done\n done;\n for i = 0 to n - 1 do\n for j = n - 1 downto 0 do\n\tfd2.(i + 1).(j + 1) <- fd2.(i).(j + 2) +. f.(i).(j)\n done\n done;\n in\n let b = ref 0.0 in\n let br = ref 0 in\n let bc = ref 0 in\n let bd = ref 0 in\n let bt = ref false in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif a.(i).[j] <> '0' then (\n\t let d =\n\t min (min aul.(i).(j) aur.(i).(j)) (min adl.(i).(j) adr.(i).(j))\n\t in\n\t let s =\n\t fd1.(i + d).(j + d) -. fd1.(i - d + 1).(j - d + 1) +.\n\t fd2.(i + d).(j - d + 2) -. fd2.(i - d + 1).(j + d + 1) -. f.(i).(j)\n\t in\n(*Printf.printf \"asd %d %d %d %d %d %d %f\\n\" i j aul.(i).(j) aur.(i).(j)\nadl.(i).(j) adr.(i).(j) s;*)\n\t if !b < s then (\n\t b := s;\n\t br := i;\n\t bc := j;\n\t bd := d;\n\t bt := true;\n\t )\n\t)\n done\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif a.(i).[j] <> '0' then (\n\t let d =\n\t min (min al.(i).(j) ar.(i).(j)) (min au.(i).(j) ad.(i).(j))\n\t in\n\t let s =\n\t fh.(i + 1).(j + d) -. fh.(i + 1).(j - d + 1) +.\n\t fv.(i + d).(j + 1) -. fv.(i - d + 1).(j + 1) -. f.(i).(j)\n\t in\n(*Printf.printf \"asd %d %d %d %d %d %d %f\\n\" i j al.(i).(j) ar.(i).(j)\nau.(i).(j) ad.(i).(j) s;\nPrintf.printf \"qwe %f %f %f %f %f\\n\"\nfh.(i + 1).(j + d) fh.(i + 1).(j - d + 1)\n fv.(i + d).(j + 1) fv.(i - d + 1).(j + 1) f.(i).(j);*)\n\t if !b < s then (\n\t b := s;\n\t br := i;\n\t bc := j;\n\t bd := d;\n\t bt := false;\n\t )\n\t)\n done\n done;\n in\n let res = ref 1L in\n(*Printf.printf \"zxc %f %d %d %d %b\\n\" !b !br !bc !bd !bt;*)\n if not !bt then (\n for i = !br - !bd + 1 to !br + !bd - 1 do\n\tres := mmod (!res *| Int64.of_int (get i !bc));\n done;\n for j = !bc - !bd + 1 to !bc + !bd - 1 do\n\tif j <> !bc\n\tthen res := mmod (!res *| Int64.of_int (get !br j));\n done;\n ) else (\n for i = - !bd + 1 to !bd - 1 do\n\tres := mmod (!res *| Int64.of_int (get (!br + i) (!bc + i)));\n done;\n for i = - !bd + 1 to !bd - 1 do\n\tif i <> 0\n\tthen res := mmod (!res *| Int64.of_int (get (!br + i) (!bc - i)));\n done;\n );\n Printf.printf \"%Ld\\n\" !res\n\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let min (x : int) y = if x < y then x else y in\n let max (x : int) y = if x > y then x else y in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n \"\" in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%s \" (fun s -> s)\n done;\n in\n let make dx dy =\n let b = Array.make_matrix n n 0 in\n let rec fill y x =\n if x >= 0 && y >= 0 && x < n && y < n then (\n\tlet x' = x - dx\n\tand y' = y - dy in\n\t if a.(y).[x] = '0' then (\n\t b.(y).(x) <- 0;\n\t ) else (\n\t let d =\n\t if x' >= 0 && y' >= 0 && x' < n && y' < n\n\t then b.(y').(x') + 1\n\t else 1\n\t in\n\t if b.(y).(x) < d\n\t then b.(y).(x) <- d;\n\t );\n\t fill (y + dy) (x + dx)\n )\n in\n for i = 0 to n - 1 do\n\tfill 0 i;\n\tfill i 0;\n\tfill (n - 1) i;\n\tfill i (n - 1);\n done;\n b\n in\n let al = make 1 0 in\n let ar = make (-1) 0 in\n let au = make 0 1 in\n let ad = make 0 (-1) in\n let aul = make 1 1 in\n let aur = make (-1) 1 in\n let adl = make 1 (-1) in\n let adr = make (-1) (-1) in\n let f = Array.make_matrix n n 0.0 in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet x =\n\t match a.(i).[j] with\n\t | '0' -> -1.0;\n\t | '1' -> 0.0;\n\t | '2' -> log 2.0;\n\t | '3' -> log 3.0;\n\t | _ -> assert false\n\tin\n\t f.(i).(j) <- x\n done;\n done;\n in\n let get y x = Char.code a.(y).[x] - Char.code '0' in\n let fh = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let fv = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let fd1 = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let fd2 = Array.make_matrix (n + 2) (n + 2) 0.0 in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfh.(i + 1).(j + 1) <- fh.(i + 1).(j) +. f.(i).(j)\n done\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfv.(i + 1).(j + 1) <- fv.(i).(j + 1) +. f.(i).(j)\n done\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfd1.(i + 1).(j + 1) <- fd1.(i).(j) +. f.(i).(j)\n done\n done;\n for i = 0 to n - 1 do\n for j = n - 1 downto 0 do\n\tfd2.(i + 1).(j + 1) <- fd2.(i).(j + 2) +. f.(i).(j)\n done\n done;\n in\n let b = ref 0.0 in\n let br = ref 0 in\n let bc = ref 0 in\n let bd = ref 0 in\n let bt = ref false in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif a.(i).[j] <> '0' then (\n\t let d =\n\t min (min aul.(i).(j) aur.(i).(j)) (min adl.(i).(j) adr.(i).(j))\n\t in\n\t let s =\n\t fd1.(i + d).(j + d) -. fd1.(i - d + 1).(j - d + 1) +.\n\t fd2.(i + d).(j - d + 2) -. fd2.(i - d + 1).(j + d + 1) -. f.(i).(j)\n\t in\n(*Printf.printf \"asd %d %d %d %d %d %d %f\\n\" i j aul.(i).(j) aur.(i).(j)\nadl.(i).(j) adr.(i).(j) s;*)\n\t if !b < s then (\n\t b := s;\n\t br := i;\n\t bc := j;\n\t bd := d;\n\t bt := true;\n\t )\n\t)\n done\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif a.(i).[j] <> '0' then (\n\t let d =\n\t min (min al.(i).(j) ar.(i).(j)) (min au.(i).(j) ad.(i).(j))\n\t in\n\t let s =\n\t fh.(i + 1).(j + d) -. fh.(i + 1).(j - d + 1) +.\n\t fv.(i + d).(j + 1) -. fv.(i - d + 1).(j + 1) -. f.(i).(j)\n\t in\n(*Printf.printf \"asd %d %d %d %d %d %d %f\\n\" i j al.(i).(j) ar.(i).(j)\nau.(i).(j) ad.(i).(j) s;\nPrintf.printf \"qwe %f %f %f %f %f\\n\"\nfh.(i + 1).(j + d) fh.(i + 1).(j - d + 1)\n fv.(i + d).(j + 1) fv.(i - d + 1).(j + 1) f.(i).(j);*)\n\t if !b < s then (\n\t b := s;\n\t br := i;\n\t bc := j;\n\t bd := d;\n\t bt := false;\n\t )\n\t)\n done\n done;\n in\n let res = ref 1L in\n(*Printf.printf \"zxc %f %d %d %d %b\\n\" !b !br !bc !bd !bt;*)\n if not !bt then (\n for i = !br - !bd + 1 to !br + !bd - 1 do\n\tres := mmod (!res *| Int64.of_int (get i !bc));\n done;\n for j = !bc - !bd + 1 to !bc + !bd - 1 do\n\tif j <> !bc\n\tthen res := mmod (!res *| Int64.of_int (get !br j));\n done;\n ) else (\n for i = - !bd + 1 to !bd - 1 do\n\tres := mmod (!res *| Int64.of_int (get (!br + i) (!bc + i)));\n done;\n for i = - !bd + 1 to !bd - 1 do\n\tif i <> 0\n\tthen res := mmod (!res *| Int64.of_int (get (!br + i) (!bc - i)));\n done;\n );\n if !bd = 0\n then res := 0L;\n Printf.printf \"%Ld\\n\" !res\n\n"}], "src_uid": "053483902f92e87f753c14e954568629"} {"nl": {"description": "Just to remind, girls in Arpa's land are really nice.Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1,\u2009a2,\u2009...,\u2009ak such that ai and ai\u2009+\u20091 are friends for each 1\u2009\u2264\u2009i\u2009<\u2009k, and a1\u2009=\u2009x and ak\u2009=\u2009y. Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.", "input_spec": "The first line contains integers n, m and w (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2009\u2264\u2009\u20091000, , 1\u2009\u2264\u2009w\u2009\u2264\u20091000)\u00a0\u2014 the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1,\u2009w2,\u2009...,\u2009wn (1\u2009\u2264\u2009wi\u2009\u2264\u20091000)\u00a0\u2014 the weights of the Hoses. The third line contains n integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009106)\u00a0\u2014 the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, xi\u2009\u2260\u2009yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi,\u2009yi) are distinct.", "output_spec": "Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.", "sample_inputs": ["3 1 5\n3 2 5\n2 4 2\n1 2", "4 2 11\n2 4 6 6\n6 4 2 1\n1 2\n2 3"], "sample_outputs": ["6", "7"], "notes": "NoteIn the first sample there are two friendship groups: Hoses {1,\u20092} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.In the second sample there are two friendship groups: Hoses {1,\u20092,\u20093} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12\u2009>\u200911, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let max_w = read_int () in\n let w = Array.init n (fun _ -> read_int()) in\n let b = Array.init n (fun _ -> read_int()) in\n\n let graph = Array.make n [] in\n\n let add_edge (u,v) =\n graph.(u) <- v::graph.(u);\n graph.(v) <- u::graph.(v)\n in\n\n for i=1 to m do\n add_edge (read_int() -1, read_int() -1)\n done;\n\n let comp = Array.make n (-1) in\n\n let rec dfs v c = if comp.(v) < 0 then (\n comp.(v) <- c;\n List.iter (fun w -> dfs w c) graph.(v)\n ) in\n\n let rec dfs_loop v c = if v=n then c\n else if comp.(v) >= 0 then\n dfs_loop (v+1) c\n else (\n dfs v c;\n dfs_loop (v+1) (c+1)\n )\n in\n\n let ncomps = dfs_loop 0 0 in\n\n let comp_weight = Array.make ncomps 0 in\n let comp_beauty = Array.make ncomps 0 in\n let comp_vertices = Array.make ncomps [] in\n\n for i=0 to n-1 do\n comp_weight.(comp.(i)) <- comp_weight.(comp.(i)) + w.(i);\n comp_beauty.(comp.(i)) <- comp_beauty.(comp.(i)) + b.(i);\n comp_vertices.(comp.(i)) <- i::comp_vertices.(comp.(i))\n done;\n\n (* pl is a list of pairs (weight, beauty) *)\n\n let rec prune lastb li ac =\n match li with\n | [] -> List.rev ac\n | (w,b)::tail ->\n\tif b > lastb then prune b tail ((w,b)::ac)\n\telse prune lastb tail ac\n in\n\n let merge l1 l2 =\n let h = Hashtbl.create 10 in\n List.iter (fun (w1,b1) ->\n List.iter (fun (w2,b2) ->\n\tif w1+w2 <= max_w then\n\t let c = try Hashtbl.find h (w1+w2) with Not_found -> 0 in\n\t Hashtbl.replace h (w1+w2) (max (b1+b2) c)\n ) l2\n ) l1;\n\n let l3 = Hashtbl.fold (fun w b ac -> (w,b)::ac) h [] in\n let l3 = List.sort compare l3 in\n\n prune (-1) l3 []\n in\n\n let pl_array = Array.init ncomps (fun c ->\n if comp_weight.(c) <= max_w\n then [(0,0);(comp_weight.(c), comp_beauty.(c))]\n else [(0,0)]\n ) in\n \n for u=0 to n-1 do\n if w.(u) <= max_w then \n pl_array.(comp.(u)) <- (w.(u), b.(u))::pl_array.(comp.(u))\n done;\n\n for c=0 to ncomps-1 do\n pl_array.(c) <- prune (-1) (List.sort compare pl_array.(c)) []\n done;\n\n let final_pl = fold 1 (ncomps-1)\n (fun c ac -> merge ac pl_array.(c)) pl_array.(0)\n in\n\n let max_beauty = List.fold_left (fun ac (w,b) -> max b ac) 0 final_pl in\n\n printf \"%d\\n\" max_beauty\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let max_w = read_int () in\n let w = Array.init n (fun _ -> read_int()) in\n let b = Array.init n (fun _ -> read_int()) in\n\n let graph = Array.make n [] in\n\n let add_edge (u,v) =\n graph.(u) <- v::graph.(u);\n graph.(v) <- u::graph.(v)\n in\n\n for i=1 to m do\n add_edge (read_int() -1, read_int() -1)\n done;\n\n let comp = Array.make n (-1) in\n\n let rec dfs v c = if comp.(v) < 0 then (\n comp.(v) <- c;\n List.iter (fun w -> dfs w c) graph.(v)\n ) in\n\n let rec dfs_loop v c = if v=n then c\n else if comp.(v) >= 0 then\n dfs_loop (v+1) c\n else (\n dfs v c;\n dfs_loop (v+1) (c+1)\n )\n in\n\n let ncomps = dfs_loop 0 0 in\n\n let comp_weight = Array.make ncomps 0 in\n let comp_beauty = Array.make ncomps 0 in\n let comp_vertices = Array.make ncomps [] in\n\n for i=0 to n-1 do\n comp_weight.(comp.(i)) <- comp_weight.(comp.(i)) + w.(i);\n comp_beauty.(comp.(i)) <- comp_beauty.(comp.(i)) + b.(i);\n comp_vertices.(comp.(i)) <- i::comp_vertices.(comp.(i))\n done;\n\n (* pl is a list of pairs (weight, beauty) *)\n\n let rec prune lastb li ac =\n match li with\n | [] -> List.rev ac\n | (w,b)::tail ->\n\tif b > lastb then prune b tail ((w,b)::ac)\n\telse prune lastb tail ac\n in\n\n let merge l1 l2 =\n let h = Hashtbl.create 10 in\n List.iter (fun (w1,b1) ->\n List.iter (fun (w2,b2) ->\n\tif w1+w2 <= max_w then\n\t let c = try Hashtbl.find h (w1+w2) with Not_found -> 0 in\n\t Hashtbl.replace h (w1+w2) (max (b1+b2) c)\n ) l2\n ) l1;\n\n let l3 = Hashtbl.fold (fun w b ac -> (w,b)::ac) h [] in\n let l3 = List.sort compare l3 in\n\n prune (-1) l3 []\n in\n\n let pl_array = Array.init ncomps (fun c ->\n if comp_weight.(c) <= max_w\n then [(0,0);(comp_weight.(c), comp_beauty.(c))]\n else [(0,0)]\n ) in\n \n for u=0 to n-1 do\n pl_array.(comp.(u)) <- (w.(u), b.(u))::pl_array.(comp.(u))\n done;\n\n for c=0 to ncomps-1 do\n pl_array.(c) <- prune (-1) (List.sort compare pl_array.(c)) []\n done;\n\n let final_pl = fold 1 (ncomps-1)\n (fun c ac -> merge ac pl_array.(c)) pl_array.(0)\n in\n\n let max_beauty = List.fold_left (fun ac (w,b) -> max b ac) 0 final_pl in\n\n printf \"%d\\n\" max_beauty\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let max_w = read_int () in\n let w = Array.init n (fun _ -> read_int()) in\n let b = Array.init n (fun _ -> read_int()) in\n\n let graph = Array.make n [] in\n\n let add_edge (u,v) =\n graph.(u) <- v::graph.(u);\n graph.(v) <- u::graph.(v)\n in\n\n for i=1 to m do\n add_edge (read_int() -1, read_int() -1)\n done;\n\n let comp = Array.make n (-1) in\n\n let rec dfs v c = if comp.(v) < 0 then (\n comp.(v) <- c;\n List.iter (fun w -> dfs w c) graph.(v)\n ) in\n\n let rec dfs_loop v c = if v=n then c\n else if comp.(v) >= 0 then\n dfs_loop (v+1) c\n else (\n dfs v c;\n dfs_loop (v+1) (c+1)\n )\n in\n\n let ncomps = dfs_loop 0 0 in\n\n let comp_weight = Array.make ncomps 0 in\n let comp_beauty = Array.make ncomps 0 in\n let comp_vertices = Array.make ncomps [] in\n\n for i=0 to n-1 do\n comp_weight.(comp.(i)) <- comp_weight.(comp.(i)) + w.(i);\n comp_beauty.(comp.(i)) <- comp_beauty.(comp.(i)) + b.(i);\n comp_vertices.(comp.(i)) <- i::comp_vertices.(comp.(i))\n done;\n\n (* pl is a list of pairs (weight, beauty) *)\n\n let rec prune lastb li ac =\n match li with\n | [] -> List.rev ac\n | (w,b)::tail ->\n\tif b > lastb then prune b tail ((w,b)::ac)\n\telse prune lastb tail ac\n in\n\n let merge l1 l2 =\n let h = Hashtbl.create 10 in\n List.iter (fun (w1,b1) ->\n List.iter (fun (w2,b2) ->\n\tif w1+w2 <= max_w then\n\t let c = try Hashtbl.find h (w1+w2) with Not_found -> 0 in\n\t Hashtbl.replace h (w1+w2) (max (b1+b2) c)\n ) l2\n ) l1;\n\n let l3 = Hashtbl.fold (fun w b ac -> (w,b)::ac) h [] in\n let l3 = List.sort compare l3 in\n\n prune (-1) l3 []\n in\n\n let pl_array = Array.make ncomps [] in\n \n for u=0 to n-1 do\n pl_array.(comp.(u)) <- (w.(u), b.(u))::pl_array.(comp.(u))\n done;\n\n for c=0 to ncomps-1 do\n let aug = (0,0)::((comp_weight.(c), comp_beauty.(c))::pl_array.(c)) in\n pl_array.(c) <- prune (-1) (List.sort compare aug) []\n done;\n\n let final_pl = fold 1 (ncomps-1)\n (fun c ac -> merge ac pl_array.(c)) pl_array.(0)\n in\n\n let max_beauty = List.fold_left (fun ac (w,b) -> max b ac) 0 final_pl in\n\n printf \"%d\\n\" max_beauty\n"}], "src_uid": "7c96bc1aa4dcabf7560d915823ba22f1"} {"nl": {"description": "Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires \"plus\" and \"minus\". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the \"plus\" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.", "input_spec": "The single line of the input contains a sequence of characters \"+\" and \"-\" of length n (1\u2009\u2264\u2009n\u2009\u2264\u2009100000). The i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) position of the sequence contains the character \"+\", if on the i-th step from the wall the \"plus\" wire runs above the \"minus\" wire, and the character \"-\" otherwise.", "output_spec": "Print either \"Yes\" (without the quotes) if the wires can be untangled or \"No\" (without the quotes) if the wires cannot be untangled.", "sample_inputs": ["-++-", "+-", "++", "-"], "sample_outputs": ["Yes", "No", "Yes", "No"], "notes": "NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the \"plus\" wire lower, thus eliminating the two crosses in the middle, and then draw it under the \"minus\" wire, eliminating also the remaining two crosses.In the second testcase the \"plus\" wire makes one full revolution around the \"minus\" wire. Thus the wires cannot be untangled: In the third testcase the \"plus\" wire simply runs above the \"minus\" wire twice in sequence. The wires can be untangled by lifting \"plus\" and moving it higher: In the fourth testcase the \"minus\" wire runs above the \"plus\" wire once. The wires cannot be untangled without moving the device itself: "}, "positive_code": [{"source_code": "let s = read_line () in\nlet l = ref [] in\nlet rec alt c = match !l with\n [] -> l := [c]\n | h::t -> l := (if h = c then t else c :: h :: t)\nin\nString.iter alt s ;\nif !l = [] then\n Printf.printf \"Yes\\n\"\nelse\n Printf.printf \"No\\n\" ;;\n"}], "negative_code": [], "src_uid": "89b4a7b4a6160ce784c588409b6ce935"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ ($$$n \\ge 3$$$) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array $$$[4, 11, 4, 4]$$$ all numbers except one are equal to $$$4$$$).Print the index of the element that does not equal others. The numbers in the array are numbered from one.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 100$$$)\u00a0\u2014 the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 100$$$). It is guaranteed that all the numbers except one in the $$$a$$$ array are the same.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the index of the element that is not equal to others.", "sample_inputs": ["4\n4\n11 13 11 11\n5\n1 4 4 4 4\n10\n3 3 3 3 10 3 3 3 3 3\n3\n20 20 10"], "sample_outputs": ["2\n1\n5\n3"], "notes": null}, "positive_code": [{"source_code": "open Str;;\r\n\r\nlet rec check (a : int list)(n : int) =\r\n if List.length (List.find_all (fun x -> x == (List.nth a n)) a) == 1 then\r\n n\r\n else\r\n check a (n+1)\r\n;;\r\n\r\nlet rec solve (t : int) =\r\n if t = 0 then\r\n ()\r\n else\r\n let n = read_int () in\r\n let arr = (Str.split (Str.regexp \" \") (read_line ())) in\r\n let a = (List.map (fun x -> int_of_string x) arr) in\r\n let ind = check a 0 in\r\n print_endline (string_of_int (ind + 1));\r\n solve (t-1)\r\n;;\r\n\r\nlet t = read_int() in\r\nsolve t;;\r\n"}, {"source_code": "(* https://codeforces.com/contest/1512/problem/0 *)\n\nlet intruder arr =\n let rec commoner () =\n let h = Array.init 3 (fun i -> arr.(i)) in\n let count =\n Array.map\n (fun e -> Array.fold_left (fun acc e' -> if e = e' then acc+1 else acc) 0 h)\n h in\n if count.(0) > 1\n then h.(0)\n else h.(1) in\n let c = commoner () in\n let rec helper i =\n if arr.(i) <> c\n then (i+1)\n else helper (i+1) in\n helper 0\n\nlet solve_n nb_cases =\n let rec helper i =\n if i > 0\n then (\n let _ = read_int () and\n arr = \n read_line () \n |> Str.split (Str.regexp \" \") \n |> List.map int_of_string \n |> Array.of_list in\n intruder arr\n |> Printf.printf \"%d\\n\";\n helper (i-1)\n ) in\n helper nb_cases\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "negative_code": [], "src_uid": "224a0b09547ec1441474efbd8e06353b"} {"nl": {"description": "We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size k.Now Marmot wonders in how many ways he can eat between a and b flowers. As the number of ways could be very large, print it modulo 1000000007 (109\u2009+\u20097).", "input_spec": "Input contains several test cases. The first line contains two integers t and k (1\u2009\u2264\u2009t,\u2009k\u2009\u2264\u2009105), where t represents the number of test cases. The next t lines contain two integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009bi\u2009\u2264\u2009105), describing the i-th test.", "output_spec": "Print t lines to the standard output. The i-th line should contain the number of ways in which Marmot can eat between ai and bi flowers at dinner modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["3 2\n1 3\n2 3\n4 4"], "sample_outputs": ["6\n5\n5"], "notes": "Note For K = 2 and length 1 Marmot can eat (R). For K = 2 and length 2 Marmot can eat (RR) and (WW). For K = 2 and length 3 Marmot can eat (RRR), (RWW) and (WWR). For K = 2 and length 4 Marmot can eat, for example, (WWWW) or (RWWR), but for example he can't eat (WWWR). "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet mm = 1000000007L\n\nlet ( %% ) a b = Int64.rem a b\nlet ( ** ) a b = (Int64.mul a b) %% mm\nlet ( ++ ) a b = (Int64.add a b) %% mm\nlet ( -- ) a b = ((Int64.sub a b) ++ mm) %% mm\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let t = read_int () in\n let k = read_int () in\n\n let input = Array.init t (fun _ -> read_pair()) in\n\n let msize = maxf 0 (t-1) (fun i -> snd input.(i)) in\n\n let count = Array.make (msize+1) (-1L) in\n count.(0) <- 1L;\n\n let rec ccount b = \n if count.(b) >= 0L then count.(b) else\n let answer = \n\tif b < k then 1L else\n\t ccount (b-k) ++ ccount (b-1)\n in\n count.(b) <- answer;\n answer\n in\n\n for b = 1 to msize do\n ignore (ccount b)\n done;\n\n let accum = Array.make (msize+1) 0L in\n accum.(0) <- count.(0);\n\n for i=1 to msize do\n accum.(i) <- accum.(i-1) ++ count.(i)\n done;\n\n for i=0 to t-1 do\n let (a,b) = input.(i) in\n printf \"%Ld\\n\" (accum.(b) -- (accum.(a-1)))\n done\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Int64;;\n\n(* This version implements \n * a(n) = a(n-1) + a(n-k)\n * where k is the number of continued W\n * - Reduce memory usage.\n *)\n\nlet (t,k) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) )\n\nlet modn i = rem i (of_int 1000000007)\n\nlet ni i = of_int i\nlet sn i = to_string i\n\n(*let nn = 100000 + 5*)\nlet nn_max = 100000 + 5\n\nlet nn = 100000 + 3\n\nlet r= Array.make nn_max (ni 0)\n\nfor i = 1 to k-1 do\n r.(i) <- (ni 1)\ndone\n\nlet () = \n r.(k) <- ni 2\n\nfor i = k+1 to nn do\n r.(i) <- modn (add r.(i-1) r.(i-k))\ndone\n\nfor i = 2 to nn do\n r.(i) <- add r.(i) r.(i-1)\ndone\n\nfor i = 1 to t do\n let (s,e) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) ) in\n let sum = ref (ni 0) in\n sum := sub r.(e) r.(s-1);\n printf \"%s\\n\" (sn (modn !sum) )\ndone\n\n\n"}, {"source_code": "open Int64;;\n\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet modulo = of_int 1000000007;;\n\nlet dyn_array = Array.make 100005 (of_int (-1));;\n\nlet rec get_ways gap = function \n | index when index = Array.length dyn_array -> one\n | index when index > Array.length dyn_array -> zero\n | index when (compare dyn_array.(index) (of_int (-1))) != 0 -> dyn_array.(index)\n | index ->\n let res = rem (add (get_ways gap (index+1)) (get_ways gap (index+gap))) modulo in\n dyn_array.(index) <- res;\n res;;\n\n(*#trace get_ways;;*)\n\nlet nbTests = read_int () in\nlet gap = read_int () in\nlet _ = get_ways gap 0 in\nfor i = 1 to Array.length dyn_array - 1 do\n dyn_array.(i) <- rem (add dyn_array.(i) dyn_array.(i - 1)) modulo\ndone;\nfor i = 1 to nbTests do\n let start = read_int () in\n let tree_end = Array.length dyn_array - start in\n let fin = read_int () in \n let tree_start = Array.length dyn_array - fin in\n let res = rem (add modulo (sub dyn_array.(tree_end) (if tree_start > 0 then dyn_array.(tree_start - 1) else zero))) modulo in\n Printf.printf \"%s\\n\" (to_string res)\ndone;;"}], "negative_code": [{"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Num;;\n\n(* This version implements \n * a(n) = a(n-1) + a(n-k)\n * where k is the number of continued W\n * - Reduce memory usage.\n *)\n\nlet (t,k) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) )\n\nlet modn i = i mod 1000000007\n\nlet ni i = i\nlet sn i = string_of_int i\n\n(*let nn = 100000 + 5*)\nlet nn_max = 100000 + 5\n\nlet nn = 100000 + 3\n\nlet r= Array.make nn_max (ni (-1))\n\nfor i = 1 to k-1 do\n r.(i) <- (ni 1)\ndone\n\nlet () = \n r.(k) <- ni 2\n\nlet f n = \n if r.(n) = (ni (-1)) then\n begin\n let x = modn ( (modn r.(n-1)) + (modn r.(n-k)) ) in \n r.(n) <- x; x\n end\n else\n r.(n)\n\nfor i = k+1 to nn do\n r.(i) <- modn ((modn (f (i-1))) + (modn (f (i-k))))\ndone\n\n(*\nfor i = 95515 to nn do\n printf \"%s %s\\n\" (sn r.(i)) (sn w.(i))\ndone\n*)\n\nfor i = 1 to t do\n let (s,e) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) ) in\n let sum = ref (ni 0) in\n for j = s to e do\n sum := !sum + r.(j)\n done;\n printf \"%s\\n\" (sn (modn !sum) )\ndone\n\n\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Num;;\n\nlet (t,k) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) )\n\nlet modn i = mod_num i (num_of_int 1000000007)\n\nlet ni i = num_of_int i\nlet sn i = string_of_num i\n\n(*let nn = 100000 + 5*)\nlet nn_max = 100000 + 5\n\nlet nn = 100000 + 1\n\nlet r= Array.make nn_max (ni 0)\nlet w= Array.make nn_max (ni 0)\n\nlet num_w = ref 1\n\nlet () = \n r.(1) <- ni 1\n\nif k = 1 then\nbegin\n w.(1) <- ni 1; \nend\nelse\nbegin\n w.(1) <- ni 0;\nend\n\nfor i = 2 to nn do\n r.(i) <- r.(i-1) +/ w.(i-1);\n w.(i) <- w.(i-1);\n num_w := !num_w + 1;\n\n if !num_w = k then\n begin\n w.(i) <- w.(i) +/ (ni 1);\nnum_w := 0;\nend\ndone\n\n(*\nfor i = 0 to nn do\n printf \"%s %s\\n\" (sn r.(i)) (sn w.(i))\ndone\n*)\n\nfor i = 1 to t do\n let (s,e) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) ) in\n let sum = ref (ni 0) in\n for j = s to e do\n sum := !sum +/ r.(j) +/ w.(j)\n done;\n printf \"%s\\n\" (sn (modn !sum) )\ndone\n\n\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Num;;\n\n(* This version implements \n * a(n) = a(n-1) + a(n-k)\n * where k is the number of continued W\n *)\n\nlet (t,k) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) )\n\nlet modn i = mod_num i (num_of_int 1000000007)\n\nlet ni i = num_of_int i\nlet sn i = string_of_num i\n\n(*let nn = 100000 + 5*)\nlet nn_max = 100000 + 5\n\nlet nn = 100000 + 3\n\nlet r= Array.make nn_max (ni (-1))\n\nfor i = 1 to k-1 do\n r.(i) <- (ni 1)\ndone\n\nlet () = \n r.(k) <- ni 2\n\nlet f n = \n if r.(n) = (ni (-1)) then\n begin\n let x = r.(n-1) +/ r.(n-k) in \n r.(n) <- x; x\n end\n else\n r.(n)\n\n\n(*\nfor i = 95515 to nn do\n printf \"%s %s\\n\" (sn r.(i)) (sn w.(i))\ndone\n*)\n\nfor i = 1 to t do\n let (s,e) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) ) in\n let sum = ref (ni 0) in\n for j = s to e do\n sum := !sum +/ (f j)\n done;\n printf \"%s\\n\" (sn (modn !sum) )\ndone\n\n\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Int64;;\n\n(* This version implements \n * a(n) = a(n-1) + a(n-k)\n * where k is the number of continued W\n * - Reduce memory usage.\n *)\n\nlet (t,k) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) )\n\nlet modn i = rem i (of_int 1000000007)\n\nlet ni i = of_int i\nlet sn i = to_string i\n\n(*let nn = 100000 + 5*)\nlet nn_max = 100000 + 5\n\nlet nn = 100000 + 3\n\nlet r= Array.make nn_max (ni (-1))\n\nfor i = 1 to k-1 do\n r.(i) <- (ni 1)\ndone\n\nlet () = \n r.(k) <- ni 2\n\nlet f n = \n if r.(n) = (ni (-1)) then\n begin\n let x = ( add (r.(n-1)) (r.(n-k)) ) in \n r.(n) <- x; x\n end\n else\n r.(n)\n\nfor i = k+1 to nn do\n r.(i) <- (add ((f (i-1))) ((f (i-k))) )\ndone\n\n(*\nfor i = 95515 to nn do\n printf \"%s %s\\n\" (sn r.(i)) (sn w.(i))\ndone\n*)\n\nfor i = 1 to t do\n let (s,e) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) ) in\n let sum = ref (ni 0) in\n for j = s to e do\n sum := add !sum r.(j)\n done;\n printf \"%s\\n\" (sn (modn !sum) )\ndone\n\n\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Num;;\n\n(* This version implements \n * a(n) = a(n-1) + a(n-k)\n * where k is the number of continued W\n * - Reduce memory usage.\n *)\n\nlet (t,k) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) )\n\nlet modn i = i mod 1000000007\n\nlet ni i = i\nlet sn i = string_of_int i\n\n(*let nn = 100000 + 5*)\nlet nn_max = 100000 + 5\n\nlet nn = 100000 + 3\n\nlet r= Array.make nn_max (ni (-1))\n\nfor i = 1 to k-1 do\n r.(i) <- (ni 1)\ndone\n\nlet () = \n r.(k) <- ni 2\n\nlet f n = \n if r.(n) = (ni (-1)) then\n begin\n let x = modn ( r.(n-1) + r.(n-k) ) in \n r.(n) <- x; x\n end\n else\n r.(n)\n\nfor i = k+1 to nn do\n r.(i) <- (f (i-1)) + (f (i-k))\ndone\n\n(*\nfor i = 95515 to nn do\n printf \"%s %s\\n\" (sn r.(i)) (sn w.(i))\ndone\n*)\n\nfor i = 1 to t do\n let (s,e) = bscanf Scanning.stdin \"%d %d \" (fun x y -> (x,y) ) in\n let sum = ref (ni 0) in\n for j = s to e do\n sum := !sum + r.(j)\n done;\n printf \"%s\\n\" (sn (modn !sum) )\ndone\n\n\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet (--) debut fin =\n let rec range aux start en =\n if start > en then aux\n else range (en::aux) start (en-1)\n in range [] debut fin;;\n\nlet print_list f lst =\n let rec print_elements = function\n | [] -> ()\n | h::t -> f h; print_string \";\"; print_elements t\n in\n print_string \"[\";\n print_elements lst;\n print_string \"]\\n\";\n lst;;\n\nlet modulo = 1000000007;;\n\nlet dyn_array = Array.make 100000 (-1);;\n\nlet rec get_ways gap = function \n | index when index = Array.length dyn_array -> 1\n | index when index > Array.length dyn_array -> 0\n | index when dyn_array.(index) != -1 -> dyn_array.(index)\n | index ->\n let res = (get_ways gap (index+1) + get_ways gap (index+gap)) mod modulo in\n dyn_array.(index) <- res;\n res;;\n\n(*#trace get_ways;;*)\n\ntype 'a node_data = {\n data:'a;\n start: int;\n fin: int\n};;\n\ntype 'a node = \n | Leaf of 'a node_data\n | Cell of 'a node_data * 'a node * 'a node;;\n\nlet get_data = function\n | Leaf data\n | Cell (data,_,_) \n -> data;;\n\nlet computing_function = (+);;\nlet default_val = 0;;\n\nlet rec get_range tree debut fin = match tree with\n | Leaf data ->\n if data.start >= debut && data.fin <= fin then\n data.data\n else\n default_val\n | Cell (d, left, right) ->\n if fin < d.start || debut > d.fin then\n default_val\n else if d.fin > fin || d.start < debut then\n computing_function (get_range left debut fin) (get_range right debut fin)\n else\n d.data;;\n\nlet rec buildTree debut fin =\n if debut = fin then \n Leaf {\n data = dyn_array.(debut);\n start = debut;\n fin = fin\n }\n else\n let mid = (debut + fin)/2 in\n let right = buildTree (mid + 1) fin in\n let left = buildTree debut mid in\n let node_d = {\n data = (computing_function (get_data left).data (get_data right).data);\n start = debut;\n fin = fin\n } in\n Cell (node_d, left, right);;\n\n\nlet nbTests = read_int () in\nlet gap = read_int () in\nlet _ = get_ways gap 0 in\nlet tree = buildTree 0 (Array.length dyn_array - 1) in\nfor i = 1 to nbTests do\n let start = read_int () in\n let tree_end = Array.length dyn_array - start in\n let fin = read_int () in \n let tree_start = Array.length dyn_array - fin in\n let res = get_range tree tree_start tree_end in\n Printf.printf \"%d\\n\" res\ndone;;"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet (--) debut fin =\n let rec range aux start en =\n if start > en then aux\n else range (en::aux) start (en-1)\n in range [] debut fin;;\n\nlet print_list f lst =\n let rec print_elements = function\n | [] -> ()\n | h::t -> f h; print_string \";\"; print_elements t\n in\n print_string \"[\";\n print_elements lst;\n print_string \"]\\n\";\n lst;;\n\nlet modulo = 1000000007;;\n\nlet dyn_array = Array.make 100005 (-1);;\n\nlet rec get_ways gap = function \n | index when index = Array.length dyn_array -> 1\n | index when index > Array.length dyn_array -> 0\n | index when dyn_array.(index) != -1 -> dyn_array.(index)\n | index ->\n let res = (get_ways gap (index+1) + get_ways gap (index+gap)) mod modulo in\n dyn_array.(index) <- res;\n res;;\n\n(*#trace get_ways;;*)\n\nlet nbTests = read_int () in\nlet gap = read_int () in\nlet _ = get_ways gap 0 in\nfor i = 1 to Array.length dyn_array - 1 do\n dyn_array.(i) <- (dyn_array.(i) + dyn_array.(i - 1)) mod modulo\ndone;\nfor i = 1 to nbTests do\n let start = read_int () in\n let tree_end = Array.length dyn_array - start in\n let fin = read_int () in \n let tree_start = Array.length dyn_array - fin in\n let res = (modulo + dyn_array.(tree_end) - if tree_start > 0 then dyn_array.(tree_start - 1) else 0) mod modulo in\n Printf.printf \"%l\\n\" res\ndone;;"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet (--) debut fin =\n let rec range aux start en =\n if start > en then aux\n else range (en::aux) start (en-1)\n in range [] debut fin;;\n\nlet print_list f lst =\n let rec print_elements = function\n | [] -> ()\n | h::t -> f h; print_string \";\"; print_elements t\n in\n print_string \"[\";\n print_elements lst;\n print_string \"]\\n\";\n lst;;\n\nlet modulo = 1000000007;;\n\nlet dyn_array = Array.make 100000 (-1);;\n\nlet rec get_ways gap = function \n | index when index = Array.length dyn_array -> 1\n | index when index > Array.length dyn_array -> 0\n | index when dyn_array.(index) != -1 -> dyn_array.(index)\n | index ->\n let res = (get_ways gap (index+1) + get_ways gap (index+gap)) mod modulo in\n dyn_array.(index) <- res;\n res;;\n\n(*#trace get_ways;;*)\n\ntype 'a node_data = {\n data:'a;\n start: int;\n fin: int\n};;\n\ntype 'a node = \n | Leaf of 'a node_data\n | Cell of 'a node_data * 'a node * 'a node;;\n\nlet get_data = function\n | Leaf data\n | Cell (data,_,_) \n -> data;;\n\nlet computing_function a b= \n (a + b) mod modulo;;\nlet default_val = 0;;\n\nlet rec get_range tree debut fin = match tree with\n | Leaf data ->\n if data.start >= debut && data.fin <= fin then\n data.data\n else\n default_val\n | Cell (d, left, right) ->\n if fin < d.start || debut > d.fin then\n default_val\n else if d.fin > fin || d.start < debut then\n computing_function (get_range left debut fin) (get_range right debut fin)\n else\n d.data;;\n\n(*#trace get_range;;*)\n\nlet rec buildTree debut fin =\n if debut = fin then \n Leaf {\n data = dyn_array.(debut);\n start = debut;\n fin = fin\n }\n else\n let mid = (debut + fin)/2 in\n let right = buildTree (mid + 1) fin in\n let left = buildTree debut mid in\n let node_d = {\n data = (computing_function (get_data left).data (get_data right).data);\n start = debut;\n fin = fin\n } in\n Cell (node_d, left, right);;\n\n\nlet nbTests = read_int () in\nlet gap = read_int () in\nlet _ = get_ways gap 0 in\nlet tree = buildTree 0 (Array.length dyn_array - 1) in\nfor i = 1 to nbTests do\n let start = read_int () in\n let tree_end = Array.length dyn_array - start in\n let fin = read_int () in \n let tree_start = Array.length dyn_array - fin in\n let res = get_range tree tree_start tree_end in\n Printf.printf \"%d\\n\" res\ndone;;"}], "src_uid": "16c016c0735be1815c7b94c5c50516f1"} {"nl": {"description": "This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a \"Discuss tasks\" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.In this task you are given a cell field $$$n \\cdot m$$$, consisting of $$$n$$$ rows and $$$m$$$ columns, where point's coordinates $$$(x, y)$$$ mean it is situated in the $$$x$$$-th row and $$$y$$$-th column, considering numeration from one ($$$1 \\leq x \\leq n, 1 \\leq y \\leq m$$$). Initially, you stand in the cell $$$(1, 1)$$$. Every move you can jump from cell $$$(x, y)$$$, which you stand in, by any non-zero vector $$$(dx, dy)$$$, thus you will stand in the $$$(x+dx, y+dy)$$$ cell. Obviously, you can't leave the field, but also there is one more important condition\u00a0\u2014 you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).Tolik's uncle is a very respectful person. Help him to solve this task!", "input_spec": "The first and only line contains two positive integers $$$n, m$$$ ($$$1 \\leq n \\cdot m \\leq 10^{6}$$$)\u00a0\u2014 the number of rows and columns of the field respectively.", "output_spec": "Print \"-1\" (without quotes) if it is impossible to visit every cell exactly once. Else print $$$n \\cdot m$$$ pairs of integers, $$$i$$$-th from them should contain two integers $$$x_i, y_i$$$ ($$$1 \\leq x_i \\leq n, 1 \\leq y_i \\leq m$$$)\u00a0\u2014 cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too. Notice that the first cell should have $$$(1, 1)$$$ coordinates, according to the statement.", "sample_inputs": ["2 3", "1 1"], "sample_outputs": ["1 1\n1 3\n1 2\n2 2\n2 3\n2 1", "1 1"], "notes": "NoteThe vectors from the first example in the order of making jumps are $$$(0, 2), (0, -1), (1, 0), (0, 1), (0, -2)$$$."}, "positive_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet writeP (x, y) = Printf.printf \"%d %d\\n\" (x+1) (y+1)\n\nlet run (n, m) =\n for x=0 to n/2-1 do\n for y=0 to m-1 do\n writeP (x, y); writeP (n-x-1, m-y-1)\n done;\n done;\n if n mod 2 = 1 then begin\n for y=0 to m/2-1 do\n writeP (n/2, y); writeP (n/2, m-y-1)\n done;\n if m mod 2 = 1 then writeP (n/2, m/2)\n end\n\nlet main () =\n let n = readInt () in\n let m = readInt () in\n run (n, m)\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "cc67015b9615f150aa06f7b8ed7e3152"} {"nl": {"description": "Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.Help Vasya! Calculate the maximum total weight of mushrooms he can collect.", "input_spec": "The first line contains the number n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) \u2014 the length of the glade. The second line contains n numbers a1,\u2009a2,\u2009...,\u2009an\u00a0(1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the growth rate of mushrooms in the first row of the glade. The third line contains n numbers b1,\u2009b2,\u2009...,\u2009bn\u00a0(1\u2009\u2264\u2009bi\u2009\u2264\u2009106) is the growth rate of mushrooms in the second row of the glade.", "output_spec": "Output one number \u2014 the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.", "sample_inputs": ["3\n1 2 3\n6 5 4", "3\n1 1000 10000\n10 100 100000"], "sample_outputs": ["70", "543210"], "notes": "NoteIn the first test case, the optimal route is as follows: Thus, the collected weight of mushrooms will be 0\u00b71\u2009+\u20091\u00b72\u2009+\u20092\u00b73\u2009+\u20093\u00b74\u2009+\u20094\u00b75\u2009+\u20095\u00b76\u2009=\u200970.In the second test case, the optimal route is as follows: Thus, the collected weight of mushrooms will be 0\u00b71\u2009+\u20091\u00b710\u2009+\u20092\u00b7100\u2009+\u20093\u00b71000\u2009+\u20094\u00b710000\u2009+\u20095\u00b7100000\u2009=\u2009543210."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0L in\n let b = Array.make n 0L in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s)\n done;\n for i = 0 to n - 1 do\n b.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s)\n done;\n in\n let sa = Array.make (n + 1) 0L in\n let sb = Array.make (n + 1) 0L in\n let pa = Array.make (n + 1) 0L in\n let pb = Array.make (n + 1) 0L in\n let qa = Array.make (n + 1) 0L in\n let qb = Array.make (n + 1) 0L in\n let _ =\n for i = 0 to n - 1 do\n sa.(i + 1) <- sa.(i) +| a.(i);\n sb.(i + 1) <- sb.(i) +| b.(i);\n pa.(i + 1) <- pa.(i) +| a.(i) *| Int64.of_int i;\n pb.(i + 1) <- pb.(i) +| b.(i) *| Int64.of_int i;\n qa.(i + 1) <- qa.(i) +| a.(i) *| Int64.of_int (n - 1 - i);\n qb.(i + 1) <- qb.(i) +| b.(i) *| Int64.of_int (n - 1 - i);\n done;\n in\n let res = ref 0L in\n let c = ref 0L in\n for i = 0 to n - 1 do\n if i mod 2 = 0 then (\n\tlet d = pa.(n) -| pa.(i) +| (sa.(n) -| sa.(i)) *| Int64.of_int i in\n\tlet e = qb.(n) -| qb.(i) +| (sb.(n) -| sb.(i)) *|\n\t Int64.of_int (2 * i + (n - i))\n\tin\n\tlet t = !c +| d +| e in\n\t res := max !res t;\n\t (*Printf.printf \"asd %Ld %Ld\\n\" d e;*)\n\t c := !c +| Int64.of_int (2 * i) *| a.(i) +|\n\t Int64.of_int (2 * i + 1) *| b.(i);\n ) else (\n\tlet d = pb.(n) -| pb.(i) +| (sb.(n) -| sb.(i)) *| Int64.of_int i in\n\tlet e = qa.(n) -| qa.(i) +| (sa.(n) -| sa.(i)) *|\n\t Int64.of_int (2 * i + (n - i))\n\tin\n\tlet t = !c +| d +| e in\n\t res := max !res t;\n\t (*Printf.printf \"asd %Ld %Ld\\n\" d e;*)\n\t c := !c +| Int64.of_int (2 * i) *| b.(i) +|\n\t Int64.of_int (2 * i + 1) *| a.(i);\n )\n done;\n Printf.printf \"%Ld\\n\" !res\n"}], "negative_code": [], "src_uid": "948429d3788b212e7763774f8cab097b"} {"nl": {"description": "Consider an n\u2009\u00d7\u2009m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. You're given a painted grid in the input. Tell Lenny if the grid is convex or not.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950) \u2014 the size of the grid. Each of the next n lines contains m characters \"B\" or \"W\". Character \"B\" denotes a black cell of the grid and \"W\" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.", "output_spec": "On the only line of the output print \"YES\" if the grid is convex, otherwise print \"NO\". Do not print quotes.", "sample_inputs": ["3 4\nWWBW\nBWWW\nWWWB", "3 1\nB\nB\nW"], "sample_outputs": ["NO", "YES"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n\n let a = Array.make_matrix n m false in\n\n let blist = ref [] in\n\n let () =\n for i=0 to n-1 do\n let s = read_string() in\n\tfor j=0 to m-1 do\n\t a.(i).(j) <- s.[j]='B';\n\t if a.(i).(j) then blist := (i,j)::(!blist)\n\tdone\n done in\n\n let hpath i j jj = \n let good = ref true in\n for jjj = min j jj to max j jj do\n\tgood := !good && a.(i).(jjj)\n done;\n !good\n in\n\n let vpath i j ii = \n let good = ref true in\n for iii = min i ii to max i ii do\n\tgood := !good && a.(iii).(j)\n done;\n !good\n in\n\n let reachable (i,j) (ii,jj) = \n ((hpath i j jj) && (vpath i jj ii)) || ((vpath i j ii) && (hpath ii j jj))\n in\n \n if List.for_all (fun (i,j) -> List.for_all (fun (ii,jj) -> reachable (i,j) (ii,jj) ) !blist) !blist\n then Printf.printf \"YES\\n\" else Printf.printf \"NO\\n\"\n"}], "negative_code": [], "src_uid": "3631eba1b28fae473cf438bc2f0552b7"} {"nl": {"description": "Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.Lyft has become so popular so that it is now used by all $$$m$$$ taxi drivers in the city, who every day transport the rest of the city residents\u00a0\u2014 $$$n$$$ riders.Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $$$i$$$ the number $$$a_{i}$$$\u00a0\u2014 the number of riders that would call the $$$i$$$-th taxi driver when all drivers and riders are at their home?The taxi driver can neither transport himself nor other taxi drivers.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n,m \\le 10^5$$$)\u00a0\u2014 number of riders and taxi drivers. The second line contains $$$n + m$$$ integers $$$x_1, x_2, \\ldots, x_{n+m}$$$ ($$$1 \\le x_1 < x_2 < \\ldots < x_{n+m} \\le 10^9$$$), where $$$x_i$$$ is the coordinate where the $$$i$$$-th resident lives. The third line contains $$$n + m$$$ integers $$$t_1, t_2, \\ldots, t_{n+m}$$$ ($$$0 \\le t_i \\le 1$$$). If $$$t_i = 1$$$, then the $$$i$$$-th resident is a taxi driver, otherwise $$$t_i = 0$$$. It is guaranteed that the number of $$$i$$$ such that $$$t_i = 1$$$ is equal to $$$m$$$.", "output_spec": "Print $$$m$$$ integers $$$a_1, a_2, \\ldots, a_{m}$$$, where $$$a_i$$$ is the answer for the $$$i$$$-th taxi driver. The taxi driver has the number $$$i$$$ if among all the taxi drivers he lives in the $$$i$$$-th smallest coordinate (see examples for better understanding).", "sample_inputs": ["3 1\n1 2 3 10\n0 0 1 0", "3 2\n2 3 4 5 6\n1 0 0 0 1", "1 4\n2 4 6 10 15\n1 1 1 1 0"], "sample_outputs": ["3", "2 1", "0 0 0 1"], "notes": "NoteIn the first example, we have only one taxi driver, which means an order from any of $$$n$$$ riders will go to him.In the second example, the first taxi driver lives at the point with the coordinate $$$2$$$, and the second one lives at the point with the coordinate $$$6$$$. Obviously, the nearest taxi driver to the rider who lives on the $$$3$$$ coordinate is the first one, and to the rider who lives on the coordinate $$$5$$$ is the second one. The rider who lives on the $$$4$$$ coordinate has the same distance to the first and the second taxi drivers, but since the first taxi driver has a smaller coordinate, the call from this rider will go to the first taxi driver.In the third example, we have one rider and the taxi driver nearest to him is the fourth one."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64,ist = Int64.(to_int,of_int,to_string)\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* input *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\texternal id : 'a -> 'a = \"%identity\"\n\tlet ( *< ) f g x = f (g x)\n\tlet ( *> ) f g x = g (f x)\n\tlet rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet fail _ = failwith \"fail\"\n\tlet dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n\tlet range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n\tlet cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n\tlet shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n\tlet binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n\t\tlet rec f0 ng ok =\n\t\t\tif labs (ok - ng) <= 1L then ok\n\t\t\telse let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n\t\tin f0 (ng-1L*d) (ok+1L*d)\n\tlet lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n\tlet upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n\tlet equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n\tlet rec fix f x = f (fix f) x\n\t(* imperative *)\n\tlet rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n\tlet repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n\tlet repm f t ?(stride=1L) m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n\tlet repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n\tlet repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n\tlet repim f t ?(stride=1) m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n\tlet rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n\tlet repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n\tlet repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n\tlet repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n\t(* output *)\n\tlet print_list_mle f ls = string_of_list f ls |> print_endline\n\tlet print_array_mle f a = string_of_array f a |> print_endline\n\tlet print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\tlet print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\t(* debug *)\n\tlet dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n\tlet dump_i64_list ls = print_list ist ls\n\tlet dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n\tlet n,m = get_2_i64 0 in\n\tlet x = input_i64_array (n+m) in\n\tlet t = input_i64_array (n+m) in\n\tlet dr = ref [] in\n\tlet re = ref [] in\n\trepi 0 (i32 (n+m)-$1) (fun i->\n\t\tlet x,t = x.(i),t.(i) in\n\t\tif t=1L then dr := x::!dr\n\t\telse re := x::!re\n\t);\n\tlet dr,re = of_list !dr,of_list !re in\n\tsort compare dr;\n\tsort compare re;\n\t(* iter (fun d ->\n\t\tlet rleft,rright = lower_bound re d,binary_search (alen re) 0L (fun i->re.(i32 i)>d)\n\t\tin\n\t\tlet vrleft = if rleft<0L || rleft>=n then Int64.max_int else re.(i32 rleft)\n\t\tin let vrright = if rright<0L || rright>=n then Int64.max_int else re.(i32 rright)\n\t\tin\n\t\tif labs (vrleft - d) < labs (vrright - d) then \n\t) dr *)\n\tlet mx = Int64.max_int in\n\tlet safe a i d = try a.(i32 i) with Invalid_argument _ -> d\n\tin\n\tlet count = make (i32 m) 0L in\n\t(* print_array ist re;\n\tprint_array ist dr; *)\n\titer (fun r ->\n\t\tlet d_l,d_r =\n\t\t\t(* binary_search (alen re-1L) 0L (fun i->safe dr i mxsafe dr i 0L>r) *)\n\t\t\tbinary_search (alen dr-1L) 0L (fun i->dr.(i32 i)dr.(i32 i)>r)\n\t\tin\n\t\tlet vdl,vdr = safe dr d_l mx,safe dr d_r (-1L) in\n\t\t(* printf \"%Ld:%Ld -- %Ld:%Ld\\n\" d_l vdl d_r vdr; *)\n\t\tlet i = if r-vdl<=0L then d_r else if vdr-r<=0L then d_l\n\t\telse if r - vdl <= vdr - r then d_l else d_r in\n\t\tcount.(i32 i) <- count.(i32 i) + 1L;\n\t) re;\n\titer (fun v->printf \"%Ld \" v) count\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "56ea328f84b2930656ff5eb9b8fda8e0"} {"nl": {"description": "Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length\u00a0$$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 50$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the array that Phoenix currently has. This array may or may not be already beautiful.", "output_spec": "For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \\le m \\le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \\le b_i \\le n$$$)\u00a0\u2014 a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.", "sample_inputs": ["4\n4 2\n1 2 2 1\n4 3\n1 2 2 1\n3 2\n1 2 3\n4 4\n4 3 4 2"], "sample_outputs": ["5\n1 2 1 2 1\n4\n1 2 2 1\n-1\n7\n4 3 2 1 4 3 2"], "notes": "NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example: $$$2, 1, 2, 1, 2, 1$$$ $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also."}, "positive_code": [{"source_code": "(* Codeforces 1348 B Phoenix and Beauty train *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\nlet list_to_s li = (String.concat \" \" (List.map string_of_int li));;\n\n(* unique elements in sorted list *)\nlet rec diffr lun last sl = match sl with\n | [] -> lun\n\t| h :: t ->\n\t\tlet nlun = if (h == last) then lun else h :: lun in\n\t\tdiffr nlun h t;;\n\n(* count number of different elements in integers list *)\nlet ldiff l = \n let sl = List.sort compare l in\n diffr [] (-1) sl;;\t\n\nlet repeat ls n =\n let rec f l = function\n | 0 -> l\n | n -> f (List.rev_append ls l) (n-1) in\n List.rev (f [] n)\n\t\t\nlet fill_to_k l k = \n\t(* let _ = Printf.printf \"fill_to_k k,l = %d %s\\n\" k (list_to_s l) in *)\n\tlet nfill = k - (List.length l) in\n\tif nfill <= 0 then l\n\telse\n\t\tlet lf = repeat [List.hd l] nfill in\n\t\t(* let _ = Printf.printf \"Fill: %s\\n\" (list_to_s lf) in *)\n\t\tList.append lf l;;\n\nlet rec beautya n k a = \n\tif n == k then (n , a)\n\telse \n\t\tlet lun = ldiff a in\n\t\t(* let _ = printlisti lun in *)\n\t\tlet lenun = List.length lun in\n\t\tif lenun > k then ((-1), [])\n\t\telse\n let lun = fill_to_k lun k in\n\t\t\tlet ln = (k * n) in \n\t\t let reta = repeat lun n in\n\t\t (ln, reta);;\n\nlet do_one () = \n let n = gr () in\n let k = gr () in\n\tlet a = List.rev (readlist n []) in\n\tlet ln,reta = beautya n k a in \n\tbegin\n\t\tprint_int ln;\n print_string \"\\n\";\n\t\tif ln > 0 then\n\t\t\tbegin\n \t\t\tprintlisti reta;\n print_string \"\\n\"\n\t\t\tend\n\tend;;\t\t\n\nlet rec do_all t = match t with\n\t| 0 -> ()\n\t| _ -> \n\t\tbegin\n\t\t\tdo_one ();\n\t\t\tdo_all (t-1)\n\t\tend;; \n\nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n\nmain();;"}], "negative_code": [{"source_code": "(* Codeforces 1348 B Phoenix and Beauty train *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\n\n(* unique elements in sorted list *)\nlet rec diffr lun last sl = match sl with\n | [] -> lun\n\t| h :: t ->\n\t\tlet nlun = if (h == last) then lun else h :: lun in\n\t\tdiffr nlun h t;;\n\n(* count number of different elements in integers list *)\nlet ldiff l = \n let sl = List.sort compare l in\n diffr [] (-1) sl;;\t\n\nlet repeat ls n =\n let rec f l = function\n | 0 -> l\n | n -> f (List.rev_append ls l) (n-1) in\n List.rev (f [] n)\n\nlet rec beautya n k a = \n\tif n == k then (n , a)\n\telse \n\t\tlet lun = ldiff a in\n\t\t(* let _ = printlisti lun in *)\n\t\tlet lenun = List.length lun in\n\t\tif lenun > k then ((-1), [])\n\t\telse\n\t\t\tlet ln = (lenun * n) in \n\t\t let reta = repeat lun n in\n\t\t (ln, reta);;\n\nlet do_one () = \n let n = gr () in\n let k = gr () in\n\tlet a = readlist n [] in\n\tlet ln,reta = beautya n k a in \n\tbegin\n\t\tprint_int ln;\n print_string \"\\n\";\n\t\tif ln > 0 then\n\t\t\tbegin\n \t\t\tprintlisti reta;\n print_string \"\\n\"\n\t\t\tend\n\tend;;\t\t\n\nlet rec do_all t = match t with\n\t| 0 -> ()\n\t| _ -> \n\t\tbegin\n\t\t\tdo_one ();\n\t\t\tdo_all (t-1)\n\t\tend;; \n\nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n\nmain();;"}, {"source_code": "(* Codeforces 1348 B Phoenix and Beauty train *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\nlet list_to_s li = (String.concat \" \" (List.map string_of_int li));;\n\n(* unique elements in sorted list *)\nlet rec diffr lun last sl = match sl with\n | [] -> lun\n\t| h :: t ->\n\t\tlet nlun = if (h == last) then lun else h :: lun in\n\t\tdiffr nlun h t;;\n\n(* count number of different elements in integers list *)\nlet ldiff l = \n let sl = List.sort compare l in\n diffr [] (-1) sl;;\t\n\nlet repeat ls n =\n let rec f l = function\n | 0 -> l\n | n -> f (List.rev_append ls l) (n-1) in\n List.rev (f [] n)\n\t\t\nlet fill_to_k l k = \n\t(* let _ = Printf.printf \"fill_to_k k,l = %d %s\\n\" k (list_to_s l) in *)\n\tlet nfill = k - (List.length l) in\n\tif nfill <= 0 then l\n\telse\n\t\tlet lf = repeat [List.hd l] nfill in\n\t\t(* let _ = Printf.printf \"Fill: %s\\n\" (list_to_s lf) in *)\n\t\tList.append lf l;;\n\nlet rec beautya n k a = \n\tif n == k then (n , a)\n\telse \n\t\tlet lun = ldiff a in\n\t\t(* let _ = printlisti lun in *)\n\t\tlet lenun = List.length lun in\n\t\tif lenun > k then ((-1), [])\n\t\telse\n let lun = fill_to_k lun k in\n\t\t\tlet ln = (k * n) in \n\t\t let reta = repeat lun n in\n\t\t (ln, reta);;\n\nlet do_one () = \n let n = gr () in\n let k = gr () in\n\tlet a = readlist n [] in\n\tlet ln,reta = beautya n k a in \n\tbegin\n\t\tprint_int ln;\n print_string \"\\n\";\n\t\tif ln > 0 then\n\t\t\tbegin\n \t\t\tprintlisti reta;\n print_string \"\\n\"\n\t\t\tend\n\tend;;\t\t\n\nlet rec do_all t = match t with\n\t| 0 -> ()\n\t| _ -> \n\t\tbegin\n\t\t\tdo_one ();\n\t\t\tdo_all (t-1)\n\t\tend;; \n\nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n\nmain();;"}], "src_uid": "80d4b2d01215b12ebd89b8ee2d1ac6ed"} {"nl": {"description": "Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.The building consists of n floors with stairs at the left and the right sides. Each floor has m rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with n rows and m\u2009+\u20092 columns, where the first and the last columns represent the stairs, and the m columns in the middle represent rooms.Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights.Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u200915 and 1\u2009\u2264\u2009m\u2009\u2264\u2009100) \u2014 the number of floors and the number of rooms in each floor, respectively. The next n lines contains the building description. Each line contains a binary string of length m\u2009+\u20092 representing a floor (the left stairs, then m rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor. The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0.", "output_spec": "Print a single integer \u2014 the minimum total time needed to turn off all the lights.", "sample_inputs": ["2 2\n0010\n0100", "3 4\n001000\n000010\n000010", "4 3\n01110\n01110\n01110\n01110"], "sample_outputs": ["5", "12", "18"], "notes": "NoteIn the first example, Sagheer will go to room 1 in the ground floor, then he will go to room 2 in the second floor using the left or right stairs.In the second example, he will go to the fourth room in the ground floor, use right stairs, go to the fourth room in the second floor, use right stairs again, then go to the second room in the last floor.In the third example, he will walk through the whole corridor alternating between the left and right stairs at each floor."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f) \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let light = Array.init n read_string in\n(* light.(f).[r] = is the light on floor f in room r *)\n let ison f r = light.(n-1-f).[r] = '1' in\n\n let floor_off f = forall 0 (m+1) (fun r -> not (ison f r)) in\n\n let top_floor = maxf 0 (n-1) (fun f -> if floor_off f then 0 else f) in\n\n let ftime f st en =\n (* time to clear floor f starting at st (=0/1 for left/right) ending at en *)\n if en <> st then m+1\n else if st=0 then 2 * (maxf 1 m (fun r -> if ison f r then r else 0))\n else if st=1 then 2 * (maxf 1 m (fun r -> if ison f r then (m+1-r) else 0))\n else failwith \"no\"\n in\n\n let dp = Array.make_matrix n 2 0 in\n\n for f=0 to n-2 do\n for en = 0 to 1 do\n dp.(f).(en) <-\n\tif f=0 then ftime f 0 en\n\telse minf 0 1 (fun st -> dp.(f-1).(st) + 1 + (ftime f st en))\n(* printf \"dp.(%d).(%d) = %d\\n\" f en dp.(f).(en) *)\n done\n done;\n\n(* handle the last floor *)\n\n let answer f =\n if f=0 then (ftime 0 0 0)/2\n else minf 0 1 (fun st -> dp.(f-1).(st) + ((ftime f st st)/2) + 1)\n in\n\n printf \"%d\\n\" (answer top_floor)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f) \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let light = Array.init n read_string in\n(* light.(f).[r] = is the light on floor f in room r *)\n let ison f r = light.(n-1-f).[r] = '1' in\n\n let floor_off f = forall 0 (m+1) (fun r -> not (ison f r)) in\n\n let top_floor = maxf 0 (n-1) (fun f -> if floor_off f then 0 else f) in\n\n let ftime f st en =\n (* time to clear floor f starting at st (=0/1 for left/right) ending at en *)\n if en <> st then m+1\n else if st=0 then 2 * (maxf 1 m (fun r -> if ison f r then r else 0))\n else if st=1 then 2 * (maxf 1 m (fun r -> if ison f r then (m+1-r) else 0))\n else failwith \"no\"\n in\n\n let best_cost = ref 1_000_000 in\n \n let rec backtrack f side cost =\n if f = top_floor then (\n let top_cost = (ftime f side side)/2 in\n best_cost := min !best_cost (cost + 1 + top_cost)\n ) else (\n backtrack (f+1) side (cost + 1 + ftime f side side);\n backtrack (f+1) (1-side) (cost + 1 + ftime f side (1-side)); \n )\n in\n\n backtrack 0 0 (-1);\n\n printf \"%d\\n\" !best_cost\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let light = Array.init n read_string in\n(* light.(f).[r] = is the light on floor f in room r *)\n let ison f r = light.(n-1-f).[r] = '1' in\n\n let ftime f st en =\n (* time to clear floor f starting at st (=0/1 for left/right) ending at en *)\n if en <> st then m+1\n else if st=0 then 2 * (maxf 1 m (fun r -> if ison f r then r else 0))\n else if st=1 then 2 * (maxf 1 m (fun r -> if ison f r then (m+1-r) else 0))\n else failwith \"no\"\n in\n\n let dp = Array.make_matrix n 2 0 in\n\n for f=0 to n-2 do\n for en = 0 to 1 do\n dp.(f).(en) <-\n\tif f=0 then ftime f 0 en\n\telse minf 0 1 (fun st -> dp.(f-1).(st) + 1 + (ftime f st en))\n(* printf \"dp.(%d).(%d) = %d\\n\" f en dp.(f).(en) *)\n done\n done;\n\n(* handle the last floor *)\n\n let answer f =\n if f=0 then (ftime 0 0 0)/2\n else minf 0 1 (fun st -> dp.(f-1).(st) + ((ftime f st st)/2) + 1)\n in\n\n printf \"%d\\n\" (answer (n-1))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let light = Array.init n read_string in\n(* light.(f).[r] = is the light on floor f in room r *)\n let ison f r = light.(n-1-f).[r] = '1' in\n\n let inf = 1_000_000_000 in\n\n let ftime f st en =\n (* time to clear floor f starting at st (=0/1 for left/right) ending at en *)\n if en <> st then m+1\n else if st=0 then 2 * (maxf 1 m (fun r -> if ison f r then r else 0))\n else if st=1 then 2 * (maxf 1 m (fun r -> if ison f r then (m+1-r) else 0))\n else failwith \"no\"\n in\n\n let dp = Array.make_matrix n 2 0 in\n\n for f=0 to n-2 do\n for en = 0 to 1 do\n dp.(f).(en) <-\n\tif f=0 then ftime f 0 en\n\telse minf 0 1 (fun st -> dp.(f-1).(st) + 1 + (ftime f st en))\n(* printf \"dp.(%d).(%d) = %d\\n\" f en dp.(f).(en) *)\n done\n done;\n\n(* handle the last floor *)\n\n let answer f = minf 0 1 (fun st ->\n let prev = if f=0 then (if st=0 then 0 else inf) else dp.(f-1).(st) in\n prev + ((ftime f st st)/2) + (if f<>0 then 1 else 0)\n ) in\n\n printf \"%d\\n\" (answer (n-1))\n"}], "src_uid": "55070f8e5dba8a6ec669a53a169e557d"} {"nl": {"description": "Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.Let's assume that strings s and t have the same length n, then the function h(s,\u2009t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s,\u2009t) can be used to define the function of Vasya distance \u03c1(s,\u2009t): where is obtained from string s, by applying left circular shift i times. For example, \u03c1(\"AGC\",\u2009\"CGT\")\u2009=\u2009 h(\"AGC\",\u2009\"CGT\")\u2009+\u2009h(\"AGC\",\u2009\"GTC\")\u2009+\u2009h(\"AGC\",\u2009\"TCG\")\u2009+\u2009 h(\"GCA\",\u2009\"CGT\")\u2009+\u2009h(\"GCA\",\u2009\"GTC\")\u2009+\u2009h(\"GCA\",\u2009\"TCG\")\u2009+\u2009 h(\"CAG\",\u2009\"CGT\")\u2009+\u2009h(\"CAG\",\u2009\"GTC\")\u2009+\u2009h(\"CAG\",\u2009\"TCG\")\u2009=\u2009 1\u2009+\u20091\u2009+\u20090\u2009+\u20090\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009+\u20090\u2009+\u20091\u2009=\u20096Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: .Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109\u2009+\u20097.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line of the input contains a single string of length n, consisting of characters \"ACGT\".", "output_spec": "Print a single number\u00a0\u2014 the answer modulo 109\u2009+\u20097.", "sample_inputs": ["1\nC", "2\nAG", "3\nTTT"], "sample_outputs": ["1", "4", "1"], "notes": "NotePlease note that if for two distinct strings t1 and t2 values \u03c1(s,\u2009t1) \u0438 \u03c1(s,\u2009t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.In the first sample, there is \u03c1(\"C\",\u2009\"C\")\u2009=\u20091, for the remaining strings t of length 1 the value of \u03c1(s,\u2009t) is 0.In the second sample, \u03c1(\"AG\",\u2009\"AG\")\u2009=\u2009\u03c1(\"AG\",\u2009\"GA\")\u2009=\u2009\u03c1(\"AG\",\u2009\"AA\")\u2009=\u2009\u03c1(\"AG\",\u2009\"GG\")\u2009=\u20094.In the third sample, \u03c1(\"TTT\",\u2009\"TTT\")\u2009=\u200927"}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\n\nlet mm = 1_000_000_007L\n\nlet rec ( ^ ) e p = \n if p=0 then 1L else\n let a = e^(p/2) in\n if (p land 1)=0 then (a**a) %% mm else (e**((a**a) %% mm)) %%mm\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let s = read_string () in\n\n let hist = Array.make 4 0 in\n \n for i=0 to n-1 do\n let j = match s.[i] with\n | 'A' -> 0\n | 'G' -> 1\n | 'C' -> 2\n | 'T' -> 3\n | _ -> failwith \"bad input\"\n in\n hist.(j) <- hist.(j) + 1\n done;\n\n Array.sort compare hist;\n\n let ct = ref 1 in\n\n for i=0 to 2 do\n if hist.(3) = hist.(i) then ct := !ct+1\n done;\n\n let answer = (long !ct) ^ n in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "f35c042f23747988f65c5b5e8d5ddacd"} {"nl": {"description": "The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the k-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.", "input_spec": "The first line contains three space-separated integers n, m and k (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7104;\u00a01\u2009\u2264\u2009m\u2009\u2264\u200910;\u00a01\u2009\u2264\u2009k\u2009\u2264\u20092\u00b7105) \u2014 the number of the employees, the number of chats and the number of events in the log, correspondingly. Next n lines contain matrix a of size n\u2009\u00d7\u2009m, consisting of numbers zero and one. The element of this matrix, recorded in the j-th column of the i-th line, (let's denote it as aij) equals 1, if the i-th employee is the participant of the j-th chat, otherwise the element equals 0. Assume that the employees are numbered from 1 to n and the chats are numbered from 1 to m. Next k lines contain the description of the log events. The i-th line contains two space-separated integers xi and yi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009yi\u2009\u2264\u2009m) which mean that the employee number xi sent one message to chat number yi. It is guaranteed that employee number xi is a participant of chat yi. It is guaranteed that each chat contains at least two employees.", "output_spec": "Print in the single line n space-separated integers, where the i-th integer shows the number of message notifications the i-th employee receives.", "sample_inputs": ["3 4 5\n1 1 1 1\n1 0 1 1\n1 1 0 0\n1 1\n3 1\n1 3\n2 4\n3 2", "4 3 4\n0 1 1\n1 0 1\n1 1 1\n0 0 0\n1 2\n2 1\n3 1\n1 3"], "sample_outputs": ["3 3 1", "0 2 3 0"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int() and k=read_int();;\nlet mat=Array.make_matrix (n+1) (m+1) 0;;\nfor i=1 to n do\n for j=1 to m do\n mat.(i).(j)<-read_int()\n done\ndone;;\nlet tab=Array.make (m+1) 0;;\nlet mess=Array.make (n+1) 0;;\nfor i=1 to k do\n let x=read_int() and j=read_int() in\n begin\n mess.(x)<-mess.(x)-1;\n tab.(j)<-tab.(j)+1\n end\ndone;;\n\nfor i=1 to n do\n for j=1 to m do\n mess.(i)<-mess.(i)+mat.(i).(j)*tab.(j)\n done;\n Printf.printf \"%d \" mess.(i)\ndone;;"}], "negative_code": [], "src_uid": "fad203b52e11706d70e9b2954c295f70"} {"nl": {"description": "Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer x on the top of the stack, and operation pop() deletes the top integer from the stack, i.\u00a0e. the last added. If the stack is empty, then the operation pop() does nothing.Nikita made m operations with the stack but forgot them. Now Nikita wants to remember them. He remembers them one by one, on the i-th step he remembers an operation he made pi-th. In other words, he remembers the operations in order of some permutation p1,\u2009p2,\u2009...,\u2009pm. After each step Nikita wants to know what is the integer on the top of the stack after performing the operations he have already remembered, in the corresponding order. Help him!", "input_spec": "The first line contains the integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105)\u00a0\u2014 the number of operations Nikita made. The next m lines contain the operations Nikita remembers. The i-th line starts with two integers pi and ti (1\u2009\u2264\u2009pi\u2009\u2264\u2009m, ti\u2009=\u20090 or ti\u2009=\u20091)\u00a0\u2014 the index of operation he remembers on the step i, and the type of the operation. ti equals 0, if the operation is pop(), and 1, is the operation is push(x). If the operation is push(x), the line also contains the integer xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009106)\u00a0\u2014 the integer added to the stack. It is guaranteed that each integer from 1 to m is present exactly once among integers pi.", "output_spec": "Print m integers. The integer i should equal the number on the top of the stack after performing all the operations Nikita remembered on the steps from 1 to i. If the stack is empty after performing all these operations, print -1.", "sample_inputs": ["2\n2 1 2\n1 0", "3\n1 1 2\n2 1 3\n3 0", "5\n5 0\n4 0\n3 1 1\n2 1 1\n1 1 2"], "sample_outputs": ["2\n2", "2\n3\n2", "-1\n-1\n-1\n-1\n2"], "notes": "NoteIn the first example, after Nikita remembers the operation on the first step, the operation push(2) is the only operation, so the answer is 2. After he remembers the operation pop() which was done before push(2), answer stays the same.In the second example, the operations are push(2), push(3) and pop(). Nikita remembers them in the order they were performed.In the third example Nikita remembers the operations in the reversed order."}, "positive_code": [{"source_code": "type op =\n | Pop\n | Push of int\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let ops = Array.make n (0, Pop) in\n let _ =\n for i = 0 to n - 1 do\n let p = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tif t = 0\n\tthen ops.(i) <- (p - 1, Pop)\n\telse (\n\t let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t ops.(i) <- (p - 1, Push x)\n\t)\n done;\n in\n let o =\n let d = ref 1 in\n while !d < n do\n\td := !d * 2;\n done;\n !d\n in\n let sum = Array.make (2 * o) 0 in\n let max_suf = Array.make (2 * o) 0 in\n let rec update i x l r k =\n if l = r then (\n sum.(k) <- x;\n max_suf.(k) <- x;\n ) else (\n let m = (l + r) / 2 in\n\tif i <= m\n\tthen update i x l m (2 * k + 1)\n\telse update i x (m + 1) r (2 * k + 2);\n\t sum.(k) <- sum.(2 * k + 1) + sum.(2 * k + 2);\n\t max_suf.(k) <- max (sum.(2 * k + 2) + max_suf.(2 * k + 1))\n\t max_suf.(2 * k + 2);\n )\n in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n (match ops.(i) with\n\t | (pos, Push x) ->\n\t a.(pos) <- x;\n\t update pos 1 0 (o - 1) 0\n\t | (pos, Pop) ->\n\t update pos (-1) 0 (o - 1) 0\n );\n if max_suf.(0) <= 0 then (\n\tPrintf.printf \"-1\\n\"\n ) else (\n\tlet idx = ref 0 in\n\tlet s = ref 0 in\n\t (*for i = 0 to 2 * o - 2 do\n\t Printf.printf \"asd %d %d %d\\n\" i sum.(i) max_suf.(i)\n\t done;*)\n\t while !idx < o - 1 do\n\t (*Printf.printf \"qwe %d\\n\" !idx;*)\n\t if 2 * !idx + 2 < 2 * o - 1 && max_suf.(2 * !idx + 2) + !s > 0 then (\n\t idx := 2 * !idx + 2;\n\t ) else (\n\t if 2 * !idx + 2 < 2 * o - 1\n\t then s := !s + sum.(2 * !idx + 2);\n\t idx := 2 * !idx + 1;\n\t )\n\t done;\n\t (*Printf.printf \"idx %d\\n\" (!idx - o + 1);*)\n\t Printf.printf \"%d\\n\" a.(!idx - o + 1)\n )\n done;\n (*for i = 0 to 2 * o - 2 do\n Printf.printf \"asd %d %d %d\\n\" i sum.(i) max_suf.(i)\n done;*)\n"}], "negative_code": [], "src_uid": "3e8433d848e7a0be5b38ea0377e35b2b"} {"nl": {"description": "The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.", "input_spec": "The first line contains space-separated integers n and m \u2014 the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers ai, bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi), these integers indicate that the person number ai owes money to a person a number bi. Assume that all the employees are numbered from 1 to n. It is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.", "output_spec": "Print -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to the CEO office first, the second number denote the person who goes second and so on. If there are multiple correct orders, you are allowed to print any of them.", "sample_inputs": ["2 1\n1 2", "3 3\n1 2\n2 3\n3 1"], "sample_outputs": ["2 1", "2 1 3"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int();;\nlet pred=Array.make (n+1) [0];;\nfor i=1 to n do\n pred.(i)<-[]\ndone;;\nfor i=1 to m do\n let x=read_int() and y=read_int() in\n pred.(x)<-y::pred.(x)\ndone;;\ntype etat=Vu|Non_vu|En_cours;;\nlet mark=Array.make (n+1) Non_vu;;\nlet res=ref [];;\n\nlet rec dfs u=function\n|[]->mark.(u)<-Vu;res:=u::(!res)\n|h::t->if mark.(h)=Non_vu then\n begin\n mark.(h)<-En_cours;\n dfs h pred.(h)\n end;\n dfs u t;;\n\nlet tri()=\nfor i=1 to n do \n if mark.(i)=Vu then () else\n begin\n mark.(i)<-En_cours;\n dfs i pred.(i)\n end;\ndone;;\n\ntri();;\n\nlet rec print_list=function\n|[]->print_newline()\n|h::t->print_list t;Printf.printf \"%d \" h;;\n\nprint_list !res;;"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let ht = Hashtbl.create m in\n let () =\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tHashtbl.add ht (v, u) ();\n done\n in\n let es = Array.map Array.of_list es in\n let used = Array.make n false in\n let res = ref [] in\n let stack = Array.make (2 * n) (fun _ -> ()) in\n let stack_pos = ref 0 in\n let rec execute () =\n if !stack_pos > 0 then (\n decr stack_pos;\n let f = stack.(!stack_pos) in\n\tf ();\n\texecute ()\n )\n in\n let rec dfs u prev =\n used.(u) <- true;\n let rec aux i =\n if i < Array.length es.(u) then (\n\tstack.(!stack_pos) <- (fun () -> aux (i + 1));\n\tincr stack_pos;\n\tlet v = es.(u).(i) in\n\t if not used.(v) then (\n\t (*let f () =\n\t (*pe.(v) <- edge;\n\t tout.(u) <- !t;\n\t incr t;*) ()\n\t in\n\t (*stack.(!stack_pos) <- f;\n\t incr stack_pos;*)*)\n\t stack.(!stack_pos) <- (fun () -> dfs v u);\n\t incr stack_pos;\n\t )\n ) else (\n )\n in\n let f () =\n res := u :: !res\n in\n stack.(!stack_pos) <- f;\n incr stack_pos;\n aux 0\n in\n for u = 0 to n - 1 do\n if not used.(u) then (\n\tstack_pos := 0;\n\tdfs u 0;\n\texecute ();\n )\n done;\n List.iter\n (fun u ->\n\t Printf.printf \"%d \" (u + 1)\n ) (List.rev !res);\n Printf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let ht = Hashtbl.create m in\n let () =\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(v) <- u :: es.(u);\n\tHashtbl.add ht (v, u) ();\n done\n in\n let es = Array.map Array.of_list es in\n let used = Array.make n false in\n let res = ref [] in\n let stack = Array.make (2 * n) (fun _ -> ()) in\n let stack_pos = ref 0 in\n let rec execute () =\n if !stack_pos > 0 then (\n decr stack_pos;\n let f = stack.(!stack_pos) in\n\tf ();\n\texecute ()\n )\n in\n let rec dfs u prev =\n used.(u) <- true;\n let rec aux i =\n if i < Array.length es.(u) then (\n\tstack.(!stack_pos) <- (fun () -> aux (i + 1));\n\tincr stack_pos;\n\tlet v = es.(u).(i) in\n\t if not used.(v) then (\n\t (*let f () =\n\t (*pe.(v) <- edge;\n\t tout.(u) <- !t;\n\t incr t;*) ()\n\t in\n\t (*stack.(!stack_pos) <- f;\n\t incr stack_pos;*)*)\n\t stack.(!stack_pos) <- (fun () -> dfs v u);\n\t incr stack_pos;\n\t )\n ) else (\n )\n in\n let f () =\n res := u :: !res\n in\n stack.(!stack_pos) <- f;\n incr stack_pos;\n aux 0\n in\n for u = 0 to n - 1 do\n if not used.(u) then (\n\tstack_pos := 0;\n\tdfs u 0;\n\texecute ();\n )\n done;\n List.iter\n (fun u ->\n\t Printf.printf \"%d \" (u + 1)\n ) ((*List.rev*) !res);\n Printf.printf \"\\n\"\n"}], "src_uid": "412c9de03713ca8b5d1461d0213b8eec"} {"nl": {"description": "Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. He thinks that each student will take place equal to . In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position. GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000), number of GukiZ's students. The second line contains n numbers a1,\u2009a2,\u2009... an (1\u2009\u2264\u2009ai\u2009\u2264\u20092000) where ai is the rating of i-th student (1\u2009\u2264\u2009i\u2009\u2264\u2009n).", "output_spec": "In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.", "sample_inputs": ["3\n1 3 3", "1\n1", "5\n3 5 3 4 5"], "sample_outputs": ["3 1 1", "1", "4 1 4 3 1"], "notes": "NoteIn the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.In the second sample, first student is the only one on the contest.In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i >= j then init else fold (i + 1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n (* let start_time = Sys.time() in *)\n\n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let b = Array.init n (fun i -> string_of_int (\n 1 + sum 0 n (fun x -> if a.(x) > a.(i) then 1 else 0)\n )) in\n print_string (String.concat \" \" (Array.to_list b));\n\n (* let finish_time = Sys.time() in *)\n (* printf \"Time of scanning %fs\\n\" (finish_time -. start_time); *)\n (* b;; *)\n"}, {"source_code": "let () =\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) and l = ref [] and tab = Array.make 2001 0 \n\tand tab' = Array.make 2001 0 in\n\t\tfor i=1 to n do\n\t\t\tScanf.scanf \" %d\" (fun j -> tab.(j) <- tab.(j) + 1; l := j::!l);\n\t\tdone;\n\t\tfor i=2000 downto 1 do\n\t\t\ttab'.(i-1) <- tab'.(i) + tab.(i);\n\t\tdone;\n\tList.iter (fun i -> Printf.printf \"%d \" (1 + tab'.(i))) (List.rev !l)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i >= j then init else fold (i + 1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet main () = \n let start_time = Sys.time() in\n\n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let b = Array.init n (fun i -> string_of_int (\n sum 0 n (fun x -> if a.(x) > a.(i) then 1 else 0)\n )) in \n print_string (String.concat \" \" (Array.to_list b));\n\n let finish_time = Sys.time() in\n printf \"Time of scanning %fs\\n\" (finish_time -. start_time);\n b;;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i >= j then init else fold (i + 1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n (* let start_time = Sys.time() in *)\n\n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let b = Array.init n (fun i -> string_of_int (\n sum 0 n (fun x -> if a.(x) > a.(i) then 1 else 0)\n )) in\n print_string (String.concat \" \" (Array.to_list b));\n\n (* let finish_time = Sys.time() in *)\n (* printf \"Time of scanning %fs\\n\" (finish_time -. start_time); *)\n (* b;; *)\n"}], "src_uid": "a5edbf422616cdac35e95a4f07efc7fd"} {"nl": {"description": "Petya loves computer games. Finally a game that he's been waiting for so long came out!The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is calculated as the sum of the values \u200b\u200bof for all i from 1 to n. The expression \u230a x\u230b denotes the result of rounding the number x down to the nearest integer.At the beginning of the game Petya got k improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if a4\u2009=\u200946, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused.Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.", "input_spec": "The first line of the input contains two positive integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009k\u2009\u2264\u2009107) \u2014 the number of skills of the character and the number of units of improvements at Petya's disposal. The second line of the input contains a sequence of n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009100), where ai characterizes the level of the i-th skill of the character.", "output_spec": "The first line of the output should contain a single non-negative integer \u2014 the maximum total rating of the character that Petya can get using k or less improvement units.", "sample_inputs": ["2 4\n7 9", "3 8\n17 15 19", "2 2\n99 100"], "sample_outputs": ["2", "5", "20"], "notes": "NoteIn the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus, Petya spends all his improvement units and the total rating of the character becomes equal to lfloor frac{100}{10} rfloor\u2009+\u2009 lfloor frac{100}{10} rfloor\u2009=\u200910\u2009+\u200910\u2009=\u2009 20.In the second test the optimal strategy for Petya is to improve the first skill to 20 (by spending 3 improvement units) and to improve the third skill to 20 (in this case by spending 1 improvement units). Thus, Petya is left with 4 improvement units and he will be able to increase the second skill to 19 (which does not change the overall rating, so Petya does not necessarily have to do it). Therefore, the highest possible total rating in this example is .In the third test case the optimal strategy for Petya is to increase the first skill to 100 by spending 1 improvement unit. Thereafter, both skills of the character will be equal to 100, so Petya will not be able to spend the remaining improvement unit. So the answer is equal to . "}, "positive_code": [{"source_code": "let cmp x y =\n let a = 10 - (x mod 10)\n and b = 10 - (y mod 10) in\n compare a b\n\nlet () = Scanf.scanf \"%d %d\\n\" (fun n k ->\n (* read initial skills *)\n let a = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n (* sort by distance from the next multiple of 10 *)\n Array.sort cmp a;\n\n (* calculate the possible improvement *)\n let (rating, rem) = Array.fold_left (fun (acc, rem) skill ->\n (* if we have enough skill points remaining, use them *)\n let diff = 10 - (skill mod 10) in\n if diff <= rem\n then (acc + (skill + diff) / 10, rem - diff)\n else (acc + skill / 10, rem)\n ) (0, k) a in\n\n Printf.printf \"%d\\n\" (min (rating + rem / 10) (n * 10)))\n"}, {"source_code": "(*I should use a cyclic list*)\nopen Scanf;;\nopen Printf;;\n\n\nlet (n,k) = Scanf.scanf \"%d %d \" (fun x y -> (x,y) )\n\nlet a = Array.make n 0\n\nlet rec readi i l =\n if i = n then\n List.rev l\n else\n begin\n let x = Scanf.scanf \"%d \" (fun x -> x) in\n readi (i+1) (x::l)\n end\n\nlet b = readi 0 []\n\nlet b1 = List.filter (fun x -> x mod 10 !=0 ) b |> List.sort (fun x y -> compare (y mod 10) (x mod 10) )\n\nlet b2 = List.filter (fun x -> x mod 10 =0 ) b |> List.sort (fun x y -> compare y x)\n\n (*\nlet _ =\n List.iter (fun x -> printf \"%d \" x) b\n\nlet _ = List.mapi (fun i x -> a.(i)<-x) (b2 @ b1)\n *)\n\nlet rec f ll rl k =\n if k==0 then\n (((List.rev ll) @ rl), k)\n else\n begin\n match rl with\n | [] -> ( (List.rev ll), k)\n | hd::tl ->\n begin\n if (hd mod 10) + k >= 10 then\n let x = 10 - (hd mod 10) in\n f ((hd + x)::ll) tl (k-x)\n else\n f (hd::ll) tl 0\n end\n end\n\nlet (l,t) = f [] b1 k\n\nlet l = l @ b2\n(*\nlet _ =\n print_endline \"\";\n printf \"%d\\n\" t;\n List. iter (fun x -> printf \"%d \" x) l;\n print_endline \"\"\n *)\n\nlet _ =\n if t>0 then\n let s = List.fold_left (fun x y -> x + (100-y)) 0 l in\n if s<= t then\n printf \"%d\\n\" (10*(List.length l))\n else\n begin\n let s1 = List.fold_left (fun x y -> x + y/10) 0 (t::l) in\n printf \"%d\\n\" s1\n end\n else\n begin\n let s1 = List.fold_left (fun x y -> x + y/10) 0 l in\n printf \"%d\\n\" s1\n end\n"}], "negative_code": [{"source_code": "let cmp x y =\n let a = 10 - (x mod 10)\n and b = 10 - (y mod 10) in\n compare a b\n\nlet () = Scanf.scanf \"%d %d\\n\" (fun n k ->\n (* read initial skills *)\n let a = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n (* sort by distance from the next multiple of 10 *)\n Array.sort cmp a;\n\n (* calculate the possible improvement *)\n let (rating, rem) = Array.fold_left (fun (acc, rem) skill ->\n (* if we have enough skill points remaining, use them *)\n let diff = 10 - (skill mod 10) in\n if diff <= rem\n then (acc + (skill + diff) / 10, rem - diff)\n else (acc + skill / 10, rem)\n ) (0, k) a in\n\n Printf.printf \"%d\\n\" (rating + rem / 10))\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Int64;;\nopen Char;;\n\nlet (n,k) = Scanf.scanf \"%d %d \" (fun x y -> (x,y) )\n\nlet a = Array.make n 0\n\nlet _ =\n for i = 0 to (n-1) do\n let x = Scanf.scanf \"%d \" (fun x -> x) in\n a.(i) <- x\n done\n\nlet cmp x y =\n if x mod 10 = 0 then\n 1\n else\n begin\n let xi = x mod 10 in\n let yi = y mod 10 in\n if xi > yi then\n 1\n else\n begin\n if xi < yi then\n -1\n else 0\n end\n end\n in\n Array.fast_sort (fun x y -> cmp y x) a\n(*\nlet _ =\n Array.iter (fun x -> printf \"%d \" x) a\n *)\n\nexception BR\n\n let _ =\n let rk = ref k in\n try\n for i = 0 to (n-1) do\n if !rk <= 0 then\n raise BR\n else\n if !rk+a.(i) >= 100 then\n begin\n rk := !rk - (100-a.(i));\n a.(i) <- 100\n end\n else\n begin\n if !rk + (a.(i) mod 10) >= 10 then\n begin\n let tmp = !rk+a.(i) in\n let tmp2 = tmp - (tmp mod 10) in\n (\n rk := !rk - (tmp2 - a.(i));\n a.(i) <- tmp2\n )\n end\n else ()\n end\n done\n with BR -> ()\n\n(*\n let _ =\n print_endline \"\";\n Array.iter (fun x -> printf \"%d \" x) a\n *)\n\n let rslt =\n Array.fold_left (fun x y -> x + y/10) 0 a\n in\n printf \"%d \" rslt\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Int64;;\nopen Char;;\n\nlet (n,k) = Scanf.scanf \"%d %d \" (fun x y -> (x,y) )\n\nlet a = Array.make n 0\n\nlet _ = \n for i = 0 to (n-1) do\n let x = Scanf.scanf \"%d \" (fun x -> x) in\n a.(i) <- x\n done\n\nlet cmp x y = \n if x mod 10 = 0 then\n 1\n else begin\n let xi = x mod 10 in\n let yi = y mod 10 in\n if xi > yi then\n 1\n else if xi < yi then\n -1\n else 0\n end\n in\n Array.fast_sort (fun x y -> cmp x y) a\n\n (*\n let _ = \n Array.iter (fun x -> printf \"%d \" x) a\n *)\n\nexception BR\n\n let _ =\n let rk = ref k in\n try \n for i = 0 to (n-1) do\n if !rk <= 0 then\n raise BR\n else\n if !rk+a.(i) >= 100 then\n begin\n rk := !rk - (100-a.(i));\n a.(i) <- 100\n end\n else\n begin\n let tmp = !rk+a.(i) in\n let tmp2 = tmp - (tmp mod 10) in\n (\n rk := !rk - (tmp2 - a.(i));\n a.(i) <- tmp2\n )\n end\n done\n with BR -> ()\n\n let rslt = \n Array.fold_left (fun x y -> x + y/10) 0 a\n in \n printf \"%d \" rslt\n"}], "src_uid": "b4341e1b0ec0b7341fdbe6edfe81a0d4"} {"nl": {"description": "You are given $$$n$$$ strings $$$a_1, a_2, \\ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \\ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \\le n \\le 10$$$) and $$$m$$$ ($$$1 \\le m \\le 10$$$)\u00a0\u2014 the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print \"-1\" (\"minus one\", without quotes).", "sample_inputs": ["5\n2 4\nabac\nzbab\n2 4\naaaa\nbbbb\n3 3\nbaa\naaa\naab\n2 2\nab\nbb\n3 1\na\nb\nc"], "sample_outputs": ["abab\n-1\naaa\nab\nz"], "notes": "NoteThe first test case was explained in the statement.In the second test case, the answer does not exist."}, "positive_code": [{"source_code": "let split_string ?(pattern=\"\") = Str.split @@ Str.regexp pattern\nlet t = Scanf.sscanf (read_line ()) \"%d\" @@ fun t -> t\n\nlet () = for _ = 1 to t do\n let (n, m) = Scanf.sscanf (read_line ()) \"%d %d\" @@ fun n m -> (n, m) in\n let a = Array.init n @@ fun _ -> read_line () in\n let ans = Bytes.of_string a.(0) in\n let diff s t = Array.init m (fun i -> if s.[i] = t.[i] then 0 else 1) |> Array.fold_left (+) 0 in\n try\n for i = 0 to m - 1 do\n let ch = Bytes.get ans i in\n for j = 0 to 25 do\n Bytes.set ans i (char_of_int ((int_of_char 'a') + j));\n if List.for_all (fun str -> diff (Bytes.to_string ans) str < 2) (Array.to_list a) then begin\n print_endline @@ Bytes.to_string ans;\n raise Exit\n end\n done;\n Bytes.set ans i ch;\n done;\n print_endline \"-1\"\n with Exit -> ()\ndone"}], "negative_code": [{"source_code": "let split_string ?(pattern=\"\") = Str.split @@ Str.regexp pattern\nlet t = Scanf.sscanf (read_line ()) \"%d\" @@ fun t -> t\n\nlet rec for_all f = function\n | [] -> true\n | x :: xs -> f x && for_all f xs\n\nlet () = for _ = 1 to t do\n let (n, m) = Scanf.sscanf (read_line ()) \"%d %d\" @@ fun n m -> (n, m) in\n let a = Array.init n (fun _ -> read_line () |> split_string |> Array.of_list) in\n let tmp = Array.init m (fun i -> let arr = Array.init n (fun j -> a.(j).(i)) in Array.sort compare arr; arr) in\n let ans = (Array.init m @@ fun i -> tmp.(i).(0)) |> Array.to_list |> String.concat \"\" in\n let diff s t =\n let res = ref 0 in\n for i = 0 to m - 1 do\n if s.[i] <> t.[i] then res := !res + 1\n done;\n !res\n in\n print_endline @@ if for_all (fun arr -> \n let str = arr |> Array.to_list |> String.concat \"\" in\n diff str ans < 2\n ) (Array.to_list a) then ans\n else \"-1\"\ndone"}], "src_uid": "8d4cdf75f726b59a8fcc374e1417374a"} {"nl": {"description": "You're given a tree with $$$n$$$ vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) denoting the size of the tree. The next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ ($$$1 \\le u, v \\le n$$$) each, describing the vertices connected by the $$$i$$$-th edge. It's guaranteed that the given edges form a tree.", "output_spec": "Output a single integer $$$k$$$ \u2014 the maximum number of edges that can be removed to leave all connected components with even size, or $$$-1$$$ if it is impossible to remove edges in order to satisfy this property.", "sample_inputs": ["4\n2 4\n4 1\n3 1", "3\n1 2\n1 3", "10\n7 1\n8 4\n8 10\n4 7\n6 5\n9 3\n3 5\n2 10\n2 5", "2\n1 2"], "sample_outputs": ["1", "-1", "4", "0"], "notes": "NoteIn the first example you can remove the edge between vertices $$$1$$$ and $$$4$$$. The graph after that will have two connected components with two vertices in each.In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $$$-1$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let g = Array.make (n + 1) []\n and subtree = Array.make (n + 1) 1\n and visited = Array.make (n + 1) false\n and ans = ref 0 in\n let rec dfs v =\n if not visited.(v) then begin\n visited.(v) <- true;\n subtree.(v) <- List.fold_left (fun acc x ->\n if not visited.(x) then begin\n dfs x;\n acc + subtree.(x)\n end\n else acc\n ) 1 g.(v);\n if subtree.(v) mod 2 = 0 then incr ans\n end in\n for i = 1 to n - 1 do\n let a = read_int () and b = read_int () in\n g.(a) <- b::g.(a);\n g.(b) <- a::g.(b)\n done;\n dfs 1;\n if n mod 2 = 1 then printf \"-1\\n\"\n else printf \"%d\\n\" (!ans - 1)"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64,ist = Int64.(to_int,of_int,to_string)\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* input *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\texternal id : 'a -> 'a = \"%identity\"\n\tlet ( *< ) f g x = f (g x)\n\tlet ( *> ) f g x = g (f x)\n\tlet rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet fail _ = failwith \"fail\"\n\tlet dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n\tlet range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n\tlet cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n\tlet shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n\tlet binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n\t\tlet rec f0 ng ok =\n\t\t\tif labs (ok - ng) <= 1L then ok\n\t\t\telse let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n\t\tin f0 (ng-1L*d) (ok+1L*d)\n\tlet lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n\tlet upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n\tlet equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n\tlet rec fix f x = f (fix f) x\n\t(* imperative *)\n\tlet rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n\tlet repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n\tlet repm f t ?(stride=1L) m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n\tlet repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n\tlet repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n\tlet repim f t ?(stride=1) m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n\tlet rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n\tlet repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n\tlet repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n\tlet repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n\t(* output *)\n\tlet print_list_mle f ls = string_of_list f ls |> print_endline\n\tlet print_array_mle f a = string_of_array f a |> print_endline\n\tlet print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\tlet print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\t(* debug *)\n\tlet dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n\tlet dump_i64_list ls = print_list ist ls\n\tlet dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n\tlet n=get_i64 0 in let n=i32 n in\n\tlet e=make n [] in\n\tlet visited = make n false in\n\trepi 2 n (fun _->\n\t\tlet u,v = get_2_i64 0 in\n\t\tlet u,v = i32 u-$1,i32 v-$1 in\n\t\te.(u) <- v::e.(u);\n\t\te.(v) <- u::e.(v);\n\t);\n\tlet res = ref 0L in\n\tlet s = fix (fun f i -> \n\t\tvisited.(i) <- true;\n\t\tList.fold_left (fun sum j->\n\t\t\tif visited.(j) then sum\n\t\t\telse (\n\t\t\t\tlet v = f j in\n\t\t\t\tif v %$ 2 = 0 then (\n\t\t\t\t\tres += 1L; sum\n\t\t\t\t) else sum +$ v\n\t\t\t)\n\t\t) 1 e.(i)\n\t) 0 in\n\tif s %$ 2 = 0 then printf \"%Ld\\n\" !res\n\telse printf \"-1\\n\"\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let g = Array.make (n + 1) []\n and subtree = Array.make (n + 1) 1\n and visited = Array.make (n + 1) false\n and ans = ref 0\n and err = ref false in\n let rec dfs v =\n let flag = ref false in\n if not visited.(v) then begin\n visited.(v) <- true;\n subtree.(v) <- List.fold_left (fun acc x ->\n if not visited.(x) then begin\n dfs x;\n if subtree.(x) mod 2 = 1 then flag := true;\n acc + subtree.(x)\n end\n else acc\n ) 1 g.(v);\n if subtree.(v) mod 2 = 0 then incr ans\n else if !flag then err := true;\n end in\n for i = 1 to n - 1 do\n let a = read_int () and b = read_int () in\n g.(a) <- b::g.(a);\n g.(b) <- a::g.(b)\n done;\n dfs 1;\n if !err then printf \"-1\\n\"\n else printf \"%d\\n\" (!ans - 1)"}], "src_uid": "711896281f4beff55a8826771eeccb81"} {"nl": {"description": "There are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c1,\u2009c2,\u2009...,\u2009cn. The Old Peykan wants to travel from city c1 to cn using roads. There are (n\u2009-\u20091) one way roads, the i-th road goes from city ci to city ci\u2009+\u20091 and is di kilometers long.The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.Each city ci (except for the last city cn) has a supply of si liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly k hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times. Initially (at time zero) the Old Peykan is at city c1 and s1 liters of fuel is transferred to it's empty tank from c1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.Find the minimum time the Old Peykan needs to reach city cn.", "input_spec": "The first line of the input contains two space-separated integers m and k (1\u2009\u2264\u2009m,\u2009k\u2009\u2264\u20091000). The value m specifies the number of roads between cities which is equal to n\u2009-\u20091. The next line contains m space-separated integers d1,\u2009d2,\u2009...,\u2009dm (1\u2009\u2264\u2009di\u2009\u2264\u20091000) and the following line contains m space-separated integers s1,\u2009s2,\u2009...,\u2009sm (1\u2009\u2264\u2009si\u2009\u2264\u20091000).", "output_spec": "In the only line of the output print a single integer \u2014 the minimum time required for The Old Peykan to reach city cn from city c1.", "sample_inputs": ["4 6\n1 2 5 2\n2 3 3 4", "2 3\n5 6\n5 5"], "sample_outputs": ["10", "14"], "notes": "NoteIn the second sample above, the Old Peykan stays in c1 for 3 hours."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let d = Array.make m 0 in\n let s = Array.make m 0 in\n let () =\n for i = 0 to m - 1 do\n d.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 0 to m - 1 do\n s.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let b = ref 0 in\n let res = ref 0 in\n let f = ref 0 in\n for i = 0 to m - 1 do\n b := max !b s.(i);\n f := !f + s.(i);\n if !f < d.(i) then (\n\tlet t = (d.(i) - !f - 1) / !b + 1 in\n\t (*Printf.printf \"asd %d %d %d\\n\" i d.(i) t;*)\n\t res := !res + k * t;\n\t f := !f + !b * t;\n );\n f := !f - d.(i);\n res := !res + d.(i);\n done;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [], "src_uid": "94f84b89e98228de170ae68c5cb8f375"} {"nl": {"description": "Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1,\u2009a2,\u2009...,\u2009an of length n, that the following condition fulfills: a2\u2009-\u2009a1\u2009=\u2009a3\u2009-\u2009a2\u2009=\u2009a4\u2009-\u2009a3\u2009=\u2009...\u2009=\u2009ai\u2009+\u20091\u2009-\u2009ai\u2009=\u2009...\u2009=\u2009an\u2009-\u2009an\u2009-\u20091.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n\u2009+\u20091 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cards. The next line contains the sequence of integers \u2014 the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108.", "output_spec": "If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples).", "sample_inputs": ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"], "sample_outputs": ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"], "notes": null}, "positive_code": [{"source_code": "exception Infinite;;\n\nmodule IntSet = Set.Make (\n struct\n let compare = Pervasives.compare\n type t = int\n end\n);;\n\nlet differences a =\n let n = Array.length a in\n let rec aux i acc = \n if i < n then\n aux (i + 1) (IntSet.add (a.(i) - a.(i - 1)) acc)\n else\n acc\n in\n IntSet.elements (aux 1 IntSet.empty)\n;;\n\ntype 'a option = None | Some of 'a;;\nlet is_none = function\n | None -> true\n | Some x -> false\n;;\n\nlet find_possible_cards a =\n let () = Array.sort compare a in\n let n = Array.length a in\n let diff = differences a in\n let try_inside x =\n let rec loop i used =\n if i > n - 2 then used\n else if x = a.(i + 1) - a.(i) then loop (i + 1) used\n else if x * 2 = a.(i + 1) - a.(i) && is_none used then\n loop (i + 1) (Some (a.(i) + x))\n else None\n in\n match loop 0 None with\n | None -> []\n | Some x -> [x]\n in\n match diff with\n | [] -> raise Infinite\n | [0] -> [a.(0)]\n | [x] -> (a.(0) - x) :: (a.(n - 1) + x) :: try_inside (x / 2)\n | [x; y] -> (try_inside (x / 2)) @ (try_inside (y / 2))\n | _ -> []\n;;\n\nlet main () =\n let n = Scanf.scanf \"%d\" (fun x -> x) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n try\n Scanf.scanf \" %d\" (Array.set a i)\n with End_of_file -> ();\n done;\n try\n let answer = find_possible_cards a in\n Printf.printf \"%d\\n\" (List.length answer);\n List.iter (fun x -> Printf.printf \"%d \" x) (List.sort compare answer)\n with Infinite ->\n Printf.printf \"-1\"\n;;\nlet _ = main ()\n"}], "negative_code": [{"source_code": "exception Infinite;;\n\nmodule IntSet = Set.Make (\n struct\n let compare = Pervasives.compare\n type t = int\n end\n);;\n\nlet differences a =\n let n = Array.length a in\n let rec aux i acc = \n if i < n then\n aux (i + 1) (IntSet.add (a.(i) - a.(i - 1)) acc)\n else\n acc\n in\n IntSet.elements (aux 1 IntSet.empty)\n;;\n\ntype 'a option = None | Some of 'a;;\nlet is_none = function\n | None -> true\n | Some x -> false\n;;\n\nlet find_possible_cards a =\n let () = Array.sort compare a in\n let n = Array.length a in\n let diff = differences a in\n let try_inside x =\n let rec loop i used =\n if i > n - 2 then used\n else if x = a.(i + 1) - a.(i) then loop (i + 1) used\n else if x * 2 = a.(i + 1) - a.(i) && is_none used then\n loop (i + 1) (Some (a.(i) + x))\n else None\n in\n match loop 0 None with\n | None -> []\n | Some x -> [x]\n in\n match diff with\n | [] -> raise Infinite\n | [x] -> (a.(0) - x) :: (a.(n - 1) + x) :: try_inside (x / 2)\n | [x; y] -> (try_inside (x / 2)) @ (try_inside (y / 2))\n | _ -> []\n;;\n\nlet main () =\n let n = Scanf.scanf \"%d\" (fun x -> x) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n try\n Scanf.scanf \" %d\" (Array.set a i)\n with End_of_file -> ();\n done;\n try\n let answer = find_possible_cards a in\n Printf.printf \"%d\\n\" (List.length answer);\n List.iter (fun x -> Printf.printf \"%d \" x) answer\n with Infinite ->\n Printf.printf \"-1\"\n;;\nlet _ = main ()\n"}, {"source_code": "exception Infinite;;\n\nmodule IntSet = Set.Make (\n struct\n let compare = Pervasives.compare\n type t = int\n end\n);;\n\nlet differences a =\n let n = Array.length a in\n let rec aux i acc = \n if i < n then\n aux (i + 1) (IntSet.add (a.(i) - a.(i - 1)) acc)\n else\n acc\n in\n IntSet.elements (aux 1 IntSet.empty)\n;;\n\ntype 'a option = None | Some of 'a;;\nlet is_none = function\n | None -> true\n | Some x -> false\n;;\n\nlet find_possible_cards a =\n let () = Array.sort compare a in\n let n = Array.length a in\n let diff = differences a in\n let try_inside x =\n let rec loop i used =\n if i > n - 2 then used\n else if x = a.(i + 1) - a.(i) then loop (i + 1) used\n else if x * 2 = a.(i + 1) - a.(i) && is_none used then\n loop (i + 1) (Some (a.(i) + x))\n else None\n in\n match loop 0 None with\n | None -> []\n | Some x -> [x]\n in\n match diff with\n | [] -> raise Infinite\n | [x] -> (a.(0) - x) :: (a.(n - 1) + x) :: try_inside (x / 2)\n | [x; y] -> (try_inside (x / 2)) @ (try_inside (y / 2))\n | _ -> []\n;;\n\nlet main () =\n let n = Scanf.scanf \"%d\" (fun x -> x) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n try\n Scanf.scanf \" %d\" (Array.set a i)\n with End_of_file -> ();\n done;\n try\n let answer = find_possible_cards a in\n Printf.printf \"%d\\n\" (List.length answer);\n List.iter (fun x -> Printf.printf \"%d \" x) (List.sort compare answer)\n with Infinite ->\n Printf.printf \"-1\"\n;;\nlet _ = main ()\n"}], "src_uid": "e3ca8338beb8852c201be72650e9aabd"} {"nl": {"description": "Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 200\\,000$$$) \u2014 the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10\\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.", "output_spec": "Print the index of the day when Polycarp will celebrate the equator.", "sample_inputs": ["4\n1 3 2 1", "6\n2 2 2 2 2 2"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training."}, "positive_code": [{"source_code": "(* Codeforces 962 A Equator - TODO *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet rec sumlist sm l = match l with\n| [] -> sm\n| h :: t -> \n\tlet nsm = Int64.add (Int64.of_int h) sm in\n\tsumlist nsm t;;\n\nlet rec limidx sm lim idx l = match l with\n| [] -> (idx + 1)\n| h :: t ->\n\tlet nidx = idx + 1 in\n\tlet nsm = Int64.add (Int64.of_int h) sm in\n\t(*let _ = begin Printf.printf \"nsm lim = %Ld %Ld\\n\" nsm lim end in *)\n\tif (Int64.compare nsm lim) >= 0 then nidx\n\telse limidx nsm lim nidx t;; \n\nlet main() =\n\tlet n = gr () in\n\tlet a = readlist n [] in\n\tlet a = List.rev a in\n\tlet sum = sumlist Int64.zero a in\n\tlet two = Int64.succ Int64.one in \n\tlet lim = Int64.div (Int64.succ sum) two in\n\tlet equator = limidx Int64.zero lim 0 a in\n\tbegin\n\t\tprint_int equator;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}], "negative_code": [], "src_uid": "241157c465fe5dd96acd514010904321"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$, both consisting of $$$n$$$ integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$; $$$i \\neq j$$$) and swap $$$a_i$$$ with $$$a_j$$$ and $$$b_i$$$ with $$$b_j$$$. You have to perform the swap in both arrays.You are allowed to perform at most $$$10^4$$$ moves (possibly, zero). Can you make both arrays sorted in a non-decreasing order at the end? If you can, print any sequence of moves that makes both arrays sorted.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$)\u00a0\u2014 the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the first array. The third line contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le n$$$)\u00a0\u2014 the second array.", "output_spec": "For each testcase, print the answer. If it's impossible to make both arrays sorted in a non-decreasing order in at most $$$10^4$$$ moves, print -1. Otherwise, first, print the number of moves $$$k$$$ $$$(0 \\le k \\le 10^4)$$$. Then print $$$i$$$ and $$$j$$$ for each move $$$(1 \\le i, j \\le n$$$; $$$i \\neq j)$$$. If there are multiple answers, then print any of them. You don't have to minimize the number of moves.", "sample_inputs": ["3\n\n2\n\n1 2\n\n1 2\n\n2\n\n2 1\n\n1 2\n\n4\n\n2 3 1 2\n\n2 3 2 3"], "sample_outputs": ["0\n-1\n3\n3 1\n3 2\n4 3"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f) \nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () =\n\n let cases = read_int()in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n let b = Array.init n read_int in\n\n if exists 0 (n-2) (fun i -> exists i (n-1) (fun j ->\n ((compare a.(i) a.(j)) * (compare b.(i) b.(j))) = -1))\n then printf \"-1\\n\" else (\n let z = Array.init n (fun i -> a.(i),b.(i),i) in\n Array.sort compare z;\n let get3rd (a,b,c) = c in\n let zinv = Array.make n 0 in\n for i=0 to n-1 do\n\tzinv.(get3rd(z.(i))) <- i\n done;\n\n let rec find i j = if j = n then failwith \"bad find\"\n\telse if zinv.(j) = i then j else find i (j+1) in\n\n let swap i j =\n\tlet (ai,aj) = (zinv.(i),zinv.(j)) in\n\tzinv.(i) <- aj;\n\tzinv.(j) <- ai\n in\n\n(* printf \"z = \";\n for i=0 to n-1 do printf \"%d \" (get3rd z.(i)) done;\n print_newline();\n*)\n let swaplist = ref [] in\n for i=0 to n-1 do\n\tlet j = find i i in\n\tif j > i then (\n\t swaplist := (i,j):: (!swaplist);\n\t swap i j\n\t)\n done;\n printf \"%d\\n\" (List.length !swaplist);\n List.iter (fun (i,j) -> printf \"%d %d\\n\" (i+1) (j+1)) (List.rev !swaplist)\n )\n done\n"}], "negative_code": [], "src_uid": "c1f13141a70c7b9228015c0382c7ca71"} {"nl": {"description": "Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is cij.Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.", "input_spec": "The first line contains two integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of streets and avenues in Munhattan. Each of the next n lines contains m integers cij (1\u2009\u2264\u2009cij\u2009\u2264\u2009109) \u2014 the cost of the dinner in the restaurant on the intersection of the i-th street and the j-th avenue.", "output_spec": "Print the only integer a \u2014 the cost of the dinner for Jack and Emma.", "sample_inputs": ["3 4\n4 1 3 5\n2 2 2 2\n5 4 5 1", "3 3\n1 2 3\n2 3 1\n3 1 2"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first example if Emma chooses the first or the third streets Jack can choose an avenue with the cost of the dinner 1. So she chooses the second street and Jack chooses any avenue. The cost of the dinner is 2.In the second example regardless of Emma's choice Jack can choose a restaurant with the cost of the dinner 1."}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\n\nlet _ = \n let (n, m) = read2 () in\n let maxi = ref 0 in\n for i=1 to n do\n let mini = ref max_int in\n for i=1 to m-1 do\n Scanf.scanf \"%d \" ( fun x -> if x < !mini then mini := x )\n done;\n Scanf.scanf \"%d\\n\" ( fun x -> if x < !mini then mini := x );\n if !mini > !maxi then maxi := !mini;\n done;\n Printf.printf \"%d\\n\" !maxi ;;\n\n\n"}, {"source_code": "let xint() = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () = \n let n = xint() and m = xint() in\n let cost = ref 0 in\n for i = 0 to n - 1 do\n let tmp = ref 1000000000 in\n for j = 0 to m - 1 do\n let x = xint() in\n tmp := if x < !tmp then x else !tmp;\n done;\n cost := if !cost < !tmp then !tmp else !cost;\n done;\n Printf.printf \"%d\\n\" !cost;\n"}], "negative_code": [], "src_uid": "f2142bc2f44e5d8b77f8561c29038a73"} {"nl": {"description": "Not so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were $$$n$$$ types of candies, there are $$$a_i$$$ candies of the type $$$i$$$ ($$$1 \\le i \\le n$$$).Vlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there are several such types, he can choose any of them). To get the maximum pleasure from eating, Vlad does not want to eat two candies of the same type in a row.Help him figure out if he can eat all the candies without eating two identical candies in a row.", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of input test cases. The following is a description of $$$t$$$ test cases of input, two lines for each. The first line of the case contains the single number $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of types of candies in the package. The second line of the case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the number of candies of the type $$$i$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer, output \"YES\" if Vlad can eat candy as planned, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["6\n2\n2 3\n1\n2\n5\n1 6 2 4 3\n4\n2 2 2 1\n3\n1 1000000000 999999999\n1\n1"], "sample_outputs": ["YES\nNO\nNO\nYES\nYES\nYES"], "notes": "NoteIn the first example, it is necessary to eat sweets in this order: a candy of the type $$$2$$$, it is the most frequent, now $$$a = [2, 2]$$$; a candy of the type $$$1$$$, there are the same number of candies of the type $$$2$$$, but we just ate one, now $$$a = [1, 2]$$$; a candy of the type $$$2$$$, it is the most frequent, now $$$a = [1, 1]$$$; a candy of the type $$$1$$$, now $$$a = [0, 1]$$$; a candy of the type $$$2$$$, now $$$a = [0, 0]$$$ and the candy has run out.In the second example, all the candies are of the same type and it is impossible to eat them without eating two identical ones in a row.In the third example, first of all, a candy of the type $$$2$$$ will be eaten, after which this kind will remain the only kind that is the most frequent, and you will have to eat a candy of the type $$$2$$$ again."}, "positive_code": [{"source_code": "let parse s len = let rep = Array.make len 0 in\r\n let temp = ref \"\" in\r\n let count = ref 0 in\r\n for j = 0 to String.length s -1 do\r\n if s.[j] = ' ' then (rep.(!count)<-(int_of_string !temp) ; incr count ; temp := \"\")\r\n else (temp := !temp ^ (String.make 1 s.[j]))\r\n done; rep.(!count)<-(int_of_string !temp) ; rep ;;\r\n\r\n\r\nlet maxes tab = let max1 = ref tab.(0) in\r\n\tlet count = ref 0 in\r\n for i = 1 to Array.length tab -1 do\r\n\tif tab.(i) = !max1 then incr count;\r\n if tab.(i) > !max1 then (max1 := tab.(i); count := 0) ;\r\n\r\n done;\r\nlet toto = ref false in\r\n if !count <> 0 then true else begin\r\n\tfor i = 0 to Array.length tab -1 do\r\n\tif tab.(i) = (!max1 -1) then toto := true\r\ndone ; !toto\t\r\n\r\nend ;;\r\n \r\n\r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str = input_line stdin in \r\n let tab = parse str len in\r\n if len < 2 then (if tab.(0) = 1 then print_endline \"YES\" else print_endline \"NO\")\r\n else begin\r\n if maxes tab then print_endline \"YES\" else print_endline \"NO\" end\r\ndone;; "}, {"source_code": "open Printf\r\nopen Scanf\r\nmodule LL = Int64\r\nlet ( !! ) x = LL.to_int x\r\nlet ( ++ ) x y = LL.add x y\r\nlet ( -- ) x y = LL.sub x y\r\nlet ( ** ) x y = LL.mul x y\r\nlet ( // ) x y = LL.div x y\r\nlet ( %% ) x y = LL.rem x y\r\nlet ( >> ) x y = (LL.compare x y) > 0\r\nlet ( << ) x y = (LL.compare x y) < 0\r\nlet ( == ) x y = (LL.compare x y) = 0\r\nlet rd_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet rd_ll _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x)\r\nlet rd_arr n = Array.init n rd_ll\r\n\r\nlet solve n a = \r\n Array.sort LL.compare a;\r\n let dx = \r\n if n = 1 then a.(0)\r\n else a.(n-1) -- a.(n-2) in\r\n\r\n if dx >> 1L then \"NO\" else \"YES\"\r\n\r\nlet () =\r\n let t = read_int () in\r\n for i=1 to t do\r\n let n = rd_int () in\r\n let a = rd_arr n in\r\n printf \"%s\\n\" (solve n a)\r\n done;"}], "negative_code": [{"source_code": "let parse s len = let rep = Array.make len 0 in\r\n let temp = ref \"\" in\r\n let count = ref 0 in\r\n for j = 0 to String.length s -1 do\r\n if s.[j] = ' ' then (rep.(!count)<-(int_of_string !temp) ; incr count ; temp := \"\")\r\n else (temp := !temp ^ (String.make 1 s.[j]))\r\n done; rep.(!count)<-(int_of_string !temp) ; rep ;;\r\n\r\n\r\nlet maxes tab = let max1 = ref tab.(0) in\r\n\tlet count = ref 0 in\r\n for i = 1 to Array.length tab -1 do\r\n if tab.(i) > !max1 then (max1 := tab.(i); count := 0) ;\r\n\tif tab.(i) = !max1 then incr count;\r\n done;\r\nlet toto = ref false in\r\n if !count <> 0 then true else begin\r\n\tfor i = 0 to Array.length tab -1 do\r\n\tif tab.(i) = !max1 -1 then toto := true\r\ndone ; !toto\t\r\n\r\nend ;;\r\n \r\n\r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str = input_line stdin in \r\n let tab = parse str len in\r\n if len < 2 then (if tab.(0) = 1 then print_endline \"YES\" else print_endline \"NO\")\r\n else begin\r\n if maxes tab then print_endline \"YES\" else print_endline \"NO\" end\r\ndone;; "}, {"source_code": "let parse s len = let rep = Array.make len 0 in\r\n let temp = ref \"\" in\r\n let count = ref 0 in\r\n for j = 0 to String.length s -1 do\r\n if s.[j] = ' ' then (rep.(!count)<-(int_of_string !temp) ; incr count ; temp := \"\")\r\n else (temp := !temp ^ (String.make 1 s.[j]))\r\n done; rep.(!count)<-(int_of_string !temp) ; rep ;;\r\n\r\n\r\nlet maxes tab = let max1 = ref tab.(0) in let max2 = ref tab.(1) in\r\n for i = 2 to Array.length tab -1 do\r\n if !max1 < !max2 && tab.(i) > !max1 then max1 := tab.(i) ;\r\n if !max1 >= !max2 && tab.(i) > !max2 then max2 := tab.(i) ;\r\n done;\r\n !max1 = !max2 || !max1 = !max2 -1 || !max2 = !max1 -1;;\r\n \r\n\r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str = input_line stdin in \r\n let tab = parse str len in\r\n if len < 2 then (if tab.(0) = 1 then print_endline \"YES\" else print_endline \"NO\")\r\n else begin\r\n if maxes tab then print_endline \"YES\" else print_endline \"NO\" end\r\ndone;;\r\n \r\n \r\n "}, {"source_code": "let parse s len = let rep = Array.make len 0 in\r\n let temp = ref \"\" in\r\n let count = ref 0 in\r\n for j = 0 to String.length s -1 do\r\n if s.[j] = ' ' then (rep.(!count)<-(int_of_string !temp) ; incr count ; temp := \"\")\r\n else (temp := !temp ^ (String.make 1 s.[j]))\r\n done; rep.(!count)<-(int_of_string !temp) ; rep ;;\r\n\r\n\r\nlet maxes tab = let max1 = ref tab.(0) in let max2 = ref tab.(1) in\r\n for i = 2 to Array.length tab -1 do\r\n if !max1 < !max2 && tab.(i) > !max1 then max1 := tab.(i) ;\r\n if !max1 >= !max2 && tab.(i) > !max2 then max2 := tab.(i) ;\r\n done;\r\n !max1 = !max2 || !max1 = !max2 +1 || !max2 = !max1 +1;;\r\n \r\n\r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str = input_line stdin in \r\n let tab = parse str len in\r\n if len < 2 then (if tab.(0) = 1 then print_endline \"YES\" else print_endline \"NO\")\r\n else begin\r\n if maxes tab then print_endline \"YES\" else print_endline \"NO\" end\r\ndone;;\r\n \r\n \r\n "}], "src_uid": "8b926a19f380a56018308668c17c6928"} {"nl": {"description": "A frog is currently at the point $$$0$$$ on a coordinate axis $$$Ox$$$. It jumps by the following algorithm: the first jump is $$$a$$$ units to the right, the second jump is $$$b$$$ units to the left, the third jump is $$$a$$$ units to the right, the fourth jump is $$$b$$$ units to the left, and so on.Formally: if the frog has jumped an even number of times (before the current jump), it jumps from its current position $$$x$$$ to position $$$x+a$$$; otherwise it jumps from its current position $$$x$$$ to position $$$x-b$$$. Your task is to calculate the position of the frog after $$$k$$$ jumps.But... One more thing. You are watching $$$t$$$ different frogs so you have to answer $$$t$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of queries. Each of the next $$$t$$$ lines contain queries (one query per line). The query is described as three space-separated integers $$$a, b, k$$$ ($$$1 \\le a, b, k \\le 10^9$$$) \u2014 the lengths of two types of jumps and the number of jumps, respectively.", "output_spec": "Print $$$t$$$ integers. The $$$i$$$-th integer should be the answer for the $$$i$$$-th query.", "sample_inputs": ["6\n5 2 3\n100 1 4\n1 10 5\n1000000000 1 6\n1 1 1000000000\n1 1 999999999"], "sample_outputs": ["8\n198\n-17\n2999999997\n0\n1"], "notes": "NoteIn the first query frog jumps $$$5$$$ to the right, $$$2$$$ to the left and $$$5$$$ to the right so the answer is $$$5 - 2 + 5 = 8$$$.In the second query frog jumps $$$100$$$ to the right, $$$1$$$ to the left, $$$100$$$ to the right and $$$1$$$ to the left so the answer is $$$100 - 1 + 100 - 1 = 198$$$.In the third query the answer is $$$1 - 10 + 1 - 10 + 1 = -17$$$.In the fourth query the answer is $$$10^9 - 1 + 10^9 - 1 + 10^9 - 1 = 2999999997$$$.In the fifth query all frog's jumps are neutralized by each other so the answer is $$$0$$$.The sixth query is the same as the fifth but without the last jump so the answer is $$$1$$$."}, "positive_code": [{"source_code": "let ri () =\n Scanf.scanf \" %d\" (fun x -> x)\n\nlet read_input () =\n let a = ri() and\n b = ri() and\n c = ri() in\n (Int64.of_int a, Int64.of_int b, Int64.of_int c)\n\nlet res a b k = \n let res1 = Int64.mul (Int64.sub a b) (Int64.div k (Int64.of_int 2)) and\n res2 = Int64.mul (Int64.rem k (Int64.of_int 2)) a in\n (*print_int a; print_int b; print_int k; *)\n Int64.add res1 res2\n\nlet solveCase () =\n let (a, b, k) = read_input () in\n let x = res a b k in\n print_endline (Int64.to_string x)\n\nlet rec solve t =\n (*print_int t; print_endline \". test\"; *)\n if t=0 then ()\n else \n (solveCase ();\n solve (t-1))\n\nlet () =\n let t = read_int() in\n solve t\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Num;;\n\nlet mprint z =\n print_endline (Num.string_of_num z);;\n\n\nlet one_jump () = \n let (a,b,k) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d %d \" (fun x y z -> (x,y,z) ) in\n let k2 = (num_of_int (k/2)) in\n let aa = num_of_int a in\n let bb = num_of_int b in\n let rslt = k2*/aa -/ k2*/bb +/ (num_of_int (k mod 2)) */ aa in\n mprint rslt\n;;\n\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x) in\nfor i = 1 to n do\n one_jump ()\ndone\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let a,b,k = get_3_i64 0 in\n let n = k/2L in\n let d = a-b in\n printf \"%Ld\\n\" @@ d * n + (if k mod 2L = 1L then a else 0L)\n )\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Scanf;;\nopen String;;\n\nlet one_jump () = \n let (a,b,k) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d %d \" (fun x y z -> (x,y,z) ) in\n let k2 = k/2 in\n let rslt = k2*a - k2*b + (k mod 2) * a in\n print_int rslt; print_string \"\\n\"\n;;\n\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x) in\nfor i = 1 to n do\n one_jump ()\ndone\n"}], "src_uid": "1f435ba837f59b007167419896c836ae"} {"nl": {"description": "A string is binary, if it consists only of characters \"0\" and \"1\".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string \"010\" has six substrings: \"0\", \"1\", \"0\", \"01\", \"10\", \"010\". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters \"1\".", "input_spec": "The first line contains the single integer k (0\u2009\u2264\u2009k\u2009\u2264\u2009106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.", "output_spec": "Print the single number \u2014 the number of substrings of the given string, containing exactly k characters \"1\". Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["1\n1010", "2\n01010", "100\n01010"], "sample_outputs": ["6", "4", "0"], "notes": "NoteIn the first sample the sought substrings are: \"1\", \"1\", \"10\", \"01\", \"10\", \"010\".In the second sample the sought substrings are: \"101\", \"0101\", \"1010\", \"01010\"."}, "positive_code": [{"source_code": "let ( +:), ( *:), ( /:), (!<) = Int64.add, Int64.mul, Int64.div, Int64.of_int\n\nlet _ =\n let main () =\n let k = read_int () in\n let s = read_line () in\n let len = String.length s in\n let arr = Array.create (len + 1) 0 in\n let rec loop pos i acc =\n if pos = len then (arr.(i) <- acc; i + 1) else\n if s.[pos] = '0' then loop (pos + 1) i (acc + 1) else\n (arr.(i) <- acc; loop (pos + 1) (i + 1) 0)\n in\n let m = loop 0 0 0 in\n let rec loop i acc =\n if i + k >= m then acc else\n let acc = acc +: if k = 0 then (!< (arr.(i)) *: !< (arr.(i) + 1)) /: 2L\n else (!< (arr.(i) + 1) *: !< (arr.(i + k) + 1))\n in\n loop (i + 1) acc\n in\n let r = loop 0 0L in\n Printf.printf \"%Ld\\n\" r\n in\n main ()\n"}], "negative_code": [], "src_uid": "adc43f273dd9b3f1c58b052a34732a50"} {"nl": {"description": "In Berland, there is the national holiday coming \u2014 the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.", "input_spec": "The first line contains two space-separated integers n (3\u2009\u2264\u2009n\u2009\u2264\u2009105) and m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers \u2014 the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.", "output_spec": "Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.", "sample_inputs": ["7 3\n1 2 3\n1 4 5\n4 6 7", "9 3\n3 6 9\n2 5 8\n1 4 7", "5 2\n4 1 5\n3 1 2"], "sample_outputs": ["1 2 3 3 2 2 1", "1 1 1 2 2 2 3 3 3", "2 3 1 1 3"], "notes": null}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet other = function\n| 1 -> (2, 3)\n| 2 -> (3, 1)\n| 3 -> (1, 2)\n| _ -> assert false\n;;\n\nlet pick colors (x, xc) (y, yc) (z, zc) =\n if xc >= 0 then let yc, zc = other xc in (y, yc), (z, zc)\n else if yc >= 0 then let xc, zc = other yc in (x, xc), (z, zc)\n else if zc >= 0 then let xc, yc = other zc in (x, xc), (y, yc)\n else begin\n colors.(x) <- 1; colors.(y) <- 2; colors.(z) <- 3;\n raise Exit\n end\n;;\n \nlet () =\n let n, m = Scanf.scanf \"%d %d \" (fun x y -> x, y) in\n let ds = fold_for 0 m ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d %d %d \" (fun x y z -> x - 1, y - 1, z - 1) :: acc) |> List.rev in\n let colors = Array.create n (-1) in\n List.iter ds ~f:(fun (x, y, z) ->\n try\n let (y, yc), (z, zc) = pick colors (x, colors.(x)) (y, colors.(y)) (z, colors.(z)) in\n colors.(y) <- yc; colors.(z) <- zc\n with\n | Exit -> ());\n Array.iter colors ~f:(fun x -> Printf.printf \"%d \" x);\n print_endline \"\";\n;;\n"}], "negative_code": [], "src_uid": "ee523bb4da5cb794e05fb62b7da8bb89"} {"nl": {"description": "Let's denote correct match equation (we will denote it as CME) an equation $$$a + b = c$$$ there all integers $$$a$$$, $$$b$$$ and $$$c$$$ are greater than zero.For example, equations $$$2 + 2 = 4$$$ (||+||=||||) and $$$1 + 2 = 3$$$ (|+||=|||) are CME but equations $$$1 + 2 = 4$$$ (|+||=||||), $$$2 + 2 = 3$$$ (||+||=|||), and $$$0 + 1 = 1$$$ (+|=|) are not.Now, you have $$$n$$$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if $$$n = 2$$$, you can buy two matches and assemble |+|=||, and if $$$n = 5$$$ you can buy one match and assemble ||+|=|||. Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer $$$q$$$ independent queries.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$)\u00a0\u2014 the number of queries. The only line of each query contains one integer $$$n$$$ ($$$2 \\le n \\le 10^9$$$)\u00a0\u2014 the number of matches.", "output_spec": "For each test case print one integer in single line\u00a0\u2014 the minimum number of matches which you have to buy for assembling CME. ", "sample_inputs": ["4\n2\n5\n8\n11"], "sample_outputs": ["2\n1\n0\n1"], "notes": "NoteThe first and second queries are explained in the statement.In the third query, you can assemble $$$1 + 3 = 4$$$ (|+|||=||||) without buying matches.In the fourth query, buy one match and assemble $$$2 + 4 = 6$$$ (||+||||=||||||)."}, "positive_code": [{"source_code": "let _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let m = int_of_string (input_line stdin) in\n if m = 2 then\n Format.printf \"2@.\"\n else if m mod 2 = 0 then\n Format.printf \"0@.\"\n else\n Format.printf \"1@.\"\n done\n"}], "negative_code": [], "src_uid": "178876bfe161ba9ccfd80c9310f75cbc"} {"nl": {"description": "There are $$$n$$$ boxes with different quantities of candies in each of them. The $$$i$$$-th box has $$$a_i$$$ candies inside.You also have $$$n$$$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none) candies from each box so that all boxes have the same quantity of candies in them. Note that you may eat a different number of candies from different boxes and you cannot add candies to any of the boxes.What's the minimum total number of candies you have to eat to satisfy the requirements?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 50$$$)\u00a0\u2014 the number of boxes you have. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq 10^7$$$)\u00a0\u2014 the quantity of candies in each box.", "output_spec": "For each test case, print a single integer denoting the minimum number of candies you have to eat to satisfy the requirements.", "sample_inputs": ["5\n\n5\n\n1 2 3 4 5\n\n6\n\n1000 1000 5 1000 1000 1000\n\n10\n\n1 2 3 5 1 2 7 9 13 5\n\n3\n\n8 8 8\n\n1\n\n10000000"], "sample_outputs": ["10\n4975\n38\n0\n0"], "notes": "NoteFor the first test case, you can eat $$$1$$$ candy from the second box, $$$2$$$ candies from the third box, $$$3$$$ candies from the fourth box and $$$4$$$ candies from the fifth box. Now the boxes have $$$[1, 1, 1, 1, 1]$$$ candies in them and you ate $$$0 + 1 + 2 + 3 + 4 = 10$$$ candies in total so the answer is $$$10$$$.For the second test case, the best answer is obtained by making all boxes contain $$$5$$$ candies in them, thus eating $$$995 + 995 + 0 + 995 + 995 + 995 = 4975$$$ candies in total."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \" %d\" (fun x -> x);;\r\nlet rec getInputs total m = function\r\n | 0 -> total, m\r\n | n -> \r\n let box = read () in\r\n getInputs \r\n (total+box) \r\n (if (box 0\r\n | n ->\r\n let numBoxes = read () in\r\n let totalAndMin = getInputs 0 (int_of_float 10e7) numBoxes in\r\n match totalAndMin with\r\n | total, m ->\r\n print_int (\r\n total - (m*numBoxes)\r\n );\r\n print_newline ();\r\n outputResult (n-1)\r\n;;\r\noutputResult (read ());;"}], "negative_code": [{"source_code": "let read () = Scanf.scanf \" %d\" (fun x -> x);;\r\nlet rec getInputs total m = function\r\n | 0 -> total, m\r\n | n -> \r\n let box = read () in\r\n getInputs \r\n (total+box) \r\n (if (box 0\r\n | n ->\r\n let totalAndMin = getInputs 0 (int_of_float 10e7) (read ()) in\r\n match totalAndMin with\r\n | total, m ->\r\n print_int (\r\n total - (m*n)\r\n );\r\n print_newline ();\r\n outputResult (n-1)\r\n;;\r\noutputResult (read ());;"}], "src_uid": "20dd260775ea71b1fb5b42bcac90a6f2"} {"nl": {"description": "Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i,\u2009j between 1 and n, he wrote the number ai,\u2009j\u2009=\u2009min(pi,\u2009pj). He writes ai,\u2009i\u2009=\u20090 for all integer i from 1 to n.Bob gave you all the values of ai,\u2009j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.", "input_spec": "The first line of the input will contain a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u200950). The next n lines will contain the values of ai,\u2009j. The j-th number on the i-th line will represent ai,\u2009j. The i-th number on the i-th line will be 0. It's guaranteed that ai,\u2009j\u2009=\u2009aj,\u2009i and there is at least one solution consistent with the information given.", "output_spec": "Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them.", "sample_inputs": ["2\n0 1\n1 0", "5\n0 2 2 1 2\n2 0 4 1 3\n2 4 0 1 3\n1 1 1 0 1\n2 3 3 1 0"], "sample_outputs": ["2 1", "2 5 4 1 3"], "notes": "NoteIn the first case, the answer can be {1,\u20092} or {2,\u20091}.In the second case, another possible answer is {2,\u20094,\u20095,\u20091,\u20093}."}, "positive_code": [{"source_code": "Scanf.scanf \"%d\" (fun n ->\n let tab = Array.make n 0 and flag = ref true in\n for i = 0 to n-1 do\n let maxi = ref 0 in\n for j=0 to n-1 do\n Scanf.scanf \" %d\" (fun k -> maxi := max !maxi k);\n done;\n tab.(i) <- if !maxi = n-1 && !flag then (flag := false; n) else !maxi; \n done;\n for i = 0 to n-1 do Printf.printf \"%d%s\" (tab.(i)) (if i=n-1 then \"\" else \" \"); done\n)\n"}], "negative_code": [], "src_uid": "1524c658129aaa4175208b278fdc467c"} {"nl": {"description": "You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \\ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \\le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "For each test case, print the answer: \"YES\" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or \"NO\" otherwise.", "sample_inputs": ["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"], "sample_outputs": ["YES\nYES\nNO\nNO\nYES"], "notes": "NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$."}, "positive_code": [{"source_code": "let read_int () =\n Scanf.scanf \" %d\" (fun x -> x)\n\nlet rec fill acc = function\n | 0 -> acc\n | n -> fill (acc @ [read_int ()]) (n - 1)\n\nlet solve (n : int) : string =\n let rec f (l : int list) : string =\n match l with\n | [] \n | [_] -> \"YES\"\n | a :: b :: tl -> if (b - a) > 1 then \"NO\" else f ([b] @ tl)\n in f (List.sort compare (fill [] n))\n\nlet () =\n let t = read_int () in\n for i = 1 to t do\n let n = read_int () in\n Printf.printf \"%s\\n\" (solve n)\n done;\n"}, {"source_code": "open Printf\nopen Scanf\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet solve () = \n let n = read_int() in\n let arr = Array.init n read_int in\n Array.sort compare arr;\n let rec loop i = \n if i >= n then (\n printf \"YES\\n\";\n ) else if arr.(i) - arr.(i - 1) > 1 then (\n printf \"NO\\n\";\n ) else (\n loop (i + 1)\n )\n in\n loop 1\n\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n solve ()\n done"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet solve () = \n let n = read_int() in\n let arr = Array.init n read_int in\n Array.sort compare arr;\n for i = 1 to n - 1 do\n if arr.(i) - arr.(i - 1) > 1 then (\n printf \"NO\\n\";\n ) else if i = n - 1 then (\n printf \"YES\\n\"\n )\n done;\n ()\n\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n solve ()\n done"}, {"source_code": "open Printf\nopen Scanf\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet solve () = \n let n = read_int() in\n let arr = Array.init n read_int in\n Array.sort compare arr;\n let rec loop i = \n if i >= n - 1 then (\n printf \"YES\\n\";\n ) else if arr.(i) - arr.(i - 1) > 1 then (\n printf \"NO\\n\";\n ) else (\n loop (i + 1)\n )\n in\n loop 1\n\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n solve ()\n done"}], "src_uid": "ed449ba7c453a43e2ac5904dc0174530"} {"nl": {"description": "You are given two positive integers $$$n$$$ ($$$1 \\le n \\le 10^9$$$) and $$$k$$$ ($$$1 \\le k \\le 100$$$). Represent the number $$$n$$$ as the sum of $$$k$$$ positive integers of the same parity (have the same remainder when divided by $$$2$$$).In other words, find $$$a_1, a_2, \\ldots, a_k$$$ such that all $$$a_i>0$$$, $$$n = a_1 + a_2 + \\ldots + a_k$$$ and either all $$$a_i$$$ are even or all $$$a_i$$$ are odd at the same time.If such a representation does not exist, then report it.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$1 \\le n \\le 10^9$$$) and $$$k$$$ ($$$1 \\le k \\le 100$$$).", "output_spec": "For each test case print: YES and the required values $$$a_i$$$, if the answer exists (if there are several answers, print any of them); NO if the answer does not exist. The letters in the words YES and NO can be printed in any case.", "sample_inputs": ["8\n10 3\n100 4\n8 7\n97 2\n8 8\n3 10\n5 3\n1000000000 9"], "sample_outputs": ["YES\n4 2 4\nYES\n55 5 5 35\nNO\nNO\nYES\n1 1 1 1 1 1 1 1\nNO\nYES\n3 1 1\nYES\n111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111110 111111120"], "notes": null}, "positive_code": [{"source_code": "let re () = Scanf.scanf \" %d\" (fun x -> x) ;;\n\nopen List\nopen Printf\n\nlet solve () =\n let n = re () in\n let k = re () in\n if (n mod 2 = 0 && ((k mod 2 = 1 && n < 2 * k) || (k mod 2 = 0 && n < k))) || (n mod 2 = 1 && (n < k || k mod 2 = 0)) then printf \"NO\\n\"\n else let _ = printf \"YES\\n\" in\n for i = 1 to k - 1 do\n if n mod 2 = 0 then\n if k mod 2 = 1 then printf \"%d \" 2\n else printf \"%d \" 1\n else printf \"%d \" 1\n done;\n if n mod 2 = 0 then\n if k mod 2 = 1 then printf \"%d \\n\" (n - 2 * (k - 1))\n else printf \"%d \\n\" (n - (k - 1))\n else printf \"%d \\n\" (n - (k - 1))\n;;\n\nlet _ =\n let t = re () in\n for i = 1 to t do\n solve ()\n done\n;;\n\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n \nopen Printf\n \nlet init (x : int) (f : int -> 'a) : 'a list =\n let rec build k =\n if k = x then []\n else (f k) :: build (k + 1) in\n build 0\n;;\n\nlet run () = \n let n = scan_int () in\n let k = scan_int () in\n if n < k || (k mod 2 = 0 && n mod 2 = 1) then\n printf \"NO\\n\"\n else begin\n let lst = \n if n mod 2 = 1 then\n init k (fun x -> if x = 0 then n - k + 1 else 1)\n else if k mod 2 = 1 then\n init k (fun x -> if x = 0 then n - 2 * (k - 1) else 2)\n else\n init k (fun x -> if x = 0 then (n - k + 1) else 1) in\n if List.hd lst < 1 then printf \"NO\\n\"\n else begin\n printf \"YES\\n\";\n List.iter (printf \"%d \") lst;\n print_endline \"\";\n end\n end\n;;\n \nlet () =\n let t = scan_int () in\n for i = 1 to t do\n run ()\n done\n;;\n"}, {"source_code": "(* Codeforces 1352 B Same Parity Summands train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec repeat a n = match n with\n | 0 -> []\n | _ -> a :: repeat a (n-1);;\n\nlet rec repeat2 o d k = match k with\n\t| 0 -> []\n\t| _ -> \n\t\tif o == 0 then repeat d k\n\t\telse\n\t\t\t(2 + d) :: repeat2 (o - 2) d (k - 1);;\n\nlet rec summands n k = \n\tif k == 1 then [ n ]\n\telse if n < k then []\n else if n == k then repeat 1 k\n else if n == (k+1) then []\n\telse if (n mod 2) == 1 && (k mod 2) == 0 then []\n\telse\n\t\tlet o = n mod k in\n\t\tlet d = n / k in\n\t\tif (o mod 2) == 0 then\t(d + o) :: repeat d (k-1)\n\t\telse if d == 1 then []\n\t\telse \n\t\t\trepeat2 (o + k) (d - 1) k;;\t\t\n \nlet do_one () = \n let n = gr () in\n let k = gr () in\n\t\tlet suml = summands n k in \n\t\tif (List.length suml) == 0 then print_string \"NO\\n\"\n\t\telse\n\t\t\tbegin\n\t\t\t\tprint_string \"YES\\n\";\n\t\t\t\tprintlisti suml;\n\t\t\t\tprint_string \"\\n\"\n\t\t\tend;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [], "src_uid": "6b94dcd088b0328966b54acefb5c6d22"} {"nl": {"description": "Polycarp doesn't like integers that are divisible by $$$3$$$ or end with the digit $$$3$$$ in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too.Polycarp starts to write out the positive (greater than $$$0$$$) integers which he likes: $$$1, 2, 4, 5, 7, 8, 10, 11, 14, 16, \\dots$$$. Output the $$$k$$$-th element of this sequence (the elements are numbered from $$$1$$$).", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \\le k \\le 1000$$$).", "output_spec": "For each test case, output in a separate line one integer $$$x$$$ \u2014 the $$$k$$$-th element of the sequence that was written out by Polycarp.", "sample_inputs": ["10\n1\n2\n3\n4\n5\n6\n7\n8\n9\n1000"], "sample_outputs": ["1\n2\n4\n5\n7\n8\n10\n11\n14\n1666"], "notes": null}, "positive_code": [{"source_code": "open Array;;\r\nlet readInt () = Scanf.scanf \" %d\" (fun i -> i);;\r\n \r\nlet print_number x = print_string (string_of_int x); print_newline();;\r\nlet ptr = ref 0;;\r\nlet a = make 10000 0;;\r\nfor i = 1 to 10000 do\r\n if i mod 3 <> 0 then \r\n if i mod 10 <> 3 then\r\n let () = \r\n ptr := !ptr + 1 in\r\n a.(!ptr) <- i\r\ndone;;\r\n\r\nlet t = readInt() in\r\nfor i = 1 to t do \r\n let k = readInt() in\r\n print_number a.(k)\r\ndone;;"}], "negative_code": [], "src_uid": "c37604d5d833a567ff284d7ce5eda059"} {"nl": {"description": "Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems \u2014 the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.A substring s[l... r] (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009|s|) of string s\u2009=\u2009s1s2... s|s| (where |s| is the length of string s) is string slsl\u2009+\u20091... sr.String x\u2009=\u2009x1x2... xp is lexicographically smaller than string y\u2009=\u2009y1y2... yq, if either p\u2009<\u2009q and x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xp\u2009=\u2009yp, or there exists such number r (r\u2009<\u2009p,\u2009r\u2009<\u2009q), that x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xr\u2009=\u2009yr and xr\u2009+\u20091\u2009<\u2009yr\u2009+\u20091. The string characters are compared by their ASCII codes.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200930) \u2014 the number of titles you've got to consider. Then follow n problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive.", "output_spec": "Print a string, consisting of lowercase English letters \u2014 the lexicographically minimum shortest original title.", "sample_inputs": ["5\nthreehorses\ngoodsubstrings\nsecret\nprimematrix\nbeautifulyear", "4\naa\nbdefghijklmn\nopqrstuvwxyz\nc"], "sample_outputs": ["j", "ab"], "notes": "NoteIn the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j.In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let s = Array.init n (fun i -> read_string()) in\n\n let h = Hashtbl.create 100 in\n\n for i=0 to n-1 do\n let ilen = String.length s.(i) in\n\tfor len = 1 to ilen do\n\t for start = 0 to ilen - len do\n\t let sub = String.sub s.(i) start len in\n\t Hashtbl.replace h sub true\n\t done\n\tdone\n done;\n\n let num_to_string k len = \n let a = String.create len in\n let n = ref k in\n\tfor i=len-1 downto 0 do\n\t a.[i] <- char_of_int ((int_of_char 'a') + (!n mod 26));\n\t n := !n / 26\n\tdone;\n\ta\n in\n\n let rec power a i = \n if i=0 then 1 else \n\tlet p = power a (i/2) in\n\t p * p * (if i land 1 = 0 then 1 else a)\n in\n\n let rec loop len = \n let hi = power 26 len in\n let rec loop2 i = if i=hi then \"0\" else \n\tlet ss = num_to_string i len in\n\t if Hashtbl.mem h ss then loop2 (i+1) else ss\n in\n let ans = loop2 0 in\n\tif ans = \"0\" then loop (len+1) else ans\n in\n\n Printf.printf \"%s\\n\" (loop 1)\n"}], "negative_code": [], "src_uid": "58fa5c2f270e2c34e8f9671d5ffdb9c8"} {"nl": {"description": "Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.", "input_spec": "In the first line of input there is one integer $$$n$$$ ($$$10^{3} \\le n \\le 10^{6}$$$). In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$\u00a0\u2014 the permutation of size $$$n$$$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$\u00a0\u2014 the size of the permutation. Then we randomly choose a method to generate a permutation\u00a0\u2014 the one of Petr or the one of Alex. Then we generate a permutation using chosen method.", "output_spec": "If the test is generated via Petr's method print \"Petr\" (without quotes). If the test is generated via Alex's method print \"Um_nik\" (without quotes).", "sample_inputs": ["5\n2 4 5 1 3"], "sample_outputs": ["Petr"], "notes": "NotePlease note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden."}, "positive_code": [{"source_code": "\nlet count_inversion (src: int array): int =\n let ninv = ref 0 in\n\n let merge lhs rhs: int array =\n let ll = Array.length lhs in\n let rl = Array.length rhs in\n let ret = Array.make (ll + rl) 0 in\n let rec loop idx i j =\n if i >= ll\n then begin\n Array.blit rhs j ret idx (rl - j)\n end else if j >= rl\n then begin\n (* ninv := !ninv + ll - i; *)\n Array.blit lhs i ret idx (ll - i)\n end else if lhs.(i) <= rhs.(j)\n then begin\n ret.(idx) <- lhs.(i);\n loop (idx + 1) (i + 1) j\n end else begin\n ret.(idx) <- rhs.(j);\n ninv := !ninv + ll - i;\n loop (idx + 1) i (j + 1)\n end\n in\n loop 0 0 0;\n ret\n in\n\n let rec do_sort (src: int array): int array =\n match Array.length src with\n | 0 | 1 -> src\n | n ->\n let m = n / 2 in\n let lhs = Array.sub src 0 m in\n let rhs = Array.sub src m (n - m) in\n let lhs = do_sort lhs in\n let rhs = do_sort rhs in\n merge lhs rhs\n in\n let sorted = do_sort src in\n (* Array.iter (fun i -> Printf.printf \"%d \" i) src; print_newline (); *)\n (* Array.iter (fun i -> Printf.printf \"%d \" i) sorted; print_newline (); *)\n !ninv\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun i -> i) in\n let src = Array.init n (fun _ -> Scanf.scanf \" %d\" (fun i -> i)) in\n let inv = count_inversion src in\n (* inv |> string_of_int |> print_endline; *)\n (if (inv - n * 3) mod 2 = 0\n then \"Petr\"\n else if (inv - (7 * n + 1)) mod 2 = 0\n then \"Um_nik\"\n else \"hhh\") |> print_endline\n"}], "negative_code": [{"source_code": "\nlet count_inversion (src: int array): int =\n let ninv = ref 0 in\n\n let merge lhs rhs: int array =\n let ll = Array.length lhs in\n let rl = Array.length rhs in\n let ret = Array.make (ll + rl) 0 in\n let rec loop idx i j =\n if i >= ll\n then begin\n Array.blit rhs j ret idx (rl - j)\n end else if j >= rl\n then begin\n ninv := !ninv + ll - i;\n Array.blit lhs i ret idx (ll - i)\n end else if lhs.(i) <= rhs.(j)\n then begin\n ret.(idx) <- lhs.(i);\n loop (idx + 1) (i + 1) j\n end else begin\n ret.(idx) <- rhs.(j);\n ninv := !ninv + 1;\n loop (idx + 1) i (j + 1)\n end\n in\n loop 0 0 0;\n ret\n in\n\n let rec do_sort (src: int array): int array =\n match Array.length src with\n | 0 | 1 -> src\n | n ->\n let m = n / 2 in\n let lhs = Array.sub src 0 m in\n let rhs = Array.sub src m (n - m) in\n let lhs = do_sort lhs in\n let rhs = do_sort rhs in\n merge lhs rhs\n in\n let sorted = do_sort src in\n (* Array.iter (fun i -> Printf.printf \"%d \" i) src; print_newline (); *)\n (* Array.iter (fun i -> Printf.printf \"%d \" i) sorted; print_newline (); *)\n !ninv\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun i -> i) in\n let src = Array.init n (fun _ -> Scanf.scanf \" %d\" (fun i -> i)) in\n let inv = count_inversion src in\n (* inv |> string_of_int |> print_endline; *)\n (if (inv - n * 3) mod 2 = 0\n then \"Petr\"\n else if (inv - (7 * n + 1)) mod 2 = 0\n then \"Um_nik\"\n else \"hhh\") |> print_endline\n"}, {"source_code": "\nlet count_inversion (src: int array): int =\n let ninv = ref 0 in\n\n let merge lhs rhs: int array =\n let ll = Array.length lhs in\n let rl = Array.length rhs in\n let ret = Array.make (ll + rl) 0 in\n let rec loop idx i j =\n if i >= ll\n then Array.blit rhs j ret idx (rl - j)\n else if j >= rl\n then Array.blit lhs i ret idx (ll - i)\n else if lhs.(i) <= rhs.(j)\n then begin\n ret.(idx) <- lhs.(i);\n loop (idx + 1) (i + 1) j\n end else begin\n ret.(idx) <- rhs.(j);\n ninv := !ninv + 1;\n loop (idx + 1) i (j + 1)\n end\n in\n loop 0 0 0;\n ret\n in\n\n let rec do_sort (src: int array): int array =\n match Array.length src with\n | 0 | 1 -> src\n | n ->\n let m = n / 2 in\n let lhs = Array.sub src 0 m in\n let rhs = Array.sub src m (n - m) in\n let lhs = do_sort lhs in\n let rhs = do_sort rhs in\n merge lhs rhs\n in\n let sorted = do_sort src in\n Array.iter (fun i -> Printf.printf \"%d \" i) src; print_newline ();\n Array.iter (fun i -> Printf.printf \"%d \" i) sorted; print_newline ();\n !ninv\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun i -> i) in\n let src = Array.init n (fun _ -> Scanf.scanf \" %d\" (fun i -> i)) in\n let inv = count_inversion src in\n (if inv = n * 3\n then \"Petr\"\n else if inv = 7 * n + 1\n then \"Um_nik\"\n else \"hhh\") |> print_endline\n"}], "src_uid": "a9cc20ba7d6e31706ab1743bdde97669"} {"nl": {"description": "You are given a keyboard that consists of $$$26$$$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.You have to type the word $$$s$$$ on this keyboard. It also consists only of lowercase Latin letters.To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $$$8$$$, $$$5$$$, $$$12$$$ and $$$15$$$, respectively. Therefore, it will take $$$|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$$$ units of time to type the word \"hello\". Determine how long it will take to print the word $$$s$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of a description contains a keyboard\u00a0\u2014 a string of length $$$26$$$, which consists only of lowercase Latin letters. Each of the letters from 'a' to 'z' appears exactly once on the keyboard. The second line of the description contains the word $$$s$$$. The word has a length from $$$1$$$ to $$$50$$$ letters inclusive and consists of lowercase Latin letters.", "output_spec": "Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to the test case is the minimal time it takes to type the word $$$s$$$ on the given keyboard.", "sample_inputs": ["5\nabcdefghijklmnopqrstuvwxyz\nhello\nabcdefghijklmnopqrstuvwxyz\ni\nabcdefghijklmnopqrstuvwxyz\ncodeforces\nqwertyuiopasdfghjklzxcvbnm\nqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\nqwertyuiopasdfghjklzxcvbnm\nabacaba"], "sample_outputs": ["13\n0\n68\n0\n74"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s\" (fun x -> x)\n\nlet explode s = \n let n = String.length s in\n let rec iter s idx n acc = \n if idx == n then\n acc\n else\n iter s (idx+1) n ((String.get s idx) :: acc) in\n List.rev (iter s 0 n [])\n\nlet time_to_type keyboard word = \n let keyboard_table = Hashtbl.create (String.length keyboard) in\n let add_char_to_map keyboard_table idx char = Hashtbl.add keyboard_table char (idx + 1) in\n let () = String.iteri (add_char_to_map keyboard_table) keyboard in\n let word_list = explode word in\n let rec count_moves keyboard_table word_list acc prev = \n match word_list with\n | [] -> acc\n | h::t -> count_moves keyboard_table t (acc + abs (prev - (Hashtbl.find keyboard_table h))) (Hashtbl.find keyboard_table h) in\n match word_list with\n | [] -> 0\n | h :: t -> count_moves keyboard_table t 0 (Hashtbl.find keyboard_table h)\n\nlet () = \n let cases = read_int() in\n for cases = 1 to cases do\n let keyboard = read_string() in\n let word = read_string() in\n printf \"%d\\n\" (time_to_type keyboard word)\n done"}], "negative_code": [], "src_uid": "7f9853be7ac857bb3c4eb17e554ad3f1"} {"nl": {"description": "The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings are the lexemes of the command line \u2014 the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command \" run.exe one, two . \", we give four lexemes to the Pindows command line: \"run.exe\", \"one,\", \"two\", \".\". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited \u2014 that is, for each occurrence of character \"\"\" we should be able to say clearly that the quotes are opening or closing. For example, as we run the command \"\"run.exe o\" \"\" \" ne, \" two . \" \" \", we give six lexemes to the Pindows command line: \"run.exe o\", \"\" (an empty string), \" ne, \", \"two\", \".\", \" \" (a single space).It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.You have a string that consists of uppercase and lowercase English letters, digits, characters \".,?!\"\" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character \"\"\" to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters.", "input_spec": "The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the \".,?!\"\" signs, or a space. It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme.", "output_spec": "In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the \"<\" (less) character to the left of your lexemes and the \">\" (more) character to the right. Print the lexemes in the order in which they occur in the command. Please, follow the given output format strictly. For more clarifications on the output format see the test samples.", "sample_inputs": ["\"RUn.exe O\" \"\" \" 2ne, \" two! . \" \"", "firstarg second \"\""], "sample_outputs": ["<RUn.exe O>\n<>\n< 2ne, >\n<two!>\n<.>\n< >", "<firstarg>\n<second>\n<>"], "notes": null}, "positive_code": [{"source_code": "(* CF Min Frac 281B TODO *)\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet debug = false;;\n\nlet cmd = rdln() ^ \" \";;\n\nlet rec prilexems lexems = match lexems with\n\t| [] -> ()\n\t| hd :: tl ->\n\t\t\tbegin\n\t\t\t\tprint_string \"<\";\n\t\t\t\tprint_string hd;\n\t\t\t\tprint_string \">\\n\";\n\t\t\t\tprilexems tl\n\t\t\tend;;\n\nlet scanbra s idx = (* idx pos exactly after bracket *)\n\tlet i1 = String.index_from s idx '\"' in\n\tlet lex = String.sub s idx (i1 - idx) in\n\t(lex, i1 +1);;\n\nlet scanspace s idx = (* idx - pos of char after space *)\n\tlet i1 = String.index_from s idx ' ' in\n\tlet lex = String.sub s idx (i1 - idx) in\n\t(lex, i1);;\n\nlet rec scancmd s idx acc =\n\tif idx >= String.length s then acc\n\telse\n\t\tlet c = s.[idx] in\n\t\tif c = ' ' then scancmd s (idx +1) acc\n\t\telse if c = '\"' then\n\t\t\tlet (lex, nextIdx) = scanbra s (idx +1) in\n\t\t\tscancmd s nextIdx (lex :: acc)\n\t\telse\n\t\t\tlet (lex, nextIdx) = scanspace s idx in\n\t\t\tscancmd s nextIdx (lex :: acc);;\n\nlet main() =\n\tlet ls = scancmd cmd 0 [] in\n\tlet rls = List.rev ls in\n\tprilexems rls;;\n\nmain ();;"}], "negative_code": [], "src_uid": "6c7858731c57e1b24c7a299a8eeab373"} {"nl": {"description": "You have $$$r$$$ red and $$$b$$$ blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet: has at least one red bean (or the number of red beans $$$r_i \\ge 1$$$); has at least one blue bean (or the number of blue beans $$$b_i \\ge 1$$$); the number of red and blue beans should differ in no more than $$$d$$$ (or $$$|r_i - b_i| \\le d$$$) Can you distribute all beans?", "input_spec": "The first line contains the single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains three integers $$$r$$$, $$$b$$$, and $$$d$$$ ($$$1 \\le r, b \\le 10^9$$$; $$$0 \\le d \\le 10^9$$$)\u00a0\u2014 the number of red and blue beans and the maximum absolute difference in each packet.", "output_spec": "For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).", "sample_inputs": ["4\n1 1 0\n2 7 3\n6 1 4\n5 4 0"], "sample_outputs": ["YES\nYES\nNO\nNO"], "notes": "NoteIn the first test case, you can form one packet with $$$1$$$ red and $$$1$$$ blue bean. The absolute difference $$$|1 - 1| = 0 \\le d$$$.In the second test case, you can form two packets: $$$1$$$ red and $$$4$$$ blue beans in the first packet and $$$1$$$ red and $$$3$$$ blue beans in the second one.In the third test case, since $$$b = 1$$$, you can form only one packet with $$$6$$$ red and $$$1$$$ blue beans. The absolute difference $$$|6 - 1| = 5 > d$$$.In the fourth test case, since $$$d = 0$$$ so each packet should contain the same number of red and blue beans, but $$$r \\neq b$$$."}, "positive_code": [{"source_code": "(** val add : int64 -> int64 -> int64 **)\r\n\r\nlet rec add = Int64.add\r\n\r\n(** val mul : int64 -> int64 -> int64 **)\r\n\r\nlet rec mul = Int64.mul\r\n\r\nmodule Nat =\r\n struct\r\n (** val leb : int64 -> int64 -> bool **)\r\n\r\n let rec leb = (fun x y -> Int64.compare x y <= 0)\r\n end\r\n\r\n(** val can_distribute : int64 -> int64 -> int64 -> bool **)\r\n\r\nlet can_distribute r b d =\r\n if Nat.leb b\r\n (mul r (add d ((fun x -> Int64.succ x) Int64.zero)))\r\n then Nat.leb r\r\n (mul b (add d ((fun x -> Int64.succ x) Int64.zero)))\r\n else false\r\n\r\nlet rec solve = function\r\n | 0 -> ()\r\n | n -> let (r,b,d) = Scanf.scanf \"%d %d %d\\n\" (fun a b c -> (Int64.of_int a, Int64.of_int b,Int64.of_int c)) in\r\n let ans = if can_distribute r b d then \"YES\" else \"NO\" in\r\n print_endline ans; \r\n solve (n-1)\r\n\r\nlet t = read_int();;\r\nsolve t;;\r\n"}, {"source_code": "\r\n(** val add : int -> int -> int **)\r\n\r\nlet rec add = Int64.add\r\n\r\n(** val mul : int -> int -> int **)\r\n\r\nlet rec mul = Int64.mul\r\n \r\nlet rec leq x y = Int64.compare x y <= 0\r\n\r\nmodule Nat =\r\n struct\r\n end\r\n\r\n(** val can_distribute : int -> int -> int -> bool **)\r\n\r\nlet can_distribute r b d =\r\n (&&) ((<=) b (mul r (add d (Int64.one))))\r\n ((<=) r (mul b (add d (Int64.one))))\r\n\r\nlet rec solve = function\r\n | 0 -> ()\r\n | n -> let (r,b,d) = Scanf.scanf \"%d %d %d\\n\" (fun a b c -> (Int64.of_int a, Int64.of_int b,Int64.of_int c)) in\r\n let ans = if can_distribute r b d then \"YES\" else \"NO\" in\r\n print_endline ans; \r\n solve (n-1)\r\n\r\nlet t = read_int();;\r\nsolve t;;\r\n"}], "negative_code": [{"source_code": "\r\n(** val add : int -> int -> int **)\r\n\r\nlet rec add = (+)\r\n\r\n(** val mul : int -> int -> int **)\r\n\r\nlet rec mul = ( * )\r\n\r\nmodule Nat =\r\n struct\r\n end\r\n\r\n(** val can_distribute : int -> int -> int -> bool **)\r\n\r\nlet can_distribute r b d =\r\n (&&) ((<=) b (mul r (add d (Pervasives.succ 0))))\r\n ((<=) r (mul b (add d (Pervasives.succ 0))))\r\n\r\nlet rec solve = function\r\n | 0 -> ()\r\n | n -> let (r,b,d) = Scanf.scanf \"%d %d %d\\n\" (fun a b c -> (a,b,c)) in\r\n let ans = if can_distribute r b d then \"YES\" else \"NO\" in\r\n print_endline ans; \r\n solve (n-1)\r\n\r\nlet t = read_int();;\r\nsolve t;;\r\n"}], "src_uid": "c0ad2a6d14b0c9e09af2221d88a34d52"} {"nl": {"description": "\"The Chamber of Secrets has been opened again\" \u2014 this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny.The Chamber of Secrets is an n\u2009\u00d7\u2009m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. The left light ray passes through a regular column, and the right ray \u2014 through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.", "input_spec": "The first line of the input contains two integer numbers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000). Each of the next n lines contains m characters. Each character is either \".\" or \"#\" and represents one cell of the Chamber grid. It's \".\" if the corresponding cell is empty and \"#\" if it's a regular column.", "output_spec": "Print the minimum number of columns to make magic or -1 if it's impossible to do.", "sample_inputs": ["3 3\n.#.\n...\n.#.", "4 3\n##.\n...\n.#.\n.#."], "sample_outputs": ["2", "2"], "notes": "NoteThe figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns."}, "positive_code": [{"source_code": "exception Found of int\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n \"\" in\n let () =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%s \" (fun s -> s)\n done\n in\n let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n if n = 1 then (\n Printf.printf \"0\\n\"\n ) else (\n let h = Array.make n false in\n let v = Array.make m false in\n let u = Array.make_matrix n m false in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let rec bfs_step k q1 l1 q2 l2 =\n\tl2 := 0;\n\tfor i = 0 to !l1 - 1 do\n\t let (x, y) = q1.(i) in\n\t let () =\n\t if y = n - 1\n\t then raise (Found k)\n\t in\n\t if not h.(y) then (\n\t for x = 0 to m - 1 do\n\t\tif a.(y).[x] = '#' then (\n\t\t if not u.(y).(x) then (\n\t\t u.(y).(x) <- true;\n\t\t q2.(!l2) <- (x, y);\n\t\t incr l2\n\t\t );\n\t\t);\n\t done;\n\t h.(y) <- true;\n\t );\n\t if not v.(x) then (\n\t for y = 0 to n - 1 do\n\t\tif a.(y).[x] = '#' then (\n\t\t if not u.(y).(x) then (\n\t\t u.(y).(x) <- true;\n\t\t q2.(!l2) <- (x, y);\n\t\t incr l2\n\t\t );\n\t\t);\n\t done;\n\t v.(x) <- true\n\t )\n\tdone;\n\tif !l2 > 0\n\tthen bfs_step (k + 1) q2 l2 q1 l1\n in\n\tfor x = 0 to m - 1 do\n\t if a.(0).[x] = '#' then (\n\t u.(0).(x) <- true;\n\t q1.(!l1) <- (x, 0);\n\t incr l1\n\t );\n\tdone;\n\ttry\n\t bfs_step 1 q1 l1 q2 l2;\n\t Printf.printf \"-1\\n\"\n\twith\n\t | Found k ->\n\t Printf.printf \"%d\\n\" k;\n )\n"}], "negative_code": [], "src_uid": "8b6f93cf2a41445649e0cbfc471541b6"} {"nl": {"description": "One remarkable day company \"X\" received k machines. And they were not simple machines, they were mechanical programmers! This was the last unsuccessful step before switching to android programmers, but that's another story.The company has now n tasks, for each of them we know the start time of its execution si, the duration of its execution ti, and the company profit from its completion ci. Any machine can perform any task, exactly one at a time. If a machine has started to perform the task, it is busy at all moments of time from si to si\u2009+\u2009ti\u2009-\u20091, inclusive, and it cannot switch to another task.You are required to select a set of tasks which can be done with these k machines, and which will bring the maximum total profit.", "input_spec": "The first line contains two integer numbers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20091000, 1\u2009\u2264\u2009k\u2009\u2264\u200950) \u2014 the numbers of tasks and machines, correspondingly. The next n lines contain space-separated groups of three integers si,\u2009ti,\u2009ci (1\u2009\u2264\u2009si,\u2009ti\u2009\u2264\u2009109, 1\u2009\u2264\u2009ci\u2009\u2264\u2009106), si is the time where they start executing the i-th task, ti is the duration of the i-th task and ci is the profit of its execution.", "output_spec": "Print n integers x1,\u2009x2,\u2009...,\u2009xn. Number xi should equal 1, if task i should be completed and otherwise it should equal 0. If there are several optimal solutions, print any of them.", "sample_inputs": ["3 1\n2 7 5\n1 3 3\n4 1 3", "5 2\n1 5 4\n1 4 5\n1 3 2\n4 1 2\n5 6 1"], "sample_outputs": ["0 1 1", "1 1 0 0 1"], "notes": "NoteIn the first sample the tasks need to be executed at moments of time 2 ... 8, 1 ... 3 and 4 ... 4, correspondingly. The first task overlaps with the second and the third ones, so we can execute either task one (profit 5) or tasks two and three (profit 6)."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0l, 0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- (s, t, c, i)\n done;\n Array.sort compare a;\n in\n let nv = 2 * n + 2 in\n let es = Array.make nv [] in\n let b = Array.make_matrix nv nv 0 in\n let c = Array.make_matrix nv nv 0 in\n let () =\n es.(0) <- [2];\n c.(0).(2) <- k;\n for i = 0 to n - 1 do\n let (s, t, cc, _) = a.(i) in\n let f = Int32.add s t in\n let j = ref (i + 1) in\n\twhile !j < n && (let (s, _, _, _) = a.(!j) in s < f) do\n\t incr j\n\tdone;\n\tlet w =\n\t if !j = n\n\t then 1\n\t else (!j + 1) * 2\n\tin\n\tlet u = 2 * i + 2 in\n\tlet v = 2 * i + 3 in\n\tlet x = if i < n - 1 then 2 * i + 4 else 1 in\n\t es.(u) <- v :: es.(u);\n\t es.(v) <- u :: es.(v);\n\t c.(u).(v) <- 1;\n\t b.(u).(v) <- -cc;\n\t es.(u) <- x :: es.(u);\n\t es.(x) <- u :: es.(x);\n\t c.(u).(x) <- k;\n\t es.(v) <- w :: es.(v);\n\t es.(w) <- v :: es.(w);\n\t c.(v).(w) <- 1;\n(*Printf.printf \"asd %d %ld %ld %d\\n\" i s t !j;*)\n done\n in\n let es = Array.map Array.of_list es in\n let f = Array.make_matrix nv nv 0 in\n let bellman_ford start finish =\n let p = Array.make nv (-1) in\n let w = Array.make nv 1000000000 in\n let stop = ref false in\n w.(start) <- 0;\n for k = 1 to nv do\n\tif not !stop then (\n\t stop := true;\n\t for u = 0 to nv - 1 do\n\t for i = 0 to Array.length es.(u) - 1 do\n\t let v = es.(u).(i) in\n\t\tif c.(u).(v) - f.(u).(v) > 0 then (\n\t\t let w' =\n\t\t if f.(u).(v) = 0\n\t\t then b.(u).(v)\n\t\t else -b.(v).(u)\n\t\t in\n\t\t if w.(u) < 1000000000 && w.(u) + w' < w.(v)\n\t\t then (\n\t\t w.(v) <- w.(u) + w';\n\t\t p.(v) <- u;\n\t\t stop := false;\n\t\t )\n\t\t)\n\t done\n\t done\n\t)\n done;\n (p, w.(finish))\n in\n let augment start finish =\n let (p, w) = bellman_ford start finish in\n(*Printf.printf \"aug\\n%!\";*)\n if p.(finish) < 0\n then -1\n else (\n\tlet v = ref finish in\n\t while !v <> start do\n\t let u = p.(!v) in\n\t f.(u).(!v) <- f.(u).(!v) + 1;\n\t f.(!v).(u) <- -f.(u).(!v);\n(*Printf.printf \"add %d %d\\n\" u !v;*)\n\t v := u;\n\t done;\n\t w\n )\n in\n let r = Array.make n 0 in\n for i = 1 to k do\n augment 0 1\n done;\n for i = 0 to n - 1 do\n let (_, _, _, j) = a.(i) in\n let res =\n\tif f.(2 * i + 2).(2 * i + 3) > 0\n\tthen 1\n\telse 0\n in\n\tr.(j) <- res\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d \" r.(i)\n done;\n Printf.printf \"\\n\"\n\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0l, 0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- (s, t, c, i)\n done;\n Array.sort compare a;\n in\n let nv = 2 * n + 2 in\n let es = Array.make nv [] in\n let b = Array.make_matrix nv nv 0 in\n let c = Array.make_matrix nv nv 0 in\n let () =\n es.(0) <- [2];\n c.(0).(2) <- k;\n for i = 0 to n - 1 do\n let (s, t, cc, _) = a.(i) in\n let f = Int32.add s t in\n let j = ref (i + 1) in\n\twhile !j < n && (let (s, _, _, _) = a.(!j) in s < f) do\n\t incr j\n\tdone;\n\tlet w =\n\t if !j = n\n\t then 1\n\t else (!j + 1) * 2\n\tin\n\tlet u = 2 * i + 2 in\n\tlet v = 2 * i + 3 in\n\tlet x = if i < n - 1 then 2 * i + 4 else 1 in\n\t es.(u) <- v :: es.(u);\n\t es.(v) <- u :: es.(v);\n\t c.(u).(v) <- 1;\n\t b.(u).(v) <- -cc;\n\t es.(u) <- x :: es.(u);\n\t es.(x) <- u :: es.(x);\n\t c.(u).(x) <- k;\n\t es.(v) <- w :: es.(v);\n\t es.(w) <- v :: es.(w);\n\t c.(v).(w) <- k;\n done\n in\n let es = Array.map Array.of_list es in\n let f = Array.make_matrix nv nv 0 in\n let bellman_ford start finish =\n let p = Array.make nv (-1) in\n let w = Array.make nv 1000000000 in\n w.(start) <- 0;\n for k = 1 to nv do\n\tfor u = 0 to nv - 1 do\n\t for i = 0 to Array.length es.(u) - 1 do\n\t let v = es.(u).(i) in\n\t if c.(u).(v) - f.(u).(v) > 0 then (\n\t\tlet w' =\n\t\t if f.(u).(v) = 0\n\t\t then b.(u).(v)\n\t\t else -b.(v).(u)\n\t\tin\n\t\t if w.(u) < 1000000000 && w.(u) + w' < w.(v)\n\t\t then (\n\t\t w.(v) <- w.(u) + w';\n\t\t p.(v) <- u;\n\t\t )\n\t )\n\t done\n\tdone\n done;\n (p, w.(finish))\n in\n let augment start finish =\n let (p, w) = bellman_ford start finish in\n if p.(finish) < 0\n then -1\n else (\n\tlet v = ref finish in\n\t while !v <> start do\n\t let u = p.(!v) in\n\t f.(u).(!v) <- f.(u).(!v) + 1;\n\t f.(!v).(u) <- -f.(u).(!v);\n\t v := u;\n\t done;\n\t w\n )\n in\n for i = 1 to k do\n augment 0 1\n done;\n for i = 0 to n - 1 do\n let (_, _, _, i) = a.(i) in\n let res =\n\tif f.(2 * i + 2).(2 * i + 3) > 0\n\tthen 1\n\telse 0\n in\n\tPrintf.printf \"%d \" res\n done;\n Printf.printf \"\\n\"\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0l, 0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- (s, t, c, i)\n done;\n Array.sort compare a;\n in\n let nv = n + 2 in\n let es = Array.make nv [] in\n let b = Array.make_matrix nv nv 0 in\n let c = Array.make_matrix nv nv 0 in\n let () =\n es.(0) <- [2];\n c.(0).(2) <- k;\n for i = 0 to n - 1 do\n let (s, t, cc, _) = a.(i) in\n let f = Int32.add s t in\n let j = ref (i + 1) in\n\twhile !j < n && (let (s, _, _, _) = a.(!j) in s < f) do\n\t incr j\n\tdone;\n\tlet w =\n\t if !j = n\n\t then 1\n\t else !j + 2\n\tin\n\tlet u = i + 2 in\n\tlet x = if i < n - 1 then i + 3 else 1 in\n\t es.(u) <- w :: es.(u);\n\t es.(w) <- u :: es.(w);\n\t c.(u).(w) <- 1;\n\t b.(u).(w) <- -cc;\n\t es.(u) <- x :: es.(u);\n\t es.(x) <- u :: es.(x);\n\t c.(u).(x) <- k;\n(*Printf.printf \"asd %d %ld %ld %d\\n\" i s t !j;*)\n done\n in\n let es = Array.map Array.of_list es in\n let f = Array.make_matrix nv nv 0 in\n let bellman_ford start finish =\n let p = Array.make nv (-1) in\n let w = Array.make nv 1000000000 in\n w.(start) <- 0;\n for k = 1 to nv do\n\tfor u = 0 to nv - 1 do\n\t for i = 0 to Array.length es.(u) - 1 do\n\t let v = es.(u).(i) in\n\t if c.(u).(v) - f.(u).(v) > 0 then (\n\t\tlet w' =\n\t\t if f.(u).(v) = 0\n\t\t then b.(u).(v)\n\t\t else -b.(v).(u)\n\t\tin\n\t\t if w.(u) < 1000000000 && w.(u) + w' < w.(v)\n\t\t then (\n\t\t w.(v) <- w.(u) + w';\n\t\t p.(v) <- u;\n\t\t )\n\t )\n\t done\n\tdone\n done;\n (p, w.(finish))\n in\n let augment start finish =\n let (p, w) = bellman_ford start finish in\n(*Printf.printf \"aug\\n%!\";*)\n if p.(finish) < 0\n then -1\n else (\n\tlet v = ref finish in\n\t while !v <> start do\n\t let u = p.(!v) in\n\t f.(u).(!v) <- f.(u).(!v) + 1;\n\t f.(!v).(u) <- -f.(u).(!v);\n(*Printf.printf \"add %d %d\\n\" u !v;*)\n\t v := u;\n\t done;\n\t w\n )\n in\n let r = Array.make n 0 in\n for i = 1 to k do\n augment 0 1\n done;\n for i = 0 to n - 1 do\n let (_, _, _, j) = a.(i) in\n let x = if i < n - 1 then i + 3 else 1 in\n let res =\n\tif f.(i + 2).(x) > 0\n\tthen 1\n\telse 0\n in\n\tr.(j) <- res\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d \" r.(i)\n done;\n Printf.printf \"\\n\"\n\n"}], "src_uid": "d0a47e1697e2639a01d785d67d73d5f0"} {"nl": {"description": "Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $$$n$$$ elements. The $$$i$$$-th element is $$$a_i$$$ ($$$i$$$ = $$$1, 2, \\ldots, n$$$). He gradually takes the first two leftmost elements from the deque (let's call them $$$A$$$ and $$$B$$$, respectively), and then does the following: if $$$A > B$$$, he writes $$$A$$$ to the beginning and writes $$$B$$$ to the end of the deque, otherwise, he writes to the beginning $$$B$$$, and $$$A$$$ writes to the end of the deque. We call this sequence of actions an operation.For example, if deque was $$$[2, 3, 4, 5, 1]$$$, on the operation he will write $$$B=3$$$ to the beginning and $$$A=2$$$ to the end, so he will get $$$[3, 4, 5, 1, 2]$$$.The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $$$q$$$ queries. Each query consists of the singular number $$$m_j$$$ $$$(j = 1, 2, \\ldots, q)$$$. It is required for each query to answer which two elements he will pull out on the $$$m_j$$$-th operation.Note that the queries are independent and for each query the numbers $$$A$$$ and $$$B$$$ should be printed in the order in which they will be pulled out of the deque.Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \\leq n \\leq 10^5$$$, $$$0 \\leq q \\leq 3 \\cdot 10^5$$$)\u00a0\u2014 the number of elements in the deque and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$, where $$$a_i$$$ $$$(0 \\leq a_i \\leq 10^9)$$$\u00a0\u2014 the deque element in $$$i$$$-th position. The next $$$q$$$ lines contain one number each, meaning $$$m_j$$$ ($$$1 \\leq m_j \\leq 10^{18}$$$).", "output_spec": "For each teacher's query, output two numbers $$$A$$$ and $$$B$$$\u00a0\u2014 the numbers that Valeriy pulls out of the deque for the $$$m_j$$$-th operation.", "sample_inputs": ["5 3\n1 2 3 4 5\n1\n2\n10", "2 0\n0 0"], "sample_outputs": ["1 2\n2 3\n5 2", ""], "notes": "Note Consider all 10 steps for the first test in detail: $$$[1, 2, 3, 4, 5]$$$\u00a0\u2014 on the first operation, $$$A$$$ and $$$B$$$ are $$$1$$$ and $$$2$$$, respectively.So, $$$2$$$ we write to the beginning of the deque, and $$$1$$$\u00a0\u2014 to the end.We get the following status of the deque: $$$[2, 3, 4, 5, 1]$$$. $$$[2, 3, 4, 5, 1] \\Rightarrow A = 2, B = 3$$$. $$$[3, 4, 5, 1, 2]$$$ $$$[4, 5, 1, 2, 3]$$$ $$$[5, 1, 2, 3, 4]$$$ $$$[5, 2, 3, 4, 1]$$$ $$$[5, 3, 4, 1, 2]$$$ $$$[5, 4, 1, 2, 3]$$$ $$$[5, 1, 2, 3, 4]$$$ $$$[5, 2, 3, 4, 1] \\Rightarrow A = 5, B = 2$$$. "}, "positive_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\nlet readInt64 () = Scanf.scanf \" %Ld\" (fun x -> x)\n\nlet (++) a b = Int64.add a b\nlet (--) a b = Int64.sub a b\nlet ( ** ) a b = Int64.mul a b\nlet (//) a b = Int64.div a b\nlet (%%) a b = Int64.rem a b\n\ntype solver = {n: int; a: int array; k: int; cyca: int array}\n\nlet precomp (n, a) =\n (* No fold_*i :( *)\n let maxi = ref 0 in\n for i=1 to n-1 do\n if a.(i) > a.(!maxi) then maxi := i\n done;\n let maxi = !maxi in\n let cyca = Array.make (maxi + n) (-1) in\n Array.blit a 0 cyca 0 n;\n for i=0 to maxi-1 do\n let x = cyca.(i) in\n let y = cyca.(i+1) in\n let x = max x y and y = min x y in\n cyca.(i+1) <- x;\n cyca.(i+n) <- y\n done;\n {n; a; k=maxi; cyca}\n\nlet query {n; a; k; cyca} m =\n let m =\n let open Int64 in\n let n = of_int n in\n let k = of_int k in\n to_int (if m < k then m else (m -- k) %% (n -- 1L) ++ k)\n in\n if m < k then (cyca.(m), a.(m+1))\n else (cyca.(k), cyca.(m+1))\n\nlet main () =\n let n = readInt () in\n let q = readInt () in\n let a = Array.init n (fun _ -> readInt ()) in\n let s = precomp (n, a) in\n for i=0 to q-1 do\n let m = readInt64 () -- 1L in\n let (x, y) = query s m in\n Printf.printf \"%d %d\\n\" x y\n done\n\nlet () = main ()\n"}, {"source_code": "let (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\n\nlet () =\n let n, q = Scanf.scanf \"%d %d\\n\" (fun x y -> x, y) in\n let a = Array.init n (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x)) in\n let max = ref a.(0)in\n let max_idx = ref 0 in\n for i = 1 to n-1 do\n if a.(i) > !max then begin max := a.(i); max_idx := i end;\n done;\n let b = Array.make (n-1) 0L in\n for i = 0 to n- !max_idx - 2 do\n b.(i) <- a.(!max_idx + 1 + i);\n done;\n let first = ref a.(0) in\n let c = Array.make !max_idx (a.(0), a.(1)) in\n for i = 1 to !max_idx do\n c.(i-1) <- (!first, a.(i));\n if a.(i) <= !first then\n b.(n- !max_idx - 2 + i) <- a.(i)\n else begin\n b.(n- !max_idx - 2 + i) <- !first;\n first := a.(i);\n end;\n done;\n\n for i = 1 to q do\n let m = Scanf.scanf \"%Ld \" (fun x -> x) in\n if m > Int64.of_int !max_idx then begin\n let r = Int64.rem (m -- Int64.of_int !max_idx -- 1L) (Int64.of_int (n-1)) |> Int64.to_int in\n Printf.printf \"%Ld %Ld\\n\" !max b.(r)\n end\n else\n let m = Int64.to_int m in\n let x, y = c.(m-1) in\n Printf.printf \"%Ld %Ld\\n\" x y;\n done\n;;\n"}], "negative_code": [], "src_uid": "3cb19ef77e9cb919a2f0a1d687b2845d"} {"nl": {"description": "Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns \u2014 from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x,\u2009y). The table corners are cells: (1,\u20091), (n,\u20091), (1,\u2009m), (n,\u2009m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1,\u2009y1), an arbitrary corner of the table (x2,\u2009y2) and color all cells of the table (p,\u2009q), which meet both inequations: min(x1,\u2009x2)\u2009\u2264\u2009p\u2009\u2264\u2009max(x1,\u2009x2), min(y1,\u2009y2)\u2009\u2264\u2009q\u2009\u2264\u2009max(y1,\u2009y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.", "input_spec": "The first line contains exactly two integers n, m (3\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1,\u2009ai2,\u2009...,\u2009aim. If aij equals zero, then cell (i,\u2009j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.", "output_spec": "Print a single number \u2014 the minimum number of operations Simon needs to carry out his idea.", "sample_inputs": ["3 3\n0 0 0\n0 1 0\n0 0 0", "4 3\n0 0 0\n0 0 1\n1 0 0\n0 0 0"], "sample_outputs": ["4", "2"], "notes": "NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2,\u20092) and corner (1,\u20091). For the second time you need to choose cell (2,\u20092) and corner (3,\u20093). For the third time you need to choose cell (2,\u20092) and corner (3,\u20091). For the fourth time you need to choose cell (2,\u20092) and corner (1,\u20093). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3,\u20091) and corner (4,\u20093). For the second time you need to choose cell (2,\u20093) and corner (1,\u20091). "}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n if skip = 0 then failwith \"fold_for\";\n let cmp = if skip > 0 then (<) else (>) in\n\n let rec iter cur acc =\n if not @@ cmp cur max then acc\n else iter (cur + skip) (f acc cur) in\n\n iter min init \n;;\n\nlet iter_for ?(skip=1) min max ~f =\n fold_for ~skip:skip min max ~init:() ~f:(fun _ i -> f i)\n;;\n\nlet input_n n fmt ~f =\n fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf fmt f :: acc) |> List.rev\n;;\n\nlet () =\n let n, m = Scanf.scanf \"%d %d \" ident2 in\n try\n iter_for 0 n ~f:(fun i ->\n iter_for 0 m ~f:(fun j ->\n let x = Scanf.scanf \"%d \" ident in\n if (i = 0 || i = n - 1 || j = 0 || j = m - 1) && x = 1 then raise Exit));\n print_endline \"4\";\n with\n | _ -> print_endline \"2\";\n;; \n \n"}], "negative_code": [], "src_uid": "0d2fd9b58142c4f5282507c916690244"} {"nl": {"description": "Greg has an array a\u2009=\u2009a1,\u2009a2,\u2009...,\u2009an and m operations. Each operation looks as: li, ri, di, (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n). To apply operation i to the array means to increase all array elements with numbers li,\u2009li\u2009+\u20091,\u2009...,\u2009ri by value di.Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1\u2009\u2264\u2009xi\u2009\u2264\u2009yi\u2009\u2264\u2009m). That means that one should apply operations with numbers xi,\u2009xi\u2009+\u20091,\u2009...,\u2009yi to the array.Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.", "input_spec": "The first line contains integers n, m, k (1\u2009\u2264\u2009n,\u2009m,\u2009k\u2009\u2264\u2009105). The second line contains n integers: a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009105) \u2014 the initial array. Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n), (0\u2009\u2264\u2009di\u2009\u2264\u2009105). Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1\u2009\u2264\u2009xi\u2009\u2264\u2009yi\u2009\u2264\u2009m). The numbers in the lines are separated by single spaces.", "output_spec": "On a single line print n integers a1,\u2009a2,\u2009...,\u2009an \u2014 the array after executing all the queries. Separate the printed numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams of the %I64d specifier.", "sample_inputs": ["3 3 3\n1 2 3\n1 2 1\n1 3 2\n2 3 4\n1 2\n1 3\n2 3", "1 1 1\n1\n1 1 1\n1 1", "4 3 6\n1 2 3 4\n1 2 1\n2 3 2\n3 4 4\n1 2\n1 3\n2 3\n1 2\n1 3\n2 3"], "sample_outputs": ["9 18 17", "2", "5 18 31 20"], "notes": null}, "positive_code": [{"source_code": "open Printf;;\nopen Scanf;;\nlet getll()=bscanf Scanning.stdib \" %Ld \" (fun x->x);;\nlet getint()=bscanf Scanning.stdib \" %d \" (fun x->x);;\nlet ( ** ) a b=Int64.mul a b;;\nlet (++) a b=Int64.add a b;;\nlet (--) a b=Int64.sub a b;;\nlet (//) a b=Int64.div a b;;\n\nlet n=getint();;\nlet m=getint();;\nlet k=getint();;\nlet aa=Array.init (n+1) (function 0->0L|_->getll());;\nlet o1=Array.init (m+1) (function 0->(0,0,0)|_ -> let a=getint()in let b=getint()in let c=getint() in (a,b,c));;\nlet o2=Array.init (k+1) (function 0->(0,0)|_ -> let a=getint()in let b=getint()in (a,b));;\nlet a=Array.create (m+2) 0;;\nlet b=Array.create (n+2) 0L;;\nfor i=1 to k do\n\tlet l=fst o2.(i)\n\tand r=snd o2.(i) in\n\t\ta.(l)<-a.(l)+1;\n\t\ta.(r+1)<-a.(r+1)-1;\ndone;;\nlet sumup a=let len=Array.length a in for i=1 to len-1 do a.(i)<-a.(i-1)+a.(i); done;;\nlet sumupl a=let len=Array.length a in for i=1 to len-1 do a.(i)<-a.(i-1)++a.(i); done;;\nsumup a;;\nlet ff c=function (l,r,x)->let d=Int64.of_int(x)**Int64.of_int(c)in b.(l)<-b.(l)++d;b.(r+1)<-b.(r+1)--d;;\nfor i=1 to m do ff a.(i) o1.(i); done;;\nsumupl b;;\nfor i=1 to n do\n\tif i>1 then print_char ' ';\n\tprintf \"%Ld\" (aa.(i)++b.(i));\ndone;;\nprint_newline();;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let m = read_int() in\n let k = read_int() in\n let a = Array.init (n+1) (fun i -> if i=0 then 0L else read_long()) in\n let op = Array.init (m+1) (fun i -> if i=0 then (0,0,0L) else \n\t\t\t let l = read_int() in\n\t\t\t let r = read_int() in\n\t\t\t let d = read_long() in\n\t\t\t\t (l,r,d)\n\t\t\t ) in\n let q = Array.init (k+1) (fun i -> if i=0 then (0,0) else\n\t\t\t let l = read_int() in\n\t\t\t let r = read_int() in\n\t\t\t\t(l,r)\n\t\t\t ) in\n \n let opcount = Array.make (m+2) 0L in\n let rcount = Array.make (n+2) 0L in\n \n for i=1 to k do\n let (l,r) = q.(i) in\n opcount.(l) <- opcount.(l) ++ 1L;\n opcount.(r+1) <- opcount.(r+1) -- 1L;\n done;\n\n for i=1 to m do\n opcount.(i) <- opcount.(i-1) ++ opcount.(i)\n done;\n\n for i=1 to m do\n let (l,r,d) = op.(i) in\n\trcount.(l) <- rcount.(l) ++ (d ** opcount.(i));\n\trcount.(r+1) <- rcount.(r+1) -- (d ** opcount.(i));\n done;\n\n for i=1 to n do\n rcount.(i) <- rcount.(i-1) ++ rcount.(i);\n done;\n\n for i=1 to n do\n if i>1 then printf \" \";\n printf \"%Ld\" (rcount.(i) ++ a.(i))\n done;\n\n print_newline()\n\n \n\n\n\n \n\n\n"}], "negative_code": [], "src_uid": "c3120f96894c17957bd8acb968bf37cd"} {"nl": {"description": "Alice got an array of length $$$n$$$ as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.Bob has chosen $$$m$$$ changes of the following form. For some integer numbers $$$x$$$ and $$$d$$$, he chooses an arbitrary position $$$i$$$ ($$$1 \\le i \\le n$$$) and for every $$$j \\in [1, n]$$$ adds $$$x + d \\cdot dist(i, j)$$$ to the value of the $$$j$$$-th cell. $$$dist(i, j)$$$ is the distance between positions $$$i$$$ and $$$j$$$ (i.e. $$$dist(i, j) = |i - j|$$$, where $$$|x|$$$ is an absolute value of $$$x$$$).For example, if Alice currently has an array $$$[2, 1, 2, 2]$$$ and Bob chooses position $$$3$$$ for $$$x = -1$$$ and $$$d = 2$$$ then the array will become $$$[2 - 1 + 2 \\cdot 2,~1 - 1 + 2 \\cdot 1,~2 - 1 + 2 \\cdot 0,~2 - 1 + 2 \\cdot 1]$$$ = $$$[5, 2, 1, 3]$$$. Note that Bob can't choose position $$$i$$$ outside of the array (that is, smaller than $$$1$$$ or greater than $$$n$$$).Alice will be the happiest when the elements of the array are as big as possible. Bob claimed that the arithmetic mean value of the elements will work fine as a metric.What is the maximum arithmetic mean value Bob can achieve?", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^5$$$) \u2014 the number of elements of the array and the number of changes. Each of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$d_i$$$ ($$$-10^3 \\le x_i, d_i \\le 10^3$$$) \u2014 the parameters for the $$$i$$$-th change.", "output_spec": "Print the maximal average arithmetic mean of the elements Bob can achieve. Your answer is considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$.", "sample_inputs": ["2 3\n-1 3\n0 0\n-1 -4", "3 2\n0 2\n5 0"], "sample_outputs": ["-2.500000000000000", "7.000000000000000"], "notes": null}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt64 = struct \n\t(* include Int64 *)\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\tlet (~~|) p = Int64.of_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\nend open MyInt64\nlet () =\n\tlet n,m = get_2_i64 ()\n\tin let a = Array.make ~|m (0L,0L)\n\tin for i=0 to ~|m-$1 do\n\t\ta.(i) <- get_2_i64 ()\n\tdone;\n\n\tlet mid = (n+1L)/2L in\n\tlet sum_left = ref 0L in\n\tlet sum_mid = ref 0L in\n\tfor i=0 to ~|n-$1 do\n\t\tsum_left := !sum_left + labs (mid - (~~|i+1L));\n\t\tsum_mid := !sum_mid + labs (~~|i);\n\tdone;\n\tArray.fold_left (fun u v -> \n\t\tlet x,d = v in\n\t\tu + x * n\n\t\t\t+ d * if d<0L then !sum_left else !sum_mid\n\t) 0L a\n\t|> (fun v -> printf \"%.10f\\n\" (Int64.to_float v /. Int64.to_float n))"}], "negative_code": [{"source_code": "open Printf open Scanf\nlet input_int_array n =\n\tArray.init n (fun _ -> Scanf.scanf \" %d\" (fun v -> v))\t\nlet get_int () = Scanf.scanf \" %d\" (fun v -> v)\nlet get_2_ints () = Scanf.scanf \" %d %d\" (fun u v -> u,v)\nlet get_3_ints () = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w)\nlet get_4_ints () = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x)\nlet get_5_ints () = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nlet () =\n\tlet n,m = get_2_ints ()\n\tin let a = Array.make m (0,0)\n\tin for i=0 to m-1 do\n\t\ta.(i) <- get_2_ints ()\n\tdone;\n\t\n\tlet mid = (n+1)/2 in\n\tlet sum_left = ref 0 in\n\tlet sum_mid = ref 0 in\n\tfor i=0 to n-1 do\n\t\tsum_left := !sum_left + abs (mid - (i+1));\n\t\tsum_mid := !sum_mid + abs (i);\n\tdone;\n\tArray.fold_left (fun u v -> \n\t\tlet x,d = v in\n\t\tu + x * n\n\t\t\t+ d * if d<0 then !sum_left else !sum_mid\n\t) 0 a\n\t|> (fun v -> printf \"%.10f\\n\" (float_of_int v /. float_of_int n))\n"}], "src_uid": "1c8423407ea7a0b2647e41392670d6b7"} {"nl": {"description": "Vova promised himself that he would never play computer games... But recently Firestorm \u2014 a well-known game developing company \u2014 published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.", "input_spec": "The first line contains two integer numbers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0\u2009\u2264\u2009ci\u2009\u2264\u2009109) \u2014 the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi,\u2009yi) which represent that characters xi and yi are friends (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, xi\u2009\u2260\u2009yi). It is guaranteed that each pair is listed at most once.", "output_spec": "Print one number \u2014 the minimum amount of gold Vova has to spend in order to finish the quest.", "sample_inputs": ["5 2\n2 5 3 4 8\n1 4\n4 5", "10 0\n1 2 3 4 5 6 7 8 9 10", "10 5\n1 6 2 7 3 8 4 9 5 10\n1 2\n3 4\n5 6\n7 8\n9 10"], "sample_outputs": ["10", "55", "15"], "notes": "NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters."}, "positive_code": [{"source_code": "open Int64;;\nlet scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet n = scan_int() and m= scan_int() in let odw = Array.make n 0 and wyn = ref zero\nand p = Array.init n (fun x ->x) and w = Array.init n (fun x->scan_int()) in\nlet rec find x =\n if p.(x) = x then x\n else begin \n\tp.(x) <- find p.(x);\n p.(x)\n end\nin let uni x y =\n let u = find x and v = find y in\n if u <> v then\n if w.(u) < w.(v) then p.(v) <- u else p.(u) <- v\nin begin for i=1 to m do \n let u = scan_int () and v = scan_int() in uni (u-1) (v-1)\ndone;\nfor i=0 to (n-1) do\n if odw.(find i) = 0 then begin\n odw.(find i) <- 1; wyn := add (!wyn) (Int64.of_int(w.(find i))) end\ndone;\nprint_string(Int64.to_string(!wyn))\nend"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nmodule type GRAPH_LABELS = \n sig \n type label\n end;;\n\n(* Typ modu\u0142u implementuj\u0105cego grafy o wierzcho\u0142kach numerowanych od 0 do n-1. *)\nmodule type GRAPH = \n sig \n (* Etykiety kraw\u0119dzi. *)\n type label\n\n (* Typ graf\u00f3w o wierzcho\u0142kach typu 'a. *)\n type graph\n \n (* Pusty graf. *)\n val init : int -> graph\n\n (* Rozmiar grafu *)\n val size : graph -> int\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_directed_edge : graph -> int -> int -> label -> unit\n\n (* Dodanie kraw\u0119dzi nieskierowanej (dwukierunkowej) \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_edge : graph -> int -> int -> label -> unit\n\n (* Lista incydencji danego wierzcho\u0142ka. *)\n val neighbours : graph -> int -> (int*label) list\n end;;\n\nmodule Graph = functor (L : GRAPH_LABELS) -> \n(struct\n (* Etykiety kraw\u0119dzi. *)\n type label = L.label\n \n (* Typ graf\u00f3w - tablica list s\u0105siedztwa. *)\n type graph = {n : int; e : (int*label) list array}\n \n (* Pusty graf. *)\n let init s = {n = s; e = Array.make s []}\n\n (* Rozmiar grafu. *)\n let size g = g.n\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n let insert_directed_edge g x y l = \n assert ((x<>y) && (x >= 0) && (x < size g) && (y >= 0) && (y < size g));\n g.e.(x) <- (y,l)::g.e.(x)\n \n (* Dodanie kraw\u0119dzi \u0142\u0105cz\u0105cej dwa (istniej\u0105ce) wierzcho\u0142ki. *)\n let insert_edge g x y l =\n insert_directed_edge g x y l;\n insert_directed_edge g y x l\n \n (* Lista incydencji danego wierzcho\u0142ka. *)\n let neighbours g x =\n g.e.(x)\nend : GRAPH with type label = L.label);;\n\nmodule IntLabel = \n struct\n type label = int\n end;;\n\nmodule G = Graph(IntLabel);;\n\nopen G;;\n\nlet n = scan_int();;\nlet m = scan_int();;\n\nlet g = G.init(n);;\nlet values = Array.make n 0;;\n\nfor i = 0 to n - 1 do\n let x = scan_int() in\n values.(i) <- x;\ndone;\n\nfor i = 0 to m - 1 do\n let (x, y) = (scan_int() - 1, scan_int() - 1) in\n insert_edge g x y 1;\ndone;;\n\nlet vis = Array.make n false;;\n\nlet rec dfs x =\n vis.(x) <- true;\n let res = ref values.(x) in\n List.iter (fun(y, _) ->\n if vis.(y) = false then res := min (!res) (dfs y)\n ) (neighbours g x);\n !res;;\n\nopen Int64;;\nlet sumek = ref zero;;\n\nfor i = 0 to n - 1 do\n if vis.(i) = false then sumek := add (!sumek) (Int64.of_int(dfs i));\ndone;\n\nprint_string(Int64.to_string(!sumek));;"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n\n let cost = Array.init n (fun i -> long(read_int())) in\n let comp = Array.make n (-1) in\n\n let graph = Array.make n [] in\n\n for i=0 to m-1 do\n let (u,v) = read_pair() in\n let (u,v) = (u-1,v-1) in\n graph.(u) <- v::graph.(u);\n graph.(v) <- u::graph.(v)\n done;\n \n let rec dfs u p c =\n if comp.(u) = -1 then (\n comp.(u) <- c;\n List.iter (fun v -> if v<>p then dfs v u c) graph.(u)\n )\n in\n\n let rec loop i c = if i=n then c else (\n if comp.(i) = -1 then (\n dfs i (-1) c;\n loop (i+1) (c+1)\n ) else loop (i+1) c\n ) in\n\n let ncomps = loop 0 0 in\n\n let mincomp = Array.make ncomps 1_000_000_001L in\n\n for i=0 to n-1 do\n mincomp.(comp.(i)) <- min cost.(i) mincomp.(comp.(i))\n done;\n\n let answer = sum 0 (ncomps-1) (fun i -> mincomp.(i)) in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet n = scan_int() and m= scan_int() in let odw = Array.make n 0 and wyn = ref 0\nand p = Array.init n (fun x ->x) and w = Array.init n (fun x->scan_int()) in\nlet rec find x =\n if p.(x) = x then x\n else begin \n\tp.(x) <- find p.(x);\n p.(x)\n end\nin let uni x y =\n let u = find x and v = find y in\n if u <> v then\n if w.(u) < w.(v) then p.(v) <- u else p.(u) <- v\nin begin for i=1 to m do \n let u = scan_int () and v = scan_int() in uni (u-1) (v-1)\ndone;\nfor i=0 to (n-1) do\n if odw.(find i) = 0 then begin\n odw.(find i) <- 1; wyn := !wyn + w.(find i) end\ndone;\nprint_int (!wyn)\nend\n"}], "src_uid": "9329cb499f003aa71c6f51556bcc7b05"} {"nl": {"description": "Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than $$$k$$$ other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.Now each knight ponders: how many coins he can have if only he kills other knights?You should answer this question for each knight.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ $$$(1 \\le n \\le 10^5, 0 \\le k \\le \\min(n-1,10))$$$ \u2014 the number of knights and the number $$$k$$$ from the statement. The second line contains $$$n$$$ integers $$$p_1, p_2 ,\\ldots,p_n$$$ $$$(1 \\le p_i \\le 10^9)$$$ \u2014 powers of the knights. All $$$p_i$$$ are distinct. The third line contains $$$n$$$ integers $$$c_1, c_2 ,\\ldots,c_n$$$ $$$(0 \\le c_i \\le 10^9)$$$ \u2014 the number of coins each knight has.", "output_spec": "Print $$$n$$$ integers \u2014 the maximum number of coins each knight can have it only he kills other knights.", "sample_inputs": ["4 2\n4 5 9 7\n1 2 11 33", "5 1\n1 2 3 4 5\n1 2 3 4 5", "1 0\n2\n3"], "sample_outputs": ["1 3 46 36", "1 3 5 7 9", "3"], "notes": "NoteConsider the first example. The first knight is the weakest, so he can't kill anyone. That leaves him with the only coin he initially has. The second knight can kill the first knight and add his coin to his own two. The third knight is the strongest, but he can't kill more than $$$k = 2$$$ other knights. It is optimal to kill the second and the fourth knights: $$$2+11+33 = 46$$$. The fourth knight should kill the first and the second knights: $$$33+1+2 = 36$$$. In the second example the first knight can't kill anyone, while all the others should kill the one with the index less by one than their own.In the third example there is only one knight, so he can't kill anyone."}, "positive_code": [{"source_code": "let ( */ ) = Big_int.mult_big_int;;\nlet ( +/ ) = Big_int.add_big_int;;\nlet ( -/ ) = Big_int.sub_big_int;;\nlet to_int = Big_int.int_of_big_int;;\nlet of_int = Big_int.big_int_of_int;;\nlet min = Big_int.min_big_int;;\nlet (modi) = Big_int.mod_big_int;;\nlet to_string = Big_int.string_of_big_int;;\nlet of_string = Big_int.big_int_of_string;;\nlet ( compare a b | c -> c\n end);;\n\nlet n,k = Scanf.sscanf (read_line ()) \"%i %i\" (fun n k -> n,k) in\nlet power = read_line () |> split_on_char ' ' |> List.map of_string |> Array.of_list in\nlet coins = read_line () |> split_on_char ' ' |> List.map of_string |> Array.of_list in\nlet result = Array.make n (of_int 0) in\nlet sorted_power = Array.mapi (fun i x -> (x,i)) power in\nArray.sort (fun (x,_) (y,_) -> to_int @@ x -/ y) sorted_power;\nlet _ = Array.fold_left (fun s (p, i) ->\n result.(i) <- SetI.fold (fun (c,_) t -> c +/t) s coins.(i);\n if SetI.cardinal s < k then SetI.add (coins.(i),i) s\n else if (not (SetI.is_empty s)) && fst @@ SetI.min_elt s n,k) in\nlet power = read_line () |> split_on_char ' ' |> List.map of_string |> Array.of_list in\nlet coins = read_line () |> split_on_char ' ' |> List.map of_string |> Array.of_list in\nlet result = Array.make n (of_int 0) in\nlet sorted_power = Array.mapi (fun i x -> (x,i)) power in\nArray.sort (fun (x,_) (y,_) -> to_int @@ x -/ y) sorted_power;\nlet _ = Array.fold_left (fun s (p, i) ->\n result.(i) <- SetI.fold (fun c t -> c +/t) s coins.(i);\n if SetI.cardinal s < k || SetI.cardinal s = 0 then SetI.add coins.(i) s\n else if SetI.min_elt s n,k) in\nlet power = read_line () |> split_on_char ' ' |> List.map of_string |> Array.of_list in\nlet coins = read_line () |> split_on_char ' ' |> List.map of_string |> Array.of_list in\nlet result = Array.make n (of_int 0) in\nlet sorted_power = Array.mapi (fun i x -> (x,i)) power in\nArray.sort (fun (x,_) (y,_) -> to_int @@ x -/ y) sorted_power;\nlet _ = Array.fold_left (fun s (p, i) ->\n result.(i) <- SetI.fold (fun c t -> c +/t) s coins.(i);\n if SetI.cardinal s < k then SetI.add coins.(i) s\n else if (not (SetI.is_empty s)) && SetI.min_elt s Array.length b then invalid_arg \"map2\";\n Array.init (Array.length a) (fun i -> f i (Array.unsafe_get a i) (Array.unsafe_get b i))\n;;\n\nlet iteri2 f a b =\n for o = 0 to Array.length a-1 do\n f o (Array.unsafe_get a o) (Array.unsafe_get b o)\n done\n;;\n\nlet custom_insert a x =\n if a.(0) < x then (a.(0) <- x; Array.sort compare a)\n;;\n\nexception End;;\n\nlet n,k = Scanf.sscanf (read_line ()) \"%i %i\" (fun n k -> n,k) in\nlet power = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet coins = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet sorted_coins = Array.mapi (fun i x -> (x,i)) coins in\nArray.sort (fun (x,_) (y,_) -> compare y x) sorted_coins;\nfor i = 0 to n-1 do\n let kill = ref 0 in\n let count = ref coins.(i) in\n begin try\n Array.iter (fun (c,j) -> if power.(j) < power.(i) then (count := !count + c; incr kill);\n if !kill = k then raise End ) sorted_coins;\n with End -> ();\n end;\n Printf.printf \"%i \" !count;\ndone;\nprint_newline ();\n"}, {"source_code": "let split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet mapi2 f a b =\n if Array.length a <> Array.length b then invalid_arg \"map2\";\n Array.init (Array.length a) (fun i -> f i (Array.unsafe_get a i) (Array.unsafe_get b i))\n;;\n\nlet iteri2 f a b =\n for o = 0 to Array.length a-1 do\n f o (Array.unsafe_get a o) (Array.unsafe_get b o)\n done\n;;\n\nlet custom_insert a x =\n if a.(0) < x then (a.(0) <- x; Array.sort compare a)\n;;\n\nexception End;;\n\nlet n,k = Scanf.sscanf (read_line ()) \"%i %i\" (fun n k -> n,k) in\nlet power = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet coins = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet sorted_coins = Array.mapi (fun i x -> (x,i)) coins in\nArray.sort (fun (x,_) (y,_) -> compare y x) sorted_coins;\nfor i = 0 to n-1 do\n let kill = ref 0 in\n let count = ref coins.(i) in\n begin try\n Array.iter (fun (c,j) -> if power.(j) < power.(i) && c >= 0 then (count := !count + c; incr kill);\n if !kill = k then raise End ) sorted_coins;\n with End -> ();\n end;\n Printf.printf \"%i \" !count;\ndone;\nprint_newline ();\n"}, {"source_code": "let ( */ ) = Big_int.mult_big_int;;\nlet ( +/ ) = Big_int.add_big_int;;\nlet ( -/ ) = Big_int.sub_big_int;;\nlet to_int = Big_int.int_of_big_int;;\nlet of_int = Big_int.big_int_of_int;;\nlet min = Big_int.min_big_int;;\nlet (modi) = Big_int.mod_big_int;;\nlet to_string = Big_int.string_of_big_int;;\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nexception End;;\n\nlet n,k = Scanf.sscanf (read_line ()) \"%i %i\" (fun n k -> n,k) in\nlet power = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet coins = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet sorted_coins = Array.mapi (fun i x -> (of_int x,i)) coins in\nArray.sort (fun (x,_) (y,_) -> to_int @@ y -/ x) sorted_coins;\nfor i = 0 to n-1 do\n let kill = ref 0 in\n let count = ref @@ of_int coins.(i) in\n begin try\n Array.iter (fun (c,j) -> if power.(j) < power.(i) then (count := !count +/ c; incr kill);\n if !kill = k then raise End ) sorted_coins;\n with End -> ();\n end;\n Printf.printf \"%s \" (to_string !count);\ndone;\nprint_newline ();\n"}], "src_uid": "fa55be247a70fb509182f2fe203f6024"} {"nl": {"description": "We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: The array consists of $$$n$$$ distinct positive (greater than $$$0$$$) integers. The array contains two elements $$$x$$$ and $$$y$$$ (these elements are known for you) such that $$$x < y$$$. If you sort the array in increasing order (such that $$$a_1 < a_2 < \\ldots < a_n$$$), differences between all adjacent (consecutive) elements are equal (i.e. $$$a_2 - a_1 = a_3 - a_2 = \\ldots = a_n - a_{n-1})$$$. It can be proven that such an array always exists under the constraints given below.Among all possible arrays that satisfy the given conditions, we ask you to restore one which has the minimum possible maximum element. In other words, you have to minimize $$$\\max(a_1, a_2, \\dots, a_n)$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$2 \\le n \\le 50$$$; $$$1 \\le x < y \\le 50$$$) \u2014 the length of the array and two elements that are present in the array, respectively.", "output_spec": "For each test case, print the answer: $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of the required array. If there are several answers, you can print any (it also means that the order of elements doesn't matter). It can be proven that such an array always exists under the given constraints.", "sample_inputs": ["5\n2 1 49\n5 20 50\n6 20 50\n5 3 8\n9 13 22"], "sample_outputs": ["1 49 \n20 40 30 50 10\n26 32 20 38 44 50 \n8 23 18 13 3 \n1 10 13 4 19 22 25 16 7"], "notes": null}, "positive_code": [{"source_code": "let line_of_numbers () =\n ()\n |> read_line\n |> Str.split (Str.regexp \" \")\n |> List.map (fun s -> s |> String.trim |> int_of_string)\n\nlet () =\n let [t] = line_of_numbers () in\n for _ = 1 to t do\n try\n let [n; x; y] = line_of_numbers () in\n let d = y - x in\n for s = 1 to d do\n if d mod s == 0 then\n let sc = d / s in\n let rs = n - (sc + 1) in\n if rs >= 0 then\n let st = x - (min rs ((x - 1) / s)) * s in\n for i = 0 to (n - 1) do\n st + i * s\n |> string_of_int\n |> print_string;\n print_char ' ';\n done;\n print_endline \"\";\n raise_notrace Exit\n done\n with\n Exit -> ()\n done\n"}], "negative_code": [{"source_code": "let line_of_numbers () =\n ()\n |> read_line\n |> Str.split (Str.regexp \" \")\n |> List.map (fun s -> s |> String.trim |> int_of_string)\n\nlet () =\n let [t] = line_of_numbers () in\n for _ = 1 to t do\n try\n let [n; x; y] = line_of_numbers () in\n let d = y - x in\n for s = 1 to d do\n if d mod s == 0 then\n let sc = d / s in\n let rs = n - (sc + 1) in\n if rs >= 0 then\n let st = x - (min rs (x / s)) * s in\n for i = 0 to (n - 1) do\n st + i * s\n |> string_of_int\n |> print_string;\n print_char ' ';\n done;\n print_endline \"\";\n raise_notrace Exit\n done\n with\n Exit -> ()\n done\n"}], "src_uid": "ca9d97e731e86cf8223520f39ef5d945"} {"nl": {"description": "Recently, Masha was presented with a chessboard with a height of $$$n$$$ and a width of $$$m$$$.The rows on the chessboard are numbered from $$$1$$$ to $$$n$$$ from bottom to top. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right. Therefore, each cell can be specified with the coordinates $$$(x,y)$$$, where $$$x$$$ is the column number, and $$$y$$$ is the row number (do not mix up).Let us call a rectangle with coordinates $$$(a,b,c,d)$$$ a rectangle lower left point of which has coordinates $$$(a,b)$$$, and the upper right one\u00a0\u2014 $$$(c,d)$$$.The chessboard is painted black and white as follows: An example of a chessboard. Masha was very happy with the gift and, therefore, invited her friends Maxim and Denis to show off. The guys decided to make her a treat\u00a0\u2014 they bought her a can of white and a can of black paint, so that if the old board deteriorates, it can be repainted. When they came to Masha, something unpleasant happened: first, Maxim went over the threshold and spilled white paint on the rectangle $$$(x_1,y_1,x_2,y_2)$$$. Then after him Denis spilled black paint on the rectangle $$$(x_3,y_3,x_4,y_4)$$$.To spill paint of color $$$color$$$ onto a certain rectangle means that all the cells that belong to the given rectangle become $$$color$$$. The cell dyeing is superimposed on each other (if at first some cell is spilled with white paint and then with black one, then its color will be black).Masha was shocked! She drove away from the guests and decided to find out how spoiled the gift was. For this, she needs to know the number of cells of white and black color. Help her find these numbers!", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$)\u00a0\u2014 the number of test cases. Each of them is described in the following format: The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n,m \\le 10^9$$$)\u00a0\u2014 the size of the board. The second line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \\le x_1 \\le x_2 \\le m, 1 \\le y_1 \\le y_2 \\le n$$$)\u00a0\u2014 the coordinates of the rectangle, the white paint was spilled on. The third line contains four integers $$$x_3$$$, $$$y_3$$$, $$$x_4$$$, $$$y_4$$$ ($$$1 \\le x_3 \\le x_4 \\le m, 1 \\le y_3 \\le y_4 \\le n$$$)\u00a0\u2014 the coordinates of the rectangle, the black paint was spilled on.", "output_spec": "Output $$$t$$$ lines, each of which contains two numbers\u00a0\u2014 the number of white and black cells after spilling paint, respectively.", "sample_inputs": ["5\n2 2\n1 1 2 2\n1 1 2 2\n3 4\n2 2 3 2\n3 1 4 3\n1 5\n1 1 5 1\n3 1 5 1\n4 4\n1 1 4 2\n1 3 4 4\n3 4\n1 2 4 2\n2 1 3 3"], "sample_outputs": ["0 4\n3 9\n2 3\n8 8\n4 8"], "notes": "NoteExplanation for examples:The first picture of each illustration shows how the field looked before the dyes were spilled. The second picture of each illustration shows how the field looked after Maxim spoiled white dye (the rectangle on which the dye was spilled is highlighted with red). The third picture in each illustration shows how the field looked after Denis spoiled black dye (the rectangle on which the dye was spilled is highlighted with red).In the first test, the paint on the field changed as follows: In the second test, the paint on the field changed as follows: In the third test, the paint on the field changed as follows: In the fourth test, the paint on the field changed as follows: In the fifth test, the paint on the field changed as follows: "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nlet hoge _ = scanf \" %Ld %Ld %Ld %Ld\" @@ fun p q r s -> p-1L,q-1L,r-1L,s-1L\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let n,m = get_2_i64 0 in\n let whites p q r s =\n let lx,ly = r-p+1L,s-q+1L in\n let white_lt = match p mod 2L,q mod 2L with\n | 0L,0L | 1L,1L -> 1L\n | _ -> 0L\n in\n match lx mod 2L,ly mod 2L with\n | 0L,0L -> lx*ly / 2L\n | 1L,1L -> (lx-1L)*(ly-1L)/2L + (lx-1L)/2L + (ly-1L)/2L + white_lt\n | 1L,0L -> lx*ly / 2L\n | 0L,1L -> lx*ly / 2L\n | _ -> fail 0 in\n let blacks p q r s = (r-p+1L)*(s-q+1L) - whites p q r s in\n let x,y,z,w = hoge 0 in\n let p,q,r,s = hoge 0\n in\n let a,b,c,d = max x p,max y q,min z r,min w s in\n let isec = if a>c || b>d then 0L else blacks a b c d in\n let white =\n whites 0L 0L (n-1L) (m-1L)\n + blacks x y z w\n - whites p q r s\n - isec in\n let black =\n blacks 0L 0L (n-1L) (m-1L)\n - blacks x y z w\n + whites p q r s\n + isec\n in assert (white + black = n*m);\n printf \"%Ld %Ld\\n\" white black;\n (* printf \" %Ld %Ld\\n\"\n (whites 0L 0L (n-1L) (m-1L))\n (blacks 0L 0L (n-1L) (m-1L));\n printf \" %Ld %Ld\\n\"\n (whites 0L 0L (n-1L) (m-1L) + blacks x y z w)\n (blacks 0L 0L (n-1L) (m-1L) - blacks x y z w); *)\n )\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "1c4607c96f7755af09445ff29a54bd08"} {"nl": {"description": "Mirror Box is a name of a popular game in the Iranian National Amusement Park (INAP). There is a wooden box, 105 cm long and 100 cm high in this game. Some parts of the box's ceiling and floor are covered by mirrors. There are two negligibly small holes in the opposite sides of the box at heights hl and hr centimeters above the floor. The picture below shows what the box looks like. In the game, you will be given a laser gun to shoot once. The laser beam must enter from one hole and exit from the other one. Each mirror has a preset number vi, which shows the number of points players gain if their laser beam hits that mirror. Also \u2014 to make things even funnier \u2014 the beam must not hit any mirror more than once.Given the information about the box, your task is to find the maximum score a player may gain. Please note that the reflection obeys the law \"the angle of incidence equals the angle of reflection\".", "input_spec": "The first line of the input contains three space-separated integers hl,\u2009hr,\u2009n (0\u2009<\u2009hl,\u2009hr\u2009<\u2009100, 0\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the heights of the holes and the number of the mirrors. Next n lines contain the descriptions of the mirrors. The i-th line contains space-separated vi,\u2009ci,\u2009ai,\u2009bi; the integer vi (1\u2009\u2264\u2009vi\u2009\u2264\u20091000) is the score for the i-th mirror; the character ci denotes i-th mirror's position \u2014 the mirror is on the ceiling if ci equals \"T\" and on the floor if ci equals \"F\"; integers ai and bi (0\u2009\u2264\u2009ai\u2009<\u2009bi\u2009\u2264\u2009105) represent the x-coordinates of the beginning and the end of the mirror. No two mirrors will share a common point. Consider that the x coordinate increases in the direction from left to right, so the border with the hole at height hl has the x coordinate equal to 0 and the border with the hole at height hr has the x coordinate equal to 105.", "output_spec": "The only line of output should contain a single integer \u2014 the maximum possible score a player could gain.", "sample_inputs": ["50 50 7\n10 F 1 80000\n20 T 1 80000\n30 T 81000 82000\n40 T 83000 84000\n50 T 85000 86000\n60 T 87000 88000\n70 F 81000 89000", "80 72 9\n15 T 8210 15679\n10 F 11940 22399\n50 T 30600 44789\n50 F 32090 36579\n5 F 45520 48519\n120 F 49250 55229\n8 F 59700 80609\n35 T 61940 64939\n2 T 92540 97769"], "sample_outputs": ["100", "120"], "notes": "NoteThe second sample is depicted above. The red beam gets 10\u2009+\u200950\u2009+\u20095\u2009+\u200935\u2009+\u20098\u2009+\u20092\u2009=\u2009110 points and the blue one gets 120.The red beam on the picture given in the statement shows how the laser beam can go approximately, this is just illustration how the laser beam can gain score. So for the second sample there is no such beam that gain score 110."}, "positive_code": [{"source_code": "let _ =\n let w = 100000 in\n let h = 100 in\n let sb = Scanf.Scanning.stdib in\n let hl = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let hr = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let v = Array.make n 0 in\n let b = Array.make n false in\n let u = Array.make w (-1) in\n let d = Array.make w (-1) in\n let res = ref 0 in\n let () =\n for i = 0 to n - 1 do\n let vv = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let aa = if c = \"T\" then u else d in\n\tv.(i) <- vv;\n\tfor j = a to b - 1 do\n\t aa.(j) <- i;\n\tdone\n done;\n in\n let solve hl hr u d =\n for i = 1 to 100 do\n Array.fill b 0 n false;\n let y =\n\t(i - 1) * h +\n\t if i mod 2 = 0\n\t then h - hr\n\t else hr\n in\n let r = ref 0 in\n\ttry\n\t for j = 0 to i - 1 do\n\t let z = j * h in\n\t let x =\n\t float_of_int (z + hl) *. float_of_int w /. float_of_int (y + hl)\n\t in\n\t (*Printf.printf \"asd %f %d %d %d\\n\" x hl y z;*)\n\t let x = int_of_float x in\n\t let a = if j mod 2 = 0 then d else u in\n\t if a.(x) < 0 || b.(a.(x))\n\t then raise Not_found\n\t else (\n\t\t(*Printf.printf \"hit %d %d %d\\n\" i a.(x) v.(a.(x));*)\n\t\tb.(a.(x)) <- true;\n\t\tr := !r + v.(a.(x));\n\t )\n\t done;\n\t res := max !res !r;\n\twith\n\t | Not_found -> ()\n done;\n in\n solve hl hr u d;\n solve (h - hl) (h - hr) d u;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [], "src_uid": "f0633a45bf4dffda694d0b8041a6d743"} {"nl": {"description": "Sengoku still remembers the mysterious \"colourful meteoroids\" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.On that night, Sengoku constructed a permutation p1,\u2009p2,\u2009...,\u2009pn of integers from 1 to n inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with n meteorids, colours of which being integer sequences a1,\u2009a2,\u2009...,\u2009an and b1,\u2009b2,\u2009...,\u2009bn respectively. Meteoroids' colours were also between 1 and n inclusive, and the two sequences were not identical, that is, at least one i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) exists, such that ai\u2009\u2260\u2009bi holds.Well, she almost had it all \u2014 each of the sequences a and b matched exactly n\u2009-\u20091 elements in Sengoku's permutation. In other words, there is exactly one i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) such that ai\u2009\u2260\u2009pi, and exactly one j (1\u2009\u2264\u2009j\u2009\u2264\u2009n) such that bj\u2009\u2260\u2009pj.For now, Sengoku is able to recover the actual colour sequences a and b through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.", "input_spec": "The first line of input contains a positive integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000) \u2014 the length of Sengoku's permutation, being the length of both meteor outbursts at the same time. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 the sequence of colours in the first meteor outburst. The third line contains n space-separated integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009n) \u2014 the sequence of colours in the second meteor outburst. At least one i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) exists, such that ai\u2009\u2260\u2009bi holds.", "output_spec": "Output n space-separated integers p1,\u2009p2,\u2009...,\u2009pn, denoting a possible permutation Sengoku could have had. If there are more than one possible answer, output any one of them. Input guarantees that such permutation exists.", "sample_inputs": ["5\n1 2 3 4 3\n1 2 5 4 5", "5\n4 4 2 3 1\n5 4 5 3 1", "4\n1 1 3 4\n1 4 3 4"], "sample_outputs": ["1 2 5 4 3", "5 4 2 3 1", "1 2 3 4"], "notes": "NoteIn the first sample, both 1,\u20092,\u20095,\u20094,\u20093 and 1,\u20092,\u20093,\u20094,\u20095 are acceptable outputs.In the second sample, 5,\u20094,\u20092,\u20093,\u20091 is the only permutation to satisfy the constraints."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n let b = Array.init n read_int in\n\n let hist = Array.make (n+1) 0 in\n\n for i=0 to n-1 do\n hist.(a.(i)) <- 1 + hist.(a.(i))\n done;\n\n let (_,dup) = maxf 1 n (fun i -> (hist.(i), i)) in\n let (_,missing) = minf 1 n (fun i -> (hist.(i), i)) in \n (* dup is the thing that occurs twice in a *)\n (* missing is the thing that does not occur in a *)\n \n let rec loop i ac = if i = n then ac else\n if a.(i) = dup then loop (i+1) (i::ac) else loop (i+1) ac\n in\n\n let dupindex = loop 0 [] in\n\n let i1 = List.nth dupindex 0 in\n let i2 = List.nth dupindex 1 in\n\n let p1 = Array.init n (fun i -> if i=i1 then missing else a.(i)) in\n let p2 = Array.init n (fun i -> if i=i2 then missing else a.(i)) in\n\n let diff1 = sum 0 (n-1) (fun i -> if b.(i) <> p1.(i) then 1 else 0) in\n let diff2 = sum 0 (n-1) (fun i -> if b.(i) <> p2.(i) then 1 else 0) in\n\n let answer = if diff1 = 1 then p1 else if diff2 = 1 then p2 else failwith \"bad\" in\n\n for i=0 to n-1 do\n printf \"%d \" answer.(i)\n done;\n print_newline()\n"}], "negative_code": [], "src_uid": "6fc3da19da8d9ab024cdd5acfc4f4164"} {"nl": {"description": "We get more and more news about DDoS-attacks of popular websites.Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds $$$100 \\cdot t$$$, where $$$t$$$ \u2014 the number of seconds in this time segment. Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence $$$r_1, r_2, \\dots, r_n$$$, where $$$r_i$$$ \u2014 the number of requests in the $$$i$$$-th second after boot. Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment $$$[1, n]$$$.", "input_spec": "The first line contains $$$n$$$ ($$$1 \\le n \\le 5000$$$) \u2014 number of seconds since server has been booted. The second line contains sequence of integers $$$r_1, r_2, \\dots, r_n$$$ ($$$0 \\le r_i \\le 5000$$$), $$$r_i$$$ \u2014 number of requests in the $$$i$$$-th second.", "output_spec": "Print the only integer number \u2014 the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.", "sample_inputs": ["5\n100 200 1 1 1", "5\n1 2 3 4 5", "2\n101 99"], "sample_outputs": ["3", "0", "1"], "notes": null}, "positive_code": [{"source_code": "open Scanf\nopen Printf\nlet read_int _ = bscanf Scanning.stdib \"%d \" (fun x -> x)\n\nlet () =\n\tlet n = read_int () in\n\tlet t = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tlet a = read_int () in\n\t\tt.(i) <- a;\n\tdone;\n\tlet res = ref 0 in\n\tfor i = 1 to n do\n\t\tlet sum = ref 0 in\n\t\tfor j = i to n do\n\t\t\tsum := !sum + t.(j);\n\t\t\tif !sum > (j - i + 1) * 100 then\n\t\t\t\tres := max (j - i + 1) (!res);\n\t\tdone;\n\t\t\n\tdone;\n\tprintf \"%d\\n\" !res\n\t"}], "negative_code": [], "src_uid": "ae531bc4b47e5d31fe71b6de1398b95e"} {"nl": {"description": "Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses (\"+\") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 109\u2009+\u20097. Help him!", "input_spec": "The first line contains two integers, n and k (0\u2009\u2264\u2009k\u2009<\u2009n\u2009\u2264\u2009105). The second line contains a string consisting of n digits.", "output_spec": "Print the answer to the problem modulo 109\u2009+\u20097.", "sample_inputs": ["3 1\n108", "3 2\n108"], "sample_outputs": ["27", "9"], "notes": "NoteIn the first sample the result equals (1\u2009+\u200908)\u2009+\u2009(10\u2009+\u20098)\u2009=\u200927.In the second sample the result equals 1\u2009+\u20090\u2009+\u20098\u2009=\u20099."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet p = 1_000_000_007L\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\nlet ( %% ) a b = Int64.rem a b\nlet ( ** ) a b = (Int64.mul a b) %% p\nlet ( ++ ) a b = (Int64.add a b) %% p\nlet ( -- ) a b = ((Int64.sub a b) ++ p)\n\nlet inverse a =\n let rec egcd a b =\n (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g *)\n if a = 0 then (0,1,b) else \n let (x,y,g) = egcd (b mod a) a in \n (y-(b/a)*x, x, g)\n in\n let (x,_,_) = egcd (short a) (short p) in\n long (if x >= 0 then x else x+(short p))\n\nlet init_factorial n =\n let f = Array.make (n+1) 1L in\n for i=1 to n do\n f.(i) <- (long i) ** f.(i-1)\n done;\n f\n\nlet binomial n k f = (* n choose k (f is the factoral table) *)\n if k < 0 || n < k then 0L else\n f.(n) ** (inverse f.(k)) ** (inverse f.(n-k))\n\nlet d2n c = (int_of_char c) - (int_of_char '0')\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let k = read_int () in\n let dig = read_string () in\n\n let fact = init_factorial n in\n\n let rec scan i s p ac = if i=n then ac else ( (* p=10^i *)\n let c = s ++ p ** (binomial (n-1-i) k fact) in\n let ac = ac ++ (long (d2n dig.[n-i-1])) ** c in\n let f = p ** (binomial (n-2-i) (k-1) fact) in\n let s = s ++ f in\n let p = 10L ** p in\n scan (i+1) s p ac\n ) in\n \n printf \"%Ld\\n\" (scan 0 0L 1L 0L)\n"}], "negative_code": [], "src_uid": "0cc9e1f64f615806d07e657be7386f5b"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$. Friends asked you to make the greatest common divisor (GCD) of all numbers in the array equal to $$$1$$$. In one operation, you can do the following: Select an arbitrary index in the array $$$1 \\leq i \\leq n$$$; Make $$$a_i = \\gcd(a_i, i)$$$, where $$$\\gcd(x, y)$$$ denotes the GCD of integers $$$x$$$ and $$$y$$$. The cost of such an operation is $$$n - i + 1$$$.You need to find the minimum total cost of operations we need to perform so that the GCD of the all array numbers becomes equal to $$$1$$$.", "input_spec": "Each test consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 5\\,000$$$) \u2014 the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 20$$$) \u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) \u2014 the elements of the array.", "output_spec": "For each test case, output a single integer \u2014 the minimum total cost of operations that will need to be performed so that the GCD of all numbers in the array becomes equal to $$$1$$$. We can show that it's always possible to do so.", "sample_inputs": ["9\n\n1\n\n1\n\n1\n\n2\n\n2\n\n2 4\n\n3\n\n3 6 9\n\n4\n\n5 10 15 20\n\n5\n\n120 60 80 40 80\n\n6\n\n150 90 180 120 60 30\n\n6\n\n2 4 6 9 12 18\n\n6\n\n30 60 90 120 125 125"], "sample_outputs": ["0\n1\n2\n2\n1\n3\n3\n0\n1"], "notes": "NoteIn the first test case, the GCD of the entire array is already equal to $$$1$$$, so there is no need to perform operations.In the second test case, select $$$i = 1$$$. After this operation, $$$a_1 = \\gcd(2, 1) = 1$$$. The cost of this operation is $$$1$$$.In the third test case, you can select $$$i = 1$$$, after that the array $$$a$$$ will be equal to $$$[1, 4]$$$. The GCD of this array is $$$1$$$, and the total cost is $$$2$$$.In the fourth test case, you can select $$$i = 2$$$, after that the array $$$a$$$ will be equal to $$$[3, 2, 9]$$$. The GCD of this array is $$$1$$$, and the total cost is $$$2$$$.In the sixth test case, you can select $$$i = 4$$$ and $$$i = 5$$$, after that the array $$$a$$$ will be equal to $$$[120, 60, 80, 4, 5]$$$. The GCD of this array is $$$1$$$, and the total cost is $$$3$$$."}, "positive_code": [{"source_code": "let rec gcd a b =\r\n\tif b=0 then a else gcd b (a mod b);;\r\n\r\nlet read_ints () =\r\n let line = read_line () in\r\n let ints = Str.split (Str.regexp \" *\") line in\r\n List.map int_of_string ints;;\r\n\r\nlet t = (List.hd (read_ints()))\r\nin\tfor i = 1 to t do\r\n\t\tlet n = (List.hd (read_ints()))\r\n\t\tin\tlet arr = read_ints()\r\n\t\t\tin\tlet g = List.fold_left gcd 0 arr in\r\n\t\t\t\tlet x = n-1 in\r\n\t\t\t\tif g = 1 then print_string \"0\\n\" else\r\n\t\t\t\t\tif (gcd g n) = 1 then print_string \"1\\n\" else\r\n\t\t\t\t\t\tif (gcd g x) = 1 then print_string \"2\\n\" else\r\n\t\t\t\t\t\t\tprint_string \"3\\n\"\r\ndone"}], "negative_code": [], "src_uid": "ff3216bcb009cb963d7e734ceb0e9722"} {"nl": {"description": "Luntik came out for a morning stroll and found an array $$$a$$$ of length $$$n$$$. He calculated the sum $$$s$$$ of the elements of the array ($$$s= \\sum_{i=1}^{n} a_i$$$). Luntik calls a subsequence of the array $$$a$$$ nearly full if the sum of the numbers in that subsequence is equal to $$$s-1$$$.Luntik really wants to know the number of nearly full subsequences of the array $$$a$$$. But he needs to come home so he asks you to solve that problem!A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. The next $$$2 \\cdot t$$$ lines contain descriptions of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 60$$$) \u2014 the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$) \u2014 the elements of the array $$$a$$$.", "output_spec": "For each test case print the number of nearly full subsequences of the array.", "sample_inputs": ["5\n5\n1 2 3 4 5\n2\n1000 1000\n2\n1 0\n5\n3 0 2 1 1\n5\n2 1 0 3 0"], "sample_outputs": ["1\n0\n2\n4\n4"], "notes": "NoteIn the first test case, $$$s=1+2+3+4+5=15$$$, only $$$(2,3,4,5)$$$ is a nearly full subsequence among all subsequences, the sum in it is equal to $$$2+3+4+5=14=15-1$$$.In the second test case, there are no nearly full subsequences.In the third test case, $$$s=1+0=1$$$, the nearly full subsequences are $$$(0)$$$ and $$$()$$$ (the sum of an empty subsequence is $$$0$$$)."}, "positive_code": [{"source_code": "\r\nlet rec count n n0 n1 =\r\n match n with\r\n | 0 -> (n0, n1)\r\n | _ -> let x = Scanf.scanf \" %d\" (fun x -> x)\r\n in match x with\r\n | 0 -> count (n - 1) (n0 + 1) n1\r\n | 1 -> count (n - 1) n0 (n1 + 1)\r\n | _ -> count (n - 1) n0 n1\r\n\r\nlet solve a b: Int64.t =\r\n Int64.mul (Int64.shift_left (Int64.of_int 1) a) (Int64.of_int b)\r\n\r\nlet () =\r\n let tc = Scanf.scanf \" %d\" (fun x -> x) in\r\n let rec loop tc =\r\n match tc with\r\n | 0 -> ()\r\n | _ -> let n = Scanf.scanf \" %d\" (fun x -> x) in\r\n let a, b = count n 0 0 in\r\n Printf.printf \"%Ld\\n\" (solve a b); loop (tc -1) \r\n in loop tc\r\n"}], "negative_code": [{"source_code": "\r\nlet rec count n n0 n1 =\r\n match n with\r\n | 0 -> (n0, n1)\r\n | _ -> let x = Scanf.scanf \" %d\" (fun x -> x)\r\n in match x with\r\n | 0 -> count (n - 1) (n0 + 1) n1\r\n | 1 -> count (n - 1) n0 (n1 + 1)\r\n | _ -> count (n - 1) n0 n1\r\n\r\nlet solve a b: Int64.t =\r\n Int64.mul (Int64.shift_left (Int64.of_int a) 1) (Int64.of_int b)\r\n\r\nlet () =\r\n let tc = Scanf.scanf \" %d\" (fun x -> x) in\r\n let rec loop tc =\r\n match tc with\r\n | 0 -> ()\r\n | _ -> let n = Scanf.scanf \" %d\" (fun x -> x) in\r\n let a, b = count n 0 0 in\r\n Printf.printf \"%Ld\\n\" (solve a b); loop (tc -1) \r\n in loop tc\r\n \r\n"}, {"source_code": "let rec count n n0 n1 =\r\n match n with\r\n | 0 -> (n0, n1)\r\n | _ -> let x = Scanf.scanf \" %d\" (fun x -> x)\r\n in match x with\r\n | 0 -> count (n - 1) (n0 + 1) n1\r\n | 1 -> count (n - 1) n0 (n1 + 1)\r\n | _ -> count (n - 1) n0 n1\r\n\r\nlet solve a b =\r\n (1 lsl a) * b\r\n\r\nlet () =\r\n let tc = Scanf.scanf \" %d\" (fun x -> x) in\r\n let rec loop tc =\r\n match tc with\r\n | 0 -> ()\r\n | _ -> let n = Scanf.scanf \" %d\" (fun x -> x) in\r\n let a, b = count n 0 0 in\r\n Printf.printf \"%d\\n\" (solve a b); loop (tc -1) \r\n in loop tc\r\n \r\n"}], "src_uid": "d786585fee251ebfd5c3e8d8b0425791"} {"nl": {"description": "There is a square matrix n\u2009\u00d7\u2009n, consisting of non-negative integer numbers. You should find such a way on it that starts in the upper left cell of the matrix; each following cell is to the right or down from the current cell; the way ends in the bottom right cell. Moreover, if we multiply together all the numbers along the way, the result should be the least \"round\". In other words, it should end in the least possible number of zeros.", "input_spec": "The first line contains an integer number n (2\u2009\u2264\u2009n\u2009\u2264\u20091000), n is the size of the matrix. Then follow n lines containing the matrix elements (non-negative integer numbers not exceeding 109).", "output_spec": "In the first line print the least number of trailing zeros. In the second line print the correspondent way itself.", "sample_inputs": ["3\n1 2 3\n4 5 6\n7 8 9"], "sample_outputs": ["0\nDDRR"], "notes": null}, "positive_code": [{"source_code": "let (|>) x f = f x\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet cnt n k : int =\n let rec go n acc =\n if n = 0 then\n 1000000\n else\n if n mod k <> 0 then\n acc\n else\n go (n/k) (acc+1)\n in go n 0\n\nlet dp n a k : int*string =\n let b : int array array = Array.init n (fun i ->\n Array.init n (fun j -> cnt a.(i).(j) k)) in\n for i = 1 to n-1 do\n b.(i).(0) <- b.(i).(0)+b.(i-1).(0);\n b.(0).(i) <- b.(0).(i)+b.(0).(i-1)\n done;\n for i = 1 to n-1 do\n for j = 1 to n-1 do\n b.(i).(j) <- b.(i).(j) + min b.(i-1).(j) b.(i).(j-1)\n done\n done;\n let plan = String.make (2*n-2) ' ' in\n let rec go i j =\n if i > 0 || j > 0 then\n if i = 0 || (j > 0 && b.(i).(j-1) < b.(i-1).(j)) then (\n plan.[i+j-1] <- 'R';\n go i (j-1)\n ) else (\n plan.[i+j-1] <- 'D';\n go (i-1) j\n ) in\n go (n-1) (n-1);\n b.(n-1).(n-1), plan\n\nlet () =\n let n = read_int 0 in\n let a : int array array = Array.init n (fun _ -> Array.init n read_int) in\n let two, two_plan = dp n a 2\n and five, five_plan = dp n a 5 in\n let zx, zy = ref (-1), ref (-1) in\n for i = 0 to n-1 do\n for j = 0 to n-1 do\n if a.(i).(j) = 0 then (\n zx := i;\n zy := j\n )\n done\n done;\n let ans = min two five in\n if ans > 0 && !zx <> (-1) then (\n print_endline \"1\";\n for i = 1 to !zx do\n print_char 'D'\n done;\n for i = 1 to !zy do\n print_char 'R'\n done;\n for i = !zx+1 to n-1 do\n print_char 'D'\n done;\n for i = !zy+1 to n-1 do\n print_char 'R'\n done\n ) else\n Printf.printf \"%d\\n%s\\n\" ans (if two < five then two_plan else five_plan)\n"}], "negative_code": [], "src_uid": "13c58291ab9cf7ad1b8c466c3e36aacf"} {"nl": {"description": "There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights. Fence for n\u2009=\u20097 and h\u2009=\u2009[1,\u20092,\u20096,\u20091,\u20091,\u20097,\u20091] Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly k consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such k consecutive planks that the sum of their heights is minimal possible.Write the program that finds the indexes of k consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).", "input_spec": "The first line of the input contains integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20091.5\u00b7105,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009n) \u2014 the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u2009100), where hi is the height of the i-th plank of the fence.", "output_spec": "Print such integer j that the sum of the heights of planks j, j\u2009+\u20091, ..., j\u2009+\u2009k\u2009-\u20091 is the minimum possible. If there are multiple such j's, print any of them.", "sample_inputs": ["7 3\n1 2 6 1 1 7 1"], "sample_outputs": ["3"], "notes": "NoteIn the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n\tlet n = read_int ()\n\tand m = read_int () \n\tand wyn = ref 100000000 \n\tand indeks = ref 1 in\n\n\tlet tab = Array.init n read_int \n\tand pref = Array.make (n + 1) 0 in\n\n\tfor i = 1 to n do\n\t\tpref.(i) <- pref.(i - 1) + tab.(i - 1);\n\tdone;\n\n\tfor i = 1 to n - m + 1 do \n\t\tlet roznica = pref.(i + m - 1) - pref.(i - 1) in\n\t\tif roznica < !wyn then begin\n\t\t\twyn := roznica;\n\t\t\tindeks := i;\n\t\tend;\n\tdone;\n\n\tprintf \"%d\\n\" !indeks;;"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet list_init n =\n let rec loop i list = \n if i < n\n then\n let element = read () in\n loop (i + 1) (element :: list)\n else\n List.rev list\n in loop 0 []\n\nlet input () = \n let n = read () in\n let k = read () in\n let list = list_init n in\n (n, k, list)\n\nlet get_sums list =\n let rec loop list sum sum_list = \n match list with\n | (head :: tail) ->\n let sum = head + sum in\n loop tail sum (sum :: sum_list)\n | [] -> List.rev sum_list\n in loop list 0 [0]\n\nlet solve (n, k, list) =\n let fence = get_sums list in\n let arr = Array.of_list fence in\n let rec loop i j min =\n if i + k <= n\n then\n let diff = arr.(i + k) - arr.(i) in\n if diff < min\n then\n loop (i + 1) i diff\n else\n loop (i + 1) j min\n else\n j + 1\n in loop 0 (n + 1) 1000000000\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input ()))"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n\tlet n = read_int ()\n\tand m = read_int () \n\tand wyn = ref 100000000 \n\tand indeks = ref 1 in\n\n\tlet tab = Array.init n read_int \n\tand pref = Array.make (n + 1) 0 in\n\n\tfor i = 1 to n do\n\t\tpref.(i) <- pref.(i - 1) + tab.(i - 1);\n\tdone;\n\n\tfor i = 1 to n - m + 1 do \n\t\tlet roznica = pref.(i + m - 1) - pref.(i) in\n\t\tif roznica < !wyn then begin\n\t\t\twyn := roznica;\n\t\t\tindeks := i;\n\t\tend;\n\tdone;\n\n\tprintf \"%d\\n\" !indeks;;"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet list_init n =\n let rec loop i list = \n if i < n\n then\n let element = read () in\n loop (i + 1) (element :: list)\n else\n List.rev list\n in loop 0 []\n\nlet input () = \n let n = read () in\n let k = read () in\n let list = list_init n in\n (n, k, list)\n\nlet get_sums list =\n let rec loop list sum sum_list = \n match list with\n | (head :: tail) ->\n let sum = head + sum in\n loop tail sum (sum :: sum_list)\n | [] -> List.rev sum_list\n in loop list 0 [0]\n\nlet solve (n, k, list) =\n let fence = get_sums list in\n let arr = Array.of_list fence in\n let rec loop i j min =\n if i + k < n\n then\n let diff = arr.(i + k) - arr.(i) in\n if diff < min\n then\n loop (i + 1) i diff\n else\n loop (i + 1) j min\n else\n j + 1\n in loop 0 (n + 1) 1500001\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input ()))"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet list_init n =\n let rec loop i list = \n if i < n\n then\n let element = read () in\n loop (i + 1) (element :: list)\n else\n List.rev list\n in loop 0 []\n\nlet input () = \n let n = read () in\n let k = read () in\n let list = list_init n in\n (n, k, list)\n\nlet get_sums list =\n let rec loop list sum sum_list = \n match list with\n | (head :: tail) ->\n let sum = head + sum in\n loop tail sum (sum :: sum_list)\n | [] -> List.rev sum_list\n in loop list 0 [0]\n\nlet solve (n, k, list) =\n let fence = get_sums list in\n let arr = Array.of_list fence in\n let rec loop i j min =\n if i + k <= n\n then\n let diff = arr.(i + k) - arr.(i) in\n if diff < min\n then\n loop (i + 1) i diff\n else\n loop (i + 1) j min\n else\n j + 1\n in loop 0 (n + 1) 1500001\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input ()))"}], "src_uid": "69f4e340b3f6e1d807e0545ebea1fe2f"} {"nl": {"description": "Given an array a1,\u2009a2,\u2009...,\u2009an of n integers, find the largest number in the array that is not a perfect square.A number x is said to be a perfect square if there exists an integer y such that x\u2009=\u2009y2.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of elements in the array. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009106\u2009\u2264\u2009ai\u2009\u2264\u2009106)\u00a0\u2014 the elements of the array. It is guaranteed that at least one element of the array is not a perfect square.", "output_spec": "Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.", "sample_inputs": ["2\n4 2", "8\n1 2 4 8 16 32 64 576"], "sample_outputs": ["2", "32"], "notes": "NoteIn the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2."}, "positive_code": [{"source_code": "let get_int () = Scanf.scanf \" %d\" (fun i -> i)\nlet get_float () = Scanf.scanf \" %f\" (fun i -> i)\n\nlet is_sqrt x =\n let r = int_of_float @@ sqrt (float_of_int x) in\n r * r = x\n\nlet get_array n =\n let rec aux acc k =\n if k = 0 then acc\n else aux (get_int () :: acc) (k - 1)\n in aux [] n\n\nlet main () =\n let n = get_int () in\n let rec aux m k =\n if k = 0 then m\n else\n let x = get_int () in\n if not (is_sqrt x) && x > m then aux x (k - 1)\n else aux m (k - 1)\n in\n let ans = aux (-1_000_000) n in\n Printf.printf \"%d\" ans\n\nlet () = main ()\n"}, {"source_code": "(* Mish test sort - worked *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet rec is_sq a n = \n (* let _ = begin print_int a; print_string \"\\n\" end in *)\n\t\tif n < 0 then false\n\t\telse if n==0 || n==1 then true\n else if a*a == n then true\n else if a*a>n then false\n else\n let da = (n - a*a)/(3*a) in\n let da = if da > a then a else da in\n let da = if da < 1 then 1 else da in\n let a1 = a+da in\n is_sq a1 n;;\n\nlet rec max_list mx l = match l with\n\t| [] -> mx\n\t| h :: t -> \n\t\tlet nmx = max mx h in\n\t\tmax_list nmx t;;\n\nlet main() =\n\tlet n = gr() in\n\tlet l = readlist (n) [] in\n\tlet lnsq = List.filter (fun x -> (not (is_sq 1 x))) l in\n\tlet ans = max_list (-100011122) lnsq in\n\tbegin\n\t\tprint_int ans;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}], "negative_code": [{"source_code": "let get_int () = Scanf.scanf \" %d\" (fun i -> i)\nlet get_float () = Scanf.scanf \" %f\" (fun i -> i)\n\nlet is_sqrt x =\n let r = int_of_float @@ sqrt (float_of_int x) in\n r * r = x\n\nlet get_array n =\n let rec aux acc k =\n if k = 0 then acc\n else aux (get_int () :: acc) (k - 1)\n in aux [] n\n\nlet main () =\n let n = get_int () in\n let rec aux m k =\n if k = 0 then m\n else\n let x = get_int () in\n if not (is_sqrt x) && x > m then aux x (k - 1)\n else aux m (k - 1)\n in\n let ans = aux 0 n in\n Printf.printf \"%d\" ans\n\nlet () = main ()\n"}], "src_uid": "d46d5f130d8c443f28b52096c384fef3"} {"nl": {"description": "Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland.Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of \u200b\u200bm pieces of paper in the garland. Calculate what the maximum total area of \u200b\u200bthe pieces of paper in the garland Vasya can get.", "input_spec": "The first line contains a non-empty sequence of n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) small English letters (\"a\"...\"z\"). Each letter means that Vasya has a sheet of paper of the corresponding color. The second line contains a non-empty sequence of m (1\u2009\u2264\u2009m\u2009\u2264\u20091000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make.", "output_spec": "Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer.", "sample_inputs": ["aaabbac\naabbccac", "a\nz"], "sample_outputs": ["6", "-1"], "notes": "NoteIn the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6.In the second test sample Vasya cannot make a garland at all \u2014 he doesn't have a sheet of color z."}, "positive_code": [{"source_code": "let s=read_line();;\nlet t=read_line();;\nlet tab=Array.make 26 0;;\nfor i=0 to String.length(t)-1 do\n let n=int_of_char(t.[i])-int_of_char 'a' in\n tab.(n)<-tab.(n)+1\ndone;;\nlet tabz=Array.make 26 0;;\nfor i=0 to String.length(s)-1 do\n let n=int_of_char(s.[i])-int_of_char 'a' in\n tabz.(n)<-tabz.(n)+1\ndone;;\nlet taba=Array.make 26 0;;\nfor i=0 to 25 do\n taba.(i)<-min tab.(i) tabz.(i)\ndone\nlet b=ref true;;\nfor i=0 to 25 do\n if (tab.(i)<>0)&&(tabz.(i)=0) then b:=false\ndone;;\nlet m=ref 0;;\nfor i=0 to 25 do\n m:= !m+taba.(i)\ndone;;\n\nif !b then print_int !m else print_int (-1);;"}], "negative_code": [{"source_code": "let s=read_line();;\nlet t=read_line();;\nlet tab=Array.make 26 0;;\nfor i=0 to String.length(t)-1 do\n let n=int_of_char(t.[i])-int_of_char 'a' in\n tab.(n)<-tab.(n)+1\ndone;;\n\nfor i=0 to String.length(s)-1 do\n let n=int_of_char(s.[i])-int_of_char 'a' in\n tab.(n)<-tab.(n)-1\ndone;;\n\nlet m=ref 0;;\nfor i=0 to 25 do\n m:= !m+max 0 (tab.(i))\ndone;;\n\nm:=String.length(t)- !m;;\nif !m=0 then m:=(-1);;\nif String.length(t)=0 then m:=0;;\nprint_int !m;;"}, {"source_code": "let s=read_line();;\nlet t=read_line();;\nlet tab=Array.make 26 0;;\nfor i=0 to String.length(t)-1 do\n let n=int_of_char(t.[i])-int_of_char 'a' in\n tab.(n)<-tab.(n)+1\ndone;;\n\nfor i=0 to String.length(s)-1 do\n let n=int_of_char(s.[i])-int_of_char 'a' in\n tab.(n)<-tab.(n)-1\ndone;;\n\nlet m=ref 0;;\nfor i=0 to 25 do\n m:= !m+max 0 (tab.(i))\ndone;;\n\nm:=String.length(t)- !m;;\nif !m=0 then m:=(-1);;\nprint_int !m;;"}], "src_uid": "b1e09df7c47dbd04992e64826337c28a"} {"nl": {"description": "One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.These events are given as a sequence of strings \"name1 reposted name2\", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string \"name1 reposted name2\" user \"name1\" didn't have the joke in his feed yet, and \"name2\" already had it in his feed by the moment of repost. Polycarp was registered as \"Polycarp\" and initially the joke was only in his feed.Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200) \u2014 the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as \"name1 reposted name2\". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive. We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.", "output_spec": "Print a single integer \u2014 the maximum length of a repost chain.", "sample_inputs": ["5\ntourist reposted Polycarp\nPetr reposted Tourist\nWJMZBMR reposted Petr\nsdya reposted wjmzbmr\nvepifanov reposted sdya", "6\nMike reposted Polycarp\nMax reposted Polycarp\nEveryOne reposted Polycarp\n111 reposted Polycarp\nVkCup reposted Polycarp\nCodeforces reposted Polycarp", "1\nSoMeStRaNgEgUe reposted PoLyCaRp"], "sample_outputs": ["6", "2", "2"], "notes": null}, "positive_code": [{"source_code": "type repost = Leaf of string\n | Node of repost list\n\nlet rec split num str = \n match str with\n | \"\" -> []\n | s ->\n let (beg,rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnStringList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (String.lowercase one) :: (returnStringList t \"\")\n else returnStringList t (one^h)\n | _ -> (String.lowercase one) :: []\n\nlet splitToList line =\n let lineList = split 1 line in\n returnStringList lineList \"\"\n\nlet rec makePairList strList =\n match strList with\n | (a :: b :: c::[]) :: t -> (c,a) :: (makePairList t)\n | _ -> []\n\n\nlet makeNode pairList st =\n let rec nodePair pList str =\n match pList with\n | (a,b) :: t ->\n if (compare a str) == 0 then\n Node (Leaf(b) :: nodePair pairList b) :: nodePair t str\n else nodePair t str\n | _ -> [] in\n Node(Leaf(st) :: nodePair pairList st) :: []\n\nlet rec countNode repost num=\n match repost with\n | Node(h :: t) :: tail ->\n let n = countNode t (num+1) in\n let m = countNode tail num in\n if (n > m) then n else m\n | _ -> num\n\n\nlet printLeaf leaf =\n match leaf with\n | Leaf(a) -> print_string \"[Leaf : \"; print_string a; print_string \" ]\"\n | _ -> print_string \" \"\n\nlet rec printList strList =\n match strList with\n | h :: t ->\n print_string h;print_string \" \";printList t\n | _ -> print_string \"\\n\"\nlet rec printPairList pairList =\n match pairList with\n | (a,b) :: t ->\n print_string a; print_string \" \"; print_string b; print_string \"\\n\";\n printPairList t\n | _ -> print_string\"\\n\"\n\nlet rec printRepost repost =\n match repost with\n | Node (h :: t) :: tail -> \n print_string \"[Node : \";printLeaf h; printRepost t; print_string \" ]\";\n printRepost tail\n | _ -> print_string \" \"\n\n\n\nlet n = read_int()\n\nlet rec strList num = \n if (num > 0) then\n let line = read_line() in\n let lineList = splitToList line in\n lineList :: (strList (num-1))\n else []\nlet pairList = makePairList (strList n)\n\nlet repost = makeNode pairList \"polycarp\"\nlet _ = print_int (countNode repost 0)\n\n"}, {"source_code": "type graph = Leaf of string | Node of graph list ;;\nlet tl = read_int() ;;\nlet rec genList num =\n if (num > 0) then\n let line = read_line() in\n let edge = Str.split (Str.regexp \" \") (String.lowercase line) in\n ((List.nth edge 2), (List.nth edge 0)) :: (genList (num-1))\n else []\n \nlet to_graph list_in str1 = \n let rec gen_pair list_in2 str2 = \n match list_in2 with\n | (a,b) :: t ->\n if (compare a str2) == 0 then\n Node (Leaf(b) :: gen_pair list_in2 b) :: gen_pair t str2\n else gen_pair t str2\n | _ -> [] in\n Node(Leaf(str1) :: gen_pair list_in str1) :: []\n\nlet rec count_node graph n =\n match graph with\n | Node(h :: t) :: tail ->\n max (count_node t (n+1)) (count_node tail n)\n | _ -> n\nlet myList = genList tl ;;\nlet graphRep = to_graph myList \"polycarp\" ;;\nprint_int(count_node graphRep 0)\n"}], "negative_code": [], "src_uid": "16d4035b138137bbad247ccd5e560051"} {"nl": {"description": "DZY loves colors, and he enjoys painting.On a colorful day, DZY gets a colorful ribbon, which consists of n units (they are numbered from 1 to n from left to right). The color of the i-th unit of the ribbon is i at first. It is colorful enough, but we still consider that the colorfulness of each unit is 0 at first.DZY loves painting, we know. He takes up a paintbrush with color x and uses it to draw a line on the ribbon. In such a case some contiguous units are painted. Imagine that the color of unit i currently is y. When it is painted by this paintbrush, the color of the unit becomes x, and the colorfulness of the unit increases by |x\u2009-\u2009y|.DZY wants to perform m operations, each operation can be one of the following: Paint all the units with numbers between l and r (both inclusive) with color x. Ask the sum of colorfulness of the units between l and r (both inclusive). Can you help DZY?", "input_spec": "The first line contains two space-separated integers n,\u2009m\u00a0(1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). Each of the next m lines begins with a integer type\u00a0(1\u2009\u2264\u2009type\u2009\u2264\u20092), which represents the type of this operation. If type\u2009=\u20091, there will be 3 more integers l,\u2009r,\u2009x\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009x\u2009\u2264\u2009108) in this line, describing an operation 1. If type\u2009=\u20092, there will be 2 more integers l,\u2009r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) in this line, describing an operation 2.", "output_spec": "For each operation 2, print a line containing the answer \u2014 sum of colorfulness.", "sample_inputs": ["3 3\n1 1 2 4\n1 2 3 5\n2 1 3", "3 4\n1 1 3 4\n2 1 1\n2 2 2\n2 3 3", "10 6\n1 1 5 3\n1 2 7 9\n1 10 10 11\n1 3 8 12\n1 1 10 3\n2 1 10"], "sample_outputs": ["8", "3\n2\n1", "129"], "notes": "NoteIn the first sample, the color of each unit is initially [1,\u20092,\u20093], and the colorfulness is [0,\u20090,\u20090].After the first operation, colors become [4,\u20094,\u20093], colorfulness become [3,\u20092,\u20090].After the second operation, colors become [4,\u20095,\u20095], colorfulness become [3,\u20093,\u20092].So the answer to the only operation of type 2 is 8."}, "positive_code": [{"source_code": "(*------------segment tree to do range increments and range sums------------------*)\n\nmodule type S = sig\n val inc_to : int -> int64 -> unit\n val sum_to : int -> int64\n val inc_range : int -> int -> int64 -> unit\n val sum_range : int -> int -> int64\nend\n\nmodule Make_sumtree (M: (sig val size : int end)) : S = struct\n let ( ** ) a b = Int64.mul a b\n let ( ++ ) a b = Int64.add a b\n let ( -- ) a b = Int64.sub a b\n\n let super_ceiling n =\n let rec log x = if x<=1 then 0 else 1 + (log (x lsr 1)) in\n 1 lsl (log (2*n-1))\n\n let n = M.size\n let sn = super_ceiling n\n let nn = n + sn\n\n let delta = Array.make nn 0L\n (* The value of a leaf is the sum of the deltas along the path from the leaf\n to the root *)\n let sum = Array.make nn 0L\n (* sum.(i) is the sum of all the leaves in the subtree rooted at i, taking into\n account all the deltas in the subtree rooted at i, but none of the deltas\n above i.*)\n\n let inc_to i d =\n (* s=size of the set of interest below node j\n p=power of 2 (size of left sibling of j if it has one)\n *)\n let rec loop j s p = if j>1 then\n let k = j/2 in\n if 2*k = j then (\n sum.(k) <- sum.(k) ++ s**d;\n loop k s (p++p)\n ) else (\n delta.(2*k) <- delta.(2*k) ++ d;\n sum.(2*k) <- sum.(2*k) ++ p**d;\n sum.(k) <- sum.(k) ++ (s++p)**d;\n loop k (s++p) (p++p)\n )\n in\n if i<0 then () else\n let i = i+sn in\n delta.(i) <- delta.(i) ++ d;\n sum.(i) <- sum.(i) ++ d;\n loop i 1L 1L\n\n let sum_to i =\n (* s=size of the set of interest below node j\n p=power of 2 (size of left sibling of j if it has one)\n ac = sum of the accumulated sum so far\n *)\n let rec loop j s p ac = if j=1 then ac else\n let k = j/2 in\n if 2*k = j then loop k s (p++p) (ac ++ delta.(k) ** s)\n else loop k (s++p) (p++p) (ac ++ sum.(2*k) ++ delta.(k) ** (s++p))\n in\n if i<0 then 0L else\n let i = i+sn in\n loop i 1L 1L sum.(i)\n\n let inc_range i j d = (\n inc_to j d; inc_to (i-1) (0L--d)\n )\n\n let sum_range i j = (sum_to j) -- (sum_to (i-1))\nend\n\n(*--------------------------------------------------------------------------------*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet long x = Int64.of_int x\n\nlet n = read_int()\nlet m = read_int()\nmodule Sum = Make_sumtree (struct let size=n end)\n\nmodule Tset = Set.Make (struct type t = int*int*int let compare = compare end)\n\nlet () =\n let process_recolor s l r x = \n let (s1,_,_) = Tset.split (l,n,0) s in\n let (s2,_,_) = Tset.split (r,n,0) s in\n let e_l = Tset.max_elt s1 in\n let e_r = Tset.max_elt s2 in\n let (left1,_,right2) = Tset.split e_l s in\n let (_,_,right1) = Tset.split e_r s in\n if e_l < e_r then (\n let (left3,_,_) = Tset.split e_r right2 in\n Tset.iter (\n\tfun (l2, r2, x2) -> Sum.inc_range l2 r2 (long (abs (x2-x)))\n ) left3;\n let (e_ll,e_lr,e_lx) = e_l in\n let (e_rl,e_rr,e_rx) = e_r in\n Sum.inc_range l e_lr (long (abs (e_lx-x)));\n Sum.inc_range e_rl r (long (abs (e_rx-x)));\n let left4 = if l>e_ll then Tset.add (e_ll,l-1,e_lx) left1 else left1 in\n let right4= if re_ll then Tset.add (e_ll,l-1,e_lx) s1 else s1 in\n let s3 = if r printf \"[%d,%d,%d] \" l r x) s;\n print_newline()\n in\n *)\n let rec loop s i = if i=m then () else\n let t = read_int() in\n let l = read_int() -1 in\n let r = read_int() -1 in\n if t=1 then \n\tlet x = read_int() in\n\tlet s = process_recolor s l r x in\n(*\tprintf \"After (%d %d %d %d): \" t l r x;\n\tprint_set s; *)\n\tloop s (i+1)\n else (\n\tprintf \"%Ld\\n\" (Sum.sum_range l r);\n\tloop s (i+1)\n )\n in\n\n let rec build_init s i = if i=n then s else\n build_init (Tset.add (i,i,i+1) s) (i+1)\n in\n\n let s = build_init Tset.empty 0 in\n(* printf \"initial set:\";\n print_set s;*)\n\n loop s 0\n"}], "negative_code": [], "src_uid": "562656bfc27b7cf06f7c4a373c6bc029"} {"nl": {"description": "Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print \"Infinity\". If there is no scenario matching the given information, print \"Impossible\".", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000). The i-th of next n lines contains two integers ci and di (\u2009-\u2009100\u2009\u2264\u2009ci\u2009\u2264\u2009100, 1\u2009\u2264\u2009di\u2009\u2264\u20092), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.", "output_spec": "If Limak's current rating can be arbitrarily big, print \"Infinity\" (without quotes). If the situation is impossible, print \"Impossible\" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.", "sample_inputs": ["3\n-7 1\n5 2\n8 2", "2\n57 1\n22 2", "1\n-5 1", "4\n27 2\n13 1\n-50 1\n8 2"], "sample_outputs": ["1907", "Impossible", "Infinity", "1897"], "notes": "NoteIn the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating: Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7. With rating 1894 Limak is in the division 2. His rating increases by 5. Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets \u2009+\u20098 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\nlet read_string () = Scanf.scanf \" %s \" (fun x -> x)\n\nlet ( $ ) f x = f x\n\n\n\nlet main () = \n let n = ref (read_int ()) in\n let l = ref (-123456789) in\n let r = ref 123456789 in\n let a, b = ref 0, ref 0 in\n for i = 1 to !n do\n a := read_int();\n b := read_int();\n if !b = 1 then\n l := max !l 1900\n else\n r := min !r 1899;\n l := (!l + !a);\n r := (!r + !a);\n done;\n if !l > !r then Printf.printf \"Impossible\"\n else if !r > 100000000 then Printf.printf \"Infinity\"\n else Printf.printf \"%d\" !r\n\n\n\n\nlet () = main ()"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let n = read_int () in\n\n let inf = 1_000_000_000 in\n\n let (++) a b = if abs a = inf then a else a+b in\n \n let rec loop i (lo,hi) = if i=n then (lo,hi) else\n let (c,div) = read_pair() in\n let hi = if div = 2 then min hi 1899 else hi in\n let lo = if div = 1 then max lo 1900 else lo in \n let lo = lo ++ c in\n let hi = hi ++ c in\n if lo > hi then (lo,hi) \n else loop (i+1) (lo,hi)\n in\n\n let (lo,hi) = loop 0 (-inf,inf) in\n\n if lo > hi then printf \"Impossible\\n\"\n else if hi = inf then printf \"Infinity\\n\"\n else printf \"%d\\n\" hi\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\nlet read_string () = Scanf.scanf \" %s \" (fun x -> x)\n\nlet ( $ ) f x = f x\n\n\n\nlet main () = \n let n = ref (read_int ()) in\n let l = ref (-min_int) in\n let r = ref max_int in\n let a, b = ref 0, ref 0 in\n for i = 1 to !n do\n a := read_int();\n b := read_int();\n if !b = 1 then\n l := max !l 1900\n else\n r := min !r 1899;\n l := (!l + !a);\n r := (!r + !a);\n done;\n if !l > !r then Printf.printf \"Impossible\"\n else if !r > 100000000 then Printf.printf \"Infinity\"\n else Printf.printf \"%d\" !r\n\n\n\n\nlet () = main ()"}], "src_uid": "2a4c24341231cabad6021697f15d953a"} {"nl": {"description": "Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1\u2009\u2264\u2009i\u2009\u2264\u2009|s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.", "input_spec": "The first line of the input contains a string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.", "output_spec": "If there is no way of replacing '#' characters which leads to a beautiful string print \u2009-\u20091. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them.", "sample_inputs": ["(((#)((#)", "()((#((#(#()", "#", "(#)"], "sample_outputs": ["1\n2", "2\n2\n1", "-1", "-1"], "notes": "Note|s| denotes the length of the string s."}, "positive_code": [{"source_code": "let s = read_line ();;\nlet l = Str.split (Str.regexp \"\") s;;\n\nlet rec balance op = function (* returns to_close net_closed *)\n| _ when op < 0 -> (-1, -1, [])\n| [] -> (op, 0, [])\n| \"(\" :: xs -> \n let (o, n, ys) = balance (op + 1) xs in \n if (n <= 0) then\n (o, n+1, ys)\n else\n (-1, -1, [])\n| \")\" :: xs -> \n let (o, n, ys) = balance (op - 1) xs in\n if (n <= 0) then\n (o, n-1, ys)\n else\n (-1, -1, [])\n| \"#\" :: xs ->\n let (o, n, ys) = balance (op - 1) xs in\n if (o >= 0 && n <= 0) then\n (0, n - (o+1), (o+1) :: ys)\n else\n (-1, -1, [])\n| _ -> assert false;;\n\n\nlet (o, n, xs) = balance 0 l;;\nif o <> 0 then\n print_newline (print_string \"-1\")\nelse\n List.iter (fun x -> print_newline (print_int x)) xs"}], "negative_code": [{"source_code": "let s = read_line ();;\nlet l = Str.split (Str.regexp \"\") s;;\n\nlet rec balance op = function (* returns to_close *)\n| _ when op < 0 -> (-1, [])\n| [] -> (op, [])\n| \"(\" :: xs -> balance (op + 1) xs\n| \")\" :: xs -> balance (op - 1) xs\n| \"#\" :: xs ->\n let (n, ys) = balance (op - 1) xs\n in \n if (n >= 0) then\n (0, (n+1) :: ys)\n else\n (-1, []);;\n\n\nlet (n, xs) = balance 0 l;;\nif n <> 0 then\n print_newline (print_string \"-1\")\nelse\n List.iter (fun x -> print_newline (print_int x)) xs"}, {"source_code": "let s = read_line ();;\nlet l = Str.split (Str.regexp \"\") s;;\n\nlet rec balance op = function (* returns to_close net_closed *)\n| _ when op < 0 -> (-1, -1, [])\n| [] -> (op, 0, [])\n| \"(\" :: xs -> let (o, n, ys) = balance (op + 1) xs in (o, n+1, ys)\n| \")\" :: xs -> let (o, n, ys) = balance (op - 1) xs in (o, n-1, ys)\n| \"#\" :: xs ->\n let (o, n, ys) = balance (op - 1) xs\n in\n if (o >= 0 && n <= 0) then\n (0, 0, (o+1) :: ys)\n else\n (-1, -1, []);;\n\n\nlet (o, n, xs) = balance 0 l;;\nif o <> 0 then\n print_newline (print_string \"-1\")\nelse\n List.iter (fun x -> print_newline (print_int x)) xs"}, {"source_code": "let s = read_line ();;\nlet l = Str.split (Str.regexp \"\") s;;\n\nlet rec balance op = function (* returns to_close net_closed *)\n| _ when op < 0 -> (-1, -1, [])\n| [] -> (op, 0, [])\n| \"(\" :: xs -> let (o, n, ys) = balance (op + 1) xs in (o, n+1, ys)\n| \")\" :: xs -> let (o, n, ys) = balance (op - 1) xs in (o, n-1, ys)\n| \"#\" :: xs ->\n let (o, n, ys) = balance (op - 1) xs\n in\n if (o >= 0 && n <= 0) then\n (0, n - (o+1), (o+1) :: ys)\n else\n (-1, -1, [])\n| _ -> assert false;;\n\n\nlet (o, n, xs) = balance 0 l;;\nif o <> 0 then\n print_newline (print_string \"-1\")\nelse\n List.iter (fun x -> print_newline (print_int x)) xs"}, {"source_code": "let s = read_line ();;\nlet l = Str.split (Str.regexp \"\") s;;\n\nlet rec balance op net = function (* returns to_close net_closed *)\n| _ when op < 0 -> (-1, -1, [])\n| [] -> (op, net, [])\n| \"(\" :: xs -> balance (op + 1) 1 xs\n| \")\" :: xs -> balance (op - 1) (-1) xs\n| \"#\" :: xs ->\n let (o, n, ys) = balance (op - 1) 0 xs\n in\n if (o >= 0 && n <= 0) then\n (0, 0, (o+1) :: ys)\n else\n (-1, -1, []);;\n\n\nlet (o, n, xs) = balance 0 0 l;;\nif o <> 0 then\n print_newline (print_string \"-1\")\nelse\n List.iter (fun x -> print_newline (print_int x)) xs"}], "src_uid": "0a30830361b26838b192d7de1efcdd2f"} {"nl": {"description": "Not so long ago, Vlad came up with an interesting function: $$$f_a(x)=\\left\\lfloor\\frac{x}{a}\\right\\rfloor + x \\bmod a$$$, where $$$\\left\\lfloor\\frac{x}{a}\\right\\rfloor$$$ is $$$\\frac{x}{a}$$$, rounded down, $$$x \\bmod a$$$ \u2014 the remainder of the integer division of $$$x$$$ by $$$a$$$.For example, with $$$a=3$$$ and $$$x=11$$$, the value $$$f_3(11) = \\left\\lfloor\\frac{11}{3}\\right\\rfloor + 11 \\bmod 3 = 3 + 2 = 5$$$.The number $$$a$$$ is fixed and known to Vlad. Help Vlad find the maximum value of $$$f_a(x)$$$ if $$$x$$$ can take any integer value from $$$l$$$ to $$$r$$$ inclusive ($$$l \\le x \\le r$$$).", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of input test cases. This is followed by $$$t$$$ lines, each of which contains three integers $$$l_i$$$, $$$r_i$$$ and $$$a_i$$$ ($$$1 \\le l_i \\le r_i \\le 10^9, 1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the left and right boundaries of the segment and the fixed value of $$$a$$$.", "output_spec": "For each test case, output one number on a separate line\u00a0\u2014 the maximum value of the function on a given segment for a given $$$a$$$.", "sample_inputs": ["5\n\n1 4 3\n\n5 8 4\n\n6 10 6\n\n1 1000000000 1000000000\n\n10 12 8"], "sample_outputs": ["2\n4\n5\n999999999\n5"], "notes": "NoteIn the first sample: $$$f_3(1) = \\left\\lfloor\\frac{1}{3}\\right\\rfloor + 1 \\bmod 3 = 0 + 1 = 1$$$, $$$f_3(2) = \\left\\lfloor\\frac{2}{3}\\right\\rfloor + 2 \\bmod 3 = 0 + 2 = 2$$$, $$$f_3(3) = \\left\\lfloor\\frac{3}{3}\\right\\rfloor + 3 \\bmod 3 = 1 + 0 = 1$$$, $$$f_3(4) = \\left\\lfloor\\frac{4}{3}\\right\\rfloor + 4 \\bmod 3 = 1 + 1 = 2$$$ As an answer, obviously, $$$f_3(2)$$$ and $$$f_3(4)$$$ are suitable."}, "positive_code": [{"source_code": "let hasMax l r a = r-l+1 >= a || (r mod a < l mod a) ;;\r\n\r\nlet searchMax r a = let toto = r/a in if r mod a = a-1 then (toto + a-1) else toto-1 + a -1;;\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let l,r,a = Scanf.sscanf(input_line stdin)\" %d %d %d\"(fun l r a->l,r,a) in\r\n let toto = if hasMax l r a then searchMax r a else (r/a + r mod a) in\r\n print_endline (string_of_int toto)\r\ndone;\r\n;;"}, {"source_code": "(* Codeforces 1638 A Reverse train done *)\r\n \r\n(* you can use either gr or rdln but not both, several gr() - inverted order *)\r\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\r\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\r\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet rdln() = input_line stdin;;\r\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\r\nlet debug = false;;\r\n \r\n(* reading list *)\r\nlet rec readlist n acc = match n with\r\n\t| 0 -> List.rev acc\r\n\t| _ -> readlist (n -1) (gr() :: acc);;\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\r\nlet list_to_s li = String.concat \" \" (List.map string_of_int li);;\r\n\r\n\r\nlet do_one () = \r\n let a,r,l = gr(), gr(), gr() in\r\n (* let _ = Printf.printf \"l,r,a = %d %d %d\\n\" l r a in *)\r\n let dl = l / a in\r\n let dr = r / a in\r\n let oor = r mod a in\r\n let mx = if dl == dr then dr + oor\r\n else \r\n let dr1 = if oor==a-1 then dr else dr-1 in\r\n dr1 + a - 1 in\r\n (print_int mx; print_string \"\\n\");;\r\n \r\nlet do_all () = \r\n let t = gr () in\r\n for i = 1 to t do\r\n do_one ()\r\n done;;\r\n \r\nlet main() =\r\n\tdo_all ();;\r\n \r\nmain();;"}], "negative_code": [{"source_code": "let hasMax l r a = r-l+1 >= a || (r mod a < l mod a) ;;\r\n\r\nlet searchMax r a = let toto = r/a in if r mod a = a-1 then (toto + a-1) else toto-1 + a -1;;\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let l,r,a = Scanf.sscanf(input_line stdin)\" %d %d %d\"(fun l r a->l,r,a) in\r\n let toto = if hasMax l r a then searchMax r a else (r/a + r mod a) in\r\n prerr_endline (string_of_int toto)\r\ndone;\r\n;;"}], "src_uid": "681ee82880ddd0de907aac2ccad8fc04"} {"nl": {"description": "CQXYM is counting permutations length of $$$2n$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).A permutation $$$p$$$(length of $$$2n$$$) will be counted only if the number of $$$i$$$ satisfying $$$p_i<p_{i+1}$$$ is no less than $$$n$$$. For example: Permutation $$$[1, 2, 3, 4]$$$ will count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$3$$$ ($$$i = 1$$$, $$$i = 2$$$, $$$i = 3$$$). Permutation $$$[3, 2, 1, 4]$$$ won't count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$1$$$ ($$$i = 3$$$). CQXYM wants you to help him to count the number of such permutations modulo $$$1000000007$$$ ($$$10^9+7$$$).In addition, modulo operation is to get the remainder. For example: $$$7 \\mod 3=1$$$, because $$$7 = 3 \\cdot 2 + 1$$$, $$$15 \\mod 4=3$$$, because $$$15 = 4 \\cdot 3 + 3$$$. ", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t (t \\geq 1)$$$ \u2014 the number of test cases. The description of the test cases follows. Only one line of each test case contains an integer $$$n(1 \\leq n \\leq 10^5)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$", "output_spec": "For each test case, print the answer in a single line.", "sample_inputs": ["4\n1\n2\n9\n91234"], "sample_outputs": ["1\n12\n830455698\n890287984"], "notes": "Note$$$n=1$$$, there is only one permutation that satisfies the condition: $$$[1,2].$$$In permutation $$$[1,2]$$$, $$$p_1<p_2$$$, and there is one $$$i=1$$$ satisfy the condition. Since $$$1 \\geq n$$$, this permutation should be counted. In permutation $$$[2,1]$$$, $$$p_1>p_2$$$. Because $$$0<n$$$, this permutation should not be counted.$$$n=2$$$, there are $$$12$$$ permutations: $$$[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[2,1,3,4],[2,3,1,4],[2,3,4,1],[2,4,1,3],[3,1,2,4],[3,4,1,2],[4,1,2,3].$$$"}, "positive_code": [{"source_code": "(* OCaml template *)\nopen Printf\nopen Scanf\n\n(* Redefine operators for Int64 *)\nlet ( + ) = Int64.add;;\nlet ( - ) = Int64.sub;;\nlet ( * ) = Int64.mul;;\nlet ( / ) = Int64.div;;\nlet ( % ) = Int64.rem;;\n\n(* Input *)\nlet read_int _ = bscanf Scanning.stdin \"%d \" @@ fun x -> x;;\nlet read_int64 _ = bscanf Scanning.stdin \"%Ld \" @@ fun x -> x;;\n\n(* Output *)\nlet print_int n = printf \"%d \" n;;\nlet print_int_endl n = printf \"%d\\n\" n;;\nlet print_int64 n = printf \"%Ld \" n;;\nlet print_int64_endl n = printf \"%Ld\\n\" n;;\n\n(* Utility functions *)\n(*\nlet sum = List.fold_left (+) 0;;\n*)\n\n(* Solve test case *)\nlet rec solve n = if n = 2L then 1L else n * solve (n - 1L) % 1000000007L;;\n\n(* Main *)\nlet t = read_int ();;\n\nfor t' = 1 to t do\n\t(* Solve test case here *)\n\tlet n = read_int64 () in\n\t\tprint_int64_endl @@ solve @@ 2L * n\ndone\n\n"}, {"source_code": "(* OCaml template *)\n\n(* Redefine operators for Int64 *)\nlet ( + ) = Int64.add;;\nlet ( - ) = Int64.sub;;\nlet ( * ) = Int64.mul;;\nlet ( / ) = Int64.div;;\nlet ( % ) = Int64.rem;;\n\n(* Utility functions *)\nlet sum = List.fold_left (+) 0L;;\n\n(* Main *)\nlet m = 1000000007L;;\n\nlet rec solve (n:int64) = if n = 2L then 1L else n * solve (n - 1L) % m;;\n\nlet t = read_int ();;\n\nfor t' = 1 to t do\n\t(* Solve test case here *)\n\tlet n = read_int () in\n\t\tprint_endline @@ Int64.to_string @@ solve @@ 2L * Int64.of_int n\ndone\n"}, {"source_code": "(* OCaml template *)\n\n(* Utility functions *)\nlet sum = List.fold_left (+) 0;;\n\n(* Main *)\nlet m = 1000000007L;;\n\nlet rec solve (n:int64) = if n = 2L then 1L else Int64.rem (Int64.mul n (solve (Int64.pred n))) m;;\n\nlet t = read_int ();;\n\nfor t' = 1 to t do\n\t(* Solve test case here *)\n\tlet n = read_int () in\n\t\tprint_endline @@ Int64.to_string @@ solve @@ Int64.mul 2L (Int64.of_int n)\ndone\n"}], "negative_code": [{"source_code": "(* OCaml template *)\n\ntype int = int64;;\n\n(* Utility functions *)\nlet print_int_endline n = print_endline @@ string_of_int n\nlet sum = List.fold_left (+) 0;;\n\nlet rec solve n = if n = 2 then 1 else n * solve (n - 1) mod 1000000007;;\n\n(* Main *)\nlet t = read_int ();;\n\nfor t' = 1 to t do\n\t(* Solve test case here *)\n\tlet n = read_int () in\n\t\tprint_int_endline @@ solve @@ 2 * n\ndone\n"}, {"source_code": "(* OCaml template *)\n\n(* Utility functions *)\nlet sum = List.fold_left (+) 0;;\n\n(* Main *)\nlet m = 1000000007;;\n\nlet rec solve (n:int) = if n = 2 then 1 else n * solve (n - 1) mod m;;\n\nlet t = read_int ();;\n\nfor t' = 1 to t do\n\t(* Solve test case here *)\n\tlet n = read_int () in\n\t\tprint_endline @@ string_of_int @@ solve @@ 2 * n;\ndone\n"}], "src_uid": "19a2550af6a46308fd92c7a352f12a5f"} {"nl": {"description": "Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day ki products will be put up for sale and exactly li clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale ki products and Noora has chosen this day for sell-out, shelves of the shop would keep 2\u00b7ki products. Consequently, there is an opportunity to sell two times more products on days of sell-out.Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.", "input_spec": "The first line contains two integers n and f (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009f\u2009\u2264\u2009n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out. Each line of the following n subsequent lines contains two integers ki,\u2009li (0\u2009\u2264\u2009ki,\u2009li\u2009\u2264\u2009109) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.", "output_spec": "Print a single integer denoting the maximal number of products that shop can sell.", "sample_inputs": ["4 2\n2 1\n3 5\n2 3\n1 5", "4 1\n0 2\n0 3\n3 5\n0 6"], "sample_outputs": ["10", "5"], "notes": "NoteIn the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2,\u20096,\u20092,\u20092] respectively. So on the first day shop will sell 1 product, on the second\u00a0\u2014 5, on the third\u00a0\u2014 2, on the fourth\u00a0\u2014 2. In total 1\u2009+\u20095\u2009+\u20092\u2009+\u20092\u2009=\u200910 product units.In the second example it is possible to sell 5 products, if you choose third day for sell-out."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %Ld %Ld \" (fun x y -> (x,y))\n \nlet () = \n let n = read_int () in\n let f = read_int () in\n let day = Array.init n read_pair in\n\n let value i =\n let (k,l) = day.(i) in \n min l k\n in\n \n let delta i =\n let (k,l) = day.(i) in\n let before = min l k in\n let after = min l (2L ** k) in\n (after -- before, i)\n in\n\n let gain = Array.init n delta in\n\n Array.sort (fun a b -> compare b a) gain;\n\n let answer = sum 0 (n-1) (fun i -> (if i x)\r\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\r\n \r\n(* Main Code file *)\r\n\r\nlet rec sum = function\r\n | [] -> 0\r\n | h::t -> if h then sum(t) + 1 else sum(t)\r\n\r\nlet () = \r\n let exist str i = \r\n String.contains str (char_of_int (i + 65))\r\n in\r\n let n = read_int() in\r\n for i=1 to n do\r\n let len = read_int() in\r\n let x = read_string() in\r\n let arr = Array.init 26 (exist x) in\r\n printf \"%d\\n\" (len + (sum (Array.to_list arr)))\r\n done;"}], "negative_code": [], "src_uid": "66777b8719b1756bf4b6bf93feb2e439"} {"nl": {"description": "The Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) element of the permutation a as ai, the j-th (1\u2009\u2264\u2009j\u2009\u2264\u2009n) element of the permutation b \u2014 as bj.The distance between permutations a and b is the minimum absolute value of the difference between the positions of the occurrences of some number in a and in b. More formally, it's such minimum |i\u2009-\u2009j|, that ai\u2009=\u2009bj.A cyclic shift number i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) of permutation b consisting from n elements is a permutation bibi\u2009+\u20091... bnb1b2... bi\u2009-\u20091. Overall a permutation has n cyclic shifts.The Little Elephant wonders, for all cyclic shifts of permutation b, what is the distance between the cyclic shift and permutation a?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of the permutations. The second line contains permutation a as n distinct numbers from 1 to n, inclusive. The numbers are separated with single spaces. The third line contains permutation b in the same format.", "output_spec": "In n lines print n integers \u2014 the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation b, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on.", "sample_inputs": ["2\n1 2\n2 1", "4\n2 1 3 4\n3 4 2 1"], "sample_outputs": ["1\n0", "2\n1\n0\n1"], "notes": null}, "positive_code": [{"source_code": "module IntPairSet = Set.Make(\n struct\n type t = int * int\n (*let compare ((x, x') : int * int) (y, y') =\n if x < y\n then -1\n else if x > y\n then 1\n else 0*)\n let compare = compare\n end\n)\n(*\nmodule IntSet = Set.Make(\n struct\n type t = int\n let compare (x : int) y =\n if x < y\n then -1\n else if x > y\n then 1\n else 0\n end\n)\n*)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = Array.make n 0 in\n let ra = Array.make n 0 in\n let rb = Array.make n 0 in\n let d = Array.make n 0 in\n let f = ref IntPairSet.empty in\n let g = ref IntPairSet.empty in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\ta.(i) <- k;\n\tra.(k) <- i;\n done;\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tb.(i) <- k;\n\trb.(k) <- i;\n done;\n for i = 0 to n - 1 do\n d.(i) <- rb.(a.(i)) - i;\n if d.(i) < 0\n then f := IntPairSet.add (d.(i), i) !f\n else g := IntPairSet.add (d.(i), i) !g\n done\n in\n for i = 0 to n - 1 do\n (try\n\t while fst (IntPairSet.min_elt !g) - i < 0 do\n\t let k = IntPairSet.min_elt !g in\n\t g := IntPairSet.remove k !g;\n\t f := IntPairSet.add k !f;\n\t done;\n with\n\t | Not_found -> ()\n );\n (*(try\n\t while fst (IntPairSet.min_elt !f) - i <= -n do\n\t let (x, y) as k = IntPairSet.min_elt !f in\n\t f := IntPairSet.remove k !f;\n\t g := IntPairSet.add (x + n, y) !g;\n\t done;\n with\n\t | Not_found -> ()\n );*)\n if i <> 0 then (\n\ttry\n\t let x = ra.(b.(i - 1)) in\n\t let k = (d.(x), x) in\n\t f := IntPairSet.remove k !f;\n\t g := IntPairSet.add (d.(x) + n, x) !g;\n\twith\n\t | Not_found -> assert false\n );\n let k1 =\n\ttry\n\t fst (IntPairSet.min_elt !g) - i\n\twith\n\t | Not_found -> n + 1\n in\n let k2 =\n\ttry\n\t -(fst (IntPairSet.max_elt !f) - i)\n\twith\n\t | Not_found -> n + 1\n in\n\t(*IntPairSet.iter (fun (k, y) -> Printf.printf \"f %d %d\\n\" k y) !f;\n\tIntPairSet.iter (fun (k, y) -> Printf.printf \"g %d %d\\n\" k y) !g;\n\tPrintf.printf \"kk %d %d\\n\" k1 k2;*)\n let res = min k1 k2 in\n\tPrintf.printf \"%d\\n\" res\n done\n"}], "negative_code": [{"source_code": "module IntSet = Set.Make(\n struct\n type t = int\n let compare (x : int) y =\n if x < y\n then -1\n else if x > y\n then 1\n else 0\n end\n)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = Array.make n 0 in\n let ra = Array.make n 0 in\n let rb = Array.make n 0 in\n let d = Array.make n 0 in\n let f = ref IntSet.empty in\n let g = ref IntSet.empty in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\ta.(i) <- k;\n\tra.(k) <- i;\n done;\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tb.(i) <- k;\n\trb.(k) <- i;\n done;\n for i = 0 to n - 1 do\n d.(i) <- rb.(i) - ra.(i);\n if d.(i) < 0\n then f := IntSet.add d.(i) !f\n else g := IntSet.add d.(i) !g\n done\n in\n for i = 0 to n - 1 do\n (try\n\t while IntSet.min_elt !g - i < 0 do\n\t let k = IntSet.min_elt !g in\n\t g := IntSet.remove k !g;\n\t f := IntSet.add k !f;\n\t done;\n with\n\t | Not_found -> ()\n );\n (try\n\t while IntSet.min_elt !f - i <= -n do\n\t let k = IntSet.min_elt !f in\n\t f := IntSet.remove k !f;\n\t g := IntSet.add (k + n) !g;\n\t done;\n with\n\t | Not_found -> ()\n );\n let k1 =\n\ttry\n\t IntSet.min_elt !g - i\n\twith\n\t | Not_found -> n + 1\n in\n let k2 =\n\ttry\n\t -(IntSet.max_elt !f - i)\n\twith\n\t | Not_found -> n + 1\n in\n let res = min k1 k2 in\n\tPrintf.printf \"%d\\n\" res\n done\n"}], "src_uid": "4b1326b0891571ef8ccb63a3351d1851"} {"nl": {"description": "Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.Fangy takes some positive integer x and wants to get a number one from it. While x is not equal to 1, Fangy repeats the following action: if x is odd, then he adds 1 to it, otherwise he divides x by 2. Fangy knows that for any positive integer number the process ends in finite time.How many actions should Fangy perform to get a number one from number x?", "input_spec": "The first line contains a positive integer x in a binary system. It is guaranteed that the first digit of x is different from a zero and the number of its digits does not exceed 106.", "output_spec": "Print the required number of actions.", "sample_inputs": ["1", "1001001", "101110"], "sample_outputs": ["0", "12", "8"], "notes": "NoteLet's consider the third sample. Number 101110 is even, which means that we should divide it by 2. After the dividing Fangy gets an odd number 10111 and adds one to it. Number 11000 can be divided by 2 three times in a row and get number 11. All that's left is to increase the number by one (we get 100), and then divide it by 2 two times in a row. As a result, we get 1."}, "positive_code": [{"source_code": "let len = ref 0;;\nlet c0 = ref 0;;\nlet c1 = ref 0;;\nlet m = ref (0-1);;\ntry while true do\n\tlet c = input_byte stdin - 48 in\n\t(if 10 - 48 = c then raise End_of_file ;\n\tincr (if c = 0 then c0 else c1);\n\tif c = 1 then m := (0-1) else incr m)\ndone with _ -> ();;\n\nif (!c1) = 1 then begin\n\tprint_int (!c0);\n\texit 0\nend;;\n\nprint_int ((!c0)*2+(!c1)-(!m));;\n"}], "negative_code": [{"source_code": "let read_bin () = \n\tlet x = Stack.create () in\n\tlet _ = (String.iter (fun c ->\n\t\tStack.push (if c = '0' then 0 else 1) x\n\t) (read_line())) in x\n;;\n\nlet rec inc_bin x =\n\tlet y = try Stack.pop x with _ -> 0 in\n\tif y = 0 then begin\n\t\tStack.push 1 x\n\tend else begin\n\t\tinc_bin x;\n\t\tStack.push 0 x\n\tend\n;;\n\nlet div2_bin x = \n\tignore(Stack.pop x)\n;;\n\nlet () = \n\tlet i = ref 0 in\n\tlet x = Stack.create () in\n let _ = (String.iter (fun c ->\n if c = '0' && Stack.top x = 0 then (incr i; incr i) \n\t\t\telse Stack.push (if c = '0' then 0 else 1) x\n ) (read_line())) in \n\tlet _ = (while Stack.length x <> 1 || Stack.top x <> 1 do\n\t\tif Stack.top x = 1 then inc_bin x else div2_bin x;\n\t\tincr i\n\tdone) in print_int (!i)\n;;\n"}], "src_uid": "e46c6406d19e8679fd282d72882ae78d"} {"nl": {"description": "And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0,\u20090), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following: during one run the minibus makes n stops, the i-th stop is in point (xi,\u20090) coordinates of all the stops are different the minibus drives at a constant speed, equal to vb it can be assumed the passengers get on and off the minibus at a bus stop momentarily Student can get off the minibus only at a bus stop Student will have to get off the minibus at a terminal stop, if he does not get off earlier the University, where the exam will be held, is in point (xu,\u2009yu) Student can run from a bus stop to the University at a constant speed vs as long as needed a distance between two points can be calculated according to the following formula: Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.", "input_spec": "The first line contains three integer numbers: 2\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009vb,\u2009vs\u2009\u2264\u20091000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn\u2009\u2264\u2009105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value. ", "output_spec": "In the only line output the answer to the problem \u2014 index of the optimum bus stop.", "sample_inputs": ["4 5 2\n0 2 4 6\n4 1", "2 1 1\n0 100000\n100000 100000"], "sample_outputs": ["3", "2"], "notes": "NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus."}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let vb = read_float 0 in\n let vs = read_float 0 in\n let a = Array.init n read_float in\n let x = read_float 0 in\n let y = read_float 0 in\n let rec go i (mit,mid,mii as mi) =\n if i = n then\n mi\n else\n let d = (a.(i)-.x)**2.0 +. y*.y |> sqrt in\n let t = a.(i)/.vb+.d/.vs in\n if t < mit || t = mit && d < mid then\n go (i+1) (t,d,i)\n else\n go (i+1) mi\n in\n let _,_,i = go 1 (1e9,1e9,-1) in\n Printf.printf \"%d\\n\" (i+1)\n"}], "negative_code": [], "src_uid": "15fa49860e978d3b3fb7a20bf9f8aa86"} {"nl": {"description": "Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $$$q$$$ questions about this song. Each question is about a subsegment of the song starting from the $$$l$$$-th letter to the $$$r$$$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $$$k$$$ times, where $$$k$$$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring \"abbcb\", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c\" three times, so that the resulting string is \"abbbbcccbb\", its length is $$$10$$$. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1\\leq n\\leq 100\\,000$$$, $$$1\\leq q \\leq 100\\,000$$$)\u00a0\u2014 the length of the song and the number of questions. The second line contains one string $$$s$$$\u00a0\u2014 the song, consisting of $$$n$$$ lowercase letters of English letters. Vasya's questions are contained in the next $$$q$$$ lines. Each line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\leq l \\leq r \\leq n$$$)\u00a0\u2014 the bounds of the question.", "output_spec": "Print $$$q$$$ lines: for each question print the length of the string obtained by Vasya.", "sample_inputs": ["7 3\nabacaba\n1 3\n2 5\n1 7", "7 4\nabbabaa\n1 3\n5 7\n6 6\n2 4", "13 7\nsonoshikumiwo\n1 5\n2 10\n7 7\n1 13\n4 8\n2 5\n3 9"], "sample_outputs": ["4\n7\n11", "5\n4\n1\n5", "82\n125\n9\n191\n62\n63\n97"], "notes": "NoteIn the first example Vasya is interested in three questions. In the first question Vasya considers the substring \"aba\", that transforms to \"abba\", so the answer is equal to $$$4$$$. In the second question Vasya considers \"baca\", that transforms to \"bbaccca\", so the answer is $$$7$$$. In the third question Vasya considers the string \"abacaba\",that transforms to \"abbacccabba\" of length $$$11$$$."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x)\r\nlet to_array s = Array.init (String.length s) (\r\n fun t ->\r\n (int_of_char (String.get s t)) - (int_of_char 'a') + 1\r\n )\r\nlet scan_string () = Scanf.scanf \" %s\" (fun s -> to_array s)\r\nlet cal_pre a =\r\n for i = 1 to (Array.length a) - 1 do\r\n a.(i) <- a.(i) + a.(i - 1)\r\n done;\r\n Array.append [|0|] a\r\n\r\nlet n = scan_int ()\r\nlet q = scan_int ()\r\nlet pre = cal_pre (scan_string());;\r\n\r\nfor i = 1 to q do\r\n let l = scan_int() in\r\n let r = scan_int() in\r\n Printf.printf \"%d\\n\" (pre.(r) - pre.(l - 1))\r\ndone"}], "negative_code": [], "src_uid": "461378e9179c9de454674ea9dc49c56c"} {"nl": {"description": "You are given an array a consisting of n integers. You have to process q queries to this array; each query is given as four numbers l, r, x and y, denoting that for every i such that l\u2009\u2264\u2009i\u2009\u2264\u2009r and ai\u2009=\u2009x you have to set ai equal to y.Print the array after all queries are processed.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200000) \u2014 the size of array a. The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) \u2014 the elements of array a. The third line contains one integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009200000) \u2014 the number of queries you have to process. Then q lines follow. i-th line contains four integers l, r, x and y denoting i-th query (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n, 1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009100).", "output_spec": "Print n integers \u2014 elements of array a after all changes are made.", "sample_inputs": ["5\n1 2 3 4 5\n3\n3 5 3 5\n1 5 5 1\n1 5 1 5"], "sample_outputs": ["5 2 5 4 5"], "notes": null}, "positive_code": [{"source_code": "module Ints =\n struct\n type t = int\n let compare = Pervasives.compare\n end;;\n\nmodule IntSet = Set.Make(Ints);;\n\nlet indexes_of_values =\n Array.make 101 IntSet.empty;;\n\n \nlet rev_split_on_char sep s =\n let len = String.length s in\n let rec aux first_index acc =\n if first_index = len then\n acc\n else\n try\n let i = String.index_from s first_index sep in\n aux (i + 1) ((String.sub s first_index (i - first_index)) :: acc)\n with Not_found -> (String.sub s first_index (len - first_index)) :: acc\n in\n aux 0 []\n\nlet read_line_of_ints () =\n let line = read_line () in\n let items = rev_split_on_char ' ' line in\n List.rev_map int_of_string items;;\n\nlet affect first_index last_index former_value new_value =\n let former_value_indexes = Array.get indexes_of_values former_value in\n let (smaller_indexes_set, first_is_former, matching_and_higher) = IntSet.split first_index former_value_indexes in\n let (matching_indexes_set, last_is_former, higher_indexes_set) = IntSet.split last_index matching_and_higher in\n Array.set indexes_of_values former_value (IntSet.union smaller_indexes_set higher_indexes_set);\n let new_values_old_set = Array.get indexes_of_values new_value in\n let new_values_new_set = IntSet.union new_values_old_set matching_indexes_set in\n let new_values_new_with_last = if last_is_former then IntSet.add last_index new_values_new_set else new_values_new_set in\n let final_new_values = if first_is_former then IntSet.add first_index new_values_new_with_last else new_values_new_with_last in\n Array.set indexes_of_values new_value final_new_values;;\n\nlet n = read_int ();;\nlet a = read_line_of_ints ();;\n(* TODO: put initial values in the indexes thing *)\nList.iteri (fun i x -> Array.set indexes_of_values x (IntSet.add i indexes_of_values.(x))) a;;\nlet queries_count = read_int ();;\nfor i = 1 to queries_count do\n let l :: r :: x :: y :: [] = read_line_of_ints () in\n affect (l - 1) (r - 1) x y\ndone;;\nlet final_array = Array.make n (-1);;\nfor i = 1 to 100 do\n IntSet.iter (fun j -> Array.set final_array j i) indexes_of_values.(i)\ndone;;\nArray.iter (fun x -> print_int x; print_char ' ') final_array;;\nprint_newline ();;\n"}], "negative_code": [], "src_uid": "56c375ba93e136715a2276d2e560dd51"} {"nl": {"description": "The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.Find any longest k-good segment.As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.", "input_spec": "The first line contains two integers n,\u2009k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105) \u2014 the number of elements in a and the parameter k. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the elements of the array a.", "output_spec": "Print two integers l,\u2009r (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) \u2014 the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.", "sample_inputs": ["5 5\n1 2 3 4 5", "9 3\n6 5 1 2 3 2 1 4 5", "3 1\n1 2 3"], "sample_outputs": ["1 5", "3 7", "1 1"], "notes": null}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet licz x = (x-|Int64.one)/|two_64;;\n\nlet _ = \n let (n,k) = Scanf.scanf \"%d %d\\n\" (fun x y-> x, y) in\n let ile = Array.make 1000001 0 \n and tab = Array.make 1000001 0\n and id = ref 1\n and wyn = ref 0\n and obc = ref 1\n and suma = ref 0 in\n for i=1 to n do\n let x = read (n-i) in\n tab.(i) <- x;\n if ile.(x) = 0 then incr suma;\n ile.(x) <- ile.(x) + 1;\n while !suma > k do\n ile.( tab.(!obc) ) <- ile.( tab.(!obc) ) - 1;\n if ile.( tab.(!obc) ) = 0 then suma := !suma - 1;\n incr obc\n done;\n if i - !obc + 1 > !wyn then begin\n id := !obc;\n wyn := i - !obc + 1\n end\n done;\n Printf.printf \"%d %d\\n\" !id (!id + !wyn -1 ) ;;\n\n\n"}, {"source_code": "let xint() = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let n = xint() and k = xint() in\n let a = Array.make n 0 in\n let c = Array.make 1000001 0 in\n for i = 0 to n - 1 do\n a.(i) <- xint();\n done;\n let add x =\n c.(x) <- c.(x) + 1;\n if c.(x) = 1 then 1 else 0\n in\n let sub x =\n c.(x) <- c.(x) - 1;\n if c.(x) = 0 then 1 else 0;\n in\n let j = ref 0 and tot = ref 0 in\n let sx = ref 0 and sy = ref ~-1 in\n for i = 0 to n - 1 do\n tot := !tot + (add a.(i));\n while !tot > k do\n tot := !tot - (sub a.(!j));\n j := !j + 1;\n done;\n if i - !j > !sy - !sx then (\n sx := !j;\n sy := i;\n );\n done;\n sx := !sx + 1;\n sy := !sy + 1;\n Printf.printf \"%d %d\\n\" !sx !sy;\n"}], "negative_code": [], "src_uid": "e0ea798c8ce0d8a4340e0fa3399bcc3b"} {"nl": {"description": "Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009105). The second line contains m integers a1,\u2009a2,\u2009...,\u2009am (1\u2009\u2264\u2009ai\u2009\u2264\u2009n). Note that Xenia can have multiple consecutive tasks in one house.", "output_spec": "Print a single integer \u2014 the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["4 3\n3 2 3", "4 3\n2 3 3"], "sample_outputs": ["6", "2"], "notes": "NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1\u2009\u2192\u20092\u2009\u2192\u20093\u2009\u2192\u20094\u2009\u2192\u20091\u2009\u2192\u20092\u2009\u2192\u20093. This is optimal sequence. So, she needs 6 time units."}, "positive_code": [{"source_code": "module My_int64 = \nstruct\n let ( + ) = Int64.add\n let ( - ) = Int64.sub\n let zero = Int64.zero\n let one = Int64.one\nend\n\nopen My_int64\n\nlet read () = Scanf.scanf \"%Ld \" (fun n -> n)\n\nlet input () = \n let houses = read () in\n let jobs = read () in\n let rec loop job_houses i =\n if i < jobs\n then\n let job_house = read () in\n loop (job_house :: job_houses) (i + one)\n else\n (houses, (List.rev job_houses)) \n in loop [] zero\n\nlet solve (houses, job_houses) =\n let rec loop count last list =\n match list with\n | (head :: tail) ->\n if head < last\n then\n loop (count + (houses - last) + head) head tail\n else\n loop (count + head - last) head tail \n | [] -> count\n in loop zero one job_houses\n\nlet print result = Printf.printf \"%Ld\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "let (n, m) = Scanf.scanf \"%Ld %d\\n\" (fun x y -> (x, y)) in\nlet pos = ref Int64.one in\nlet t = ref Int64.zero in\nfor i = 1 to m do\n let p = Scanf.scanf \"%Ld%[ ]\" (fun x _ -> x) in\n t := Int64.add !t (Int64.rem (Int64.sub (Int64.add p n) !pos) n) ;\n pos := p\ndone ;\nPrintf.printf \"%Ld\\n\" !t ;;\n"}], "negative_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let houses = read () in\n let jobs = read () in\n let rec loop job_houses i =\n if i < jobs\n then\n let job_house = Scanf.scanf \"%d \" (fun n -> n) in\n loop (job_house :: job_houses) (i + 1)\n else\n (houses, jobs, (List.rev job_houses)) \n in loop [] 0\n\nlet solve (houses, jobs, job_houses) =\n let rec loop count last list =\n match list with\n | (head :: tail) ->\n if head < last\n then\n loop (count + (houses - last) + head) head tail\n else\n loop (count + head - last) head tail \n | [] -> count\n in loop 0 1 job_houses\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}], "src_uid": "2c9c96dc5b6f8d1f0ddeea8e07640d3e"} {"nl": {"description": "A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it\u00a0\u2014 the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \\dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \\dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$: $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$\u00a0\u2014 that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$\u00a0\u2014 that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$\u00a0\u2014 that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$. $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$\u00a0\u2014 that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 99$$$)\u00a0\u2014 the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$)\u00a0\u2014 the required length of permutations in the chain.", "output_spec": "For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \\dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \\dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$.", "sample_inputs": ["2\n\n2\n\n3"], "sample_outputs": ["2\n1 2\n2 1\n3\n1 2 3\n3 2 1\n3 1 2"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x->x);;\r\n\r\nlet get_permutation = function\r\n| (k, num_swaps) ->\r\n (* 1,2,3,4,5 \r\n 2,1,3,4,5\r\n 2,3,1,4,5\r\n 2,3,4,1,5\r\n 2,3,4,5,1\r\n \r\n 1=number of swaps index\r\n do rest in order , skipping\r\n the number of swaps index\r\n *)\r\n let rec iter_p = function\r\n | i -> \r\n if (i=k) then []\r\n else if (inum_swaps) then\r\n (i+1)::(iter_p (i+1))\r\n else\r\n 1::(iter_p (i+1))\r\n in iter_p (0)\r\n;;\r\n\r\nlet run_case = function\r\n| k ->\r\n print_int (k);\r\n print_newline ();\r\n let rec run_permutations = function\r\n | swaps ->\r\n if (swaps =k) then ()\r\n else begin\r\n let p = get_permutation (k, swaps) in\r\n let rec out_p = function\r\n | [] -> print_newline ()\r\n | x::xs ->\r\n Printf.printf \"%d \" x;\r\n out_p (xs)\r\n in out_p (p);\r\n run_permutations (swaps+1)\r\n end\r\n in run_permutations (0);\r\n;;\r\n\r\n \r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| n ->\r\n let k = read_int () in\r\n run_case (k);\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet cases = read_int () in iter_cases (cases);;\r\n \r\n \r\n "}], "negative_code": [], "src_uid": "02bdd12987af6e666d4283f075f73725"} {"nl": {"description": "Two people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell. An example of the initial situation at s = \"abacaba\" A player's move is the sequence of actions: The player chooses one of the available pieces of paper with some string written on it. Let's denote it is t. Note that initially, only one piece of paper is available. The player chooses in the string t\u2009=\u2009t1t2... t|t| character in position i (1\u2009\u2264\u2009i\u2009\u2264\u2009|t|) such that for some positive integer l (0\u2009<\u2009i\u2009-\u2009l;\u00a0i\u2009+\u2009l\u2009\u2264\u2009|t|) the following equations hold: ti\u2009-\u20091\u2009=\u2009ti\u2009+\u20091, ti\u2009-\u20092\u2009=\u2009ti\u2009+\u20092, ..., ti\u2009-\u2009l\u2009=\u2009ti\u2009+\u2009l. Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string t1t2... ti\u2009-\u20091, the second one will contain a string consisting of a single character ti, the third one contains string ti\u2009+\u20091ti\u2009+\u20092... t|t|. An example of making action (i\u2009=\u20094) with string s = \u00ababacaba\u00bb Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.", "input_spec": "The first line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20095000). It is guaranteed that string s only contains lowercase English letters.", "output_spec": "If the second player wins, print in the single line \"Second\" (without the quotes). Otherwise, print in the first line \"First\" (without the quotes), and in the second line print the minimal possible winning move \u2014 integer i (1\u2009\u2264\u2009i\u2009\u2264\u2009|s|).", "sample_inputs": ["abacaba", "abcde"], "sample_outputs": ["First\n2", "Second"], "notes": "NoteIn the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2. In the second sample the first player has no available moves."}, "positive_code": [{"source_code": "(*\nSubject: Re: CF 184 div 2 E (game theory problem)\nDate: May 21, 2013 7:14:46 AM EDT\n\nAn allowed move is of the form: a1 a2 ... an ---> a1...ai -1 ai a+1....an\nas long as ai-1 = ai+1. The middle piece is irrelevant because no future move can\nbe made there. (This description of the allowed moves seems to differ from yours.)\n\nThere's an O(n^3) algorithm. For every (i,j) we're going to compute the nimber\nof the game ai....aj, using DP. For a given string you try all the legal moves,\nand look up the nimbers of the left and right part. Take the xor of the two\nparts. And over all these options, take the MEX. This gives you the nimber of\nthe string.\n\n[[\nThe MEX of a set of numbers is the minimum excluded integer. \ne.g. MEX(2,3,4,5)= 0. MEX(0,1,2,3,5) = 4.\n\nI'm attaching my 251 lecture which contains a description of this material\non sums of games in the following message\n]]\n\nIf the nimber of the final string is 0 then then it's a Second player win, otherwise\nit is a First player win. In the latter case the winning move is any one that makes\nthe nimber be 0.\n\nSince n=5000, the O(n^3) algorithm will be too slow. So another trick is\nneeded.\n\nHere's how to make this O(n^2). Let's go through and mark all the positions\nwhich admit a legal move at the beginning. Let a 1 indicate the position is \nlegal to move and a 0 otherwise. This pattern of zeros and ones completely\ndetermines the game. \n\nIf two 1s are isolated, as in 01010, then those two moves are completely\nindependent. (both moves can be made independently of the other). The\nsame holds for any blocks of 1s. So, 00111101110. has two separate \ngames, one is \"1111\" and the other is \"111\". So all that is required to figure\nout the nimber of a game is to evaluate the nimbers of all the blocks of 1s\nof various sizes. When you make a move in a block of 1s, the move\nsplits the string in two, and removes up to two neighboring ones. E.g. the\nlegal moves from 111111 are to 1111, 111, 1+11,11+1,111, 1111.\n\nFor each block length we just have to try all the moves, each of which splits\nit into two blocks, and xor the parts together, then take the MEX (just like the\nabove algorithm). The difference here is that only the length matters, not\nthe starting and ending points. So it's O(n^2) to evaluate the nimber of\nall block lengths up to n.\n\n*)\n\nopen Printf\n\nmodule Iset = Set.Make (struct type t = int let compare = compare end)\n\nlet solve n s =\n let bits = Array.init n (\n fun i -> if i=0 || i=n-1 then 0 else if s.[i-1] = s.[i+1] then 1 else 0\n ) in\n \n let rec find_blocks i j ac = if i=n then List.rev ac else\n (* j is the length of the block of 1s prior to this point *)\n if bits.(i) = 1 then find_blocks (i+1) (j+1) ac\n else find_blocks (i+1) 0 (if j>0 then (i-j,j)::ac else ac)\n in\n\n let blocks = find_blocks 0 0 [] in\n\n(*\n List.iter (fun (p,j) -> printf \"(%d,%d) \" p j) blocks;\n print_newline()\n*)\n \n let m = List.fold_left (fun ac (_,j) -> max ac j) 0 blocks in\n\n let nimber = Array.make (m+1) 0 in\n\n let mex_of_set s = \n let rec loop i = if Iset.mem i s then loop (i+1) else i in\n loop 0\n in\n\n let eval_move k j = \n let leftnimber = if k=0 then 0 else nimber.(k-1) in\n let rightnimber = if k=j-1 then 0 else nimber.(j-k-2) in\n leftnimber lxor rightnimber \n in\n\n for j=1 to m do\n let rec loop k s = if k=(j+1)/2 then s else\n\t loop (k+1) (Iset.add (eval_move k j) s)\n in\n let s = loop 0 Iset.empty in\n\tnimber.(j) <- mex_of_set s;\n(*\tprintf \"nimber.(%d) = %d\\n\" j nimber.(j) *)\n done;\n\n let total_nimber = List.fold_left (fun ac (_,j) -> ac lxor nimber.(j)) 0 blocks in\n if total_nimber = 0 then 0 else\n\tlet rec loop bl = match bl with \n\t | [] -> failwith \"should not happen\"\n\t | (p,j)::bl -> \n\t let goal = total_nimber lxor nimber.(j) in\n\t let rec findmove k = if k=(j+1)/2 then -1 else\n\t\tif eval_move k j = goal then k else findmove (k+1) in\n\t let k = findmove 0 in\n\t\tif k<0 then loop bl else k+p+1\n\tin\n\t loop blocks\n\nlet () = \n let s = read_line() in\n let n = String.length s in\n let k = solve n s in\n if k=0 then printf \"Second\\n\"\n else printf \"First\\n%d\\n\" k\n"}], "negative_code": [{"source_code": "(*\nSubject: Re: CF 184 div 2 E (game theory problem)\nDate: May 21, 2013 7:14:46 AM EDT\n\nAn allowed move is of the form: a1 a2 ... an ---> a1...ai -1 ai a+1....an\nas long as ai-1 = ai+1. The middle piece is irrelevant because no future move can\nbe made there. (This description of the allowed moves seems to differ from yours.)\n\nThere's an O(n^3) algorithm. For every (i,j) we're going to compute the nimber\nof the game ai....aj, using DP. For a given string you try all the legal moves,\nand look up the nimbers of the left and right part. Take the xor of the two\nparts. And over all these options, take the MEX. This gives you the nimber of\nthe string.\n\n[[\nThe MEX of a set of numbers is the minimum excluded integer. \ne.g. MEX(2,3,4,5)= 0. MEX(0,1,2,3,5) = 4.\n\nI'm attaching my 251 lecture which contains a description of this material\non sums of games in the following message\n]]\n\nIf the nimber of the final string is 0 then then it's a Second player win, otherwise\nit is a First player win. In the latter case the winning move is any one that makes\nthe nimber be 0.\n\nSince n=5000, the O(n^3) algorithm will be too slow. So another trick is\nneeded.\n\nHere's how to make this O(n^2). Let's go through and mark all the positions\nwhich admit a legal move at the beginning. Let a 1 indicate the position is \nlegal to move and a 0 otherwise. This pattern of zeros and ones completely\ndetermines the game. \n\nIf two 1s are isolated, as in 01010, then those two moves are completely\nindependent. (both moves can be made independently of the other). The\nsame holds for any blocks of 1s. So, 00111101110. has two separate \ngames, one is \"1111\" and the other is \"111\". So all that is required to figure\nout the nimber of a game is to evaluate the nimbers of all the blocks of 1s\nof various sizes. When you make a move in a block of 1s, the move\nsplits the string in two, and removes up to two neighboring ones. E.g. the\nlegal moves from 111111 are to 1111, 111, 1+11,11+1,111, 1111.\n\nFor each block length we just have to try all the moves, each of which splits\nit into two blocks, and xor the parts together, then take the MEX (just like the\nabove algorithm). The difference here is that only the length matters, not\nthe starting and ending points. So it's O(n^2) to evaluate the nimber of\nall block lengths up to n.\n\n*)\n\nopen Printf\n\nmodule Iset = Set.Make (struct type t = int let compare = compare end)\n\nlet solve n s =\n let bits = Array.init n (\n fun i -> if i=0 || i=n-1 then 0 else if s.[i-1] = s.[i+1] then 1 else 0\n ) in\n \n let rec find_blocks i j ac = if i=n then List.rev ac else\n (* j is the length of the block of 1s prior to this point *)\n if bits.(i) = 1 then find_blocks (i+1) (j+1) ac\n else find_blocks (i+1) 0 (if j>0 then (i-j,j) ::ac else ac)\n in\n\n let blocks = find_blocks 0 0 [] in\n\n(*\n List.iter (fun (p,j) -> printf \"(%d,%d) \" p j) blocks;\n print_newline()\n*)\n \n let m = List.fold_left (fun ac (_,j) -> max ac j) 0 blocks in\n\n let nimber = Array.make (m+1) 0 in\n\n let mex_of_set s = \n let rec loop i = if Iset.mem i s then loop (i+1) else i in\n loop 0\n in\n\n let eval_move k j = \n let leftnimber = if k=0 then 0 else nimber.(k-1) in\n let rightnimber = if k=j-1 then 0 else nimber.(j-k-2) in\n leftnimber lxor rightnimber \n in\n\n for j=1 to m do\n let rec loop k s = if k=(j+1)/2 then s else\n\t loop (k+1) (Iset.add (eval_move k j) s)\n in\n let s = loop 0 Iset.empty in\n\tnimber.(j) <- mex_of_set s;\n(*\tprintf \"nimber.(%d) = %d\\n\" j nimber.(j) *)\n done;\n\n let total_nimber = List.fold_left (fun ac (_,j) -> ac lxor nimber.(j)) 0 blocks in\n if total_nimber = 0 then 0 else\n\tlet rec loop bl = match bl with \n\t | [] -> failwith \"should not happen\"\n\t | (p,j)::bl -> \n\t if (total_nimber lxor nimber.(j)) < nimber.(j) then (p,j) else loop bl\n\tin\n\tlet (p,j) = loop blocks in\n\tlet goal = total_nimber lxor nimber.(j) in\n\tlet rec findmove k = if eval_move k j = goal then k else findmove (k+1) in\n\t (findmove 0) + p + 1\n\nlet () = \n let s = read_line() in\n let n = String.length s in\n let k = solve n s in\n if k=0 then printf \"Second\\n\"\n else printf \"First\\n%d\\n\" k\n"}], "src_uid": "f5d9490dc6e689944649820df5f23657"} {"nl": {"description": "Ashishgup and FastestFinger play a game. They start with a number $$$n$$$ and play in turns. In each turn, a player can make any one of the following moves: Divide $$$n$$$ by any of its odd divisors greater than $$$1$$$. Subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer \u00a0\u2014 $$$n$$$ ($$$1 \\leq n \\leq 10^9$$$).", "output_spec": "For each test case, print \"Ashishgup\" if he wins, and \"FastestFinger\" otherwise (without quotes).", "sample_inputs": ["7\n1\n2\n3\n4\n5\n6\n12"], "sample_outputs": ["FastestFinger\nAshishgup\nAshishgup\nFastestFinger\nAshishgup\nFastestFinger\nAshishgup"], "notes": "NoteIn the first test case, $$$n = 1$$$, Ashishgup cannot make a move. He loses.In the second test case, $$$n = 2$$$, Ashishgup subtracts $$$1$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the third test case, $$$n = 3$$$, Ashishgup divides by $$$3$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the last test case, $$$n = 12$$$, Ashishgup divides it by $$$3$$$. Now $$$n = 4$$$, FastestFinger is forced to subtract $$$1$$$, and Ashishgup gets $$$3$$$, so he wins by dividing it by $$$3$$$."}, "positive_code": [{"source_code": "let rec is_pow_of_two (t : int) =\n if t mod 2 = 1 then\n false\n else\n if t = 2 then\n true\n else\n is_pow_of_two (t / 2)\n;;\n\nlet rec is_prime (t : int) (i : int) =\n if t = 1 then\n false\n else if i * i > t then\n true\n else\n if t mod i = 0 then\n false\n else\n is_prime t (i + 1)\n;;\n\nlet rec main (t : int) =\n if t = 0 then\n ()\n else\n let n = read_int () in\n (if (n = 1) || ((is_pow_of_two n) && n <> 2) || (n mod 2 = 0 && is_prime (n / 2) 2) then\n print_endline \"FastestFinger\"\n else\n print_endline \"Ashishgup\"; main (t-1))\n\n;;\n\nlet n = read_int ()\nin\nmain n\n"}], "negative_code": [], "src_uid": "b533572dd6d5fe7350589c7f4d5e1c8c"} {"nl": {"description": "Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence $$$a$$$ of length $$$n$$$. In each operation, she can select an arbitrary interval $$$[l, r]$$$ and for all values $$$i$$$ ($$$0\\leq i \\leq r-l$$$), replace $$$a_{l+i}$$$ with $$$a_{l+i} \\,\\&\\, a_{r-i}$$$ at the same time, where $$$\\&$$$ denotes the bitwise AND operation. This operation can be performed any number of times.For example, if $$$n=5$$$, the array is $$$[a_1,a_2,a_3,a_4,a_5]$$$, and Mocha selects the interval $$$[2,5]$$$, then the new array is $$$[a_1,a_2\\,\\&\\, a_5, a_3\\,\\&\\, a_4, a_4\\,\\&\\, a_3, a_5\\,\\&\\, a_2]$$$.Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$).", "output_spec": "For each test case, print one integer \u2014 the minimal value of the maximum value in the sequence.", "sample_inputs": ["4\n2\n1 2\n3\n1 1 3\n4\n3 11 3 7\n5\n11 7 15 3 7"], "sample_outputs": ["0\n1\n3\n3"], "notes": "NoteIn the first test case, Mocha can choose the interval $$$[1,2]$$$, then the sequence becomes $$$[ 0, 0]$$$, where the first element is $$$1\\,\\&\\,2$$$, and the second element is $$$2\\,\\&\\,1$$$.In the second test case, Mocha can choose the interval $$$[1,3]$$$, then the sequence becomes $$$[ 1,1,1]$$$, where the first element is $$$1\\,\\&\\,3$$$, the second element is $$$1\\,\\&\\,1$$$, and the third element is $$$3\\,\\&\\,1$$$."}, "positive_code": [{"source_code": "(* This is an OCaml editor.\r\n Enter your program here and send it to the toplevel using the \"Eval code\"\r\n button. *)\r\n\r\nlet readInt () = Scanf.scanf \" %d\" (fun i -> i);;\r\n\r\nlet print_number x = print_string (string_of_int x); print_newline();;\r\n\r\nlet p2 = Array.make 31 0;;\r\nlet p = ref 1;;\r\n\r\nfor i = 0 to 30 do\r\n p2.(i) <- !p;\r\n p := 2 * !p;\r\ndone;;\r\n\r\nlet f x y z =\r\n if x + y = 2 then p2.(z) else 0;;\r\n\r\nlet rec func x y z =\r\n match z with\r\n | 31 -> 0 \r\n | z -> f (x mod 2) (y mod 2) z + func (x / 2) (y / 2) (z + 1);;\r\n\r\nlet comp x y = func x y 0;;\r\n\r\n\r\nlet t = readInt() in\r\nfor _ = 1 to t do \r\n let l = ref [] in\r\n let n = readInt() in\r\n let x = readInt() in\r\n if n = 1 then print_number x\r\n else\r\n for i = 2 to n do\r\n l := readInt() :: !l;\r\n if i = n then print_number (List.fold_left comp (x) !l);\r\n done;\r\ndone;;"}], "negative_code": [{"source_code": "(* This is an OCaml editor.\r\n Enter your program here and send it to the toplevel using the \"Eval code\"\r\n button. *)\r\n\r\nlet readInt () = Scanf.scanf \" %d\" (fun i -> i);;\r\n\r\nlet print_number x = print_string (string_of_int x); print_newline();;\r\n\r\nlet p2 = Array.make 31 0;;\r\nlet p = ref 1;;\r\n\r\nfor i = 0 to 30 do\r\n p2.(i) <- !p;\r\n p := 2 * !p;\r\ndone;;\r\n\r\nlet f x y z =\r\n if x + y = 2 then p2.(z) else 0;;\r\n\r\nlet rec func x y z =\r\n match z with\r\n | 31 -> 0 \r\n | z -> f (x mod 2) (y mod 2) z + func (x / 2) (y / 2) (z + 1);;\r\n\r\nlet comp x y = func x y 0;;\r\n\r\n\r\nlet t = readInt() in\r\nfor _ = 1 to t do \r\n let l = ref [] in\r\n let n = readInt() in\r\n let x = readInt() in\r\n for i = 2 to n do\r\n l := readInt() :: !l;\r\n if i = n then print_number (List.fold_left comp (x) !l);\r\n done;\r\ndone;;"}], "src_uid": "4f8eac547bbd469a69de2f4aae4a87f0"} {"nl": {"description": "You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \\le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.", "input_spec": "The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 4 \\cdot 10^5$$$) \u2014 the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.", "output_spec": "Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).", "sample_inputs": ["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"], "sample_outputs": ["cccbbabaccbc", "cccccc", ""], "notes": null}, "positive_code": [{"source_code": "let ( */ ) = Big_int.mult_big_int;;\nlet ( +/ ) = Big_int.add_big_int;;\nlet ( -/ ) = Big_int.sub_big_int;;\nlet to_int = Big_int.int_of_big_int;;\nlet of_int = Big_int.big_int_of_int;;\nlet min = Big_int.min_big_int;;\nlet (modi) = Big_int.mod_big_int;;\nlet to_string = Big_int.string_of_big_int;;\nlet of_string = Big_int.big_int_of_string;;\nlet ( compare a b | c -> c\n;;\n\nlet n,k = Scanf.sscanf (read_line ()) \"%i %i\" (fun n k -> n,k) in\nlet s = read_line () |> split n in\nlet sorted_s = Array.mapi (fun i c -> (c,i)) s in\nArray.sort compare_ci sorted_s;\nlet remove = Array.sub sorted_s 0 k in\nArray.sort (fun (_,x) (_,y) -> compare x y) remove;\nlet position = ref 0 in\nfor i = 0 to n - 1 do\n if !position = Array.length remove || snd remove.(!position) != i then Printf.printf \"%c\" s.(i)\n else incr position\ndone;\nprint_newline ()\n"}], "negative_code": [], "src_uid": "9f095a5f5b39d8c2f99c4162f2d7c5ff"} {"nl": {"description": "The police department of your city has just started its journey. Initially, they don\u2019t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.", "input_spec": "The first line of input will contain an integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of events. The next line will contain n space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.", "output_spec": "Print a single integer, the number of crimes which will go untreated.", "sample_inputs": ["3\n-1 -1 1", "8\n1 -1 1 -1 -1 1 1 1", "11\n-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1"], "sample_outputs": ["2", "1", "8"], "notes": "NoteLets consider the second example: Firstly one person is hired. Then crime appears, the last hired person will investigate this crime. One more person is hired. One more crime appears, the last hired person will investigate this crime. Crime appears. There is no free policeman at the time, so this crime will go untreated. One more person is hired. One more person is hired. One more person is hired. The answer is one, as one crime (on step 5) will go untreated."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet solve () = \n let n = read () in\n let rec loop i unsolved police = \n if i < n\n then\n let temp = read () in\n if temp < 0\n then\n if police >= 1\n then\n loop (i + 1) unsolved (police - 1)\n else\n loop (i + 1) (unsolved + 1) police\n else\n loop (i + 1) unsolved (police + temp)\n else\n unsolved\n in loop 0 0 0\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve ())"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let rec loop unsolved police = function\n | 0 -> unsolved\n | n ->\n let x = read_int () in\n if x < 0 then\n if police > 0 then\n loop unsolved (police - 1) (n - 1)\n else\n loop (unsolved + 1) police (n - 1)\n else\n loop unsolved (police + x) (n - 1)\n in Printf.printf \"%d\\n\" (loop 0 0 n)\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet read_int () = scanf \" %d\" (fun x -> x)\n\nlet n = read_int ()\nlet a = Array.init n (fun i -> read_int ())\n\nlet comp (s, r) x = \n match (x, s) with\n | (-1, 0) -> (0, r + 1)\n | _ -> (s + x, r)\n\nlet () = printf \"%d\\n\" (snd (Array.fold_left comp (0, 0) a))\n"}], "negative_code": [], "src_uid": "af47635f631381b4578ba599a4f8b317"} {"nl": {"description": "You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: Pick a random segment (continuous subsequence) from l to r. All segments are equiprobable. Let k\u2009=\u2009r\u2009-\u2009l\u2009+\u20091, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p1,\u2009p2,\u2009...,\u2009pk. All k! permutation are equiprobable. This permutation is applied to elements of the chosen segment, i.e. permutation a1,\u2009a2,\u2009...,\u2009al\u2009-\u20091,\u2009al,\u2009al\u2009+\u20091,\u2009...,\u2009ar\u2009-\u20091,\u2009ar,\u2009ar\u2009+\u20091,\u2009...,\u2009an is transformed to a1,\u2009a2,\u2009...,\u2009al\u2009-\u20091,\u2009al\u2009-\u20091\u2009+\u2009p1,\u2009al\u2009-\u20091\u2009+\u2009p2,\u2009...,\u2009al\u2009-\u20091\u2009+\u2009pk\u2009-\u20091,\u2009al\u2009-\u20091\u2009+\u2009pk,\u2009ar\u2009+\u20091,\u2009...,\u2009an. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i,\u2009j) such that i\u2009<\u2009j and ai\u2009>\u2009aj. Find the expected number of inversions after we apply exactly one operation mentioned above.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the length of the permutation. The second line contains n distinct integers from 1 to n\u00a0\u2014 elements of the permutation.", "output_spec": "Print one real value\u00a0\u2014 the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20099. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["3\n2 3 1"], "sample_outputs": ["1.916666666666666666666666666667"], "notes": null}, "positive_code": [{"source_code": "module Fenwick64 :\nsig\n type t\n val create : int -> t\n val add : t -> int -> int64 -> unit\n val sumto : t -> int -> int64\nend=\nstruct\n type t = int64 array\n \n let create n =\n Array.make (n+1) Int64.zero\n\n let add fw n x =\n let len = Array.length fw in\n let pos = ref (n+1) in\n let rec loop () =\n let p = !pos in\n if p < len\n then\n begin\n Array.set fw p (Int64.add fw.(p) x);\n pos := p + (p land (~- p));\n loop ()\n end\n in loop ()\n \n let sumto fw n =\n let pos, sum = ref n, ref Int64.zero in\n let rec loop () =\n let p = !pos in\n if p > 0\n then\n begin\n sum := Int64.add (!sum) fw.(p);\n pos := p - (p land (~- p));\n loop ()\n end\n else\n !sum\n in loop ()\nend\n\n\n\nlet inversion_in_interval (n, a) =\n let ans = ref Int64.zero in\n let fw = Fenwick64.create n in\n for i = n-1 downto 0 do\n ans := Int64.add (!ans) (Int64.mul (Int64.of_int (i+1)) (Fenwick64.sumto fw a.(i)));\n Fenwick64.add fw a.(i) (Int64.of_int (n-i))\n done;\n !ans\n\n\nlet inversion (n, a) =\n let ans = ref Int64.zero in\n let fw = Fenwick64.create n in\n for i = n-1 downto 0 do\n ans := Int64.add (!ans) (Fenwick64.sumto fw a.(i));\n Fenwick64.add fw a.(i) Int64.one\n done;\n !ans\n\n\nlet inversion_after_shuffle (n, a) =\n Int64.to_float (inversion (n, a))\n +. float (n+2) *. float (n-1) /. 24.\n -. Int64.to_float (inversion_in_interval (n, a)) /. (float n *. float (n+1) /. 2.)\n\n\nlet main () =\n let n = read_int () in\n let a = Array.make n 0 in\n for i = 0 to n-1 do\n Scanf.scanf \" %u\"\n (fun x -> Array.set a i (x-1))\n done;\n print_float (inversion_after_shuffle (n, a))\n\n\nlet () = main ()\n"}], "negative_code": [{"source_code": "module Fenwick :\nsig\n type t\n val create : int -> t\n val add : t -> int -> int -> unit\n val sumto : t -> int -> int\nend=\nstruct\n type t = int array\n \n let create n =\n Array.make (n+1) 0\n\n let add fw n x =\n let len = Array.length fw in\n let pos = ref (n+1) in\n let rec loop () =\n let p = !pos in\n if p < len\n then\n begin\n Array.set fw p (fw.(p) + x);\n pos := p + (p land (~- p));\n loop ()\n end\n in loop ()\n \n let sumto fw n =\n let pos, sum = ref n, ref 0 in\n let rec loop () =\n let p = !pos in\n if p > 0\n then\n begin\n sum := (!sum) + fw.(p);\n pos := p - (p land (~- p));\n loop ()\n end\n else\n !sum\n in loop ()\nend\n\n\n\nlet inversion_in_interval (n, a) =\n let ans = ref 0 in\n let fw = Fenwick.create n in\n for i = n-1 downto 0 do\n ans := (!ans) + (i+1) * Fenwick.sumto fw a.(i);\n Fenwick.add fw a.(i) (n-i)\n done;\n !ans\n\n\nlet inversion (n, a) =\n let ans = ref 0 in\n let fw = Fenwick.create n in\n for i = n-1 downto 0 do\n ans := (!ans) + Fenwick.sumto fw a.(i);\n Fenwick.add fw a.(i) 1\n done;\n !ans\n\n\nlet inversion_after_shuffle (n, a) =\n (float (inversion (n, a)))\n +. (float ((n+2) * (n-1))) /. 24.\n -. (float (inversion_in_interval (n, a)) /. float (n * (n+1) / 2))\n\n\nlet main () =\n let n = read_int () in\n let a = Array.make n 0 in\n for i = 0 to n-1 do\n Scanf.scanf \" %u\"\n (fun x -> Array.set a i (x-1))\n done;\n print_float (inversion_after_shuffle (n, a))\n\n\nlet () = main ()\n"}, {"source_code": "module Fenwick :\nsig\n type t\n val create : int -> t\n val add : t -> int -> int -> unit\n val sumto : t -> int -> int\nend=\nstruct\n type t = int array\n \n let create n =\n Array.make (n+1) 0\n\n let add fw n x =\n let len = Array.length fw in\n let pos = ref (n+1) in\n let rec loop () =\n let p = !pos in\n if p < len\n then\n begin\n Array.set fw p (fw.(p) + x);\n pos := p + (p land (~- p));\n loop ()\n end\n in loop ()\n \n let sumto fw n =\n let pos, sum = ref n, ref 0 in\n let rec loop () =\n let p = !pos in\n if p > 0\n then\n begin\n sum := (!sum) + fw.(p);\n pos := p - (p land (~- p));\n loop ()\n end\n else\n !sum\n in loop ()\nend\n\n\n\nlet inversion_in_interval (n, a) =\n let ansf = ref 0. in\n let fw = Fenwick.create n in\n for i = n-1 downto 0 do\n ansf := (!ansf) +. float ((i+1) * Fenwick.sumto fw a.(i));\n Fenwick.add fw a.(i) (n-i)\n done;\n !ansf\n\n\nlet inversion (n, a) =\n let ans = ref 0 in\n let fw = Fenwick.create n in\n for i = n-1 downto 0 do\n ans := (!ans) + Fenwick.sumto fw a.(i);\n Fenwick.add fw a.(i) 1\n done;\n !ans\n\n\nlet inversion_after_shuffle (n, a) =\n (float (inversion (n, a)))\n +. (float ((n+2) * (n-1))) /. 24.\n -. (inversion_in_interval (n, a)) /. float (n * (n+1) / 2)\n\n\nlet main () =\n let n = read_int () in\n let a = Array.make n 0 in\n for i = 0 to n-1 do\n Scanf.scanf \" %u\"\n (fun x -> Array.set a i (x-1))\n done;\n print_float (inversion_after_shuffle (n, a))\n\n\nlet () = main ()\n"}], "src_uid": "977aef0dfcf65b60bfe805757057aa73"} {"nl": {"description": "There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n\u2009>\u20091. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of banks. The second line contains n integers ai (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.", "output_spec": "Print the minimum number of operations required to change balance in each bank to zero.", "sample_inputs": ["3\n5 0 -5", "4\n-1 0 1 0", "4\n1 2 3 -6"], "sample_outputs": ["1", "2", "3"], "notes": "NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer: transfer 1 from the first bank to the second bank; transfer 3 from the second bank to the third; transfer 6 from the third bank to the fourth. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun i -> long (read_int())) in\n\n let count = Hashtbl.create 10 in\n\n let increment key = \n let c = try Hashtbl.find count key with Not_found -> 0 in\n Hashtbl.replace count key (c+1)\n in\n \n let rec scan i carry = if i=n then () else\n let carry = carry ++ a.(i) in\n increment carry;\n scan (i+1) carry\n in\n\n scan 0 0L;\n\n let mcount = Hashtbl.fold (fun _ v ac -> max ac v) count 0 in\n\n printf \"%d\\n\" (n-mcount)\n\n"}], "negative_code": [], "src_uid": "be12bb8148708f9ad3dc33b83b55eb1e"} {"nl": {"description": "Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of $$$2$$$ rows and $$$n$$$ columns. Monocarp controls a character, which starts in cell $$$(1, 1)$$$\u00a0\u2014 at the intersection of the $$$1$$$-st row and the $$$1$$$-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ in one step if $$$|x_1 - x_2| \\le 1$$$ and $$$|y_1 - y_2| \\le 1$$$. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell $$$(2, n)$$$\u00a0\u2014 at the intersection of row $$$2$$$ and column $$$n$$$.Help Monocarp determine if it is possible to complete the level.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$3 \\le n \\le 100$$$)\u00a0\u2014 the number of columns. The next two lines describe the level. The $$$i$$$-th of these lines describes the $$$i$$$-th line of the level\u00a0\u2014 the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell. Additional constraint on the input: cells $$$(1, 1)$$$ and $$$(2, n)$$$ are safe.", "output_spec": "For each test case, output YES if it is possible to complete the level, and NO otherwise.", "sample_inputs": ["4\n3\n000\n000\n4\n0011\n1100\n4\n0111\n1110\n6\n010101\n101010"], "sample_outputs": ["YES\nYES\nNO\nYES"], "notes": "NoteConsider the example from the statement.In the first test case, one of the possible paths is $$$(1, 1) \\rightarrow (2, 2) \\rightarrow (2, 3)$$$.In the second test case, one of the possible paths is $$$(1, 1) \\rightarrow (1, 2) \\rightarrow (2, 3) \\rightarrow (2, 4)$$$.In the fourth test case, one of the possible paths is $$$(1, 1) \\rightarrow (2, 2) \\rightarrow (1, 3) \\rightarrow (2, 4) \\rightarrow (1, 5) \\rightarrow (2, 6)$$$."}, "positive_code": [{"source_code": "\r\n\r\nlet solve () =\r\n let n = read_int () in\r\n let s1 = read_line () in\r\n let s2 = read_line () in\r\n let rec parse d1 d2 = function\r\n i when i = n -> d2\r\n | i -> ((s1.[i] = '0') || \r\n (s2.[i] = '0')) &&\r\n parse (s1.[i] = '0') (s2.[i] = '0') (i+1) \r\n in\r\n parse true false 0;;\r\n\r\n\r\n\r\nlet t = read_int () ;;\r\n\r\nlet rec main = function\r\n 0 -> ();\r\n| n -> \r\n begin\r\n (if solve () then print_string \"YES\\n\"\r\n else print_string \"NO\\n\") ;\r\n main (n-1)\r\n end ;;\r\n\r\nmain t;;"}], "negative_code": [{"source_code": "\r\n\r\nlet solve () =\r\n let n = read_int () in\r\n let s1 = read_line () in\r\n let s2 = read_line () in\r\n let rec parse d1 d2 = function\r\n i when i = n -> d2\r\n | i -> ((d1 && s1.[i] = '0') || \r\n (d2 && s2.[i] = '0')) &&\r\n parse (s1.[i] = '0') (s2.[i] = '0') (i+1) \r\n in\r\n parse true false 0;;\r\n\r\n\r\n\r\nlet t = read_int () ;;\r\n\r\nlet rec main = function\r\n 0 -> ();\r\n| n -> \r\n begin\r\n (if solve () then print_string \"YES\\n\"\r\n else print_string \"NO\\n\") ;\r\n main (n-1)\r\n end ;;\r\n\r\nmain t;;"}, {"source_code": "\r\n\r\nlet solve () =\r\n let n = read_int () in\r\n let s1 = read_line () in\r\n let s2 = read_line () in\r\n let rec parse d1 d2 = function\r\n i when i = n -> d2\r\n | i -> ((d1 && s1.[i] = '1') || \r\n (d2 && s2.[i] = '1')) &&\r\n parse (s1.[i] = '1') (s2.[i] = '1') (i+1) \r\n in\r\n parse true false 0;;\r\n\r\n\r\n\r\nlet t = read_int () ;;\r\n\r\nlet rec main = function\r\n 0 -> ();\r\n| n -> \r\n begin\r\n (if solve () then print_string \"YES\\n\"\r\n else print_string \"NO\\n\") ;\r\n main (n-1)\r\n end ;;\r\n\r\nmain t;;"}], "src_uid": "fefec879efd4f524de00684adee7cd19"} {"nl": {"description": "Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009k\u2009\u2264\u2009109)\u00a0\u2014 the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1,\u2009w2,\u2009...,\u2009wn (1\u2009\u2264\u2009wi\u2009\u2264\u2009104)\u00a0\u2014 number of pebbles of each type. ", "output_spec": "The only line of output contains one integer\u00a0\u2014 the minimum number of days Anastasia needs to collect all the pebbles.", "sample_inputs": ["3 2\n2 3 4", "5 4\n3 1 8 9 7"], "sample_outputs": ["3", "5"], "notes": "NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type\u00a0\u2014 on the second day, and of third type\u00a0\u2014 on the third day.Optimal sequence of actions in the second sample case: In the first day Anastasia collects 8 pebbles of the third type. In the second day she collects 8 pebbles of the fourth type. In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type. In the fourth day she collects 7 pebbles of the fifth type. In the fifth day she collects 1 pebble of the second type. "}, "positive_code": [{"source_code": "(*#load \"str.cma\"*)\nopen Printf;;\nlet ans = ref 0;;\nlet proc k vs = \n\tlet x = (int_of_string vs) in \n\t\tans := !ans + (x / k) + (if x mod k != 0 then 1 else 0);;\nlet main =\n\tlet [n; k] = List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\n\tlet ans = ref 0 in\n\tlet s = List.map (proc k) (Str.split (Str.regexp \" \") (read_line ())) in 0;;\nprint_int (!ans / 2 + !ans mod 2);;\n"}], "negative_code": [], "src_uid": "3992602be20a386f0ec57c51e14b39c5"} {"nl": {"description": "Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a \"type\" is in language X--: First, a type is a string \"int\". Second, a type is a string that starts with \"pair\", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces. No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either \"pair\" or \"int\" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words \"int\".", "output_spec": "If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print \"Error occurred\" (without the quotes). Inside the record of a type should not be any extra spaces and other characters. It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values.", "sample_inputs": ["3\npair pair int int int", "1\npair int"], "sample_outputs": ["pair<pair<int,int>,int>", "Error occurred"], "notes": null}, "positive_code": [{"source_code": "type t0 = P | I\ntype t1 = Pair of t1 * t1 | Int\n\nlet _ =\n let rec dump k =\n match k with\n | Int -> print_string \"int\"\n | Pair (a, b) -> print_string \"pair<\";dump a;print_string \",\"; dump b; print_string \">\"\n in\n\n let main () =\n let _ = read_int () in\n let s = read_line () in\n let l = String.length s in\n let rec loop p acc =\n if p >= l then acc else\n if s.[p] = 'p' then loop (p + 4) (P :: acc) else\n if s.[p] = 'i' then loop (p + 3) (I :: acc) else\n loop (p + 1) acc\n in\n let k = List.rev (loop 0 []) in\n let rec parse = function\n | [] -> None\n | I :: tl -> Some (Int, tl)\n | P :: tl -> (\n match parse tl with\n | None -> None\n | Some (a, tl2) -> (\n match parse tl2 with\n | None -> None\n | Some (b, tl3) -> Some (Pair (a, b), tl3)\n )\n )\n in\n match parse k with\n | Some (a, []) -> dump a; print_newline ()\n | _ -> print_endline \"Error occurred\"\n in\n main ()\n"}, {"source_code": "open Scanf;;\nopen Printf;;\nopen Str;;\n\nlet split_by_space = split (regexp \" +\")\n\ntype token = P | I\n\nlet token_of_str = function\n \"pair\" -> P\n | \"int\" -> I\n | _ -> failwith \"hoge\"\n \nlet input () =\n let n = int_of_string(read_line ()) in\n let str = read_line () in\n (n, List.map token_of_str (split_by_space str))\n\ntype tree = Pair of (tree * tree) | Int\n\nlet solve ls =\n let rec solve = function\n [] -> failwith \"\"\n | P::ls -> \n let (res1, ls) = solve ls in\n let (res2, ls) = solve ls in\n (Pair (res1, res2), ls)\n | I::ls ->\n (Int, ls) in\n let (res, ls) = solve ls in\n match ls with\n [] -> res\n | _ -> failwith \"\"\n\nlet rec print_res = function\n Pair(x, y) -> \n print_string \"pair<\";\n print_res x;\n print_string \",\";\n print_res y;\n print_string \">\"\n | Int ->\n print_string \"int\"\n \nlet () = \n let (n, ss) = input () in\n (* List.iter (fun x -> printf \"%s\\n\" x) ss; *)\n try \n let res = solve ss in\n print_res res;\n print_string \"\\n\"\n with\n Failure _ -> print_endline \"Error occurred\"\n \n"}], "negative_code": [], "src_uid": "6587be85c64a0d5fb66eec0c5957cb62"} {"nl": {"description": "Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are $$$n$$$ students living in a building, and for each of them the favorite drink $$$a_i$$$ is known. So you know $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$, where $$$a_i$$$ ($$$1 \\le a_i \\le k$$$) is the type of the favorite drink of the $$$i$$$-th student. The drink types are numbered from $$$1$$$ to $$$k$$$.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $$$k$$$ types of drink sets, the $$$j$$$-th type contains two portions of the drink $$$j$$$. The available number of sets of each of the $$$k$$$ types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $$$\\lceil \\frac{n}{2} \\rceil$$$, where $$$\\lceil x \\rceil$$$ is $$$x$$$ rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $$$n$$$ is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if $$$\\lceil \\frac{n}{2} \\rceil$$$ sets will be chosen optimally and students will distribute portions between themselves optimally?", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 1\\,000$$$) \u2014 the number of students in the building and the number of different drinks. The next $$$n$$$ lines contain student's favorite drinks. The $$$i$$$-th line contains a single integer from $$$1$$$ to $$$k$$$ \u2014 the type of the favorite drink of the $$$i$$$-th student.", "output_spec": "Print exactly one integer \u2014 the maximum number of students that can get a favorite drink.", "sample_inputs": ["5 3\n1\n3\n1\n1\n2", "10 3\n2\n1\n3\n2\n3\n3\n1\n3\n1\n2"], "sample_outputs": ["4", "9"], "notes": "NoteIn the first example, students could choose three sets with drinks $$$1$$$, $$$1$$$ and $$$2$$$ (so they will have two sets with two drinks of the type $$$1$$$ each and one set with two drinks of the type $$$2$$$, so portions will be $$$1, 1, 1, 1, 2, 2$$$). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks $$$1$$$, $$$2$$$ and $$$3$$$. In this case the portions will be $$$1, 1, 2, 2, 3, 3$$$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $$$a_i = 1$$$ (i.e. the first, the third or the fourth)."}, "positive_code": [{"source_code": "(* Input *)\nlet (num_students, num_drink_types) = Scanf.scanf \"%d %d\\n\" (fun x y -> (x, y));;\nlet student_drink_types =\n let rec read_int_list = function\n | 0 -> []\n | n -> (Scanf.scanf \"%d\\n\" (fun x -> x - 1)) :: read_int_list (n - 1)\n in\n List.rev (read_int_list num_students)\n;;\n\n(* Process *)\nlet favorite_counts = Array.make num_drink_types 0;;\nList.iter (fun tp -> (favorite_counts.(tp) <- favorite_counts.(tp) + 1)) student_drink_types;;\n\nlet num_leftout = Array.fold_left (fun a b -> a + b mod 2) 0 favorite_counts;;\nlet result = num_students - num_leftout + (num_leftout + 1) / 2;;\nPrintf.printf \"%d\\n\" result;;\n"}, {"source_code": "(* Input *)\nlet (num_students, num_drink_types) = Scanf.scanf \"%d %d\\n\" (fun x y -> (x, y));;\n\nlet rec read_rev_int_list n =\n if n == 0\n then []\n else (Scanf.scanf \"%d\\n\" (fun x -> x - 1)) :: read_rev_int_list(n - 1)\n;;\n\nlet student_drink_types = List.rev (read_rev_int_list (num_students));;\n\n(* Process *)\nlet favorite_counts = Array.make num_drink_types 0;;\nList.iter (fun tp -> (favorite_counts.(tp) <- favorite_counts.(tp) + 1)) student_drink_types;;\n\nlet num_leftout = ref 0;;\nArray.iter (fun cnt -> num_leftout := !num_leftout + (cnt mod 2)) favorite_counts;;\n\nlet result = num_students - !num_leftout + (!num_leftout + 1) / 2;;\nPrintf.printf \"%d\\n\" result;;"}], "negative_code": [], "src_uid": "dceeb739a56bb799550138aa8c127996"} {"nl": {"description": "Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious \"Pihters\" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x,\u2009y) to one of these four points: to point (x\u2009-\u20091,\u2009y) which we will mark by letter \"L\", to point (x\u2009+\u20091,\u2009y) \u2014 \"R\", to point (x,\u2009y\u2009-\u20091) \u2014 \"D\", to point (x,\u2009y\u2009+\u20091) \u2014 \"U\".The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: \"UL\", \"UR\", \"DL\", \"DR\" or \"ULDR\". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string \"UL\" means that the car moved either \"U\", or \"L\".You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0,\u20090), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of the car's movements from the headquarters to the stall. Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: \"UL\", \"UR\", \"DL\", \"DR\" or \"ULDR\". All movements are given in chronological order. Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.", "output_spec": "Print a single integer \u2014 the number of different possible locations of the gang's headquarters.", "sample_inputs": ["3\nUR\nUL\nULDR", "2\nDR\nDL"], "sample_outputs": ["9", "4"], "notes": "NoteThe figure below shows the nine possible positions of the gang headquarters from the first sample: For example, the following movements can get the car from point (1,\u20090) to point (0,\u20090): "}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let w = ref 1 in\n let h = ref 1 in\n for i = 1 to n do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tmatch s with\n\t | \"UL\" ->\n\t incr h\n\t | \"UR\" ->\n\t incr w\n\t | \"DL\" ->\n\t incr w\n\t | \"DR\" ->\n\t incr h\n\t | \"ULDR\" ->\n\t incr h;\n\t incr w;\n\t | _ -> assert false\n done;\n let res = Int64.mul (Int64.of_int !h) (Int64.of_int !w) in\n Printf.printf \"%Ld\\n\" res\n\n"}], "negative_code": [], "src_uid": "566b91c278449e8eb3c724a6f00797e8"} {"nl": {"description": "You are given a table $$$a$$$ of size $$$n \\times m$$$. We will consider the table rows numbered from top to bottom from $$$1$$$ to $$$n$$$, and the columns numbered from left to right from $$$1$$$ to $$$m$$$. We will denote a cell that is in the $$$i$$$-th row and in the $$$j$$$-th column as $$$(i, j)$$$. In the cell $$$(i, j)$$$ there is written a number $$$(i - 1) \\cdot m + j$$$, that is $$$a_{ij} = (i - 1) \\cdot m + j$$$.A turtle initially stands in the cell $$$(1, 1)$$$ and it wants to come to the cell $$$(n, m)$$$. From the cell $$$(i, j)$$$ it can in one step go to one of the cells $$$(i + 1, j)$$$ or $$$(i, j + 1)$$$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path. For example, with $$$n = 2$$$ and $$$m = 3$$$ the table will look as shown above. The turtle can take the following path: $$$(1, 1) \\rightarrow (1, 2) \\rightarrow (1, 3) \\rightarrow (2, 3)$$$. The cost of such way is equal to $$$a_{11} + a_{12} + a_{13} + a_{23} = 12$$$. On the other hand, the paths $$$(1, 1) \\rightarrow (1, 2) \\rightarrow (2, 2) \\rightarrow (2, 1)$$$ and $$$(1, 1) \\rightarrow (1, 3)$$$ are incorrect, because in the first path the turtle can't make a step $$$(2, 2) \\rightarrow (2, 1)$$$, and in the second path it can't make a step $$$(1, 1) \\rightarrow (1, 3)$$$.You are asked to tell the turtle a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. Please note that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are a part of the way.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) \u2014 the number of test cases. The description of test cases follows. A single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 10^4$$$) \u2014 the number of rows and columns of the table $$$a$$$ respectively.", "output_spec": "For each test case output a single integer \u2014 a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$.", "sample_inputs": ["7\n\n1 1\n\n2 3\n\n3 2\n\n7 1\n\n1 10\n\n5 5\n\n10000 10000"], "sample_outputs": ["1\n12\n13\n28\n55\n85\n500099995000"], "notes": "NoteIn the first test case the only possible path consists of a single cell $$$(1, 1)$$$.The path with the minimal cost in the second test case is shown in the statement.In the fourth and the fifth test cases there is only one path from $$$(1, 1)$$$ to $$$(n, m)$$$. Both paths visit every cell in the table. "}, "positive_code": [{"source_code": "(* nxm table, aij = (i-1)*m +j \r\n turtle in 1,1 wants to go to (n,m)\r\n find min possible cost to go from 1,1 to n,m\r\n \r\n down cost from aij = (i)*m + j\r\n right cost from aij = (i-1)*m + j+1 \r\n\r\n down -right = m-1\r\n since m>=1, then down>=right\r\n \r\n d, r = (i*m +j) + (i*m + j +1) = 2*(i*m+j)+1\r\n r, d = ((i-1)*m + j+1) + (i*m + j+1) = 2*(i*m+j)+2-m\r\n\r\n since m>=1, then -m<=-1, 2-m<=1, (r, d<=d, r)\r\n\r\n d, d, r, r = 4*(i*m+j)+3*m+3\r\n d, r, d, r = 4*(i*m+j)+1+m+1+m+2\r\n\r\n diff = m-1, so (ddrr>=drdr)\r\n\r\n if (n>=m) then dr... m times... d... n-m times\r\n \r\n\r\n in any order we will have to pay: \r\n\r\n going down payment = m*(0 + 1 + 2 + ... + n-1) = m*n*(n-1)/2\r\n going along payment, exc row = 1 + 2 + 3 + 4+ ... + m = m*(m+1)/2\r\n \r\n payment = e + m * (n(n-1)/2 + (m+1)/2)\r\n\r\n e = (m*m*(n-k1)) + (n*(m-k2)) where m*(n-k1) is mean row going along and m-k2 is mean column going down\r\n\r\n e = m(n(m+1)) - m*m*k1 - n*k2\r\n (want to maximise k1 and k2)\r\n k1 <= n and k2 <= m \r\n m*m*k1 <= m*m*n, n*k2 <= n*m\r\n\r\n (k1, k2) = (0, n), (1)\r\n\r\n so better to maximise k1 than k2\r\n for each increase in k1, cost decreases by m*m\r\n for each increase in k2, cost decreases by n\r\n\r\n we can increase k1 n times and k2 m times.\r\n\r\n\r\n if k1 increases by 1, then \r\n\r\n 3, 2 -> 1+2+4+6\r\n 7, 1 -> 1+...+7\r\n 1, 10 -> 1+2+...+10\r\n 5, 5->1+2+...+5+10+15+20+25\r\n\r\n\r\n any extra cost is the cost of the row each\r\n time we go along + the cost of the column each\r\n time we go down\r\n\r\n there is always a +m increase going down\r\n there is always a +1 increase going along\r\n\r\n want to minimise the current sum\r\n\r\n current sum starts at 1\r\n\r\n need to go along m and down n\r\n\r\n always optimal to go along first and m>=1 then go along\r\n\r\n p(n+m)=p(n+m-1)+m=(p(n+m-2)+m)+m\r\n\r\n s = p(1)+p(2)+...+p(n+m-1)\r\n = p(1)+(p(1)+k1)+...+p(n+m-1)\r\n = p(1)+(p(1)+k1)+(p(1)+k1+k2)+...+p(n+m-1)\r\n = (n+m-1)p(1)+(n+m-2)*k1+(n+m-3)*k2+...+k(n+m-2)\r\n\r\n so to minimise the payment it is best to \r\n choose +1 first then +m\r\n\r\n we need choose n-1 +m and m-1 +1\r\n\r\n s = (n+m-1)p(1)+((n+m-1-1)+...+(n+m-1-(m-1)))+(n-1+...+1)*m\r\n = (n+m-1)+((m-1)(n+m-1)-(m(m-1)/2))+n(n-1)*m/2\r\n = (n+m-1)m-m((m-1)+n(n-1))/2\r\n = m((n+m-1)-((m-1)+n(n-1))/2)\r\n\r\n n=2, m=3\r\n\r\n s = (1+2+3+...+m-1)+m*(1+2+3+...+n)\r\n s = m(m-1)/2+m*n(n+1)/2\r\n\r\n n=2, m=3\r\n s=3+3*2*3/2=12\r\n\r\n*)\r\n\r\n\r\nlet read_long () = Scanf.scanf \" %Ld\" (fun x->x);;\r\nlet read_int () = Scanf.scanf \" %d\" (fun x-> x);;\r\nlet run_case = function \r\n| () ->\r\n let n = read_long () in \r\n let m = read_long () in \r\n let s1 = Int64.div (Int64.mul m (Int64.pred m)) (Int64.of_int 2) in \r\n let s2 = Int64.div (Int64.mul m (Int64.mul n (Int64.succ n))) (Int64.of_int 2) in \r\n let s = Int64.add s1 s2 in\r\n Printf.printf \"%Ld\\n\" s\r\n;;\r\n\r\nlet rec iter_cases = function \r\n| 0 -> ()\r\n| t -> \r\n run_case ();\r\n iter_cases (t-1)\r\n\r\n;;\r\n\r\nlet t=read_int() in iter_cases t;;\r\n"}], "negative_code": [], "src_uid": "7d774a003d2e3e8ae6fe1912b3998c96"} {"nl": {"description": "You are given a tree (a connected undirected graph without cycles) of $$$n$$$ vertices. Each of the $$$n - 1$$$ edges of the tree is colored in either black or red.You are also given an integer $$$k$$$. Consider sequences of $$$k$$$ vertices. Let's call a sequence $$$[a_1, a_2, \\ldots, a_k]$$$ good if it satisfies the following criterion: We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from $$$a_1$$$ and ending at $$$a_k$$$. Start at $$$a_1$$$, then go to $$$a_2$$$ using the shortest path between $$$a_1$$$ and $$$a_2$$$, then go to $$$a_3$$$ in a similar way, and so on, until you travel the shortest path between $$$a_{k-1}$$$ and $$$a_k$$$. If you walked over at least one black edge during this process, then the sequence is good. Consider the tree on the picture. If $$$k=3$$$ then the following sequences are good: $$$[1, 4, 7]$$$, $$$[5, 5, 3]$$$ and $$$[2, 3, 7]$$$. The following sequences are not good: $$$[1, 4, 6]$$$, $$$[5, 5, 5]$$$, $$$[3, 7, 3]$$$.There are $$$n^k$$$ sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo $$$10^9+7$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 10^5$$$, $$$2 \\le k \\le 100$$$), the size of the tree and the length of the vertex sequence. Each of the next $$$n - 1$$$ lines contains three integers $$$u_i$$$, $$$v_i$$$ and $$$x_i$$$ ($$$1 \\le u_i, v_i \\le n$$$, $$$x_i \\in \\{0, 1\\}$$$), where $$$u_i$$$ and $$$v_i$$$ denote the endpoints of the corresponding edge and $$$x_i$$$ is the color of this edge ($$$0$$$ denotes red edge and $$$1$$$ denotes black edge).", "output_spec": "Print the number of good sequences modulo $$$10^9 + 7$$$.", "sample_inputs": ["4 4\n1 2 1\n2 3 1\n3 4 1", "4 6\n1 2 0\n1 3 0\n1 4 0", "3 5\n1 2 1\n2 3 0"], "sample_outputs": ["252", "0", "210"], "notes": "NoteIn the first example, all sequences ($$$4^4$$$) of length $$$4$$$ except the following are good: $$$[1, 1, 1, 1]$$$ $$$[2, 2, 2, 2]$$$ $$$[3, 3, 3, 3]$$$ $$$[4, 4, 4, 4]$$$ In the second example, all edges are red, hence there aren't any good sequences."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\nlet (%%) = Int64.rem\nlet landl = Int64.logand\nlet lorl = Int64.logor\nlet lnotl = Int64.lognot\nlet lxorl = Int64.logxor\nlet lsll = Int64.shift_left\nlet lsrl = Int64.shift_right_logical\nlet long = Int64.of_int\nlet succl = Int64.succ\nlet predl = Int64.pred\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x)\n\nlet m = 1_000_000_007L\n\nlet rec mod_pow a = function\n | 0L -> 1L\n | b -> (if b %% 2L = 0L then 1L else a) ** mod_pow (a ** a %% m) (b//2L) %% m\n\n\nmodule UnionFind : sig\n type t\n val create: int -> t\n val find: t -> int -> int\n val unite: t -> int -> int -> unit\n val same: t -> int -> int -> bool\n val size: t -> int -> int\nend = struct\n type t = {\n par: int array;\n rank: int array;\n size: int array;\n }\n\n let create n = {\n par = Array.init n (fun x -> x);\n rank = Array.make n 1;\n size = Array.make n 1;\n }\n\n let rec find uf a =\n if a = uf.par.(a)\n then a\n else\n let () = uf.par.(a) <- find uf uf.par.(a) in\n uf.par.(a)\n\n let unite uf a b =\n let a = find uf a in\n let b = find uf b in\n let (a,b) = if a <= b then (a,b) else (b,a) in\n if a != b\n then\n let () = uf.par.(a) <- b in\n let () = uf.size.(b) <- uf.size.(b) + uf.size.(a) in\n if uf.rank.(a) = uf.rank.(b)\n then uf.rank.(b) <- uf.rank.(b) + 1\n\n let same uf a b = find uf a = find uf b\n\n let size uf a = uf.size.(find uf a)\n\nend\n\nlet read_edge _ = bscanf Scanning.stdin \" %d %d %d \" (fun u v x -> u-1,v-1,x)\n\nlet rec foldi i n accum f =\n if i >= n\n then accum\n else foldi (i+1) n (f accum i) f\n\nlet () =\n let n,k = bscanf Scanning.stdin \" %d %d \" (fun x y -> x,y) in\n let edges = Array.init (n-1) read_edge in\n let open UnionFind in\n let uf = create n in\n Array.iter (fun (u,v,x) -> if x = 0 then unite uf u v) edges;\n let seen = Array.make n false in\n let res = foldi 0 n 0L (fun accum i ->\n let v = find uf i in\n let accum' = if not seen.(v)\n then mod_pow (long @@ size uf v) (long k) ++ accum\n else accum in\n seen.(v) <- true;\n accum' %% m) in\n let n_k = mod_pow (long n) (long k) in\n printf \"%Ld\\n\" @@ (n_k -- res ++ m) %% m\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\nlet (%%) = Int64.rem\nlet landl = Int64.logand\nlet lorl = Int64.logor\nlet lnotl = Int64.lognot\nlet lxorl = Int64.logxor\nlet lsll = Int64.shift_left\nlet lsrl = Int64.shift_right_logical\nlet long = Int64.of_int\nlet succl = Int64.succ\nlet predl = Int64.pred\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x)\n\nlet m = 1_000_000_007L\n\nlet rec mod_pow a = function\n | 0L -> 1L\n | b -> (if b %% 2L = 0L then 1L else a) ** mod_pow (a ** a %% m) (b//2L)\n\n\nmodule UnionFind : sig\n type t\n val create: int -> t\n val find: t -> int -> int\n val unite: t -> int -> int -> unit\n val same: t -> int -> int -> bool\n val size: t -> int -> int\nend = struct\n type t = {\n par: int array;\n rank: int array;\n size: int array;\n }\n\n let create n = {\n par = Array.init n (fun x -> x);\n rank = Array.make n 1;\n size = Array.make n 1;\n }\n\n let rec find uf a =\n if a = uf.par.(a)\n then a\n else\n let () = uf.par.(a) <- find uf uf.par.(a) in\n uf.par.(a)\n\n let unite uf a b =\n let a = find uf a in\n let b = find uf b in\n let (a,b) = if a <= b then (a,b) else (b,a) in\n if a != b\n then\n let () = uf.par.(a) <- b in\n let () = uf.size.(b) <- uf.size.(b) + uf.size.(a) in\n if uf.rank.(a) = uf.rank.(b)\n then uf.rank.(b) <- uf.rank.(b) + 1\n\n let same uf a b = find uf a = find uf b\n\n let size uf a = uf.size.(find uf a)\n\nend\n\nlet read_edge _ = bscanf Scanning.stdin \" %d %d %d \" (fun u v x -> u-1,v-1,x)\n\nlet rec foldi i n accum f =\n if i >= n\n then accum\n else foldi (i+1) n (f accum i) f\n\nlet () =\n let n,k = bscanf Scanning.stdin \" %d %d \" (fun x y -> x,y) in\n let edges = Array.init (n-1) read_edge in\n let open UnionFind in\n let uf = create n in\n Array.iter (fun (u,v,x) -> if x = 0 then unite uf u v) edges;\n let seen = Array.make n false in\n let res = foldi 0 n 0L (fun accum i ->\n let v = find uf i in\n let accum' = if not seen.(v)\n then mod_pow (long @@ size uf v) (long k) ++ accum\n else accum in\n seen.(v) <- true;\n accum' %% m) in\n let n_k = mod_pow (long n) (long k) in\n printf \"%Ld\\n\" @@ (n_k -- res ++ m) %% m\n"}], "src_uid": "94559f08866b6136ba4791c440025a68"} {"nl": {"description": "You are given an array $$$s$$$ consisting of $$$n$$$ integers.You have to find any array $$$t$$$ of length $$$k$$$ such that you can cut out maximum number of copies of array $$$t$$$ from array $$$s$$$.Cutting out the copy of $$$t$$$ means that for each element $$$t_i$$$ of array $$$t$$$ you have to find $$$t_i$$$ in $$$s$$$ and remove it from $$$s$$$. If for some $$$t_i$$$ you cannot find such element in $$$s$$$, then you cannot cut out one more copy of $$$t$$$. The both arrays can contain duplicate elements.For example, if $$$s = [1, 2, 3, 2, 4, 3, 1]$$$ and $$$k = 3$$$ then one of the possible answers is $$$t = [1, 2, 3]$$$. This array $$$t$$$ can be cut out $$$2$$$ times. To cut out the first copy of $$$t$$$ you can use the elements $$$[1, \\underline{\\textbf{2}}, 3, 2, 4, \\underline{\\textbf{3}}, \\underline{\\textbf{1}}]$$$ (use the highlighted elements). After cutting out the first copy of $$$t$$$ the array $$$s$$$ can look like $$$[1, 3, 2, 4]$$$. To cut out the second copy of $$$t$$$ you can use the elements $$$[\\underline{\\textbf{1}}, \\underline{\\textbf{3}}, \\underline{\\textbf{2}}, 4]$$$. After cutting out the second copy of $$$t$$$ the array $$$s$$$ will be $$$[4]$$$. Your task is to find such array $$$t$$$ that you can cut out the copy of $$$t$$$ from $$$s$$$ maximum number of times. If there are multiple answers, you may choose any of them.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in $$$s$$$ and the desired number of elements in $$$t$$$, respectively. The second line of the input contains exactly $$$n$$$ integers $$$s_1, s_2, \\dots, s_n$$$ ($$$1 \\le s_i \\le 2 \\cdot 10^5$$$).", "output_spec": "Print $$$k$$$ integers \u2014 the elements of array $$$t$$$ such that you can cut out maximum possible number of copies of this array from $$$s$$$. If there are multiple answers, print any of them. The required array $$$t$$$ can contain duplicate elements. All the elements of $$$t$$$ ($$$t_1, t_2, \\dots, t_k$$$) should satisfy the following condition: $$$1 \\le t_i \\le 2 \\cdot 10^5$$$.", "sample_inputs": ["7 3\n1 2 3 2 4 3 1", "10 4\n1 3 1 3 10 3 7 7 12 3", "15 2\n1 2 1 1 1 2 1 1 2 1 2 1 1 1 1"], "sample_outputs": ["1 2 3", "7 3 1 3", "1 1"], "notes": "NoteThe first example is described in the problem statement.In the second example the only answer is $$$[7, 3, 1, 3]$$$ and any its permutations. It can be shown that you cannot choose any other array such that the maximum number of copies you can cut out would be equal to $$$2$$$.In the third example the array $$$t$$$ can be cut out $$$5$$$ times."}, "positive_code": [{"source_code": "(* Problem 2 of round 521*)\n(* Comments:\n\n\n This is one type of binary_search problem. You will encounter many such\n problems. General binary_search which you might have studied(or will study)\n in the university is done over an array of numbers. In this kind of problems,\n you need to perform the binary_search over the entire solution space.\n\n For e.g.: In this problem, you can consider the entire solution space as all\n numbers ranging from 1 to n (as you cannot have more than \"n\" copies).\n\n So, step 1 of this problem is to find the maximum number of copies which can be\n cut out from the the given array. Let me call this value as val. How we are\n going to find val, I will come back to that later. Let us move to Step 2\n\n\n*)\nopen Scanf;;\nopen Num;;\nopen Printf;;\n\n(*These are some utility functions*)\nmodule U = struct\n let mprint z =\n print_endline (Num.string_of_num z);;\n\n let read_one format = Scanf.scanf format (fun x -> x)\n\n let read_one_number () =\n let rslt= read_one \"%d \" in\n rslt\n\n let read_array n a =\n for i = 0 to n-1 do\n let r = read_one_number () in\n a.(i) <- r\n done\n\nend\n\n(*The solutions*)\nlet nn = 200002;;\n\nlet n = U.read_one_number ()\nlet k = U.read_one_number ()\nlet a = Array.make n 0\nlet b = Array.make nn 0\nlet () = U.read_array n a;;\n\nlet () = Array.iter (fun x-> b.(x) <- b.(x) + 1 ) a;;\nlet c = Array.mapi (fun i x -> (i,x) ) b;;\n\nlet my_compare h1 h2 =\n let (_,v1) = h1 in\n let (_,v2) = h2 in\n compare v2 v1;;\n\nlet d = c\n |> Array.to_list\n |> List.filter (fun h -> let (_,v) = h in v > 0 )\n |> List.sort (fun h1 h2 -> my_compare h1 h2)\n |> Array.of_list\n;;\n\nlet dl = Array.length d;;\n\n(* This function determines if cc copies is possible*)\nlet is_possible cc =\n let flag = true in\n let total = ref 0 in \n for i = 0 to dl -1 do\n let (_,v1) = d.(i) in\n total := !total + v1 / cc\n done;\n if !total < k then\n flag = false\n else\n true\n;;\n\nlet rec binary_search s e = \n if s == e then\n s\n else if e - s == 1 then\n if is_possible e then\n e\n else\n s\n else\n begin\n let mid = (s+e) / 2 in\n if is_possible mid then\n binary_search mid e\n else\n binary_search s (mid - 1)\n end\n;;\n\nlet rslt = binary_search 1 n;;\n\n(*\nlet () =\n Printf.printf \"%B %d\\n\" (is_possible 2) rslt\n\nlet () =\n Array.iter (fun (k1,v1) -> Printf.printf \"%d %d\\n\" k1 v1) d\n *)\n\n\nlet () = \n let nx = ref k in\n for i = 0 to dl -1 do\n let (k1,v1) = d.(i) in\n let m = v1 / rslt in\n if m > 0 && !nx >0 then\n let test = !nx - m in\n if test >=0 then\n begin\n for i = 0 to m-1 do\n Printf.printf \"%d \" k1\n done;\n nx := test\n end \n else\n begin\n for i = 0 to !nx-1 do\n Printf.printf \"%d \" k1\n done;\n nx := 0\n end\n done\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet appearance a = (* (value,count) *)\n Array.fold_left (fun u v -> IMap.add v (1L + try IMap.find v u with Not_found -> 0L) u) IMap.empty a\nlet () =\n let n,k = get_2_i64 0 in\n let a = input_i64_array n in\n let ls =\n let mp = appearance a in\n IMap.bindings mp |> List.map (fun (k,v) -> (v,k))\n |> List.sort (fun u v -> compare v u)\n in\n (* print_list (fun (v,k) -> sprintf \"%Ld(%Ld) \" v k) ls; *)\n let constr d =\n let ans = ref [] in\n List.iter (fun (c,v) ->\n let p = c / d in\n rep 1L p (fun _ -> ans := v::!ans)\n ) ls;\n (* printf \"%Ld : %s\\n\" d (string_of_list ist !ans); *)\n !ans in\n let check d =\n if llen @@ constr d >= k then true\n else false\n in\n let d = binary_search n 0L (fun d -> check d) in\n (* constr d |> List.iter (fun v -> printf \"%Ld \" v) *)\n constr d |> of_list |> iteri (fun i v ->\n if i=0 then printf \"%Ld\" v\n else if i x) in\n n;;\n\n let read_one_number () =\n let n = read_one \"%d \" in\n n\n\n let read_array n a =\n for i = 0 to n-1 do\n let n = read_one_number () in\n a.(i) <- n\n done\n\nend\n\n(*The solutions*)\n\nlet n = U.read_one_number ()\nlet k = U.read_one_number ()\nlet a = Array.make n 0\nlet () = U.read_array n a\n\nmodule H = Hashtbl\nlet t = H.create n\n\n(*\nlet () =\n Array.iter (fun x-> print_int x; print_endline \"\") a\n*)\n\nlet my_find s x =\n try Some (H.find s x)\n with\n Not_found -> None\n;;\n\nlet () = Array.iter (fun x-> \n match my_find t x with\n None -> H.add t x 1\n | Some z -> H.replace t x (1+z)\n ) a\n;;\n\n\nlet my_compare h1 h2 =\n let (_,v1) = h1 in\n let (_,v2) = h2 in\n if v1 > v2 then 1\n else if v1 == v2 then 0\n else -1;;\n\nlet ll = H.fold (fun k v x -> (k,v) :: x) t [];;\n\nif n==k then\n print_int (List.length ll); print_endline \"\";;\n\nlet lr = List.stable_sort my_compare ll\n |> List.rev;;\n(*\nlet () =\n List.iter (fun h ->\n let (k,v) = h in Printf.printf \"%d %d\\n\" k v\n ) lr;;\n *)\n\nlet rec cut l1 l2 =\n let n1 = List.length l1 in\n if List.length l2 == k then\n l2\n else\n begin\n if n1 == 1 then\n (List.hd l1) :: l2\n else\n begin\n let h1 :: _ = l1 in\n let h2 :: _ = List.tl l1 in\n let (k1,a1) = h1 in\n let (_,a2) = h2 in\n if a1 < 2*a2 then\n cut (List.tl l1) (h1 :: l2)\n else\n cut ((k1,a1-a1/2) :: (List.tl l1)) ((k1,a1/2) :: l2)\n end\n end\n;;\n\nif n==k then\n begin\n print_int (List.length lr); print_endline \"\";\n List.iter (fun h ->\n let (i,_) = h in Printf.printf \"%d \" i\n ) lr\n end\nelse\n begin\n let rslt = cut lr [] in\n if List.length rslt < k then\n begin\n print_int 0; print_endline \"\"\n end\n else\n List.iter (fun h ->\n let (i,_) = h in Printf.printf \"%d \" i\n ) rslt;\n end\n;;\n"}, {"source_code": "(* Problem 2 of round 521*)\n(* Comments:\n To make this program is even faster, I need to have in the function 'cut'\n l1 to be an array, use another integer (starting from k) to indicate stop.\n\n But this is so boring, I better use C.\n\n*)\nopen Scanf;;\nopen String;;\nopen Num;;\n\n(*These are some utility functions*)\nmodule U = struct\n let mprint z =\n print_endline (Num.string_of_num z);;\n\n let read_one format =\n let n = Scanf.scanf format (fun x -> x) in\n n;;\n\n let read_one_number () =\n let n = read_one \"%d \" in\n n\n\n let read_array n a =\n for i = 0 to n-1 do\n let n = read_one_number () in\n a.(i) <- n\n done\n\nend\n\n(*The solutions*)\n\nlet n = U.read_one_number ()\nlet k = U.read_one_number ()\nlet a = Array.make n 0\nlet () = U.read_array n a\n\nmodule H = Hashtbl\nlet t = H.create n\n\n(*\nlet () =\n Array.iter (fun x-> print_int x; print_endline \"\") a\n*)\n\nlet my_find s x =\n try Some (H.find s x)\n with\n Not_found -> None\n\nlet total = ref 0\n\nlet () = Array.iter (fun x-> \n let y = my_find t x in\n match y with\n None -> H.add t x 1\n | Some z -> H.replace t x (1+z)\n ) a\n;;\n\nlet my_compare h1 h2 =\n let (_,v1) = h1 in\n let (_,v2) = h2 in\n if v1 > v2 then 1\n else if v1 == v2 then 0\n else -1;;\n\nlet ll = H.fold (fun k v x -> (k,v) :: x) t [];;\n\nlet lr = List.stable_sort my_compare ll\n |> List.rev;;\n(*\nlet () =\n List.iter (fun h ->\n let (k,v) = h in Printf.printf \"%d %d\\n\" k v\n ) lr;;\n *)\n\nlet rec cut l1 l2 =\n let n1 = List.length l1 in\n if List.length l2 == k then\n l2\n else\n begin\n if n1 == 1 then\n (List.hd l1) :: l2\n else\n begin\n let h1 :: _ = l1 in\n let h2 :: _ = List.tl l1 in\n let (k1,a1) = h1 in\n let (_,a2) = h2 in\n if a1 < 2*a2 then\n cut (List.tl l1) (h1 :: l2)\n else\n cut ((k1,a1-a1/2) :: (List.tl l1)) ((k1,a1/2) :: l2)\n end\n end\n;;\n\nif n==k then\n List.iter (fun h ->\n let (k,_) = h in Printf.printf \"%d \" k\n ) lr\nelse\n begin\n let rslt = cut lr [] in\n if List.length rslt < k then\n begin\n print_int 0; print_endline \"\"\n end\n else\n List.iter (fun h ->\n let (k,_) = h in Printf.printf \"%d \" k\n ) rslt;\n end\n;;\n"}, {"source_code": "(* Problem 2 of round 521*)\n(* Comments:\n To make this program is even faster, I need to have in the function 'cut'\n l1 to be an array, use another integer (starting from k) to indicate stop.\n\n But this is so boring, I better use C.\n\n*)\nopen Scanf;;\nopen String;;\nopen Num;;\n\n(*These are some utility functions*)\nmodule U = struct\n let mprint z =\n print_endline (Num.string_of_num z);;\n\n let read_one format =\n let n = Scanf.scanf format (fun x -> x) in\n n;;\n\n let read_one_number () =\n let n = read_one \"%d \" in\n n\n\n let read_array n a =\n for i = 0 to n-1 do\n let n = read_one_number () in\n a.(i) <- n\n done\n\nend\n\n(*The solutions*)\n\nlet n = U.read_one_number ()\nlet k = U.read_one_number ()\nlet a = Array.make n 0\nlet () = U.read_array n a\n\nmodule H = Hashtbl\nlet t = H.create n\n\n(*\nlet () =\n Array.iter (fun x-> print_int x; print_endline \"\") a\n*)\n\nlet my_find s x =\n try Some (H.find s x)\n with\n Not_found -> None\n\nlet total = ref 0\n\nlet () = Array.iter (fun x-> \n let y = my_find t x in\n match y with\n None -> H.add t x 1\n | Some z -> H.replace t x (1+z)\n ) a\n;;\n\nlet my_compare h1 h2 =\n let (_,v1) = h1 in\n let (_,v2) = h2 in\n if v1 > v2 then 1\n else if v1 == v2 then 0\n else -1;;\n\nlet ll = H.fold (fun k v x -> (k,v) :: x) t [];;\n\nlet lr = List.stable_sort my_compare ll\n |> List.rev;;\n(*\nlet () =\n List.iter (fun h ->\n let (k,v) = h in Printf.printf \"%d %d\\n\" k v\n ) lr;;\n *)\n\nlet rec cut l1 l2 =\n let n1 = List.length l1 in\n if List.length l2 == k then\n l2\n else\n begin\n if n1 == 1 then\n (List.hd l1) :: l2\n else\n begin\n let h1 :: _ = l1 in\n let h2 :: _ = List.tl l1 in\n let (k1,a1) = h1 in\n let (_,a2) = h2 in\n if a1 < 2*a2 then\n cut (List.tl l1) (h1 :: l2)\n else\n cut ((k1,a1-a1/2) :: (List.tl l1)) ((k1,a1/2) :: l2)\n end\n end\n;;\n\nif n==k then\n begin\n print_int (List.length lr); print_endline \"\";\n List.iter (fun h ->\n let (i,_) = h in Printf.printf \"%d \" i\n ) lr\n end\nelse\n begin\n let rslt = cut lr [] in\n if List.length rslt < k then\n begin\n print_int 0; print_endline \"\"\n end\n else\n List.iter (fun h ->\n let (i,_) = h in Printf.printf \"%d \" i\n ) rslt;\n end\n;;\n"}, {"source_code": "(* Problem 2 of round 521*)\n(* Comments:\n To make this program is even faster, I need to have in the function 'cut'\n l1 to be an array, use another integer (starting from k) to indicate stop.\n\n But this is so boring, I better use C.\n\n*)\nopen Scanf;;\nopen String;;\nopen Num;;\n\n(*These are some utility functions*)\nmodule U = struct\n let mprint z =\n print_endline (Num.string_of_num z);;\n\n let read_one format =\n let n = Scanf.scanf format (fun x -> x) in\n n;;\n\n let read_one_number () =\n let n = read_one \"%d \" in\n n\n\n let read_array n a =\n for i = 0 to n-1 do\n let n = read_one_number () in\n a.(i) <- n\n done\n\nend\n\n(*The solutions*)\n\nlet n = U.read_one_number ()\nlet k = U.read_one_number ()\nlet a = Array.make n 0\nlet () = U.read_array n a\n\nmodule H = Hashtbl\nlet t = H.create n\n\n(*\nlet () =\n Array.iter (fun x-> print_int x; print_endline \"\") a\n*)\n\nlet my_find s x =\n try Some (H.find s x)\n with\n Not_found -> None\n\nlet total = ref 0\n\nlet () = Array.iter (fun x-> \n let y = my_find t x in\n match y with\n None -> H.add t x 1\n | Some z -> H.replace t x (1+z)\n ) a\n;;\n\nlet my_compare h1 h2 =\n let (_,v1) = h1 in\n let (_,v2) = h2 in\n if v1 > v2 then 1\n else if v1 == v2 then 0\n else -1;;\n\nlet ll = H.fold (fun k v x -> (k,v) :: x) t [];;\n\nlet lr = List.stable_sort my_compare ll\n |> List.rev;;\n(*\nlet () =\n List.iter (fun h ->\n let (k,v) = h in Printf.printf \"%d %d\\n\" k v\n ) lr;;\n *)\n\nlet rec cut l1 l2 =\n let n1 = List.length l1 in\n if List.length l2 == k then\n l2\n else\n begin\n if n1 == 1 then\n (List.hd l1) :: l2\n else\n begin\n let h1 :: _ = l1 in\n let h2 :: _ = List.tl l1 in\n let (k1,a1) = h1 in\n let (_,a2) = h2 in\n if a1 < 2*a2 then\n cut (List.tl l1) (h1 :: l2)\n else\n cut ((k1,a1-a1/2) :: (List.tl l1)) ((k1,a1/2) :: l2)\n end\n end\n;;\n\nif n==k then\n List.iter (fun h ->\n let (i,_) = h in Printf.printf \"%d \" i\n ) lr\nelse\n begin\n let rslt = cut lr [] in\n if List.length rslt < k then\n begin\n print_int 0; print_endline \"\"\n end\n else\n List.iter (fun h ->\n let (i,_) = h in Printf.printf \"%d \" i\n ) rslt;\n end\n;;\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet appearance a = (* (value,count) *)\n Array.fold_left (fun u v -> IMap.add v (1L + try IMap.find v u with Not_found -> 0L) u) IMap.empty a\nlet () =\n let n,k = get_2_i64 0 in\n let a = input_i64_array n in\n let ls =\n let mp = appearance a in\n IMap.bindings mp |> List.map (fun (k,v) -> (v,k))\n |> List.sort (fun u v -> compare v u)\n in\n (* print_list (fun (v,k) -> sprintf \"%Ld(%Ld) \" v k) ls; *)\n let constr d =\n let ans = ref [] in\n List.iter (fun (c,v) ->\n let p = c / d in\n rep 1L p (fun _ -> ans := v::!ans)\n ) ls;\n (* printf \"%Ld : %s\\n\" d (string_of_list ist !ans); *)\n !ans in\n let check d =\n if llen @@ constr d >= k then true\n else false\n in\n let d = binary_search n 0L (fun d -> check d) in\n constr d |> print_list ist\n\n (* let r = make 20010 [] in\n IMap.iter (fun p q ->\n (* if q=k then r := (p+1L)::!r *)\n (* arr.(i32 q) <- p::arr.(i32 q) *)\n r.(i32 q) <- p::r.(i32 q)\n ) mp;\n let ls = ref [] in\n iteri (fun c v -> if List.length v<>0 then ls:=(c,v)::!ls) r;\n (* let r = List.sort (fun u v -> -compare u v) !r in *)\n let ls = !ls |> List.sort (fun u v -> -compare u v) in\n let d = binary_search n 0L (fun d ->\n (* printf \"%Ld\\n\" d; *)\n let l = List.map (fun (c,v) -> ((i64 c)/d,v)) ls |> List.sort (fun u v -> compare v u) in\n let _,f = List.fold_left (fun (sum,f) (v,ls) ->\n let ne = sum + v * (llen ls) in\n (* printf \"%Ld %Ld\\n\" v ne; *)\n if ne >= k then (ne,true) else (ne,f)\n ) (0L,false) l\n in f\n ) in\n let l = List.map (fun (c,v) -> ((i64 c)/d,v)) ls |> List.sort (fun u v -> compare v u) in\n let rest = ref k in\n let _,f = List.fold_left (fun (sum,f) (v,ls) ->\n let ne = (v * llen ls) in\n if ne <= !rest then (\n rep 0L (ne-1L) (fun i ->\n let b = init (i32 v) (fun _ -> ls) |> to_list |> List.flatten |> of_list\n in printf \"%Ld \" b.(i32 i)\n );\n rest -= ne; (sum,f)\n ) else (\n let b = init (i32 v) (fun _ -> ls) |> to_list |> List.flatten |> of_list in\n rep 0L (!rest) (fun i ->\n printf \"%Ld \" b.(i32 i)\n ); (sum,f)\n )\n (* if >= k then (ne,true) else (ne,f) *)\n ) (0L,false) l\n in\n () *)\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet appearance a = (* (value,count) *)\n Array.fold_left (fun u v -> IMap.add v (1L + try IMap.find v u with Not_found -> 0L) u) IMap.empty a\nlet () =\n let n,k = get_2_i64 0 in\n let a = input_i64_array n in\n let ls =\n let mp = appearance a in\n IMap.bindings mp |> List.map (fun (k,v) -> (v,k))\n |> List.sort (fun u v -> compare v u)\n in\n (* print_list (fun (v,k) -> sprintf \"%Ld(%Ld) \" v k) ls; *)\n let constr d =\n let ans = ref [] in\n List.iter (fun (c,v) ->\n let p = c / d in\n rep 1L p (fun _ -> ans := v::!ans)\n ) ls;\n (* printf \"%Ld : %s\\n\" d (string_of_list ist !ans); *)\n !ans in\n let check d =\n if llen @@ constr d >= k then true\n else false\n in\n let d = binary_search n 0L (fun d -> check d) in\n constr d |> List.iter (fun v -> printf \"%Ld \" v)\n\n (* let r = make 20010 [] in\n IMap.iter (fun p q ->\n (* if q=k then r := (p+1L)::!r *)\n (* arr.(i32 q) <- p::arr.(i32 q) *)\n r.(i32 q) <- p::r.(i32 q)\n ) mp;\n let ls = ref [] in\n iteri (fun c v -> if List.length v<>0 then ls:=(c,v)::!ls) r;\n (* let r = List.sort (fun u v -> -compare u v) !r in *)\n let ls = !ls |> List.sort (fun u v -> -compare u v) in\n let d = binary_search n 0L (fun d ->\n (* printf \"%Ld\\n\" d; *)\n let l = List.map (fun (c,v) -> ((i64 c)/d,v)) ls |> List.sort (fun u v -> compare v u) in\n let _,f = List.fold_left (fun (sum,f) (v,ls) ->\n let ne = sum + v * (llen ls) in\n (* printf \"%Ld %Ld\\n\" v ne; *)\n if ne >= k then (ne,true) else (ne,f)\n ) (0L,false) l\n in f\n ) in\n let l = List.map (fun (c,v) -> ((i64 c)/d,v)) ls |> List.sort (fun u v -> compare v u) in\n let rest = ref k in\n let _,f = List.fold_left (fun (sum,f) (v,ls) ->\n let ne = (v * llen ls) in\n if ne <= !rest then (\n rep 0L (ne-1L) (fun i ->\n let b = init (i32 v) (fun _ -> ls) |> to_list |> List.flatten |> of_list\n in printf \"%Ld \" b.(i32 i)\n );\n rest -= ne; (sum,f)\n ) else (\n let b = init (i32 v) (fun _ -> ls) |> to_list |> List.flatten |> of_list in\n rep 0L (!rest) (fun i ->\n printf \"%Ld \" b.(i32 i)\n ); (sum,f)\n )\n (* if >= k then (ne,true) else (ne,f) *)\n ) (0L,false) l\n in\n () *)\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet appearance a = (* (value,count) *)\n Array.fold_left (fun u v -> IMap.add v (1L + try IMap.find v u with Not_found -> 0L) u) IMap.empty a\nlet () =\n let n,k = get_2_i64 0 in\n let a = input_i64_array n in\n let ls =\n let mp = appearance a in\n IMap.bindings mp |> List.map (fun (k,v) -> (v,k))\n |> List.sort (fun u v -> compare v u)\n in\n (* print_list (fun (v,k) -> sprintf \"%Ld(%Ld) \" v k) ls; *)\n let constr d =\n let ans = ref [] in\n List.iter (fun (c,v) ->\n let p = c / d in\n rep 1L p (fun _ -> ans := v::!ans)\n ) ls;\n (* printf \"%Ld : %s\\n\" d (string_of_list ist !ans); *)\n !ans in\n let check d =\n if llen @@ constr d >= k then true\n else false\n in\n let d = binary_search n 0L (fun d -> check d) in\n (* constr d |> List.iter (fun v -> printf \"%Ld \" v) *)\n constr d |> of_list |> iteri (fun i v ->\n (if i=0 then printf \"%Ld\"\n else printf \" %Ld\") v\n )"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet arr = make 50 []\nlet appearance a = (* (value,count) *)\n let open IMap in Array.fold_left (fun u v -> IMap.add v (1L + try IMap.find v u with Not_found -> 0L) u) IMap.empty a\nlet () =\n let n,k = get_2_i64 0 in\n let a = input_i64_array n in\n let mp = appearance a in\n let r = ref [] in\n IMap.iter (fun p q ->\n (* if q=k then r := (p+1L)::!r *)\n arr.(i32 q) <- p::arr.(i32 q)\n ) mp;\n let n_max = IMap.fold (fun _ v u -> max v u) mp 0L in\n (* iteri (fun i r ->\n if List.length r<>0 then\n printf \"%d : %s\\n\" i (string_of_list ist r);\n ) arr; *)\n let amari = ref 0 in\n (* let r_amari = ref [] in *)\n rep_rev n_max 1L (fun p ->\n let p = i32 p in\n if !amari +$ List.length arr.(p) >= i32 k then (\n (* print_list ist arr.(i32 p); *)\n if List.length arr.(p) >= i32 k then (\n let a = arr.(p) |> of_list in\n repi 0 (p) (fun i -> printf \"%Ld \" a.(i));\n exit 0;\n ) else (\n let rest = ref @@ i32 k -$ (List.length arr.(p)) in\n let a = arr.(p) |> of_list in\n repi 0 (length a-$1) (fun i -> printf \"%Ld \" a.(i));\n let q,res = ref @@ p+$1,ref [] in\n while !rest > 0 do\n (* printf \"%d:\\n \" !rest;\n print_list ist !res; *)\n match arr.(!q) with\n | [] -> (q := !q +$ 1)\n | ls -> (\n (* let b = arr.(!q) |> of_list in *)\n let v = List.length arr.(!q) in\n let lls = make !q 0L |> to_list |> List.map (fun _ -> ls) |> List.flatten\n |> of_list\n in\n (* print_array ist lls; *)\n let r = ref 0 in\n while !rest > 0 && !r < length lls do\n res := lls.(!r) :: !res;\n r := !r +$ 1;\n rest := !rest -$ 1\n done;\n if !rest = 0 then (\n print_list ist !res; exit 0\n ) else (q := !q +$ 1)\n )\n done\n\n )\n ) else (\n let q = List.length arr.(p) in\n amari := !amari +$ q *$ p;\n (* r_amari := ()::!r_amari *)\n )\n );\n (* print_array (string_of_list ist) arr; *)\n (* print_list ist !r *)\n\n\n\n\n\n\n\n\n\n"}], "src_uid": "cfccf06c4d0de89bf0978dc6512265c4"} {"nl": {"description": "Polycarp is sad \u2014 New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.The local store introduced a new service this year, called \"Build your own garland\". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!For example, if you provide $$$3$$$ red, $$$3$$$ green and $$$3$$$ blue lamps, the resulting garland can look like this: \"RGBRBGBGR\" (\"RGB\" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.However, if you provide, say, $$$1$$$ red, $$$10$$$ green and $$$2$$$ blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of sets of lamps Polycarp has bought. Each of the next $$$t$$$ lines contains three integers $$$r$$$, $$$g$$$ and $$$b$$$ ($$$1 \\le r, g, b \\le 10^9$$$) \u2014 the number of red, green and blue lamps in the set, respectively.", "output_spec": "Print $$$t$$$ lines \u2014 for each set of lamps print \"Yes\" if the store workers can build a garland from them and \"No\" otherwise.", "sample_inputs": ["3\n3 3 3\n1 10 2\n2 1 1"], "sample_outputs": ["Yes\nNo\nYes"], "notes": "NoteThe first two sets are desribed in the statement.The third set produces garland \"RBRG\", for example."}, "positive_code": [{"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet fuck str b ch =\n try\n Some (String.index_from str b ch)\n with _ ->\n None\n\nlet split str ch =\n let rec split' b e =\n if b >= e\n then\n []\n else\n match (fuck str b ch) with\n | None -> let res = String.sub str b (e - b) |> int_of_string in [res]\n | Some(dest) ->\n let res = String.sub str b (dest - b) |> int_of_string in\n res :: split' (dest + 1) e\n in\n let res = split' 0 (String.length str) in\n res\n;;\n\n\nlet () =\n let n = read_int () in\n let rec loop num =\n if num = 0\n then\n ()\n else\n let line = read_line () in\n Scanf.sscanf line \"%Ld %Ld %Ld\" (fun a b c ->\n let open Int64 in\n let ls' = List.sort (fun a b -> compare a b) [a;b;c] in\n let n1 = List.nth ls' 0 in\n let n2 = List.nth ls' 1 in\n let n3 = List.nth ls' 2 in\n if (compare (add (add n2 n1) 1L) n3) >= 0 then Printf.printf \"Yes\\n\" else Printf.printf \"No\\n\"\n )\n ;\n num - 1 |> loop\n in\n loop n\n;;\n"}], "negative_code": [{"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet fuck str b ch =\n try\n Some (String.index_from str b ch)\n with _ ->\n None\n\nlet split str ch =\n let rec split' b e =\n if b >= e\n then\n []\n else\n match (fuck str b ch) with\n | None -> let res = String.sub str b (e - b) |> int_of_string in [res]\n | Some(dest) ->\n let res = String.sub str b (dest - b) |> int_of_string in\n res :: split' (dest + 1) e\n in\n let res = split' 0 (String.length str) in\n res\n;;\n\n\nlet () =\n let n = read_int () in\n let rec loop num =\n if num = 0\n then\n ()\n else\n let line = read_line () in\n Scanf.sscanf line \"%Ld %Ld %Ld\" (fun a b c ->\n let open Int64 in\n let ls' = List.sort (fun a b -> compare a b) [a;b;c] in\n let n1 = List.nth ls' 0 in\n let n2 = List.nth ls' 1 in\n let n3 = List.nth ls' 2 in\n if (compare (add (add n3 n1) 1L) n2) > 0 then Printf.printf \"Yes\\n\" else Printf.printf \"No\\n\"\n );\nin\nloop n\n;;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet fuck str b ch =\n try\n Some (String.index_from str b ch)\n with _ ->\n None\n\nlet split str ch =\n let rec split' b e =\n if b >= e\n then\n []\n else\n match (fuck str b ch) with\n | None -> let res = String.sub str b (e - b) |> int_of_string in [res]\n | Some(dest) ->\n let res = String.sub str b (dest - b) |> int_of_string in\n res :: split' (dest + 1) e\n in\n let res = split' 0 (String.length str) in\n res\n;;\n\n\nlet () =\n let n = read_int () in\n let rec loop num =\n if num = 0\n then\n ()\n else\n let line = read_line () in\n Scanf.sscanf line \"%Ld %Ld %Ld\" (fun a b c ->\n let open Int64 in\n let comp n1 n2 n3 =\n (compare (add n1 n2) n3) < 0\n in let eq n1 n2 =\n (compare n1 n2) = 0\n in let relate n1 n2 =\n (compare (div n1 n2) 1L) = 0 || (compare (div n2 n1) 1L) = 0 ||\n (eq n1 1L && eq n2 2L) || (eq n1 2L && eq n2 1L)\n in\n if comp a b c || comp a c b || comp b c a || not (relate a b && relate b c)\n then\n Printf.printf \"No\\n\"\n else\n Printf.printf \"Yes\\n\"\n );\n loop (num - 1)\n in\n loop n\n;;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet fuck str b ch =\n try\n Some (String.index_from str b ch)\n with _ ->\n None\n\nlet split str ch =\n let rec split' b e =\n if b >= e\n then\n []\n else\n match (fuck str b ch) with\n | None -> let res = String.sub str b (e - b) |> int_of_string in [res]\n | Some(dest) ->\n let res = String.sub str b (dest - b) |> int_of_string in\n res :: split' (dest + 1) e\n in\n let res = split' 0 (String.length str) in\n res\n;;\n\n\nlet () =\n let n = read_int () in\n let rec loop num =\n if num = 0\n then\n ()\n else\n let line = read_line () in\n Scanf.sscanf line \"%Ld %Ld %Ld\" (fun a b c ->\n let open Int64 in\n let ls' = List.sort (fun a b -> compare a b) [a;b;c] in\n let n1 = List.nth ls' 0 in\n let n2 = List.nth ls' 1 in\n let n3 = List.nth ls' 2 in\n if (compare (add (add n3 n1) 1L) n2) >= 0 then Printf.printf \"Yes\\n\" else Printf.printf \"No\\n\"\n );\nin\nloop n\n;;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet fuck str b ch =\n try\n Some (String.index_from str b ch)\n with _ ->\n None\n\nlet split str ch =\n let rec split' b e =\n if b >= e\n then\n []\n else\n match (fuck str b ch) with\n | None -> let res = String.sub str b (e - b) |> int_of_string in [res]\n | Some(dest) ->\n let res = String.sub str b (dest - b) |> int_of_string in\n res :: split' (dest + 1) e\n in\n let res = split' 0 (String.length str) in\n res\n;;\n\n\nlet () =\n let n = read_int () in\n let rec loop num =\n if num = 0\n then\n ()\n else\n Scanf.scanf \"%Ld %Ld %Ld\" (fun a b c ->\n let open Int64 in\n let comp n1 n2 n3 =\n (compare (add n1 n2) n3) < 0\n in\n if comp a b c || comp a c b || comp b c a\n then\n Printf.printf \"No\\n\"\n else\n Printf.printf \"Yes\\n\"\n )\n in\n loop n\n;;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet fuck str b ch =\n try\n Some (String.index_from str b ch)\n with _ ->\n None\n\nlet split str ch =\n let rec split' b e =\n if b >= e\n then\n []\n else\n match (fuck str b ch) with\n | None -> let res = String.sub str b (e - b) |> int_of_string in [res]\n | Some(dest) ->\n let res = String.sub str b (dest - b) |> int_of_string in\n res :: split' (dest + 1) e\n in\n let res = split' 0 (String.length str) in\n res\n;;\n\n\nlet () =\n try\n let n = read_int () in\n let rec loop num =\n if num = 0\n then\n ()\n else\n let line = read_line () in\n Scanf.sscanf line \"%Ld %Ld %Ld\" (fun a b c ->\n let open Int64 in\n let comp n1 n2 n3 =\n (compare (add n1 n2) n3) < 0\n in\n if comp a b c || comp a c b || comp b c a\n then\n Printf.printf \"No\\n\"\n else\n Printf.printf \"Yes\\n\"\n );\n loop (n - 1)\n in\n loop n\n with End_of_file ->\n ()\n\n;;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet fuck str b ch =\n try\n Some (String.index_from str b ch)\n with _ ->\n None\n\nlet split str ch =\n let rec split' b e =\n if b >= e\n then\n []\n else\n match (fuck str b ch) with\n | None -> let res = String.sub str b (e - b) |> int_of_string in [res]\n | Some(dest) ->\n let res = String.sub str b (dest - b) |> int_of_string in\n res :: split' (dest + 1) e\n in\n let res = split' 0 (String.length str) in\n res\n;;\n\n\nlet () =\n let n = read_int () in\n let rec loop num =\n if num = 0\n then\n ()\n else\n let line = read_line () in\n Scanf.sscanf line \"%Ld %Ld %Ld\" (fun a b c ->\n let open Int64 in\n let comp n1 n2 n3 =\n (compare (add n1 n2) n3) < 0\n in let equal n1 n2 =\n (compare n1 n2) = 0\n in\n if comp a b c || comp a c b || comp b c a || equal a 0L || equal b 0L || equal c 0L\n then\n Printf.printf \"No\\n\"\n else\n Printf.printf \"Yes\\n\"\n );\n loop (num - 1)\n in\n loop n\n;;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet fuck str b ch =\n try\n Some (String.index_from str b ch)\n with _ ->\n None\n\nlet split str ch =\n let rec split' b e =\n if b >= e\n then\n []\n else\n match (fuck str b ch) with\n | None -> let res = String.sub str b (e - b) |> int_of_string in [res]\n | Some(dest) ->\n let res = String.sub str b (dest - b) |> int_of_string in\n res :: split' (dest + 1) e\n in\n let res = split' 0 (String.length str) in\n res\n;;\n\n\nlet () =\n let n = read_int () in\n let rec loop num =\n if num = 0\n then\n ()\n else\n let line = read_line () in\n Scanf.sscanf line \"%Ld %Ld %Ld\" (fun a b c ->\n let open Int64 in\n let comp n1 n2 =\n let res = sub n1 n2 in\n res = 0L || res = -1L || res = 1L\n in\n if comp a b && comp a c && comp b c\n then\n Printf.printf \"Yes\\n\"\n else\n Printf.printf \"No\\n\"\n );\n loop (num - 1)\n in\n loop n\n;;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet fuck str b ch =\n try\n Some (String.index_from str b ch)\n with _ ->\n None\n\nlet split str ch =\n let rec split' b e =\n if b >= e\n then\n []\n else\n match (fuck str b ch) with\n | None -> let res = String.sub str b (e - b) |> int_of_string in [res]\n | Some(dest) ->\n let res = String.sub str b (dest - b) |> int_of_string in\n res :: split' (dest + 1) e\n in\n let res = split' 0 (String.length str) in\n res\n;;\n\n\nlet () =\n let n = read_int () in\n let rec loop num =\n if num = 0\n then\n ()\n else\n let line = read_line () in\n Scanf.sscanf line \"%Ld %Ld %Ld\" (fun a b c ->\n let open Int64 in\n let comp n1 n2 n3 =\n (compare (add n1 n2) n3) < 0\n in\n if comp a b c || comp a c b || comp b c a\n then\n Printf.printf \"No\\n\"\n else\n Printf.printf \"Yes\\n\"\n );\n loop (num - 1)\n in\n loop n\n;;\n"}], "src_uid": "34aa41871ee50f06e8acbd5eee94b493"} {"nl": {"description": "Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.Let's assume that S(n) is the sum of digits of number n, for example, S(4098)\u2009=\u20094\u2009+\u20090\u2009+\u20099\u2009+\u20098\u2009=\u200921. Then the digital root of number n equals to: dr(n)\u2009=\u2009S(n), if S(n)\u2009<\u200910; dr(n)\u2009=\u2009dr(\u2009S(n)\u2009), if S(n)\u2009\u2265\u200910. For example, dr(4098)\u2009\u2009=\u2009\u2009dr(21)\u2009\u2009=\u2009\u20093.Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n)\u2009\u2009=\u2009\u2009S(\u2009S(\u2009S(\u2009S(n)\u2009)\u2009)\u2009) (n\u2009\u2264\u2009101000).Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.", "input_spec": "The first line contains two integers k and d (1\u2009\u2264\u2009k\u2009\u2264\u20091000;\u20020\u2009\u2264\u2009d\u2009\u2264\u20099).", "output_spec": "In a single line print either any number that meets the requirements (without the leading zeroes) or \"No solution\" (without the quotes), if the corresponding number does not exist. The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes.", "sample_inputs": ["4 4", "5 1", "1 0"], "sample_outputs": ["5881", "36172", "0"], "notes": "NoteFor the first test sample dr(5881)\u2009\u2009=\u2009\u2009dr(22)\u2009\u2009=\u2009\u20094.For the second test sample dr(36172)\u2009\u2009=\u2009\u2009dr(19)\u2009\u2009=\u2009\u2009dr(10)\u2009\u2009=\u2009\u20091."}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet solve k d =\n if d <> 0 then begin\n let s = String.create k in\n s.[0] <- char_of_int (d + int_of_char '0');\n String.fill s 1 (k - 1) '0';\n print_endline s\n end else if k = 1 then begin\n print_endline \"0\"\n end else begin\n print_endline \"No solution\";\n end\n;;\n\nlet () =\n let k, d = Scanf.scanf \"%d %d \" (fun k d -> k, d) in\n solve k d\n;;\n"}], "negative_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet solve k d =\n if d <> 0 then begin\n let s = String.create k in\n s.[0] <- char_of_int (d + int_of_char '0');\n String.fill s 1 (k - 1) '0';\n print_endline s\n end else if k = 1 then begin\n print_endline \"0\"\n end else begin\n let s = String.create k in\n s.[0] <- char_of_int (1 + int_of_char '0');\n s.[1] <- char_of_int (9 + int_of_char '0');\n String.fill s 2 (k - 2) '0';\n print_endline s\n end\n;;\n\nlet () =\n let k, d = Scanf.scanf \"%d %d \" (fun k d -> k, d) in\n solve k d\n;;\n"}, {"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet solve k d =\n let s = String.create k in\n s.[0] <- char_of_int (d + int_of_char '0');\n String.fill s 1 (k - 1) '0';\n print_endline s\n;;\n\nlet () =\n let k, d = Scanf.scanf \"%d %d \" (fun k d -> k, d) in\n solve k d\n;;\n"}], "src_uid": "5dd0d518f315d81204b25e48fea0793a"} {"nl": {"description": "Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.You are a new applicant for his company. Boboniu will test you with the following chess question:Consider a $$$n\\times m$$$ grid (rows are numbered from $$$1$$$ to $$$n$$$, and columns are numbered from $$$1$$$ to $$$m$$$). You have a chess piece, and it stands at some cell $$$(S_x,S_y)$$$ which is not on the border (i.e. $$$2 \\le S_x \\le n-1$$$ and $$$2 \\le S_y \\le m-1$$$).From the cell $$$(x,y)$$$, you can move your chess piece to $$$(x,y')$$$ ($$$1\\le y'\\le m, y' \\neq y$$$) or $$$(x',y)$$$ ($$$1\\le x'\\le n, x'\\neq x$$$). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.Your goal is to visit each cell exactly once. Can you find a solution?Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.", "input_spec": "The only line of the input contains four integers $$$n$$$, $$$m$$$, $$$S_x$$$ and $$$S_y$$$ ($$$3\\le n,m\\le 100$$$, $$$2 \\le S_x \\le n-1$$$, $$$2 \\le S_y \\le m-1$$$) \u2014 the number of rows, the number of columns, and the initial position of your chess piece, respectively.", "output_spec": "You should print $$$n\\cdot m$$$ lines. The $$$i$$$-th line should contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\leq x_i \\leq n$$$, $$$1 \\leq y_i \\leq m$$$), denoting the $$$i$$$-th cell that you visited. You should print exactly $$$nm$$$ pairs $$$(x_i, y_i)$$$, they should cover all possible pairs $$$(x_i, y_i)$$$, such that $$$1 \\leq x_i \\leq n$$$, $$$1 \\leq y_i \\leq m$$$. We can show that under these constraints there always exists a solution. If there are multiple answers, print any.", "sample_inputs": ["3 3 2 2", "3 4 2 2"], "sample_outputs": ["2 2\n1 2\n1 3\n2 3\n3 3\n3 2\n3 1\n2 1\n1 1", "2 2\n2 1\n2 3\n2 4\n1 4\n3 4\n3 3\n3 2\n3 1\n1 1\n1 2\n1 3"], "notes": "NotePossible routes for two examples: "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_4 _ = bscanf Scanning.stdin \" %d %d %d %d \" (fun a b c d -> (a,b,c,d)) \n\nlet () = \n let (n,m,row,col) = read_4() in\n\n let trans (i,j) =\n ((if i=row then 1 else if i=1 then row else i),\n (if j=col then 1 else if j=1 then col else j))\n in\n\n for i=1 to n do\n for j=1 to m do\n let j = if i mod 2 = 1 then j else m+1-j in\n let (i,j) = trans (i,j) in\n printf \"%d %d\\n\" i j\n done\n done\n"}], "negative_code": [], "src_uid": "ed26479cdf72ad9686bbf334d90aa0be"} {"nl": {"description": "Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!", "input_spec": "The first line of the input contains single integer n n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1\u2009\u2264\u2009mi,\u2009\u2009ci\u2009\u2264\u20096)\u00a0\u2014 values on dice upper face after Mishka's and Chris' throws in i-th round respectively.", "output_spec": "If Mishka is the winner of the game, print \"Mishka\" (without quotes) in the only line. If Chris is the winner of the game, print \"Chris\" (without quotes) in the only line. If the result of the game is draw, print \"Friendship is magic!^^\" (without quotes) in the only line.", "sample_inputs": ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"], "sample_outputs": ["Mishka", "Friendship is magic!^^", "Chris"], "notes": "NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n) \nlet print result = Printf.printf \"%s\\n\" result\n\nlet count () =\n let n = read () in\n let rec loop i count_a count_b =\n if i < n\n then\n let a = read () in\n let b = read () in\n if a > b\n then\n loop (i + 1) (count_a + 1) count_b\n else\n if a < b\n then\n loop (i + 1) count_a (count_b + 1)\n else\n loop (i + 1) count_a count_b\n else\n (count_a, count_b)\n in loop 0 0 0\n\nlet solve (count_a, count_b) =\n if count_a > count_b\n then\n print \"Mishka\"\n else\n if count_a < count_b\n then\n print \"Chris\"\n else\n print \"Friendship is magic!^^\"\n\nlet () = solve (count ())"}, {"source_code": "\nlet read_pair () = \n let s = read_line () in \n let nums = List.map int_of_string (Str.split (Str.regexp \" \") s) in\n match nums with\n | [a;b] -> (a, b)\n | _ -> (0, 0)\n\n;;\n\nlet rec get_pair n (a, b)= \n if n > 0 then\n match read_pair () with\n | (x, y) -> if x > y then\n get_pair (n-1) (a+1, b)\n else if x < y then\n get_pair (n-1) (a, b+1)\n else\n get_pair (n-1) (a, b)\n\n else\n (a, b)\n\n;;\n\nlet read_nums () = \n let n = read_int () in\n let (a, b) = get_pair n (0, 0) in\n if a = b then\n print_string \"Friendship is magic!^^\\n\"\n else if a > b then\n print_string \"Mishka\\n\"\n else\n print_string \"Chris\\n\"\n;;\n\n\nread_nums () ;;\n"}, {"source_code": "let n = read_line () |> int_of_string in\nlet scores = Array.init n (fun x -> read_line()) \n |> Array.map (fun x -> let b = Str.split (Str.regexp \" *\") x |> List.map int_of_string in (List.nth b 0, List.nth b 1)) |> Array.to_list in\nlet (m,c) = List.split scores in\nlet sum = List.fold_left ( + ) 0 in\nprint_string (match List.map2 compare m c |> sum with\n | 0 -> \"Friendship is magic!^^\"\n | e when e > 0 -> \"Mishka\"\n | _ -> \"Chris\"\n) \n"}], "negative_code": [{"source_code": "\nlet read_pair () = \n let s = read_line () in \n let nums = List.map int_of_string (Str.split (Str.regexp \" \") s) in\n match nums with\n | [a;b] -> (a, b)\n | _ -> (0, 0)\n\n;;\n\nlet rec get_pair n (a, b)= \n if n > 0 then\n match read_pair () with\n | (a, b) -> if a > b then\n get_pair (n-1) (a+1, b)\n else if a < b then\n get_pair (n-1) (a, b+1)\n else\n get_pair (n-1) (a, b)\n\n else\n (a, b)\n\n;;\n\nlet read_nums () = \n let n = read_int () in\n let (a, b) = get_pair n (0, 0) in\n if a = b then\n print_string \"Friendship is magic!^^\\n\"\n else if a > b then\n print_string \"Mishka\\n\"\n else\n print_string \"Chris\\n\"\n;;\n\n\nread_nums () ;;\n"}, {"source_code": "let n = read_line () |> int_of_string in\nlet scores = Array.init n (fun x -> read_line()) \n |> Array.map (fun x -> let b = Str.split (Str.regexp \" *\") x |> List.map int_of_string in (List.nth b 0, List.nth b 1)) |> Array.to_list in\nlet (m,c) = List.split scores in\nlet sum = List.fold_left ( + ) 0 in\nprint_string (match List.map2 compare m c |> sum with\n | 0 -> \"Friendship is magic!^^\"\n | e when e > 0 -> \"Minska\"\n | _ -> \"Chris\"\n) \n"}], "src_uid": "76ecde4a445bbafec3cda1fc421e6d42"} {"nl": {"description": "DZY loves Fast Fourier Transformation, and he enjoys using it.Fast Fourier Transformation is an algorithm used to calculate convolution. Specifically, if a, b and c are sequences with length n, which are indexed from 0 to n\u2009-\u20091, andWe can calculate c fast using Fast Fourier Transformation.DZY made a little change on this formula. NowTo make things easier, a is a permutation of integers from 1 to n, and b is a sequence only containing 0 and 1. Given a and b, DZY needs your help to calculate c.Because he is naughty, DZY provides a special way to get a and b. What you need is only three integers n, d, x. After getting them, use the code below to generate a and b.//x is 64-bit variable;function getNextX() { x = (x * 37 + 10007) % 1000000007; return x;}function initAB() { for(i = 0; i < n; i = i + 1){ a[i] = i + 1; } for(i = 0; i < n; i = i + 1){ swap(a[i], a[getNextX() % (i + 1)]); } for(i = 0; i < n; i = i + 1){ if (i < d) b[i] = 1; else b[i] = 0; } for(i = 0; i < n; i = i + 1){ swap(b[i], b[getNextX() % (i + 1)]); }}Operation x % y denotes remainder after division x by y. Function swap(x, y) swaps two values x and y.", "input_spec": "The only line of input contains three space-separated integers n,\u2009d,\u2009x\u00a0(1\u2009\u2264\u2009d\u2009\u2264\u2009n\u2009\u2264\u2009100000;\u00a00\u2009\u2264\u2009x\u2009\u2264\u20091000000006). Because DZY is naughty, x can't be equal to 27777500.", "output_spec": "Output n lines, the i-th line should contain an integer ci\u2009-\u20091.", "sample_inputs": ["3 1 1", "5 4 2", "5 4 3"], "sample_outputs": ["1\n3\n2", "2\n2\n4\n5\n5", "5\n5\n5\n5\n4"], "notes": "NoteIn the first sample, a is [1 3 2], b is [1 0 0], so c0\u2009=\u2009max(1\u00b71)\u2009=\u20091, c1\u2009=\u2009max(1\u00b70,\u20093\u00b71)\u2009=\u20093, c2\u2009=\u2009max(1\u00b70,\u20093\u00b70,\u20092\u00b71)\u2009=\u20092.In the second sample, a is [2 1 4 5 3], b is [1 1 1 0 1].In the third sample, a is [5 2 1 4 3], b is [1 1 1 1 0]."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n(* The following two functions require the range to be of length at least 1 *)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet x = ref 0L\n\nlet getNextX () = \n x := (!x ** 37L ++ 10007L) %% 1000000007L;\n !x\n\nlet genab n d =\n let a = Array.init n (fun i -> i+1) in\n let b = Array.init n (fun i -> if i i) in\n\n Array.sort (fun i j -> compare a.(j) a.(i)) index;\n\n let ones = Array.make n 0 in\n\n let rec fill_ones c i = if c = d then () else\n if b.(i) = 1 then (ones.(c) <- i; fill_ones (c+1) (i+1))\n else fill_ones c (i+1)\n in\n fill_ones 0 0;\n\n let answer = Array.make n 0 in\n\n let stopping_value = if d<=1000 then n else (999*n)/1000 in\n\n let rec loop n_finished i = if n_finished >= stopping_value || i = n then () else\n let j = index.(i) in\n let rec do_ones k ac = if k=d then ac else\n\t let l = ones.(k) in\n\t let i = l+j in\n\t if i >= n then ac else\n\t if answer.(i) = 0 then (answer.(i) <- a.(j); do_ones (k+1) (ac+1))\n\t else do_ones (k+1) ac\n in\n let more_finished = do_ones 0 0 in\n loop (n_finished + more_finished) (i+1)\n in\n\n loop 0 0;\n \n if stopping_value < n then \n for i=0 to n-1 do\n if answer.(i) = 0 then (\n\tanswer.(i) <- maxf 0 i (fun j -> a.(j) * b.(i-j))\n )\n done;\n\n for i=0 to n-1 do\n printf \"%d\\n\" answer.(i)\n done\n"}], "negative_code": [], "src_uid": "948ae7a0189ada07c8c67a1757f691f0"} {"nl": {"description": "The Berland language consists of words having exactly two letters. Moreover, the first letter of a word is different from the second letter. Any combination of two different Berland letters (which, by the way, are the same as the lowercase letters of Latin alphabet) is a correct word in Berland language.The Berland dictionary contains all words of this language. The words are listed in a way they are usually ordered in dictionaries. Formally, word $$$a$$$ comes earlier than word $$$b$$$ in the dictionary if one of the following conditions hold: the first letter of $$$a$$$ is less than the first letter of $$$b$$$; the first letters of $$$a$$$ and $$$b$$$ are the same, and the second letter of $$$a$$$ is less than the second letter of $$$b$$$. So, the dictionary looks like that: Word $$$1$$$: ab Word $$$2$$$: ac ... Word $$$25$$$: az Word $$$26$$$: ba Word $$$27$$$: bc ... Word $$$649$$$: zx Word $$$650$$$: zy You are given a word $$$s$$$ from the Berland language. Your task is to find its index in the dictionary.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 650$$$)\u00a0\u2014 the number of test cases. Each test case consists of one line containing $$$s$$$\u00a0\u2014 a string consisting of exactly two different lowercase Latin letters (i.\u2009e. a correct word of the Berland language).", "output_spec": "For each test case, print one integer\u00a0\u2014 the index of the word $$$s$$$ in the dictionary.", "sample_inputs": ["7\n\nab\n\nac\n\naz\n\nba\n\nbc\n\nzx\n\nzy"], "sample_outputs": ["1\n2\n25\n26\n27\n649\n650"], "notes": null}, "positive_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x);;\r\nlet readBerland () = Scanf.scanf \" %c%c\" (fun a b -> a, b);;\r\n\r\nlet convertCharsToAlphabetPos = function\r\n | a, b -> (Char.code a) - 97, (Char.code b) - 97\r\n;;\r\nlet getBerlandPos = function\r\n | a, b -> \r\n if ba then a*25+b-1\r\n else raise (Failure \"Value Err!\")\r\n;;\r\n\r\nlet rec iterator = function\r\n | 0 -> 0\r\n | n -> \r\n let a, b = convertCharsToAlphabetPos (readBerland ()) in \r\n (* Add 1 as we aren't zero indexing *)\r\n print_int ((getBerlandPos (a, b))+1);\r\n print_newline ();\r\n iterator (n-1)\r\n;;\r\n\r\nlet test_cases = readInt () in iterator test_cases;;\r\n\r\n"}, {"source_code": "let n = int_of_string (read_line ())\r\n\r\nlet solve () = \r\n let s = read_line () in\r\n let first = (Char.code s.[0]) - 97 in\r\n let second = (Char.code s.[1]) - 97 in\r\n if second < first then\r\n Printf.printf \"%d\\n\" ((26 * first) + second - (first - 1))\r\n else\r\n Printf.printf \"%d\\n\" ((26 * first) + second - first)\r\n;;\r\nfor i = 0 to n - 1 do\r\n solve ()\r\ndone;;"}], "negative_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x);;\r\nlet readBerland () = Scanf.scanf \" %c%c\" (fun a b -> a, b);;\r\n\r\nlet convertCharsToAlphabetPos = function\r\n | a, b -> (Char.code a) - 97, (Char.code b) - 97\r\n;;\r\nlet getBerlandPos = function\r\n | a, b -> a*26+b \r\n;;\r\n\r\nlet rec iterator = function\r\n | 0 -> 0\r\n | n -> \r\n let a, b = convertCharsToAlphabetPos (readBerland ()) in \r\n print_int (getBerlandPos (a, b));\r\n print_newline ();\r\n iterator (n-1)\r\n;;\r\n\r\nlet test_cases = readInt () in iterator test_cases;;\r\n\r\n"}], "src_uid": "2e3006d663a3c7ad3781aba1e37be3ca"} {"nl": {"description": "After too much playing on paper, Iahub has switched to computer games. The game he plays is called \"Block Towers\". It is played in a rectangular grid with n rows and m columns (it contains n\u2009\u00d7\u2009m cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any building. The rest of cells are empty. In some empty cell Iahub can build exactly one tower of two following types: Blue towers. Each has population limit equal to 100. Red towers. Each has population limit equal to 200. However, it can be built in some cell only if in that moment at least one of the neighbouring cells has a Blue Tower. Two cells are neighbours is they share a side. Iahub is also allowed to destroy a building from any cell. He can do this operation as much as he wants. After destroying a building, the other buildings are not influenced, and the destroyed cell becomes empty (so Iahub can build a tower in this cell if needed, see the second example for such a case).Iahub can convince as many population as he wants to come into his city. So he needs to configure his city to allow maximum population possible. Therefore he should find a sequence of operations that builds the city in an optimal way, so that total population limit is as large as possible.He says he's the best at this game, but he doesn't have the optimal solution. Write a program that calculates the optimal one, to show him that he's not as good as he thinks. ", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500). Each of the next n lines contains m characters, describing the grid. The j-th character in the i-th line is '.' if you're allowed to build at the cell with coordinates (i,\u2009j) a tower (empty cell) or '#' if there is a big hole there. ", "output_spec": "Print an integer k in the first line (0\u2009\u2264\u2009k\u2009\u2264\u2009106) \u2014 the number of operations Iahub should perform to obtain optimal result. Each of the following k lines must contain a single operation in the following format: \u00abB x y\u00bb (1\u2009\u2264\u2009x\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009m) \u2014 building a blue tower at the cell (x,\u2009y); \u00abR x y\u00bb (1\u2009\u2264\u2009x\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009m) \u2014 building a red tower at the cell (x,\u2009y); \u00abD x y\u00bb (1\u2009\u2264\u2009x\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009m) \u2014 destroying a tower at the cell (x,\u2009y). If there are multiple solutions you can output any of them. Note, that you shouldn't minimize the number of operations.", "sample_inputs": ["2 3\n..#\n.#.", "1 3\n..."], "sample_outputs": ["4\nB 1 1\nR 1 2\nR 2 1\nB 2 3", "5\nB 1 1\nB 1 2\nR 1 3\nD 1 2\nR 1 2"], "notes": null}, "positive_code": [{"source_code": "module Deque = struct\n type 'a der = { mutable l : 'a del; e : 'a; mutable r : 'a del }\n and 'a del = Null | El of 'a der ;;\n type 'a deq = { mutable len : int; mutable top : 'a del ;\n mutable bot : 'a del } ;;\n\n (* create empty deque *)\n let create () = { len = 0; top = Null; bot = Null } ;;\n\n let length q = q.len ;;\n\n (* add element x to deque q *)\n let add x q =\n if q.len = 0 then\n begin\n let e = El { l = Null; e = x; r = Null } in\n q.len <- 1 ;\n q.top <- e ;\n q.bot <- e\n end\n else\n begin\n let El b = q.bot in\n let e = El { l = q.bot; e = x; r = Null } in\n b.r <- e ;\n q.len <- q.len + 1 ;\n q.bot <- e\n end ;;\n\n (* drop bottom element of deque *)\n let drop q = match q.bot with\n Null -> ()\n | El { l=b; e=_; r=_} -> q.len <- q.len - 1 ;\n q.bot <- b ;;\n\n (* iterate over deque *)\n let iter f q = \n let rec aux = function\n Null -> ()\n | El { l=_; e=x; r=r } -> f x ; aux r\n in aux q.top ;;\nend ;;\n\nlet (n, m) = Scanf.sscanf (read_line ()) \"%d %d\" (fun a b -> a, b) in\nlet grid = Array.init n (fun _ -> read_line ()) in\nlet moves = Deque.create () in (* : (char * (int * int)) -- queue of (char,\n coord) pairs *)\n\n(* while v is not empty, choose an element of v and DFS to construct a tree of\n * connected components *)\nlet deltas = [(0, 1); (0, -1); (-1, 0); (1, 0)] in\nfor rx = 0 to n - 1 do\n for ry = 0 to m - 1 do\n let rec dfs ((x, y) as pos) =\n (* if we haven't seen this node, and it's valid *)\n try\n if grid.(x).[y] = '.' then\n begin\n grid.(x).[y] <- ' ' ;\n (* build a blue building here *)\n Deque.add ('B', pos) moves ;\n\n let r = List.filter (fun (dx, dy) -> dfs (x + dx, y + dy)) deltas in\n let c = List.length r in\n\n (* if this isn't the root, destroy and replace with red *)\n if pos <> (rx, ry) then\n if c = 0 then\n begin\n Deque.drop moves ;\n Deque.add ('R', pos) moves\n end\n else\n begin\n Deque.add ('D', pos) moves ;\n Deque.add ('R', pos) moves\n end ;\n true\n end\n else false\n with\n Invalid_argument _ -> false\n in\n ignore (dfs (rx, ry))\n done\ndone ;\n\nPrintf.printf \"%d\\n\" (Deque.length moves) ;\nDeque.iter (fun (c, (x, y)) ->\n Printf.printf \"%c %d %d\\n\" c (x + 1) (y + 1)) moves ;;\n"}], "negative_code": [{"source_code": "module Deque = struct\n type 'a der = { mutable l : 'a del; e : 'a; mutable r : 'a del }\n and 'a del = Null | El of 'a der ;;\n type 'a deq = { mutable len : int; mutable top : 'a del ;\n mutable bot : 'a del } ;;\n\n (* create empty deque *)\n let create () = { len = 0; top = Null; bot = Null } ;;\n\n let length q = q.len ;;\n\n (* add element x to deque q *)\n let add x q =\n if q.len = 0 then\n begin\n let e = El { l = Null; e = x; r = Null } in\n q.len <- 1 ;\n q.top <- e ;\n q.bot <- e\n end\n else\n begin\n let El b = q.bot in\n let e = El { l = q.bot; e = x; r = Null } in\n b.r <- e ;\n q.len <- q.len + 1 ;\n q.bot <- e\n end ;;\n\n (* drop bottom element of deque *)\n let drop q = match q.bot with\n Null -> ()\n | El { l=b; e=_; r=_} -> q.len <- q.len - 1 ;\n q.bot <- b ;;\n\n (* iterate over deque *)\n let iter f q = \n let rec aux = function\n Null -> ()\n | El { l=_; e=x; r=r } -> f x ; aux r\n in aux q.top ;;\nend ;;\n\nlet (n, m) = Scanf.sscanf (read_line ()) \"%d %d\" (fun a b -> a, b) in\nlet grid = Array.init n (fun _ -> read_line ()) in\nlet moves = Deque.create () in (* : (char * (int * int)) -- queue of (char,\n coord) pairs *)\n\n(* while v is not empty, choose an element of v and DFS to construct a tree of\n * connected components *)\nlet deltas = [(0, 1); (0, -1); (-1, 0); (1, 0)] in\nfor rx = 0 to n - 1 do\n for ry = 0 to m - 1 do\n let rec dfs ((x, y) as pos) =\n (* if we haven't seen this node, and it's valid *)\n try\n if grid.(x).[y] = '.' then\n begin\n grid.(x).[y] <- ' ' ;\n (* build a blue building here *)\n Deque.add ('B', pos) moves ;\n\n let r = List.filter (fun (dx, dy) -> dfs (x + dx, y + dy)) deltas in\n let c = List.length r in\n\n (* if this isn't the root, destroy and replace with red *)\n if pos <> (rx, ry) then\n if c = 0 then\n begin\n Deque.drop moves ;\n Deque.add ('R', pos) moves\n end\n else\n begin\n Deque.add ('D', pos) moves ;\n Deque.add ('R', pos) moves\n end ;\n true\n end\n else false\n with\n Invalid_argument _ -> false\n in\n ignore (dfs (rx, ry))\n done\ndone ;\n\nPrintf.printf \"%d\\n\" (Deque.length moves) ;\nDeque.iter (fun (c, (x, y)) ->\n Printf.printf \"%c %d %d\\n\" c x y) moves ;;\n"}], "src_uid": "9b9f6d95aecc1b6c95e5d9acca4f5453"} {"nl": {"description": "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 \u2014 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$$$).", "input_spec": "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$$$) \u2014 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$$$.", "output_spec": "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.", "sample_inputs": ["3 6 5 4", "40 40 40 60", "201 101 101 200"], "sample_outputs": ["2 1 3", "20 20 20", "1 100 100"], "notes": null}, "positive_code": [{"source_code": "let main () =\n let gr () = Scanf.scanf \" %d\" (fun i -> i) in \n let gs () = Scanf.scanf \" %s\" (fun i -> i) in \n \n let print_ans x y z s = \n Printf.printf \"%d %d %d\\n\" (s - x) (s - y) (s - z)\n in\n let p = gr () in\n let r = gr() in\n let s = gr() in\n let t = gr() in\n if p+r+s == 2 * t then print_ans p r s t\n else if p + r + t == 2 * s then print_ans p r t s\n else if p + s + t == 2 * r then print_ans p s t r\n else print_ans r s t p\n\nlet _ = main();;\n"}, {"source_code": "let scan_int () =\n Scanf.scanf \" %d\" (fun x -> x)\n;;\n\nlet f () = \n let b = Array.init 4 (fun x -> scan_int ()) in\n Array.sort compare b;\n b\n;;\n\nlet _ =\n let arr = f () in\n Printf.printf \"%d %d %d\\n\" (arr.(3) - arr.(0)) (arr.(3) - arr.(1)) (arr.(3) - arr.(2))\n;;\n"}], "negative_code": [], "src_uid": "cda949a8fb1f158f3c06109a2d33f084"} {"nl": {"description": "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\u00b7h 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\u2009<\u2009j), then the inequation mi\u2009\u2264\u2009mj should be fulfilled.Since there are n lemmings and only k ledges (k\u2009\u2264\u2009n), 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.", "input_spec": "The first line contains space-separated integers n, k and h (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009h\u2009\u2264\u2009104) \u2014 the total number of lemmings, the number of ledges and the distance between adjacent ledges. The second line contains n space-separated integers m1,\u2009m2,\u2009...,\u2009mn (1\u2009\u2264\u2009mi\u2009\u2264\u2009109), where mi is the weight of i-th lemming. The third line contains n space-separated integers v1,\u2009v2,\u2009...,\u2009vn (1\u2009\u2264\u2009vi\u2009\u2264\u2009109), where vi is the speed of i-th lemming.", "output_spec": "Print k different numbers from 1 to n \u2014 the numbers of the lemmings who go to ledges at heights h,\u20092h,\u2009...,\u2009kh, correspondingly, if the jump is organized in an optimal way. If there are multiple ways to select the lemmings, pick any of them.", "sample_inputs": ["5 3 2\n1 2 3 2 1\n1 2 1 2 10", "5 3 10\n3 4 3 2 1\n5 4 3 2 1"], "sample_outputs": ["5 2 4", "4 3 1"], "notes": "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. "}, "positive_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let k = getnum () in\n let h = getnum () in\n let m = Array.make n 0 in\n let v = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = getnum () in\n\tm.(i) <- k\n done;\n for i = 0 to n - 1 do\n let k = getnum () in\n\tv.(i) <- k\n done;\n in\n let a = Array.init n (fun i -> (m.(i), v.(i), i)) in\n let () = Array.sort compare a in\n let res = Array.make (k + 1) 0 in\n let solve t =\n let j = ref 0 in\n try\n\tfor i = 1 to k do\n\t while !j < n && (let (_, v, _) = a.(!j) in\n\t\t\t t *. float_of_int v <= float_of_int i) do\n\t incr j\n\t done;\n\t if !j < n then (\n\t let (_, _, ii) = a.(!j) in\n\t res.(i) <- ii + 1;\n\t incr j;\n\t ) else raise Not_found\n\tdone;\n\ttrue\n with\n\t| Not_found ->\n\t false\n in\n let l = ref 0.0 in\n let r = ref (float_of_int (k + 1)) in\n let eps = float_of_int k *. 10e-16 in\n for i = 1 to 64 do\n let m = (!l +. !r) /. 2.0 in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n ignore (solve !r);\n (*Printf.printf \"asd %f\\n\" !r;*)\n for i = 1 to k do\n Printf.printf \"%d \" res.(i);\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let k = getnum () in\n let h = getnum () in\n let m = Array.make n 0 in\n let v = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = getnum () in\n\tm.(i) <- k\n done;\n for i = 0 to n - 1 do\n let k = getnum () in\n\tv.(i) <- k\n done;\n in\n let a = Array.init n (fun i -> (m.(i), v.(i), i)) in\n let () = Array.sort compare a in\n let res = Array.make (k + 1) 0 in\n let solve t =\n let j = ref 0 in\n try\n\tfor i = 1 to k do\n\t while !j < n && (let (_, v, _) = a.(!j) in\n\t\t\t t *. float_of_int v <= float_of_int i) do\n\t incr j\n\t done;\n\t if !j < n then (\n\t let (_, _, ii) = a.(!j) in\n\t res.(i) <- ii + 1;\n\t incr j;\n\t ) else raise Not_found\n\tdone;\n\ttrue\n with\n\t| Not_found ->\n\t false\n in\n let l = ref 0.0 in\n let r = ref (float_of_int (k + 1)) in\n let eps = 10e-14 in\n while !r -. !l > eps do\n let m = (!l +. !r) /. 2.0 in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n ignore (solve !r);\n (*Printf.printf \"asd %f\\n\" !r;*)\n for i = 1 to k do\n Printf.printf \"%d \" res.(i);\n done;\n Printf.printf \"\\n\"\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let k = getnum () in\n let h = getnum () in\n let m = Array.make n 0 in\n let v = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = getnum () in\n\tm.(i) <- k\n done;\n for i = 0 to n - 1 do\n let k = getnum () in\n\tv.(i) <- k\n done;\n in\n let a = Array.init n (fun i -> (m.(i), v.(i), i)) in\n let () = Array.sort compare a in\n let res = Array.make (k + 1) 0 in\n let solve t =\n let j = ref 0 in\n try\n\tfor i = 1 to k do\n\t while !j < n && (let (_, v, _) = a.(!j) in\n\t\t\t t *. float_of_int v <= float_of_int i) do\n\t incr j\n\t done;\n\t if !j < n then (\n\t let (_, _, ii) = a.(!j) in\n\t res.(i) <- ii + 1;\n\t incr j;\n\t ) else raise Not_found\n\tdone;\n\ttrue\n with\n\t| Not_found ->\n\t false\n in\n let l = ref 0.0 in\n let r = ref (float_of_int (k + 1)) in\n let eps = 10e-15 in\n while !r -. !l > eps do\n let m = (!l +. !r) /. 2.0 in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n ignore (solve !r);\n (*Printf.printf \"asd %f\\n\" !r;*)\n for i = 1 to k do\n Printf.printf \"%d \" res.(i);\n done;\n Printf.printf \"\\n\"\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let k = getnum () in\n let h = getnum () in\n let m = Array.make n 0 in\n let v = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = getnum () in\n\tm.(i) <- k\n done;\n for i = 0 to n - 1 do\n let k = getnum () in\n\tv.(i) <- k\n done;\n in\n let a = Array.init n (fun i -> (m.(i), v.(i), i)) in\n let () = Array.sort compare a in\n let res = Array.make (k + 1) 0 in\n let solve t =\n let j = ref 0 in\n try\n\tfor i = 1 to k do\n\t while !j < n && (let (_, v, _) = a.(!j) in\n\t\t\t t *. float_of_int v <= float_of_int i) do\n\t incr j\n\t done;\n\t if !j < n then (\n\t let (_, _, ii) = a.(!j) in\n\t res.(i) <- ii + 1;\n\t incr j;\n\t ) else raise Not_found\n\tdone;\n\ttrue\n with\n\t| Not_found ->\n\t false\n in\n let l = ref 0.0 in\n let r = ref (float_of_int (k + 1)) in\n let eps = 10e-10 in\n while !r -. !l > eps do\n let m = (!l +. !r) /. 2.0 in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n ignore (solve !r);\n (*Printf.printf \"asd %f\\n\" !r;*)\n for i = 1 to k do\n Printf.printf \"%d \" res.(i);\n done;\n Printf.printf \"\\n\"\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let k = getnum () in\n let h = getnum () in\n let m = Array.make n 0 in\n let v = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = getnum () in\n\tm.(i) <- k\n done;\n for i = 0 to n - 1 do\n let k = getnum () in\n\tv.(i) <- k\n done;\n in\n let a = Array.init n (fun i -> (m.(i), v.(i), i)) in\n let () = Array.sort compare a in\n let res = Array.make (k + 1) 0 in\n let solve t =\n let j = ref 0 in\n try\n\tfor i = 1 to k do\n\t while !j < n && (let (_, v, _) = a.(!j) in\n\t\t\t t *. float_of_int v <= float_of_int i) do\n\t incr j\n\t done;\n\t if !j < n then (\n\t let (_, _, ii) = a.(!j) in\n\t res.(i) <- ii + 1;\n\t incr j;\n\t ) else raise Not_found\n\tdone;\n\ttrue\n with\n\t| Not_found ->\n\t false\n in\n let l = ref 0.0 in\n let r = ref (float_of_int (k + 1)) in\n let eps = float_of_int k *. 10e-16 in\n while !r -. !l > eps do\n let m = (!l +. !r) /. 2.0 in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n ignore (solve !r);\n (*Printf.printf \"asd %f\\n\" !r;*)\n for i = 1 to k do\n Printf.printf \"%d \" res.(i);\n done;\n Printf.printf \"\\n\"\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let k = getnum () in\n let h = getnum () in\n let m = Array.make n 0 in\n let v = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = getnum () in\n\tm.(i) <- k\n done;\n for i = 0 to n - 1 do\n let k = getnum () in\n\tv.(i) <- k\n done;\n in\n let a = Array.init n (fun i -> (m.(i), v.(i), i)) in\n let () = Array.sort compare a in\n let res = Array.make (k + 1) 0 in\n let solve t =\n let j = ref 0 in\n try\n\tfor i = 1 to k do\n\t while !j < n && (let (_, v, _) = a.(!j) in\n\t\t\t t *. float_of_int v <= float_of_int i) do\n\t incr j\n\t done;\n\t if !j < n then (\n\t let (_, _, ii) = a.(!j) in\n\t res.(i) <- ii + 1;\n\t incr j;\n\t ) else raise Not_found\n\tdone;\n\ttrue\n with\n\t| Not_found ->\n\t false\n in\n let l = ref 0.0 in\n let r = ref (float_of_int (k + 1)) in\n let eps = float_of_int k *. 10e-9 in\n while !r -. !l > eps do\n let m = (!l +. !r) /. 2.0 in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n ignore (solve !r);\n (*Printf.printf \"asd %f\\n\" !r;*)\n for i = 1 to k do\n Printf.printf \"%d \" res.(i);\n done;\n Printf.printf \"\\n\"\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let k = getnum () in\n let h = getnum () in\n let m = Array.make n 0 in\n let v = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = getnum () in\n\tm.(i) <- k\n done;\n for i = 0 to n - 1 do\n let k = getnum () in\n\tv.(i) <- k\n done;\n in\n let a = Array.init n (fun i -> (m.(i), v.(i), i)) in\n let () = Array.sort compare a in\n let res = Array.make (k + 1) 0 in\n let solve t =\n let j = ref 0 in\n try\n\tfor i = 1 to k do\n\t while !j < n && (let (_, v, _) = a.(!j) in\n\t\t\t t *. float_of_int v <= float_of_int i) do\n\t incr j\n\t done;\n\t if !j < n then (\n\t let (_, _, ii) = a.(!j) in\n\t res.(i) <- ii + 1;\n\t incr j;\n\t ) else raise Not_found\n\tdone;\n\ttrue\n with\n\t| Not_found ->\n\t false\n in\n let l = ref 0.0 in\n let r = ref (float_of_int (k + 1)) in\n let eps = float_of_int k *. 10e-7 in\n while !r -. !l > eps do\n let m = (!l +. !r) /. 2.0 in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n ignore (solve !r);\n (*Printf.printf \"asd %f\\n\" !r;*)\n for i = 1 to k do\n Printf.printf \"%d \" res.(i);\n done;\n Printf.printf \"\\n\"\n"}], "src_uid": "6861128fcd83c752b0ea0286869901c2"} {"nl": {"description": "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\u2009<\u2009n\u2009-\u20091), you can reach the tiles number i\u2009+\u20091 or the tile number i\u2009+\u20092 from it (if you stand on the tile number n\u2009-\u20091, 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\u2009+\u20091 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.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 the boulevard's length in tiles. The second line contains n space-separated integers ai \u2014 the number of days after which the i-th tile gets destroyed (1\u2009\u2264\u2009ai\u2009\u2264\u2009103). ", "output_spec": "Print a single number \u2014 the sought number of days.", "sample_inputs": ["4\n10 3 5 10", "5\n10 2 8 3 5"], "sample_outputs": ["5", "5"], "notes": "NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1\u2009\u2192\u20093\u2009\u2192\u20094. 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\u2009\u2192\u20093\u2009\u2192\u20095 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted."}, "positive_code": [{"source_code": "let ni () = Scanf.scanf \" %d\" (fun x -> x) in\nlet n = ni () in\nlet a = Array.init n (fun _ -> ni ()) in\nlet ans = ref (min a.(0) a.(n - 1)) in\nfor i = 2 to n - 1 do\n ans := min !ans (max a.(i - 1) a.(i))\ndone;\nprint_int !ans;;\n"}], "negative_code": [], "src_uid": "d526af933b5afe9abfdf9815e9664144"} {"nl": {"description": "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\u2009\u2264\u2009i\u2009\u2264\u2009n) 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\u2009\u2264\u2009j\u2009\u2264\u2009m) day, he will read the book that is numbered with integer bj (1\u2009\u2264\u2009bj\u2009\u2264\u2009n). 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?", "input_spec": "The first line contains two space-separated integers n (2\u2009\u2264\u2009n\u2009\u2264\u2009500) and m (1\u2009\u2264\u2009m\u2009\u2264\u20091000) \u2014 the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1,\u2009w2,\u2009...,\u2009wn (1\u2009\u2264\u2009wi\u2009\u2264\u2009100) \u2014 the weight of each book. The third line contains m space separated integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bj\u2009\u2264\u2009n) \u2014 the order of books that he would read. Note that he can read the same book more than once.", "output_spec": "Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.", "sample_inputs": ["3 5\n1 2 3\n1 3 2 3 1"], "sample_outputs": ["12"], "notes": "NoteHere's a picture depicting the example. Each vertical column presents the stacked books. "}, "positive_code": [{"source_code": "type 'a el = {\n v : 'a;\n mutable next : 'a el option;\n mutable prev : 'a el option;\n}\n\nlet () = Scanf.scanf \"%d %d\\n\" (fun n m ->\n (* book weights *)\n let w = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n (* reading order *)\n let b = Array.init m (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x - 1)) in\n (* seen array *)\n let seen = Array.make n false in\n (* head of pile *)\n let p = { v = b.(0); next = None; prev = None } in\n let hd = ref p in\n (* tail of pile *)\n let tl = ref p in\n seen.(b.(0)) <- true;\n\n let add i =\n let el = { v = i; next = None; prev = Some !tl } in\n !tl.next <- Some el;\n tl := el\n in\n\n (* construct the pile *)\n Array.iter (fun b ->\n if not seen.(b) then begin\n add b;\n seen.(b) <- true\n end\n ) b;\n let c = Array.fold_left (fun acc b ->\n let rec part a h =\n if h.v = b then (a, h)\n else match h.next with\n | None -> failwith \"No more list!\"\n | Some n -> part (a + w.(h.v)) n\n in\n let (cost, h) = part 0 !hd in\n let () = match h.prev with\n | None -> () (* already at head *)\n | Some p -> begin\n p.next <- h.next;\n\n let () = match h.next with\n | None -> ()\n | Some n -> n.prev <- Some p\n in\n h.next <- Some !hd;\n h.prev <- None;\n !hd.prev <- Some h;\n hd := h\n end\n in\n acc + cost\n ) 0 b in\n Printf.printf \"%d\\n\" c\n)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let n = read_int () in\n let m = read_int () in\n \n let w = Array.init n (fun _ -> read_int()) in\n let b = Array.init m (fun _ -> read_int() - 1) in\n\n let indices = Array.make n 0 in\n let locator = Array.make n 0 in\n \n let h = Hashtbl.create 10 in\n\n let place = ref 0 in\n\n for j=0 to m-1 do\n if not (Hashtbl.mem h b.(j)) then (\n Hashtbl.replace h b.(j) true;\n indices.(!place) <- b.(j);\n locator.(b.(j)) <- !place;\n place := !place + 1;\n )\n done;\n\n (* some books may never be read and thus not be in this data structure.\n I don't think this matters. They'll never be accessed below. *)\n\n\n let swap j =\n let (a,b) = (indices.(j), indices.(j+1)) in\n locator.(a) <- locator.(a) + 1;\n locator.(b) <- locator.(b) - 1;\n indices.(j) <- b;\n indices.(j+1) <- a;\n in\n\n let read_book k =\n let i = locator.(k) in\n let weight = ref 0 in\n for j=i-1 downto 0 do\n (* swap the books at positions j+1 and j *)\n weight := !weight + w.(indices.(j));\n swap j;\n done;\n !weight\n in\n\n let answer = sum 0 (m-1) (fun j -> read_book b.(j)) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "a18edcadb31f76e69968b0a3e1cb7e3e"} {"nl": {"description": "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.", "input_spec": "The first line contains single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of groups. The second line contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20092), where ai is the number of people in group i.", "output_spec": "Print the maximum number of teams of three people the coach can form.", "sample_inputs": ["4\n1 1 2 1", "2\n2 2", "7\n2 2 2 1 1 1 1", "3\n1 1 1"], "sample_outputs": ["1", "0", "3", "1"], "notes": "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). "}, "positive_code": [{"source_code": "\n\nlet input () =\n let l = ref []\n in let getNumber () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\n in let n = getNumber ()\n in begin\n for i = 0 to n - 1 do\n l := (getNumber ()) :: !l\n done;\n !l\n end;;\n\nlet divideList l =\n let l = List.sort compare l\n in let l1 = List.filter (fun x -> x = 1) l\n in let l2 = List.filter (fun x -> x = 2) l\n in (l1, l2)\n\nlet rec firstStep a l1 l2 =\n match l1, l2 with\n | x1 :: t1, x2 :: t2 -> firstStep (a + 1) t1 t2\n | _ -> (a, l1)\n\nlet rec secondStep a = function\n | x :: y :: z :: t -> secondStep (a + 1) t\n | _ -> a\n\nlet teams (l1, l2) =\n let n, newL1 = firstStep 0 l1 l2\n in secondStep n newL1\n\nlet altMethod l =\n let rec int a1 a2 = function\n | 1 :: t -> int (a1 + 1) a2 t\n | 2 :: t -> int a1 (a2 + 1) t\n | _ -> (a1, a2)\n in let n1, n2 = int 0 0 l\n in if n1 > n2 then\n n2 + (n1 - n2) / 3\n else\n n1\n\nlet main () =\n let l = input ()\n in let n = altMethod l\n in Printf.printf \"%d\" n\n;;\n\nmain ();;\n"}, {"source_code": "\n\nlet input () =\n let l = ref []\n in let getNumber () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\n in let n = getNumber ()\n in begin\n for i = 0 to n - 1 do\n l := (getNumber ()) :: !l\n done;\n !l\n end;;\n\nlet divideList l =\n let l = List.sort compare l\n in let l1 = List.filter (fun x -> x = 1) l\n in let l2 = List.filter (fun x -> x = 2) l\n in (l1, l2)\n\nlet rec firstStep a l1 l2 =\n match l1, l2 with\n | x1 :: t1, x2 :: t2 -> firstStep (a + 1) t1 t2\n | _ -> (a, l1)\n\nlet rec secondStep a = function\n | x :: y :: z :: t -> secondStep (a + 1) t\n | _ -> a\n\nlet teams (l1, l2) =\n let n, newL1 = firstStep 0 l1 l2\n in secondStep n newL1\n\nlet main () =\n let l = input ()\n in let n = teams (divideList l)\n in Printf.printf \"%d\" n\n;;\n\nmain ();;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n\n let rec loop n1 n2 i = if i=n then (n1,n2) else\n if read_int() = 1 then loop (n1+1) n2 (i+1)\n else loop n1 (n2+1) (i+1)\n in\n\n let (n1, n2) = loop 0 0 0 in\n\n if n2 >= n1 then printf \"%d\\n\" n1\n else printf \"%d\\n\" (n2 + (n1-n2)/3)\n"}], "negative_code": [], "src_uid": "6c9cbe714f8f594654ebc59b6059b30a"} {"nl": {"description": "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,\u2009yi).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\u2009-\u2009xj|\u2009+\u2009|yi\u2009-\u2009yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i,\u2009j) (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n), 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.", "input_spec": "The first line of the input contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|,\u2009|yi|\u2009\u2264\u2009109). Some positions may coincide.", "output_spec": "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.", "sample_inputs": ["3\n1 1\n7 5\n1 5", "6\n0 0\n0 1\n0 2\n-1 1\n0 1\n1 1"], "sample_outputs": ["2", "11"], "notes": "NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1\u2009-\u20097|\u2009+\u2009|1\u2009-\u20095|\u2009=\u200910 for Doctor Manhattan and for Daniel. For pairs (1,\u20091), (1,\u20095) and (7,\u20095), (1,\u20095) Doctor Manhattan and Daniel will calculate the same distances."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet () =\n let n = read_int() in\n\n let increment h t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n let xtable = Hashtbl.create 10 in\n let ytable = Hashtbl.create 10 in \n let pairtable = Hashtbl.create 10 in\n \n for i=1 to n do\n let (x,y) = read_pair() in\n increment xtable x;\n increment ytable y;\n increment pairtable (x,y)\n done;\n\n let eval_table h =\n Hashtbl.fold (fun _ v ac ->\n let v = long v in\n ac ++ ((v ** (v -- 1L))//2L)\n ) h 0L\n in\n\n let eval_pairtable h =\n Hashtbl.fold (fun _ v ac ->\n let v = long v in\n ac ++ ((v ** (v -- 1L))//2L)\n ) h 0L\n in\n \n let answer =\n (eval_table xtable)\n ++ (eval_table ytable)\n -- (eval_pairtable pairtable)\n in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "bd7b85c0204f6b36dc07f8a96fc36161"} {"nl": {"description": "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$$$?", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$) \u2014 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. ", "output_spec": "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).", "sample_inputs": ["5\n\nabcde\n\nc\n\nabcde\n\nb\n\nx\n\ny\n\naaaaaaaaaaaaaaa\n\na\n\ncontest\n\nt"], "sample_outputs": ["YES\nNO\nNO\nYES\nYES"], "notes": "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."}, "positive_code": [{"source_code": "let n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let line = input_line stdin in\r\n let chara = input_line stdin in\r\n let toto = ref false in\r\n if String.length line mod 2 = 1 then (\r\n for j = 0 to String.length line -1 do\r\n if chara = (String.make 1 line.[j]) && j mod 2 = 0 then (toto:=true)\r\n done ; if !toto then print_endline \"YES\" else print_endline \"NO\")\r\n else (print_endline \"NO\")\r\ndone ;;"}], "negative_code": [], "src_uid": "c569b47cf80dfa98a7105e246c3c1e01"} {"nl": {"description": "A new cottage village called \u00abFlatville\u00bb is being built in Flatland. By now they have already built in \u00abFlatville\u00bb n square houses with the centres on the \u041ex-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 \u00abFlatville\u00bb. The customer wants his future house to be on the \u041ex-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 \u00abFlatville\u00bb. Would you help him find the amount of possible positions of the new house?", "input_spec": "The first line of the input data contains numbers n and t (1\u2009\u2264\u2009n,\u2009t\u2009\u2264\u20091000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi \u2014 x-coordinate of the centre of the i-th house, and ai \u2014 length of its side (\u2009-\u20091000\u2009\u2264\u2009xi\u2009\u2264\u20091000, 1\u2009\u2264\u2009ai\u2009\u2264\u20091000).", "output_spec": "Output the amount of possible positions of the new house.", "sample_inputs": ["2 2\n0 4\n6 2", "2 2\n0 4\n5 2", "2 3\n0 4\n5 2"], "sample_outputs": ["4", "3", "2"], "notes": "NoteIt is possible for the x-coordinate of the new house to have non-integer value."}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let t = read_int 0 in\n let rec go acc i =\n if i >= n then\n acc\n else\n let x = read_int 0 in\n let y = read_int 0 in\n go ((x*2-y)::(x*2+y)::acc) (i+1)\n in\n let rec f s = function\n | [] | [_] -> s\n | x::y::xs ->\n f (s + compare (y-x) (2*t) + 1) xs\n in\n let tt = go [] 0 |> List.sort compare |> List.tl in\n tt |> f 2 |> Printf.printf \"%d\\n\"\n"}], "negative_code": [], "src_uid": "c31fed523230af1f904218b2fe0d663d"} {"nl": {"description": "A new entertainment has appeared in Buryatia \u2014 a mathematical circus! The magician shows two numbers to the audience \u2014 $$$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.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 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) \u2014 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$$$.", "output_spec": "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 \u2014 first the integer $$$a$$$, then the integer $$$b$$$.", "sample_inputs": ["4\n\n4 1\n\n2 0\n\n12 10\n\n14 11"], "sample_outputs": ["YES\n1 2\n3 4\nNO\nYES\n3 4\n7 8\n11 12\n2 1\n6 5\n10 9\nYES\n1 2\n3 4\n5 6\n7 8\n9 10\n11 12\n13 14"], "notes": "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."}, "positive_code": [{"source_code": "(*\r\nConsider the following:\r\n\r\ni) kmod4=0:\r\n means bmod4=0\r\nor anod4=0\r\nor amod4=bmod4=2\r\n-> (4,),(8,),...\r\n-> (,4),(,8),...\r\n-> (2,6),(10,14),...\r\n-> (1,4),(3,8),(5,12),...\r\n-> not possible\r\n\r\nii) kmod4=1\r\namod4=3 or bmod4=0 \r\nor (amod4=1 and bmod4=2)\r\n->(1,2),(5,6),...\r\n->(3,),(7,),...\r\n->(,4),(8,),...\r\n->(1,2),(3,4),(5,6),...\r\n-> possible when n is even\r\n\r\niii) kmod4=2\r\namod4=2 or bmod4=0\r\nor (amod4=0 and bmod4=2)\r\n->(4,2),(8,6),(12,10),...\r\n->(2,1),(6,5),(10,9)...\r\n->(3,4),(7,8),(11,12),...\r\n->(2,1),(3,4),(6,5),...\r\n-> possible when n is even\r\n\r\niv) kmod4=3\r\namod4=1 or bmod4=0\r\nor (amod4=3 and bmod4=2)\r\n->(1,),(5,),(9,)...\r\n->(,4),(,8),...\r\n->(3,2),(7,6),...\r\n->(1,2),(5,6),...\r\n->(3,4),(7,8)...\r\n->(1,2),(3,4),(5,6),....\r\n-> possible when n is even\r\n*)\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x->x);;\r\nlet read_long () = Scanf.scanf \" %Ld\" (fun l->l);;\r\nlet run_case = function\r\n| () ->\r\n let n = read_long () in\r\n let k = read_long () in\r\n let remk = Int64.sub k (Int64.mul 4L (Int64.div k 4L)) in\r\n if (remk=0L) then Printf.printf \"NO\\n\"\r\n else if (remk=2L) then begin\r\n Printf.printf \"YES\\n\";\r\n let rec pairPrint = function\r\n | x, r ->\r\n if (x>n) then ()\r\n else if (r=false) then begin\r\n Printf.printf \"%Ld %Ld\\n\" x (Int64.succ x);\r\n pairPrint ((Int64.add x 2L), true)\r\n end\r\n else begin\r\n Printf.printf \"%Ld %Ld\\n\" (Int64.succ x) x;\r\n pairPrint ((Int64.add x 2L), false)\r\n end\r\n in pairPrint (1L,true)\r\n end\r\n else begin\r\n Printf.printf \"YES\\n\";\r\n let rec pairPrint =function\r\n | x ->\r\n if (x>n) then ()\r\n else begin\r\n Printf.printf \"%Ld %Ld\\n\" x (Int64.succ x);\r\n pairPrint (Int64.add x 2L)\r\n end\r\n in pairPrint 1L\r\n end\r\n;;\r\n\r\n\r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| t -> run_case (); iter_cases (t-1)\r\n;;\r\n\r\nlet t = read_int () in iter_cases t;;"}, {"source_code": "\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let k' = read_int () in\n if (k' mod 4 = 0) then print_endline \"NO\"\n else begin\n print_endline \"YES\";\n let k = k' mod 4 in\n for i = 0 to n / 2 - 1 do\n let x = 2 * i + 1 in\n let y = 2 * i + 2 in\n if ((x + k) * y mod 4 = 0) then\n pf \"%d %d\\n\" x y\n else\n pf \"%d %d\\n\" y x\n done;\n end;\n done;"}], "negative_code": [], "src_uid": "d4fc7e683f389e0c7bbee8e115cef459"} {"nl": {"description": "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.", "input_spec": "The first line of the input contains two integer numbers m (1\u2009\u2264\u2009m\u2009\u2264\u200950) and n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7107). 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_spec": "Output the color of the block which will be current after n steps of program interpretation.", "sample_inputs": ["2 10\n12\n43", "3 12\n1423\n6624\n6625", "5 9\n10345\n23456\n34567\n45678\n56789"], "sample_outputs": ["1", "6", "5"], "notes": "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 \u2014 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 \u2014 the direction of CP."}, "positive_code": [{"source_code": "let read_int () = \n Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = \n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet di = [|0; -1; 0; 1|]\nlet dj = [|1; 0; -1; 0|]\n\nlet m = read_int()\nlet n = read_int()\nlet matrix = Array.make m \"\"\nlet _ = \n for i=0 to m-1 do\n matrix.(i) <- read_string()\n done\n\nlet c = String.length matrix.(0)\n\nlet advance_ptr (i,j,dp,cp) = \n match cp with \n | 1 -> (i,j,dp,0)\n | 0 -> (i,j,(4+dp-1) mod 4,1)\n | _ -> failwith \"bad cp\"\n\nlet advance (i,j,dp,cp) = \n let rec move (di,dj) (i,j) =\n let (ii,jj) = (i+di, j+dj) in\n if ii>=0 && ii=0 && jj=0 && ii=0 && jj '0' \n then (ii,jj,dp,cp) else advance_ptr (i,j,dp,cp)\n\nlet table = Hashtbl.create 10\nlet get s = try Hashtbl.find table s with Not_found -> 0\nlet inc s = Hashtbl.replace table s ((get s)+1)\n\nlet rec loop s v c = \n if get s = v then (\n inc s;\n loop (advance s) v (c+1)\n ) else (s,c)\n\nlet (s,c1) = loop (0,0,0,1) 0 0\nlet (s,c2) = loop s 1 0\n\nlet rec iterate s c = \n if c=0 then s else iterate (advance s) (c-1)\n\nlet adv = if n x)\n\nlet () = \n let h = read_int () in\n let a = Array.init (h+1) read_int in\n\n if a.(0) <> 1 then failwith \"bad tree\";\n\n let rec is_unique i = if i=h then true else\n if a.(i) <> 1 && a.(i+1) <> 1 then false\n else is_unique (i+1)\n in\n\n if is_unique 0 then printf \"perfect\\n\" else (\n printf \"ambiguous\\n\";\n\n let rec printtree version nn i = if i<=h then (\n (* i is the level we're about to print. nn is the node number whose\n\t parent we are about to print. The previous row ended in nn-1 *)\n(* printf \"(printing row %d): \" i; *)\n if a.(i-1) = 1 then (\n\tfor k=1 to a.(i) do printf \"%d \" (nn-1) done;\n ) else (\n\tif version = 0 then (\n\t for k=1 to a.(i) do printf \"%d \" (nn-1) done;\n\t) else (\n\t printf \"%d \" (nn-1);\n\t for k=2 to a.(i) do printf \"%d \" (nn-2) done;\t \n\t)\n );\n printtree version (nn+a.(i)) (i+1)\n )\n in\n\n printf \"0 \";\n printtree 0 2 1;\n print_newline();\n printf \"0 \";\n printtree 1 2 1;\n print_newline();\n )\n"}], "negative_code": [], "src_uid": "a186acbdc88a7ed131a7e5f999877fd6"} {"nl": {"description": "$$$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.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 500$$$) \u2014 the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 100$$$) \u2014 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.", "output_spec": "For each test case, print one integer \u2014 the number of possible winners among the given $$$n$$$ heroes.", "sample_inputs": ["3\n3\n3 2 2\n2\n5 5\n4\n1 3 3 7"], "sample_outputs": ["1\n0\n3"], "notes": "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."}, "positive_code": [{"source_code": "module Stdlib = Pervasives\r\n\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n\r\nlet identity x = x;;\r\n\r\nlet space_regexp = Str.regexp \" \";;\r\n\r\nlet rec repeat f inp outp n =\r\n if n <= 0 then ()\r\n else\r\n let () = f inp outp in\r\n repeat f inp outp (n - 1);;\r\n\r\nlet max a b = if a > b then a else b;;\r\n\r\nlet rec solve items acc =\r\n match items, acc with\r\n | [], acc -> acc\r\n | head::tail, None -> solve tail (Some (head, 1))\r\n | head::tail, (Some (value, count) as tmp) ->\r\n if head < value then solve tail (Some (head, 1))\r\n else if head = value then solve tail (Some (value, count + 1))\r\n else solve tail tmp;;\r\n\r\nlet solution inp outp =\r\n let n = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let items = input_line inp |> Str.split space_regexp |> List.map int_of_string in\r\n let result = solve items None in\r\n let () =\r\n match result with\r\n | None -> Printf.fprintf outp \"invariant: takogo ne bivaet\"\r\n | Some (_, count) -> Printf.fprintf outp \"%d\\n\" (n - count)\r\n in\r\n ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let () = repeat solution inp outp tests_count in\r\n ();;\r\n"}], "negative_code": [], "src_uid": "99e5c907b623c310d6f1599f485ca21d"} {"nl": {"description": "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?", "input_spec": "The first line of the input contains two integers n and h (1\u2009\u2264\u2009n\u2009\u2264\u20091000, 1\u2009\u2264\u2009h\u2009\u2264\u20091000)\u00a0\u2014 the number of friends and the height of the fence, respectively. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u20092h), the i-th of them is equal to the height of the i-th person.", "output_spec": "Print a single integer\u00a0\u2014 the minimum possible valid width of the road.", "sample_inputs": ["3 7\n4 5 14", "6 1\n1 1 1 1 1 1", "6 5\n7 6 8 9 10 5"], "sample_outputs": ["4", "6", "11"], "notes": "NoteIn the first sample, only person number 3 must bend down, so the required width is equal to 1\u2009+\u20091\u2009+\u20092\u2009=\u20094.In the second sample, all friends are short enough and no one has to bend, so the width 1\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009=\u20096 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\u2009+\u20092\u2009+\u20092\u2009+\u20092\u2009+\u20092\u2009+\u20091\u2009=\u200911."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let total = read () in\n let limit = read () in\n let rec loop heights i =\n if i < total\n then\n let height = Scanf.scanf \"%d \" (fun h -> h) in\n loop (height :: heights) (i + 1)\n else\n (total, limit, heights) \n in loop [] 0\n\nlet solve (total, limit, heights) = \n let double_width = List.length (List.filter (fun n -> n > limit) heights) in\n let single_width = total - double_width in\n let total_width = single_width + 2 * double_width in\n Printf.printf \"%d\\n\" total_width\n\nlet () = solve (input ())"}, {"source_code": "open !Scanf \nopen !Printf\n\nlet read_int () = bscanf Scanning.stdin \"%d \" (fun x -> x) \n\nlet () = \n let n = read_int () in \n let h = read_int () in \n\n let rec solve n h = \n match n with \n | 0 -> 0\n | _ -> (if read_int () <= h then 1 else 2) + solve (n-1) h\n \n in printf \"%d\" (solve n h)"}, {"source_code": "(* Codeforces 677 A VaniaFence *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet rec widlist li zh = match li with\n| [] -> 0\n| h :: t -> (if (h > zh) then 2 else 1) +\n\t(widlist t zh);;\n\nlet main() =\n\tlet n = gr() in\n\tlet h = gr() in\n\tlet a = readlist (n) [] in\n\tlet wid = widlist a h in\n\tbegin\n\t\tprint_int wid;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let h = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let res = ref 0 in\n for i = 1 to n do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tif x > h\n\tthen res := !res + 2\n\telse res := !res + 1;\n done;\n Printf.printf \"%d\\n\" !res\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) in\nlet n = scan_int () in\nlet h = scan_int () in\n\nlet rec read_n_ints n =\n if n = 0 then []\n else (scan_int ()) :: (read_n_ints (n-1)) in\n\nlet l = read_n_ints n in\n\nPrintf.printf \"%d\\n\" (n + (List.length (List.filter (fun hh -> hh > h) l)))"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let h = read_int () in\n \n let answer = sum 1 n (\n fun _ -> let y = read_int() in\n\t if y > h then 2 else 1\n ) 0 in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "e7ed5a733e51b6d5069769c3b1d8d22f"} {"nl": {"description": "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?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 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$$$)\u00a0\u2014 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$$$)\u00a0\u2014 the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$b$$$.", "output_spec": "For each test case, print the maximum possible sum of the sequence $$$c$$$.", "sample_inputs": ["3\n2 3 2\n3 3 1\n4 0 1\n2 3 0\n0 0 1\n0 0 1"], "sample_outputs": ["4\n2\n0"], "notes": "NoteIn the first sample, one of the optimal solutions is:$$$a = \\{2, 0, 1, 1, 0, 2, 1\\}$$$$$$b = \\{1, 0, 1, 0, 2, 1, 0\\}$$$$$$c = \\{2, 0, 0, 0, 0, 2, 0\\}$$$In the second sample, one of the optimal solutions is:$$$a = \\{0, 2, 0, 0, 0\\}$$$$$$b = \\{1, 1, 0, 1, 0\\}$$$$$$c = \\{0, 2, 0, 0, 0\\}$$$In the third sample, the only possible solution is:$$$a = \\{2\\}$$$$$$b = \\{2\\}$$$$$$c = \\{0\\}$$$"}, "positive_code": [{"source_code": "(* Codeforces 1352 0 Sum of Round Numbers comp *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet min_sum2 a1 b1 a2 b2 = \n\t(* let _ = Printf.printf \"b1,b2 = %d %d\\n\" b1 b2 in *)\n\tif b2 > b1 then\n\t\t(-2) * (b2 - b1)\n\telse\n\t\t0;;\n\nlet max_sum3 x1 y1 z1 x2 y2 z2 =\n\t\tif z1 > y2 then\n\t\t\tlet sm = 2*y2 in\n\t\t\t(* let _ = Printf.printf \"sm1 = %d\\n\" sm in *)\n\t\t\tlet zz1 = z1 - y2 in\n\t\t\tlet yy2 = 0 in\n\t\t\tlet a1 = y1 in\n\t\t\tlet b1 = x1 + zz1 in\n\t\t\tlet a2 = x2 + yy2 in\n\t\t\tlet b2 = z2 in\n\t\t\t(sm + min_sum2 a1 b1 a2 b2) \n\t\telse\n\t\t\tlet sm = 2*z1 in\n (* let _ = Printf.printf \"sm2 = %d\\n\" sm in *)\n\t\t\tlet zz1 = 0 in\n\t\t\tlet yy2 = y2 - z1 in\n\t\t\tlet a1 = y1 in\n\t\t\tlet b1 = x1 + zz1 in\n\t\t\tlet a2 = x2 + yy2 in\n\t\t\tlet b2 = z2 in\n\t\t\t(sm + min_sum2 a1 b1 a2 b2);;\t\t\n \nlet do_one () = \n let z1,y1,x1 = gr(),gr(),gr() in\n let z2,y2,x2 = gr(),gr(),gr() in\n\t\tlet max_sum = max_sum3 x1 y1 z1 x2 y2 z2 in\n\t\tbegin\n\t\t\tprint_int max_sum;\n\t\t\tprint_string \"\\n\"\n\t\tend;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [{"source_code": "(* Codeforces 1005 A Tanya and Stairways done *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec to_tania acc last l = match l with\n\t| [] -> last :: acc\n\t| h :: t -> match h with\n\t\t\t| 1 -> \n\t\t\t\tlet lacc = if last == 0 then acc else last :: acc in\n\t\t\t\tto_tania lacc 1 t\n\t\t\t| _ -> to_tania acc h t;;\n\nlet main() =\n\tlet n = gr () in\n\tlet ra = readlist n [] in\n\tlet a = List.rev ra in\n\tlet ro = to_tania [] 0 a in\n\tlet o = List.rev ro in\n\tlet lno = List.length o in\n\tbegin\n\t\tprint_int lno;\n\t\tprint_string \"\\n\";\n\t\tprintlisti o;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}], "src_uid": "e1de1e92fac8a6db3222c0d3c26843d8"} {"nl": {"description": "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.", "input_spec": "The input contains three strings in three separate lines: s1, s2 and virus (1\u2009\u2264\u2009|s1|,\u2009|s2|,\u2009|virus|\u2009\u2264\u2009100). Each string consists only of uppercase English letters.", "output_spec": "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.", "sample_inputs": ["AJKEQSLOBSROFGZ\nOVGURWZLWVLUXTH\nOZ", "AA\nA\nA"], "sample_outputs": ["ORZ", "0"], "notes": null}, "positive_code": [{"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Str;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) ;;\n\nlet vl = String.length virus;;\n\nlet n = String.length s1;;\nlet m = String.length s2;;\nlet a = Array.make_matrix (n+1) (m+1) [];;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus;;\n\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\n;;\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c i j = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n begin\n let sL = a.(i).(j) in\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> let rslt = List.map (fun x -> c^x) sL in\n let rslt2 = List.filter (fun x -> not (contains x) ) rslt in \n match rslt2 with \n [] ->List.filter (fun x -> not (contains x) ) (\n uniq(List.append \n (List.append \n (List.map (fun x -> c^x) a. (i+1).(j))\n (List.map (fun x -> c^x) a. (i).(j+1)) \n )\n a.(i).(j)\n )\n )\n |_ ->rslt2\n end\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs contains =\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get s1 i) = (String.get s2 j) then\n let cs = String.sub s1 i 1 in\n sList_merge cs (i+1) (j+1) \n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\nlet remove_char x r = \n if r = 0 then\n String.sub x 1 ((String.length x) -1)\n else \n (String.sub x 0 r)^(String.sub x (r+1)\n ((String.length x) - r-1)) \n;;\n\nlet rec return_longest xl = \n match xl with\n [] -> \"\"\n |hd :: tl ->let xxl = return_longest tl in\n if (String.length hd )> (String.length xxl) then\n hd \n else xxl\n;;\n\nlet rec remove x =\n try \n let r = Str.search_forward re x 0 in\n let basket = ref [] in\n for i = 0 to vl - 1 do\n let newx = remove_char x (r+i) in\n basket := List.append !basket [(remove newx)]\n done;\n return_longest !basket\n with Not_found -> x\n;;\n\n\nif s1=s2 then \n begin\n print_string (remove s1); print_endline \"\"\n end\nelse\n begin\n let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\n in\n if not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\n else\n let rslt = lcs contains in\n print_sList rslt\n end\n"}], "negative_code": [{"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Char;;\nopen Str;;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c sL contains = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> let rslt = List.map (fun x -> c^x) sL in\n let rslt2 = List.filter (fun x -> not (contains x) ) rslt in \n match rslt2 with \n [] -> List.append sL (List.map \n (fun x -> c^(String.sub x 1\n ((String.length x) -1)))\n sL)\n |_ ->rslt2\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs xs ys contains =\n let n = String.length xs\n and m = String.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get xs i) = (String.get ys j) then\n let cs = String.sub xs i 1 in\n sList_merge cs a.(i+1).(j+1) contains \n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) in\nlet s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\nin\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus in\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\nin\nif not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\nelse\n let rslt = lcs s1 s2 contains in\n print_sList rslt;;\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Str;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) ;;\n\nlet n = String.length s1;;\nlet m = String.length s2;;\nlet a = Array.make_matrix (n+1) (m+1) [];;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c sL contains = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> let rslt = List.map (fun x -> c^x) sL in\n let rslt2 = List.filter (fun x -> not (contains x) ) rslt in \n match rslt2 with \n [] -> List.append sL (List.map \n (fun x -> c^(String.sub x 1\n ((String.length x) -1)))\n sL)\n |_ ->rslt2\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs contains =\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get s1 i) = (String.get s2 j) then\n let cs = String.sub s1 i 1 in\n sList_merge cs a.(i+1).(j+1) contains \n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\n\nlet s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\nin\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus in\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\nin\nif not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\nelse\n let rslt = lcs contains in\n print_sList rslt;;\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Char;;\nopen Str;;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c sL contains = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> List.filter (fun x -> not (contains x) ) (List.map (fun x -> c^x) sL)\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs xs ys contains =\n let n = String.length xs\n and m = String.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get xs i) = (String.get ys j) then\n let rslt = sList_merge (String.sub xs i 1) a.(i+1).(j+1)\n contains in\n match rslt with \n []-> a.(i+1).(j+1)\n | _-> rslt\n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) in\nlet s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\nin\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus in\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\nin\nif not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\nelse\n let rslt = lcs s1 s2 contains in\n print_sList rslt;;\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Char;;\nopen Str;;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c sL contains = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> List.filter (fun x -> not (contains x) ) (List.map (fun x -> c^x) sL)\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs xs ys contains =\n let n = String.length xs\n and m = String.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get xs i) = (String.get ys j) then\n sList_merge (String.sub xs i 1) a.(i+1).(j+1) contains\n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) in\nlet s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\nin\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus in\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\nin\nif not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\nelse\n let rslt = lcs s1 s2 contains in\n print_sList rslt;;\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Str;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) ;;\n\nlet n = String.length s1;;\nlet m = String.length s2;;\nlet a = Array.make_matrix (n+1) (m+1) [];;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus;;\n\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\n;;\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c i j = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n begin\n let sL = a.(i).(j) in\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> let rslt = List.map (fun x -> c^x) sL in\n let rslt2 = List.filter (fun x -> not (contains x) ) rslt in \n match rslt2 with \n [] ->List.filter (fun x -> not (contains x) ) (\n uniq(List.append \n (List.append \n (List.map (fun x -> c^x) a. (i+1).(j))\n (List.map (fun x -> c^x) a. (i).(j+1)) \n )\n a.(i).(j)\n )\n )\n |_ ->rslt2\n end\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs contains =\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get s1 i) = (String.get s2 j) then\n let cs = String.sub s1 i 1 in\n sList_merge cs (i+1) (j+1) \n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\nlet rec remove x =\n try \n let r = Str.search_forward re x 0 in\n match r with\n | 0 -> remove (String.sub x 1 ((String.length x) -1))\n | a when a >0 -> remove (String.sub x 0 a)^(String.sub x (a+1)\n ((String.length x) - a -1)) \n with Not_found -> x\n;;\n\nif s1=s2 then\n begin\n print_string (remove s1); print_endline \"\"\n end\nelse\n begin\n let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\n in\n if not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\n else\n let rslt = lcs contains in\n print_sList rslt\n end\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Str;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) ;;\n\nlet n = String.length s1;;\nlet m = String.length s2;;\nlet a = Array.make_matrix (n+1) (m+1) [];;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus;;\n\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\n;;\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c i j = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n begin\n let sL = a.(i).(j) in\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> let rslt = List.map (fun x -> c^x) sL in\n let rslt2 = List.filter (fun x -> not (contains x) ) rslt in \n match rslt2 with \n [] ->List.filter (fun x -> not (contains x) ) (\n uniq(List.append \n (List.append \n (List.map (fun x -> c^x) a. (i+1).(j))\n (List.map (fun x -> c^x) a. (i).(j+1)) \n )\n a.(i).(j)\n )\n )\n |_ ->rslt2\n end\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs contains =\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get s1 i) = (String.get s2 j) then\n let cs = String.sub s1 i 1 in\n sList_merge cs (i+1) (j+1) \n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\nlet rec remove x =\n try \n let r = Str.search_forward re x 0 in\n if r = 0 then\n remove (String.sub x 1 ((String.length x) -1))\n else \n remove ( (String.sub x 0 r)^(String.sub x (r+1)\n ((String.length x) - r-1)) )\n with Not_found -> x\n;;\n\n\n\nif s1=s2 then\n begin\n print_string (remove s1); print_endline \"\"\n end\nelse\n begin\n let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\n in\n if not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\n else\n let rslt = lcs contains in\n print_sList rslt\n end\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Str;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) ;;\n\nlet n = String.length s1;;\nlet m = String.length s2;;\nlet a = Array.make_matrix (n+1) (m+1) [];;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus;;\n\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\n;;\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c i j = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n begin\n let sL = a.(i).(j) in\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> let rslt = List.map (fun x -> c^x) sL in\n let rslt2 = List.filter (fun x -> not (contains x) ) rslt in \n match rslt2 with \n [] ->List.filter (fun x -> not (contains x) ) (\n uniq(List.append \n (List.append \n (List.map (fun x -> c^x) a. (i+1).(j))\n (List.map (fun x -> c^x) a. (i).(j+1)) \n )\n a.(i).(j)\n )\n )\n |_ ->rslt2\n end\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs contains =\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get s1 i) = (String.get s2 j) then\n let cs = String.sub s1 i 1 in\n sList_merge cs (i+1) (j+1) \n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\nlet rec remove x =\n try \n let r = Str.search_forward re x 0 in\n if r = 0 then\n remove (String.sub x 1 ((String.length x) -1))\n else \n remove ( (String.sub x 0 r)^(String.sub x (r+1)\n ((String.length x) - r-1)) )\n with Not_found -> x\n;;\n\n\n\nif s1=s2 then \n begin\n print_string (remove s1); print_endline \"\"\n end\nelse\n begin\n let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\n in\n if not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\n else\n let rslt = lcs contains in\n print_sList rslt\n end\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Char;;\nopen Str;;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c sL contains = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> List.filter (fun x -> not (contains x) ) (List.map (fun x -> c^x) sL)\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs xs ys contains =\n let n = String.length xs\n and m = String.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get xs i) = (String.get ys j) then\n sList_merge (String.sub xs i 1) a.(i+1).(j+1) contains\n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) in\nlet s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\nin\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus in\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\nin\nif not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\nelse\n let rslt = lcs s1 s2 contains in\n print_sList rslt;;\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen List;;\nopen Str;;\n\nlet (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin \"%s %s %s \"\n (fun x y z -> (x,y,z) ) ;;\n\nlet n = String.length s1;;\nlet m = String.length s2;;\nlet a = Array.make_matrix (n+1) (m+1) [];;\n\ntype sList = string list;;\nlet print_sList rl = (*iter (fun x -> print_string x; print_string \"\n \") rl;;*)\n match rl with\n [] -> print_endline \"0\"\n |hd :: _ -> print_string hd; print_endline \"\"\n;;\n\n\n(*If string s1 contains string s2*)\nlet re = Str.regexp_string virus;;\n\nlet contains x =\n try ignore (Str.search_forward re x 0); true\n with Not_found -> false\n;;\n\n(*Make sure a list contains unique elements*)\nlet rec uniq x =\n let rec uniq_help l n = \n match l with\n | [] -> []\n | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in\n match x with\n | [] -> []\n | h::t -> h::(uniq_help (uniq t) h)\n;;\n\nlet sList_merge c i j = \n (*print_string cs; print_string \" \"; print_sList sL; print_endline \"\";\n print_sList ( List.map (fun x -> cs^x) sL );*)\n begin\n let sL = a.(i).(j) in\n match sL with \n |[] -> if not (contains c) then [c] else []\n |_ -> let rslt = List.map (fun x -> c^x) sL in\n let rslt2 = List.filter (fun x -> not (contains x) ) rslt in \n match rslt2 with \n [] ->List.filter (fun x -> not (contains x) ) (\n uniq(List.append \n (List.append \n (List.map (fun x -> c^x) a. (i+1).(j))\n (List.map (fun x -> c^x) a. (i).(j+1)) \n )\n a.(i).(j)\n )\n )\n |_ ->rslt2\n end\n;;\n\nlet sList_merge2 sL1 sL2 = match sL1, sL2 with\n |([],[]) -> []\n |([], x) -> x\n |( x, []) -> x\n |(x, y) -> \n begin\n let xl = String.length (List.hd x) in\n let yl = String.length (List.hd y) in \n if xl > yl then \n x\n else if xl < yl then\n y\n else uniq ( List.append x y )\n end\n;;\n \n(*Find the LCS, record them all*)\nlet lcs contains =\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if (String.get s1 i) = (String.get s2 j) then\n let cs = String.sub s1 i 1 in\n sList_merge cs (i+1) (j+1) \n else\n sList_merge2 a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0)\n;;\n\n\nlet longest xs ys = if List.length xs > List.length ys then xs else\n ys;;\n\nlet lcs2 xs' ys' =\n let xs = Array.of_list xs'\n and ys = Array.of_list ys' in\n let n = Array.length xs\n and m = Array.length ys in\n let a = Array.make_matrix (n+1) (m+1) [] in\n for i = n-1 downto 0 do\n for j = m-1 downto 0 do\n a.(i).(j) <- if xs.(i) = ys.(j) then\n xs.(i) :: a.(i+1).(j+1)\n else\n longest a.(i).(j+1) a.(i+1).(j)\n done\n done;\n a.(0).(0);;\n\nlet list_of_string str =\n let result = ref [] in\n String.iter (fun x -> result := x :: !result)\n str;\n List.rev !result;;\n\nlet string_of_list lst =\n let result = String.create (List.length lst) in\n ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); result\n;;\n\n\nlet s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))\nin\nif not (contains s) then \n begin\n print_string s; print_endline \"\";\n end\nelse\n let rslt = lcs contains in\n print_sList rslt;;\n"}], "src_uid": "391c2abbe862139733fcb997ba1629b8"} {"nl": {"description": "Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n\u2009\u00d7\u2009m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i,\u2009j). 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,\u2009j) 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. ", "input_spec": "The first line of input contains three integers n, m and q (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500 and 1\u2009\u2264\u2009q\u2009\u2264\u20095000). 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\u2009\u2264\u2009i\u2009\u2264\u2009n and 1\u2009\u2264\u2009j\u2009\u2264\u2009m), the row number and the column number of the bear changing his state.", "output_spec": "After each round, print the current score of the bears.", "sample_inputs": ["5 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n1 0 0 1\n0 0 0 0\n1 1\n1 4\n1 1\n4 2\n4 3"], "sample_outputs": ["3\n4\n3\n3\n4"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet judge_line l =\n let n = Array.length l in\n let rec ju i c m =\n if i = n then m\n else\n if l.(i) = 0 then ju (i+1) 0 (max c m)\n else ju (i+1) (c+1) (max (c+1) m)\n in\n ju 0 0 0\n\nlet _ =\n let n = read_int () in\n let m = read_int () in\n let q = read_int () in\n let a = Array.init n (fun _ -> Array.init m (fun _ -> read_int ())) in\n let s = Array.init n (fun i -> judge_line a.(i)) in\n for i = 1 to q do\n let u = read_int () - 1 in\n let v = read_int () - 1 in\n a.(u).(v) <- 1-a.(u).(v);\n s.(u) <- judge_line a.(u);\n Printf.printf \"%d\\n\" (Array.fold_left max 0 s)\n done\n"}], "negative_code": [], "src_uid": "337b6d2a11a25ef917809e6409f8edef"} {"nl": {"description": "A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.", "input_spec": "First line of the input contains the string s\u00a0\u2014 the coating that is present in the shop. Second line contains the string t\u00a0\u2014 the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.", "output_spec": "The first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating. If the answer is not -1, then the following n lines should contain two integers xi and yi\u00a0\u2014 numbers of ending blocks in the corresponding piece. If xi\u2009\u2264\u2009yi then this piece is used in the regular order, and if xi\u2009>\u2009yi piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.", "sample_inputs": ["abc\ncbaabc", "aaabrytaaa\nayrat", "ami\nno"], "sample_outputs": ["2\n3 1\n1 3", "3\n1 1\n6 5\n8 7", "-1"], "notes": "NoteIn the first sample string \"cbaabc\" = \"cba\" + \"abc\".In the second sample: \"ayrat\" = \"a\" + \"yr\" + \"at\"."}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet licz x = (x-|Int64.one)/|two_64;;\n\nlet init n g = \n let q = String.make n 'a' in\n for i=0 to (n-1) do\n q.[i] <- g i\n done; q;;\n\nlet szukaj w t wynik =\n let nt = String.length t in\n let rt = init nt (fun x -> t.[nt-x-1]) in\n let s = \"!\"^w^\"#\"^t^\"$\"^rt in\n let n = String.length s in\n let pre = Array.make n 0 \n and d = ref (-1)\n and maxi = ref 0 \n and juz = ref false in\n pre.(0) <- -1;\n for i=1 to (n-1) do\n while !d >= 0 && s.[!d+1] <> s.[i] do\n d := pre.( !d )\n done;\n incr d;\n pre.(i) <- !d;\n if !juz then maxi := max !maxi !d;\n if s.[i] = '#' then juz := true\n done;\n if !maxi = 0 then 0\n else begin\n let id = ref 0 \n and wyn = ref (0,0)\n and wzrost = ref 0 in\n for i=0 to n-1 do\n id := !id + !wzrost;\n if s.[i] = '#' then wzrost := 1;\n if s.[i] = '$' then begin wzrost := -1; id := nt+1 end;\n if pre.(i) = !maxi then wyn := (!id - ( (!maxi-1) * !wzrost), !id )\n done;\n wynik := !wyn :: !wynik;\n !maxi\n end;;\n\nlet rec wypisz lista =\n match lista with\n | [] -> ()\n | (a,b)::t -> wypisz t;Printf.printf \"%d %d\\n\" a b;;\n\nlet _ = \n let (t,ww) = Scanf.scanf \"%s\\n%s\\n\" ( fun x y -> x,y ) in\n let w = ref ww\n and wynik = ref [] \n and dalej = ref true\n in\n while String.length !w <> 0 && !dalej do\n let k = szukaj !w t wynik in\n if k = 0 then dalej := false\n else \n let q = init (String.length !w - k) (fun x -> !w.[x+k])\n in w := q\n done;\n if String.length !w <> 0 then Printf.printf \"-1\\n\"\n else begin Printf.printf \"%d\\n\" (List.length !wynik); wypisz !wynik end;;\n"}], "negative_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet licz x = (x-|Int64.one)/|two_64;;\n\nlet init n g = \n let q = String.make n 'a' in\n for i=0 to (n-1) do\n q.[i] <- g i\n done; q;;\n\nlet szukaj w t wynik =\n let nt = String.length t in\n let rt = init nt (fun x -> t.[nt-x-1]) in\n let s = w^\"#\"^t^\"$\"^rt in\n let n = String.length s in\n let pre = Array.make n 0 \n and d = ref (-1)\n and maxi = ref 0 \n and juz = ref false in\n pre.(0) <- -1;\n for i=1 to (n-1) do\n while !d >= 0 && s.[!d] <> s.[i] do\n d := pre.(!d)\n done;\n incr d;\n pre.(i) <- !d;\n if !juz then maxi := max !maxi !d;\n if s.[i] = '#' then juz := true\n done;\n if !maxi = 0 then 0\n else begin\n let id = ref 0 \n and wyn = ref (0,0)\n and wzrost = ref 0 in\n for i=0 to n-1 do\n id := !id + !wzrost;\n if s.[i] = '#' then wzrost := 1;\n if s.[i] = '$' then begin wzrost := -1; id := nt+1 end;\n if pre.(i) = !maxi then wyn := (!id - ( (!maxi-1) * !wzrost), !id )\n done;\n wynik := !wyn :: !wynik;\n !maxi\n end;;\n\nlet rec wypisz lista =\n match lista with\n | [] -> ()\n | (a,b)::t -> wypisz t;Printf.printf \"%d %d\\n\" a b;;\n\nlet _ = \n let (t,ww) = Scanf.scanf \"%s\\n%s\\n\" ( fun x y -> x,y ) in\n let w = ref ww\n and wynik = ref [] \n and dalej = ref true\n in\n while String.length !w <> 0 && !dalej do\n let k = szukaj !w t wynik in\n if k = 0 then dalej := false\n else \n let q = init (String.length !w - k) (fun x -> !w.[x+k])\n in w := q\n done;\n if String.length !w <> 0 then Printf.printf \"-1\\n\"\n else begin Printf.printf \"%d\\n\" (List.length !wynik); wypisz !wynik end;;\n"}, {"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet licz x = (x-|Int64.one)/|two_64;;\n\nlet init n g = \n let q = String.make n 'a' in\n for i=0 to (n-1) do\n q.[i] <- g i\n done; q;;\n\nlet szukaj w t wynik =\n let nt = String.length t in\n let rt = init nt (fun x -> t.[nt-x-1]) in\n let s = w^\"#\"^t^\"$\"^rt in\n let n = String.length s in\n let pre = Array.make n 0 \n and d = ref (-1)\n and maxi = ref 0 \n and juz = ref false in\n pre.(0) <- 0;\n for i=1 to (n-1) do\n while !d >= 0 && s.[!d] <> s.[i] do\n if !d = 0 then d := -1\n else d := pre.( !d - 1 )\n done;\n incr d;\n pre.(i) <- !d;\n if !juz then maxi := max !maxi !d;\n if s.[i] = '#' then juz := true\n done;\n if !maxi = 0 then 0\n else begin\n let id = ref 0 \n and wyn = ref (0,0)\n and wzrost = ref 0 in\n for i=0 to n-1 do\n id := !id + !wzrost;\n if s.[i] = '#' then wzrost := 1;\n if s.[i] = '$' then begin wzrost := -1; id := nt+1 end;\n if pre.(i) = !maxi then wyn := (!id - ( (!maxi-1) * !wzrost), !id )\n done;\n wynik := !wyn :: !wynik;\n !maxi\n end;;\n\nlet rec wypisz lista =\n match lista with\n | [] -> ()\n | (a,b)::t -> wypisz t;Printf.printf \"%d %d\\n\" a b;;\n\nlet _ = \n let (t,ww) = Scanf.scanf \"%s\\n%s\\n\" ( fun x y -> x,y ) in\n let w = ref ww\n and wynik = ref [] \n and dalej = ref true\n in\n while String.length !w <> 0 && !dalej do\n let k = szukaj !w t wynik in\n if k = 0 then dalej := false\n else \n let q = init (String.length !w - k) (fun x -> !w.[x+k])\n in w := q\n done;\n if String.length !w <> 0 then Printf.printf \"-1\\n\"\n else begin Printf.printf \"%d\\n\" (List.length !wynik); wypisz !wynik end;;\n"}, {"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet licz x = (x-|Int64.one)/|two_64;;\n\nlet init n g = \n let q = String.make n 'a' in\n for i=0 to (n-1) do\n q.[i] <- g i\n done; q;;\n\nlet szukaj w t wynik =\n let nt = String.length t in\n let rt = init nt (fun x -> t.[nt-x-1]) in\n let s = w^\"#\"^t^\"$\"^rt in\n let n = String.length s in\n let pre = Array.make n 0 \n and d = ref (-1)\n and maxi = ref 0 \n and juz = ref false in\n pre.(0) <- -1;\n for i=1 to (n-1) do\n while !d >= 0 && s.[!d] <> s.[i] do\n d := pre.(!d)\n done;\n incr d;\n pre.(i) <- !d;\n if !juz then maxi := max !maxi !d;\n if s.[i] = '#' then juz := true\n done;\n if !maxi = 0 then 0\n else begin\n let id = ref 0 \n and wyn = ref (0,0)\n and wzrost = ref 0 in\n for i=0 to n-1 do\n id := !id + !wzrost;\n if s.[i] = '#' then wzrost := 1;\n if s.[i] = '$' then begin wzrost := -1; id := nt+1 end;\n if pre.(i) = !maxi then wyn := (!id - ( (!maxi-1) * !wzrost), !id )\n done;\n wynik := !wyn :: !wynik;\n !maxi\n end;;\n\nlet rec wypisz lista =\n match lista with\n | [] -> ()\n | (a,b)::t -> wypisz t;Printf.printf \"%d %d\\n\" a b;;\n\nlet _ = \n let (t,ww) = Scanf.scanf \"%s\\n%s\\n\" ( fun x y -> x,y ) in\n let w = ref ww\n and wynik = ref [] \n and dalej = ref true\n in\n while String.length !w <> 0 && !dalej do\n let k = szukaj !w t wynik in\n if k = 0 then dalej := false\n else \n let q = init (String.length !w - k) (fun x -> !w.[x+k])\n in w := q\n done;\n if String.length !w <> 0 then Printf.printf \"-1\\n\"\n else Printf.printf \"%d\\n\" (List.length !wynik); wypisz !wynik;\n"}], "src_uid": "c6c4a833843d479c94f9ebd3e2774775"} {"nl": {"description": "Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1,\u2009a2,\u2009...,\u2009an are good.Now she is interested in good sequences. A sequence x1,\u2009x2,\u2009...,\u2009xk is called good if it satisfies the following three conditions: The sequence is strictly increasing, i.e. xi\u2009<\u2009xi\u2009+\u20091 for each i (1\u2009\u2264\u2009i\u2009\u2264\u2009k\u2009-\u20091). No two adjacent elements are coprime, i.e. gcd(xi,\u2009xi\u2009+\u20091)\u2009>\u20091 for each i (1\u2009\u2264\u2009i\u2009\u2264\u2009k\u2009-\u20091) (where gcd(p,\u2009q) denotes the greatest common divisor of the integers p and q). All elements of the sequence are good integers. Find the length of the longest good sequence.", "input_spec": "The input consists of two lines. The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of good integers. The second line contains a single-space separated list of good integers a1,\u2009a2,\u2009...,\u2009an in strictly increasing order (1\u2009\u2264\u2009ai\u2009\u2264\u2009105;\u00a0ai\u2009<\u2009ai\u2009+\u20091).", "output_spec": "Print a single integer \u2014 the length of the longest good sequence.", "sample_inputs": ["5\n2 3 4 6 9", "9\n1 2 3 5 6 7 8 9 10"], "sample_outputs": ["4", "4"], "notes": "NoteIn the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet factor n = \n let rec loop n p ac = \n if n=1 then ac\n else if p*p > n then (n::ac)\n else if n mod p = 0 then loop (n/p) p (p::ac)\n else loop n (p+1) ac\n in\n List.rev (loop n 2 [])\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun _ -> read_int()) in\n\n let h = Hashtbl.create 10 in\n \n let getp p = try Hashtbl.find h p with Not_found -> 0 in\n\n let rec loop i ac = if i=n then ac else (\n let fl = factor a.(i) in\n let m = 1 + List.fold_left (fun ac p -> max ac (getp p)) 0 fl in\n List.iter (fun p -> Hashtbl.replace h p m) fl;\n loop (i+1) (max ac m)\n\t\n ) in\n\n let ans = loop 0 0 in\n Printf.printf \"%d\\n\" ans\n"}], "negative_code": [], "src_uid": "0f8ad0ea2befbbe036fbd5e5f6680c21"} {"nl": {"description": "Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that. Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then: at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \\le 2$$$ and $$$a_5=1 \\le 2$$$); at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \\le 5$$$, $$$a_3=4 \\le 5$$$ and $$$a_4=5 \\le 5$$$); the $$$6$$$-th granny cannot be called into the yard \u00a0\u2014 therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies). ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 2\\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single integer $$$k$$$ ($$$1 \\le k \\le n + 1$$$) \u2014 the maximum possible number of grannies in the courtyard.", "sample_inputs": ["4\n5\n1 1 2 2 1\n6\n2 3 4 5 6 7\n6\n1 5 4 5 1 9\n5\n1 2 3 5 6"], "sample_outputs": ["6\n1\n6\n4"], "notes": "NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n Array.sort compare a;\n let rec loop i j current =\n (* grannies 0...i-1 are already there.\n\t current = #there counting maria.\n\t Try to put all grannies from i to j there all\n\t at once. If possible do it. Otherwise move\n\t onto i (j+1).\n *)\n if current + (j-i) >= a.(j) then (\n\tlet current = current + (j-i+1) in\n\tif j+1 = n then current else loop (j+1) (j+1) current\n ) else (\n\tif j+1 = n then current else loop i (j+1) current\n )\n in\n printf \"%d\\n\" (loop 0 0 1)\n done\n"}], "negative_code": [], "src_uid": "718cea81f609055cece58cae5310f703"} {"nl": {"description": "Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!", "input_spec": "The first line of the input contains two space-separated integers, n and d (1\u2009\u2264\u2009n\u2009\u2264\u2009105, ) \u2014 the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively. Next n lines contain the descriptions of Kefa's friends, the (i\u2009+\u20091)-th line contains the description of the i-th friend of type mi, si (0\u2009\u2264\u2009mi,\u2009si\u2009\u2264\u2009109) \u2014 the amount of money and the friendship factor, respectively. ", "output_spec": "Print the maximum total friendship factir that can be reached.", "sample_inputs": ["4 5\n75 5\n0 100\n150 20\n75 1", "5 100\n0 7\n11 32\n99 10\n46 8\n87 54"], "sample_outputs": ["100", "111"], "notes": "NoteIn the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.In the second sample test we can take all the friends."}, "positive_code": [{"source_code": "open Big_int;;\n\nlet main () =\n\tlet (n,d) = Scanf.scanf \"%d %d\" (fun i j -> (i,j)) and l = ref []\n\tin\n\t\tfor i=1 to n do\n\t\t\tScanf.scanf \" %d %s\" (fun i j -> l := (i,big_int_of_string j)::!l);\n\t\tdone;\n\tlet tab = Array.of_list (List.sort (fun (i,_) (j,_) -> compare i j) !l) and i = ref 0\n\tand j = ref 0 in\n\tlet act = ref (snd (tab.(0))) and maxi= ref (big_int_of_int 0) in\n\t\twhile !j < n do\n\t\t\tif fst (tab.(!j)) - fst (tab.(!i)) < d\n\t\t\t\tthen (\n\t\t\tmaxi := max_big_int !maxi !act;incr j;if !j < n then act := add_big_int !act (snd (tab.(!j))))\n\t\t\t\telse (act := sub_big_int !act (snd (tab.(!i))); incr i);\n\t\tdone;\n\tPrintf.printf \"%s\" (string_of_big_int !maxi);;\n\nmain ();;\n"}, {"source_code": "let read_int64 () = Scanf.bscanf Scanf.Scanning.stdin \" %s \" (fun x -> Big_int.big_int_of_string x);;\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\nlet read_pair _ = let x = read_int64 () in let y = read_int64 () in (x, y);;\nlet comp (a, b) (c, d) = if (Big_int.compare_big_int a c) = 0 then Big_int.compare_big_int b d else Big_int.compare_big_int a c;; \nlet main () = \n let n = read_int () in\n let d = read_int64 () in\n let a = Array.init n read_pair in\n let _ = Array.sort comp a in\n let (i, j, k, c) = (ref 0, ref 0, ref (Big_int.big_int_of_int 0), ref (Big_int.big_int_of_int 0)) in (\n while !i < n do (\n match (a.(!i), a.(!j)) with\n | ((x, y), (z, w)) -> (\n if Big_int.compare_big_int (Big_int.sub_big_int x z) d < 0 then\n (k := (Big_int.add_big_int !k y); c := (Big_int.max_big_int (!c) (!k)); incr i)\n else \n (k := (Big_int.sub_big_int !k w); incr j)\n )\n )\n done;\n Printf.printf \"%s\\n\" (Big_int.string_of_big_int !c)\n )\n;;\n\nmain ();;"}, {"source_code": "let read_int64 () = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> Int64.of_int x);;\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\nlet read_pair _ = let x = read_int64 () in let y = read_int64 () in (x, y);;\nlet comp (a, b) (c, d) = if (Int64.compare a c) = 0 then Int64.compare b d else Int64.compare a c;; \nlet main () = \n let n = read_int () in\n let d = read_int64 () in\n let a = Array.init n read_pair in\n let _ = Array.sort comp a in\n let (i, j, k, c) = (ref 0, ref 0, ref 0L, ref 0L) in (\n while !i < n do (\n match (a.(!i), a.(!j)) with\n | ((x, y), (z, w)) -> (\n if Int64.compare (Int64.sub x z) d < 0 then\n (k := (Int64.add !k y); c := (max (!c) (!k)); incr i)\n else \n (k := (Int64.sub !k w); incr j)\n )\n )\n done;\n Printf.printf \"%s\\n\" (Int64.to_string !c)\n )\n;;\nmain ();;\n"}], "negative_code": [{"source_code": "let main () =\n\tlet (n,d) = Scanf.scanf \"%d %d\" (fun i j -> (i,j)) and l = ref []\n\tin\n\t\tfor i=1 to n do\n\t\t\tScanf.scanf \" %d %d\" (fun i j -> l := (i,j)::!l);\n\t\tdone;\n\tlet tab = Array.of_list (List.sort compare !l) and i = ref 0\n\tand j = ref 0 in\n\tlet act = ref (snd (tab.(0))) and maxi= ref 0 in\n\t\twhile !j < n do\n\t\t\tif fst (tab.(!j)) - fst (tab.(!i)) < d\n\t\t\t\tthen (\n\t\t\tmaxi := max !maxi !act;incr j;if !j < n then act := !act + snd (tab.(!j)))\n\t\t\t\telse (act := !act - snd (tab.(!i)); incr i);\n\t\tdone;\n\tPrintf.printf \"%d\" !maxi;;\n\nmain ();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\nlet read_pair _ = let x = read_int () in let y = read_int () in (x, y);;\nlet comp a b = if a < b then -1 else if a = b then 0 else 1;;\nlet main () = \n let n = read_int () in\n let d = read_int () in\n let a = Array.init n read_pair in\n let _ = Array.sort comp a in\n let (i, j, k, c) = (ref 0, ref 0, ref 0, ref 0) in (\n while !i < n do (\n match (a.(!i), a.(!j)) with\n | ((x, y), (z, w)) -> (\n if x - z < d then\n (k := !k + y; c := max (!c) (!k); incr i)\n else \n (k := !k - w; incr j)\n )\n )\n done;\n Printf.printf \"%d\\n\" (!c)\n )\n;;\n\nmain ();;\n"}], "src_uid": "38fe0e19974a7bc60153793b9060369a"} {"nl": {"description": "Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrary order. Just when Vanya will have entered the correct password, he is immediately authorized on the site. Vanya will not enter any password twice.Entering any passwords takes one second for Vanya. But if Vanya will enter wrong password k times, then he is able to make the next try only 5 seconds after that. Vanya makes each try immediately, that is, at each moment when Vanya is able to enter password, he is doing that.Determine how many seconds will Vanya need to enter Codehorses in the best case for him (if he spends minimum possible number of second) and in the worst case (if he spends maximum possible amount of seconds).", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100)\u00a0\u2014 the number of Vanya's passwords and the number of failed tries, after which the access to the site is blocked for 5 seconds. The next n lines contains passwords, one per line\u00a0\u2014 pairwise distinct non-empty strings consisting of latin letters and digits. Each password length does not exceed 100 characters. The last line of the input contains the Vanya's Codehorses password. It is guaranteed that the Vanya's Codehorses password is equal to some of his n passwords.", "output_spec": "Print two integers\u00a0\u2014 time (in seconds), Vanya needs to be authorized to Codehorses in the best case for him and in the worst case respectively.", "sample_inputs": ["5 2\ncba\nabc\nbb1\nabC\nABC\nabc", "4 100\n11\n22\n1\n2\n22"], "sample_outputs": ["1 15", "3 4"], "notes": "NoteConsider the first sample case. As soon as all passwords have the same length, Vanya can enter the right password at the first try as well as at the last try. If he enters it at the first try, he spends exactly 1 second. Thus in the best case the answer is 1. If, at the other hand, he enters it at the last try, he enters another 4 passwords before. He spends 2 seconds to enter first 2 passwords, then he waits 5 seconds as soon as he made 2 wrong tries. Then he spends 2 more seconds to enter 2 wrong passwords, again waits 5 seconds and, finally, enters the correct password spending 1 more second. In summary in the worst case he is able to be authorized in 15 seconds.Consider the second sample case. There is no way of entering passwords and get the access to the site blocked. As soon as the required password has length of 2, Vanya enters all passwords of length 1 anyway, spending 2 seconds for that. Then, in the best case, he immediately enters the correct password and the answer for the best case is 3, but in the worst case he enters wrong password of length 2 and only then the right one, spending 4 seconds at all."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet find array n =\n let rec loop low high i =\n if i = Array.length array then low, high\n else begin\n let sl = String.length array.(i) in\n if sl < n then loop (low + 1) high (i + 1)\n else if sl = n then loop low (high + 1) (i + 1)\n else loop low high (i + 1)\n end\n in\n let low, high = loop 0 0 0 in\n low, low + high\n\nlet () =\n let n = read_int () in\n let k = read_int () in\n let array = Array.init n (fun _ ->\n read_string ()\n )\n in\n let ra = read_string () in\n let (low, high) = find array (String.length ra) in\n let a, b =\n let c = if k = 0 then 0 else (high -1) / k in\n let d = if k = 0 then 0 else low / k in\n if low = 0 then 1, (5 * c + high)\n else (5 * d + low + 1), (5 * c + high)\n in\n Printf.printf \"%d %d\" a b\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet find array n =\n let rec loop low high i =\n if i = Array.length array then low, high\n else begin\n let sl = String.length array.(i) in\n if sl < n then loop (low + 1) high (i + 1)\n else if sl = n then loop low (high + 1) (i + 1)\n else loop low high (i + 1)\n end\n in\n let low, high = loop 0 0 0 in\n low, low + high\n\nlet () =\n let n = read_int () in\n let k = read_int () in\n let array = Array.init n (fun _ ->\n read_string ()\n )\n in\n let ra = read_string () in\n let (low, high) = find array (String.length ra) in\n let a, b =\n let c = if k = 0 then 0 else high / k in\n let d = if k = 0 then 0 else low / k in\n if low = 0 then 1, (5 * c + high)\n else (5 * d + low + 1), (5 * c + high)\n in\n Printf.printf \"%d %d\" a b\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet find array n =\n let rec loop low high i =\n if i = Array.length array then low, high\n else begin\n let sl = String.length array.(i) in\n if sl < n then loop (low + 1) high (i + 1)\n else if sl = n then loop low (high + 1) (i + 1)\n else loop low high (i + 1)\n end\n in\n let low, high = loop 0 0 0 in\n low, low + high\n\nlet () =\n let n = read_int () in\n let k = read_int () in\n let array = Array.init n (fun _ ->\n read_string ()\n )\n in\n let ra = read_string () in\n let (low, high) = find array (String.length ra) in\n let a, b =\n if low = 0 then 1, (5 * (high / k) + high)\n else (5 * (low / k) + low + 1), (5 * (high / k) + high)\n in\n Printf.printf \"%d %d\" a b\n"}], "src_uid": "06898c5e25de2664895f512f6b766915"} {"nl": {"description": "One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of laptops. Next n lines contain two integers each, ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct. ", "output_spec": "If Alex is correct, print \"Happy Alex\", otherwise print \"Poor Alex\" (without the quotes).", "sample_inputs": ["2\n1 2\n2 1"], "sample_outputs": ["Happy Alex"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet make_sorted_list () = \n let n = read () in\n let rec loop i list =\n if i < n\n then\n let price = read () in\n let quality = read () in\n loop (i + 1) ((price, quality) :: list)\n else\n List.sort (Pervasives.compare) list\n in loop 0 []\n\nlet solve () = \n let notebooks = make_sorted_list () in\n let rec loop list prev_price prev_quality =\n match list with\n | ((price, quality) :: tail) ->\n if prev_quality > quality\n then\n \"Happy Alex\"\n else\n loop tail price quality\n | [] -> \"Poor Alex\"\n in loop notebooks 0 (-1)\n\n\nlet print result = Printf.printf \"%s\\n\" result\nlet () = print (solve ())"}], "negative_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet make_sorted_list () = \n let n = read () in\n let rec loop i list =\n if i < n\n then\n let price = read () in\n let quality = read () in\n loop (i + 1) ((price, quality) :: list)\n else\n List.sort (Pervasives.compare) list\n in loop 0 []\n\nlet solve () = \n let notebooks = make_sorted_list () in\n let rec loop list prev_price prev_quality =\n match list with\n | ((price, quality) :: tail) ->\n if prev_quality > quality\n then\n \"Happy Alex\"\n else\n loop tail price quality\n | [] -> \"Poor Alex\"\n in loop notebooks 0 1000001\n\n\nlet print result = Printf.printf \"%s\\n\" result\nlet () = print (solve ())"}], "src_uid": "c21a84c4523f7ef6cfa232cba8b6ee2e"} {"nl": {"description": "A string is called palindrome if it reads the same from left to right and from right to left. For example \"kazak\", \"oo\", \"r\" and \"mikhailrubinchikkihcniburliahkim\" are palindroms, but strings \"abb\" and \"ij\" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.", "input_spec": "The only line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20092\u00b7105) consisting of only lowercase Latin letters.", "output_spec": "Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.", "sample_inputs": ["aabc", "aabcd"], "sample_outputs": ["abba", "abcba"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let a = Array.make 26 0 in\n for i = 0 to n - 1 do\n let c = Char.code s.[i] - Char.code 'a' in\n\ta.(c) <- a.(c) + 1\n done;\n let res = ref [] in\n let res2 = ref [] in\n let l = ref 0 in\n let r = ref 25 in\n let odd = ref (-1) in\n (*if n mod 2 <> 0 then (\n\twhile a.(!r) mod 2 = 0 do\n\t decr r\n\tdone;\n\todd := !r;\n\ta.(!r) <- a.(!r) - 1;\n\tr := 25;\n );*)\n for i = 1 to n / 2 do\n\twhile a.(!l) = 0 do\n\t incr l\n\tdone;\n\twhile a.(!r) = 0 do\n\t decr r\n\tdone;\n(*Printf.printf \"asd %d %d %d %d\\n\" !l !r a.(!l) a.(!r);*)\n\tif a.(!l) mod 2 = 0 then (\n\t res := !l :: !res;\n\t a.(!l) <- a.(!l) - 2;\n\t) else if a.(!r) mod 2 = 0 then (\n\t res2 := !r :: !res2;\n\t a.(!r) <- a.(!r) - 2;\n\t) else (\n\t res := !l :: !res;\n\t a.(!l) <- a.(!l) - 1;\n\t a.(!r) <- a.(!r) - 1;\n\t)\n done;\n if n mod 2 <> 0 then (\n\twhile a.(!l) = 0 do\n\t incr l\n\tdone;\n\twhile a.(!r) = 0 do\n\t decr r\n\tdone;\n\tassert (!l = !r && a.(!l) = 1);\n\todd := !l;\n\ta.(!l) <- a.(!l) - 1;\n );\n let res =\n\tif n mod 2 = 0\n\tthen List.rev !res @ !res2 @ List.rev !res2 @ !res\n\telse List.rev !res @ !res2 @ [!odd] @ List.rev !res2 @ !res\n in\n\tList.iter\n\t (fun c ->\n\t Printf.printf \"%c\" (Char.chr (c + Char.code 'a'))\n\t ) res;\n\tPrintf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let a = Array.make 26 0 in\n for i = 0 to n - 1 do\n let c = Char.code s.[i] - Char.code 'a' in\n\ta.(c) <- a.(c) + 1\n done;\n let res = ref [] in\n let res2 = ref [] in\n let l = ref 0 in\n let r = ref 25 in\n let odd = ref (-1) in\n (*if n mod 2 <> 0 then (\n\twhile a.(!r) mod 2 = 0 do\n\t decr r\n\tdone;\n\todd := !r;\n\ta.(!r) <- a.(!r) - 1;\n\tr := 25;\n );*)\n for i = 1 to n / 2 do\n\twhile a.(!l) = 0 do\n\t incr l\n\tdone;\n\twhile a.(!r) = 0 do\n\t decr r\n\tdone;\n(*Printf.printf \"asd %d %d %d %d\\n\" !l !r a.(!l) a.(!r);*)\n\tif a.(!l) mod 2 = 0 then (\n\t res := !l :: !res;\n\t a.(!l) <- a.(!l) - 2;\n\t) else if a.(!r) mod 2 = 0 then (\n\t res2 := !r :: !res2;\n\t a.(!r) <- a.(!r) - 2;\n\t) else (\n\t res := !l :: !res;\n\t a.(!l) <- a.(!l) - 1;\n\t a.(!r) <- a.(!r) - 1;\n\t)\n done;\n if n mod 2 <> 0 then (\n\twhile a.(!l) = 0 do\n\t incr l\n\tdone;\n\twhile a.(!r) = 0 do\n\t decr r\n\tdone;\n\tassert (!l = !r && a.(!l) = 1);\n\todd := !l;\n\ta.(!l) <- a.(!l) - 1;\n );\n let res =\n\tif n mod 2 = 0\n\tthen List.rev !res @ List.rev !res2 @ !res2 @ !res\n\telse List.rev !res @ List.rev !res2 @ [!odd] @ !res2 @ !res\n in\n\tList.iter\n\t (fun c ->\n\t Printf.printf \"%c\" (Char.chr (c + Char.code 'a'))\n\t ) res;\n\tPrintf.printf \"\\n\"\n"}], "src_uid": "f996224809df700265d940b12622016f"} {"nl": {"description": "A Martian boy is named s \u2014 he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if s=\u00ababa\u00bb, then strings \u00abbaobab\u00bb, \u00abaabbaa\u00bb, \u00abhelloabahello\u00bb make him very happy and strings \u00abaab\u00bb, \u00abbaaa\u00bb and \u00abhelloabhello\u00bb do not.However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.", "input_spec": "The first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters. The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 106 letters.", "output_spec": "Print the sought number of ways to cut string t in two so that each part made s happy. ", "sample_inputs": ["aba\nbaobababbah", "mars\nsunvenusearthmarsjupitersaturnuranusneptune"], "sample_outputs": ["2", "0"], "notes": null}, "positive_code": [{"source_code": "let explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n\nlet _ =\n let a = explode (read_line ()) in\n let b = explode (read_line ()) in\n let rec least a b i =\n match (a, b) with\n | (x, []) -> -1\n | ([], y) -> i\n | (x :: xs, y :: ys) when x = y\n -> least xs ys (i + 1)\n | (x, y :: ys)\n -> least x ys (i + 1)\n in\n let start = least a b 0 in\n let finish = 1 + (List.length b) - least (List.rev a) (List.rev b) 0 in\n if start > finish || start = -1 || finish = -1 then\n print_endline \"0\"\n else\n print_endline (string_of_int (finish - start))\n"}], "negative_code": [], "src_uid": "724fa4b1d35b8765048857fa8f2f6802"} {"nl": {"description": "You are given an undirected weighted connected graph with $$$n$$$ vertices and $$$m$$$ edges without loops and multiple edges.The $$$i$$$-th edge is $$$e_i = (u_i, v_i, w_i)$$$; the distance between vertices $$$u_i$$$ and $$$v_i$$$ along the edge $$$e_i$$$ is $$$w_i$$$ ($$$1 \\le w_i$$$). The graph is connected, i.\u2009e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.A minimum spanning tree (MST) in case of positive weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by $$$1$$$. You can increase the weight of each edge multiple (possibly, zero) times.Suppose that the initial MST cost is $$$k$$$. Your problem is to increase weights of some edges with minimum possible number of operations in such a way that the cost of MST in the obtained graph remains $$$k$$$, but MST is unique (it means that there is only one way to choose MST in the obtained graph).Your problem is to calculate the minimum number of operations required to do it.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5, n - 1 \\le m \\le 2 \\cdot 10^5$$$) \u2014 the number of vertices and the number of edges in the initial graph. The next $$$m$$$ lines contain three integers each. The $$$i$$$-th line contains the description of the $$$i$$$-th edge $$$e_i$$$. It is denoted by three integers $$$u_i, v_i$$$ and $$$w_i$$$ ($$$1 \\le u_i, v_i \\le n, u_i \\ne v_i, 1 \\le w \\le 10^9$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices connected by the $$$i$$$-th edge and $$$w_i$$$ is the weight of this edge. It is guaranteed that the given graph doesn't contain loops and multiple edges (i.e. for each $$$i$$$ from $$$1$$$ to $$$m$$$ $$$u_i \\ne v_i$$$ and for each unordered pair of vertices $$$(u, v)$$$ there is at most one edge connecting this pair of vertices). It is also guaranteed that the given graph is connected.", "output_spec": "Print one integer \u2014 the minimum number of operations to unify MST of the initial graph without changing the cost of MST.", "sample_inputs": ["8 10\n1 2 1\n2 3 2\n2 4 5\n1 4 2\n6 3 3\n6 1 3\n3 5 2\n3 7 1\n4 8 1\n6 2 4", "4 3\n2 1 3\n4 3 4\n2 4 1", "3 3\n1 2 1\n2 3 2\n1 3 3", "3 3\n1 2 1\n2 3 3\n1 3 3", "1 0", "5 6\n1 2 2\n2 3 1\n4 5 3\n2 4 2\n1 4 2\n1 5 3"], "sample_outputs": ["1", "0", "0", "1", "0", "2"], "notes": "NoteThe picture corresponding to the first example: You can, for example, increase weight of the edge $$$(1, 6)$$$ or $$$(6, 3)$$$ by $$$1$$$ to unify MST.The picture corresponding to the last example: You can, for example, increase weights of edges $$$(1, 5)$$$ and $$$(2, 4)$$$ by $$$1$$$ to unify MST."}, "positive_code": [{"source_code": "let jajka n k = \n\tlet rzm = min (k + 1) 31 in\n\tlet a = Array.make_matrix (n + 1) rzm 0 in\n\tlet wynik = ref 0 in\n\tfor i = 1 to n do\n\t\tfor j = 1 to rzm - 1 do \n\t\t\ta.(i).(j) <- a.(i - 1).(j - 1) + a.(i - 1).(j) + 1;\n\t\t\tprint_int a.(i).(j);\n\t\t\tprint_string \" \";\n\t\t\tif a.(i).(j) >= n && !wynik = 0 then wynik := i\n\t\tdone;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik;;\n\nlet liczba () =\n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\n\nlet plecak l p =\n\tlet a = Array.make (p + 1) 0 in\n\tlet dodaj (poj, k) =\n\t\tfor i = p downto poj do \n\t\t\ta.(i) <- max a.(i) (a.(i - poj) + k)\n\t\tdone in\n\tList.iter dodaj l;\n\tArray.fold_left max 0 a;;\n\nlet repair_road t x =\n\tlet p = ref 0 in\n\tlet dl = (Array.length t) in\n\tlet wynik = ref 0 in\n\tlet odp = ref 0 in\n\tfor i = 0 to dl - 1 do\n\t\twhile !wynik <= x && !p < dl do \n\t\t\twynik := !wynik + 1 - t.(!p);\n\t\t\tincr p\n\t\tdone;\n\t\tif !wynik > x then begin\n\t\t\tdecr p;\n\t\t\twynik := !wynik - 1 + t.(!p)\n\t\tend;\n\t\todp := max (!odp) (!p - i);\n\t\twynik := !wynik - 1 + t.(i);(* \n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tprint_int !p;\n\t\tprint_endline \"\"; *)\n\tdone;\n\t!odp\n\n\nlet wczytaj () =\n\tlet n = liczba () in\n\tlet s = liczba () in\n\tlet t = Array.make n 0 in\n\tfor i = 0 to n - 1 do \n\t\tlet pole = liczba () in(* \n\t\tprint_int pole;\n\t\tprint_endline \"\"; *)\n\t\tt.(i) <- pole\n\tdone;\n\tprint_int (repair_road t s);\n\tprint_endline \"\";;\n\nlet main () =\n\tlet n = liczba () in\n\tfor i = 1 to n do\n\t\twczytaj ()\n\tdone;;\n\nlet examin x =\n\tlet sito = Array.make (x + 1) 0 in\n\tlet kolejka = Queue.create () in\n\tlet mapa = Hashtbl.create 1000000 in\n\tlet skad = Hashtbl.create 1000000 in\n\tlet prims = ref [] in\n\tfor i = 2 to x do\n\t\tprims := i :: !prims\n\tdone;\n\tlet primes = !prims in\n\tlet dodaj a = \n\t\tif sito.(a) = 0 then\n\t\tlet it = ref (a * a) in\n\t\twhile !it <= x do\n\t\t\tsito.(!it) <- a;\n\t\t\tit := !it + a\n\t\tdone in \n\tlet rec dzielniki a =\n\t\tlet akt_dziel = sito.(a) in\n\t\tif akt_dziel = 0 then [a] else\n\t\tlet aktliczba = ref a in\n\t\twhile !aktliczba mod akt_dziel = 0 do\n\t\t\taktliczba := !aktliczba / akt_dziel\n\t\tdone;\n\t\t(akt_dziel :: dzielniki !aktliczba) in\n\tList.iter dodaj primes;\n\tHashtbl.add mapa x 0;\n\tQueue.add x kolejka;\n\twhile not (Hashtbl.mem mapa 1) do\n\t\tlet gora = Queue.take kolejka in\n\t\tlet przejscia = dzielniki gora in\n\t\tlet dodaj liczba wynik = \n\t\t\tHashtbl.add mapa liczba wynik;\n\t\t\tHashtbl.add skad liczba gora;\n\t\t\tQueue.add liczba kolejka in\n\t\tlet przejdz dzielnik = \n\t\t\tif not (Hashtbl.mem mapa (gora / dzielnik)) then\n\t\t\t\tdodaj (gora / dzielnik) (Hashtbl.find mapa gora + 1) in\n\t\tList.iter przejdz przejscia;\n\t\tif not (Hashtbl.mem mapa (gora - 1)) then\n\t\t\tdodaj (gora - 1) (Hashtbl.find mapa gora + 1)\n\tdone;\n\tlet wynik = ref [] in\n\tlet akt = ref 1 in\n\twhile !akt <> x do\n\t\twynik := (!akt :: !wynik);\n\t\takt := Hashtbl.find skad !akt \n\tdone;\n\twynik := (x :: !wynik);\n\tList.rev !wynik\n\nlet to_array l = \n\tlet n = List.length l in\n\tlet tbl = Array.make n (List.hd l) in\n\tlet lista = ref l in\n\tfor i = 0 to n - 1 do\n\t\ttbl.(i) <- List.hd !lista;\n\t\tlista := List.tl !lista\n\tdone;\n\ttbl\n\nlet dbg t =\n\tArray.iter (fun x -> print_int x) t;\n\tprint_endline \"\"\n\n\nlet palindromy l =\n\tlet n = List.length l in\n\tlet l2 = l @ (List.rev l) in\n\tlet tbl = to_array l2 in\n\tlet knp = Array.make (List.length l2) 0 in \n\tfor j = 0 to 1 do\n\t\tfor i = 1 + n * j to n * (j + 1) - 1 do \n\t\t\tlet odp = ref knp.(i - 1) in\n\t\t\twhile tbl.(!odp) <> tbl.(i) && !odp <> 0 do\n\t\t\t\todp := knp.(!odp - 1)\n\t\t\tdone;\n\t\t\tif tbl.(!odp) = tbl.(i) then\n\t\t\t\tincr odp;\n\t\t\tknp.(i) <- !odp\n\t\tdone;\n\t\tif tbl.(n) = tbl.(0) then \n\t\t\tknp.(n) <- 1\n\tdone;\n\tknp.(2 * n - 1);;\n\nlet main () =\n\tlet n = liczba () in\n\tlet m = liczba () in\n\tlet kraw = Array.make (m + 1) (0, 0, 0) in\n\tfor i = 1 to m do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\tlet w = liczba () in\n\t\tkraw.(i) <- (u, v, w)\n\tdone; \n\tlet fu = Array.make (n + 1) 0 in\n\tlet rozm = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tfu.(i) <- i;\n\t\trozm.(i) <- 1\n\tdone; \n\tlet rec znajdz x =\n\t\tif fu.(x) = x then x else \n\t\t\tlet wynik = znajdz (fu.(x)) in\n\t\t\tfu.(x) <- wynik;\n\t\t\twynik in\n\tlet rec znajdz_rozm x =\n\t\tif fu.(x) = x then rozm.(x) else znajdz_rozm (fu.(x)) in\n\tlet merge (x, y, _) =\n\t\tlet v1 = znajdz x in\n\t\tlet v2 = znajdz y in\n\t\tif znajdz_rozm v1 < znajdz_rozm v2 then begin\n\t\t\tfu.(v1) <- v2;\n\t\t\trozm.(v2) <- rozm.(v2) + rozm.(v1)\n\t\tend else begin\n\t\t\tfu.(v2) <- v1;\n\t\t\trozm.(v1) <- rozm.(v1) + rozm.(v2);\n\t\tend in\n\tlet waga_kraw (_, _, w) = w in\n\tlet pierw_kraw (w, _, _) = w in\n\tlet drug_kraw (_, w, _) = w in\n\tArray.sort (fun (u1, v2, w1) (u2, v2, w2) -> w1 - w2) kraw;\n\tlet poprz_waga = ref 0 in\n\tlet lista = ref [] in\n\tlet wynik = ref (m - n + 1) in\n\tfor i = 1 to m do\n\t\tif waga_kraw kraw.(i) > !poprz_waga then begin\n\t\t\tList.iter (fun x -> merge kraw.(x)) !lista;\n\t\t\tlista := [];\n\t\t\tpoprz_waga := waga_kraw kraw.(i)\n\t\tend;\n\t\tif znajdz (pierw_kraw kraw.(i)) = znajdz (drug_kraw kraw.(i)) then\n\t\t\tdecr wynik\n\t\telse\n\t\t\tlista := (i :: !lista)\n\tdone;\n\tprint_int !wynik;;\n\nmain() ;;\n\nlet segment t =\n\tlet n = Array.length t in\n\tlet p = ref 0 in\n\tlet lista = Array.make n 0 in\n\tlet pocz = ref 0 in\n\tlet kon = ref (-1) in\n\tlet wynik = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tlet mini () =\n\t\t\tif !pocz > !kon then t.(!p) else \n\t\t\tmin t.(lista.(!pocz)) t.(!p) in\n\t\twhile !p < n && mini () >= !p - i + 1 do\n\t\t\twhile pocz <= kon && t.(lista.(!kon)) > t.(i) do\n\t\t\t\tdecr kon\n\t\t\tdone;\n\t\t\tincr kon;\n\t\t\tlista.(!kon) <- !p;\n\t\t\tincr p\n\t\tdone;\n\t\twynik := max !wynik (!p - i);\n\t\tif lista.(!pocz) = i && !pocz <= !kon then\n\t\t\tincr pocz;\n\t\tprint_int !p;\n\t\tif !p = i then\n\t\t\tincr p;\n\t\tprint_int !p;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik\n"}], "negative_code": [], "src_uid": "92afa6f770493109facb1b9ca8d94e0c"} {"nl": {"description": "Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.", "input_spec": "The first line contains two integers: n and d (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009d\u2009\u2264\u2009109). The next line contains n integers x1,\u2009x2,\u2009...,\u2009xn, their absolute value doesn't exceed 109 \u2014 the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.", "output_spec": "Print a single integer \u2014 the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["4 3\n1 2 3 4", "4 2\n-3 -2 -1 0", "5 19\n1 10 20 30 50"], "sample_outputs": ["4", "2", "1"], "notes": "NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n(* it fails because they were using a 32 bit installation instead of 64 bit *)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\nlet () = \n let n = read_int() in\n let d = read_int() in\n let x = Array.init n (fun i -> read_int()) in\n \n let rec loop l r ac = \n let r = max r (l+1) in\n if r=n then ac else (\n\tif x.(r) - x.(l) > d then loop (l+1) r ac else (\n\t if r=n-1 || x.(r+1) > x.(l) + d then (\n\t let ll = Int64.of_int l in\n\t let rr = Int64.of_int r in\n\t let ac = ac ++ ((rr--ll) ** (rr--ll--1L)) // 2L in\n\t\tloop (l+1) r ac \n\t ) else (\n\t loop l (r+1) ac\n\t )\n\t)\n )\n in\n \n Printf.printf \"%s\\n\" (Int64.to_string (loop 0 0 0L))\n \n \n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let d = read_int() in\n let x = Array.init n (fun i -> read_int()) in\n \n let rec loop l r ac = \n let r = max r (l+1) in\n if r=n then ac else (\n\tif x.(r) - x.(l) > d then loop (l+1) r ac else (\n\t if r=n-1 || x.(r+1) > x.(l) + d then (\n\t let ac = ac + ((r-l) * (r-l-1)) / 2 in\n\t\tloop (l+1) r ac \n\t ) else (\n\t loop l (r+1) ac\n\t )\n\t)\n )\n in\n \n Printf.printf \"%d\\n\" (loop 0 0 0)\n \n \n"}], "src_uid": "1f6491999bec55cb8d960181e830f4c8"} {"nl": {"description": "Polycarp has a checkered sheet of paper of size n\u2009\u00d7\u2009m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's \"Black Square\", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each \u2014 the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white.", "output_spec": "Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1.", "sample_inputs": ["5 4\nWWWW\nWWWB\nWWWB\nWWBB\nWWWW", "1 2\nBB", "3 3\nWWW\nWWW\nWWW"], "sample_outputs": ["5", "-1", "1"], "notes": "NoteIn the first example it is needed to paint 5 cells \u2014 (2,\u20092), (2,\u20093), (3,\u20092), (3,\u20093) and (4,\u20092). Then there will be a square with side equal to three, and the upper left corner in (2,\u20092).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n \n \nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let (n,m) = read_pair () in\n let board = Array.init n read_string in\n\n if forall 0 (n-1) (fun r -> forall 0 (m-1) (fun c -> board.(r).[c] = 'W')) then (\n printf \"1\\n\"\n ) else (\n let r1 = ref (n-1) in\n let r2 = ref 0 in\n let c1 = ref (m-1) in\n let c2 = ref 0 in\n for r=0 to n-1 do\n for c=0 to m-1 do\n\tif board.(r).[c] = 'B' then (\n\t r1 := min !r1 r;\n\t r2 := max !r1 r;\n\t c1 := min !c1 c;\n\t c2 := max !c2 c\n\t)\n done\n done;\n\n let dx = !c2 - !c1 + 1 in\n let dy = !r2 - !r1 + 1 in\n\n let side = max dx dy in\n\n if side > (min n m) then printf \"-1\\n\" else (\n let nblacks = sum !r1 !r2 (fun r -> sum !c1 !c2 (fun c ->\n\tif board.(r).[c] = 'B' then 1 else 0\n )) in\n printf \"%d\\n\" (side * side - nblacks)\n )\n )\n"}], "negative_code": [], "src_uid": "cd6bc23ea61c43b38c537f9e04ad11a6"} {"nl": {"description": "You are given an integer $$$n$$$. In one move, you can either multiply $$$n$$$ by two or divide $$$n$$$ by $$$6$$$ (if it is divisible by $$$6$$$ without the remainder).Your task is to find the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ or determine if it's impossible to do that.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ if it's possible to do that or -1 if it's impossible to obtain $$$1$$$ from $$$n$$$.", "sample_inputs": ["7\n1\n2\n3\n12\n12345\n15116544\n387420489"], "sample_outputs": ["0\n-1\n2\n-1\n-1\n12\n36"], "notes": "NoteConsider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $$$15116544$$$: Divide by $$$6$$$ and get $$$2519424$$$; divide by $$$6$$$ and get $$$419904$$$; divide by $$$6$$$ and get $$$69984$$$; divide by $$$6$$$ and get $$$11664$$$; multiply by $$$2$$$ and get $$$23328$$$; divide by $$$6$$$ and get $$$3888$$$; divide by $$$6$$$ and get $$$648$$$; divide by $$$6$$$ and get $$$108$$$; multiply by $$$2$$$ and get $$$216$$$; divide by $$$6$$$ and get $$$36$$$; divide by $$$6$$$ and get $$$6$$$; divide by $$$6$$$ and get $$$1$$$. "}, "positive_code": [{"source_code": "let divBy3 x =\n let rec loop acc x' =\n if x' <= 1 then Some acc\n else if (x' mod 3) = 0 then loop (acc + 1) (x' / 3)\n else None\n in loop 0 x\n\nlet divBy6 x =\n let rec loop acc x' =\n if (x' mod 6) = 0 then loop (acc + 1) (x' / 6) else acc\n in loop 0 x\n\nlet rec without6 x =\n if (x mod 6) = 0 then without6 (x / 6) else x\n\nlet solveFor x =\n match divBy3 (without6 x) with\n | None -> -1\n | Some x' -> (divBy6 x) + (x' * 2)\n\nlet read_int () = Scanf.scanf \"%d \" (fun x -> x)\n\nlet () =\n for i = 1 to (read_int ()) do\n read_int ()\n |> solveFor\n |> Printf.printf \"%d\\n\"\n done\n"}, {"source_code": "open Printf\n\nlet rec divide a b c = if a mod b = 0 then divide (a / b) b (c + 1) else (a,c)\n\nlet main =\n let n = read_int() in\n for i = 1 to n do\n let x = read_int() in\n let (y,n2) = divide x 2 0 in\n let (z,n3) = divide y 3 0 in\n if z <> 1 || n2 > n3 then\n printf \"-1\\n\"\n else \n printf \"%d\\n\" (2 * n3 - n2)\n done"}], "negative_code": [], "src_uid": "3ae468c425c7b156983414372fd35ab8"} {"nl": {"description": "The \"BerCorp\" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of employees and the number of languages. Then n lines follow \u2014 each employee's language list. At the beginning of the i-th line is integer ki (0\u2009\u2264\u2009ki\u2009\u2264\u2009m) \u2014 the number of languages the i-th employee knows. Next, the i-th line contains ki integers \u2014 aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009m) \u2014 the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.", "output_spec": "Print a single integer \u2014 the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).", "sample_inputs": ["5 5\n1 2\n2 2 3\n2 3 4\n2 4 5\n1 5", "8 7\n0\n3 1 2 3\n1 1\n2 5 4\n2 6 7\n1 3\n2 7 4\n1 1", "2 2\n1 2\n0"], "sample_outputs": ["0", "2", "1"], "notes": "NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n\n let s = Array.make n (-1) in (* the sets *)\n let rec find i = if s.(i) < 0 then i else \n let r = find s.(i) in\n s.(i) <- r;\n r\n in\n\n let union i j = (* union the two sets together, and return 1 if something happened 0 otherwise *)\n let (i,j) = ((find i), (find j)) in\n if i <> j then (\n\ts.(i) <- j;\n\t1\n ) else 0\n in\n\n let lange = Array.make m [] in\n\n let all_zero = ref true in\n\n for i=0 to n-1 do\n let numlang = read_int() in\n\tall_zero := (numlang = 0) && !all_zero;\n\tfor j=0 to numlang-1 do\n\t let lang = (read_int()) -1 in\n\t lange.(lang) <- i::(lange.(lang))\n\tdone\n done;\n\n let unioncount = ref 0 in\n\n for l=0 to m-1 do\n\tlet rec loop e llist ucount = match llist with [] -> ucount \n\t | f::llist -> loop e llist (ucount + (union e f))\n\tin\n\t if lange.(l) <> [] then \n\t let e = List.hd lange.(l) in\n\t let rest = List.tl lange.(l) in\n\t unioncount := !unioncount + (loop e rest 0)\n done;\n \n let components = n - !unioncount in\n\n (* take care of the special case when all employees no zero languages *)\n\n let answer = components -1 + (if !all_zero then 1 else 0) in\n\t\n\tPrintf.printf \"%d\\n\" answer\n \n \n"}], "negative_code": [], "src_uid": "e2836276aee2459979b232e5b29e6d57"} {"nl": {"description": "Polycarp has $$$x$$$ of red and $$$y$$$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $$$a$$$ red candies and $$$b$$$ blue candies, or $$$a$$$ blue candies and $$$b$$$ red candies. Any candy can belong to at most one gift set.Help Polycarp to find the largest number of gift sets he can create.For example, if $$$x = 10$$$, $$$y = 12$$$, $$$a = 5$$$, and $$$b = 2$$$, then Polycarp can make three gift sets: In the first set there will be $$$5$$$ red candies and $$$2$$$ blue candies; In the second set there will be $$$5$$$ blue candies and $$$2$$$ red candies; In the third set will be $$$5$$$ blue candies and $$$2$$$ red candies. Note that in this example there is one red candy that Polycarp does not use in any gift set.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single string containing four integers $$$x$$$, $$$y$$$, $$$a$$$, and $$$b$$$ ($$$1 \\le x, y, a, b \\le 10^9$$$).", "output_spec": "For each test case, output one number\u00a0\u2014 the maximum number of gift sets that Polycarp can make.", "sample_inputs": ["9\n10 12 2 5\n1 1 2 2\n52 311 13 27\n1000000000 1000000000 1 1\n1000000000 1 1 1000000000\n1 1000000000 1000000000 1\n1 2 1 1\n7 8 1 2\n4 1 2 3"], "sample_outputs": ["3\n0\n4\n1000000000\n1\n1\n1\n5\n0"], "notes": null}, "positive_code": [{"source_code": "(* 7:31 *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet sort (a,b) = if a < b then (a,b) else (b,a)\n \nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let (x,y) = sort (read_pair ()) in\n let (a,b) = sort (read_pair ()) in\n if a = b then (\n let m = min (x/a) (y/b) in\n printf \"%d\\n\" m\n ) else (\n let delxy = y-x in\n let delab = b-a in\n let z = delxy/delab in\n (* if we go beyond this many moves x becomes less than y *)\n let m = min (x/a) (y/b) in\n (* maximum number where we remove (a,b) from (x,y) *)\n let m = min m z in\n let (x,y) = sort (x - m*a, y-m*b) in\n let w = if a+b < 0 then 0 else x/(a+b) in (* overflow fix *)\n let (x,y) = sort (x-w*(a+b), y-w*(a+b)) in\n let v = if x >= a && y >= b then 1 else 0 in\n printf \"%d\\n\" (m + 2*w + v)\n ) \n done\n"}], "negative_code": [{"source_code": "(* 7:31 *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet sort (a,b) = if a < b then (a,b) else (b,a)\n \nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let (x,y) = sort (read_pair ()) in\n let (a,b) = sort (read_pair ()) in\n if a = b then (\n let m = min (x/a) (y/b) in\n printf \"%d\\n\" m\n ) else (\n let delxy = y-x in\n let delab = b-a in\n let z = delxy/delab in\n (* if we go beyond this many moves x becomes less than y *)\n let m = min (x/a) (y/b) in\n (* maximum number where we remove (a,b) from (x,y) *)\n let m = min m z in\n let (x,y) = sort (x - m*a, y-m*b) in\n let w = x/(a+b) in\n let (x,y) = sort (x-w*(a+b), y-w*(a+b)) in\n let v = if x >= a && y >= b then 1 else 0 in\n printf \"%d\\n\" (m + 2*w + v)\n ) \n done\n"}], "src_uid": "e6eb839ef4e688796050b34f1ca599a5"} {"nl": {"description": "Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000)\u00a0\u2014 then number of Famil Door's friends. Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009bi\u2009\u2264\u2009366), providing that the i-th friend can come to the party from day ai to day bi inclusive.", "output_spec": "Print the maximum number of people that may come to Famil Door's party.", "sample_inputs": ["4\nM 151 307\nF 343 352\nF 117 145\nM 24 128", "6\nM 128 130\nF 128 131\nF 131 140\nF 131 141\nM 131 200\nM 140 200"], "sample_outputs": ["2", "4"], "notes": "NoteIn the first sample, friends 3 and 4 can come on any day in range [117,\u2009128].In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () =\n let n = read_int () in\n let d = 366 in\n let deltaf = Array.make (d+1) 0 in\n let deltam = Array.make (d+1) 0 in\n\n for i=0 to n-1 do\n let darray = if read_string () = \"M\" then deltam else deltaf in\n let st = -1 + read_int() in\n let ed = -1 + read_int() in\n darray.(st) <- darray.(st) + 1;\n darray.(ed+1) <- darray.(ed+1) - 1; \n done;\n\n let rec loop i nmale nfemale best =\n let nmale = deltam.(i) + nmale in\n let nfemale = deltaf.(i) + nfemale in\n let best = max best (2 * (min nmale nfemale)) in\n if i = d then best else loop (i+1) nmale nfemale best\n in\n\n printf \"%d\\n\" (loop 0 0 0 0)\n\n \n"}], "negative_code": [], "src_uid": "75d500bad37fbd2c5456a942bde09cd3"} {"nl": {"description": "There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet \u2014 the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations: alloc n \u2014 to allocate n bytes of the memory and return the allocated block's identifier x; erase x \u2014 to erase the block with the identifier x; defragment \u2014 to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.", "input_spec": "The first line of the input data contains two positive integers t and m (1\u2009\u2264\u2009t\u2009\u2264\u2009100;1\u2009\u2264\u2009m\u2009\u2264\u2009100), where t \u2014 the amount of operations given to the memory manager for processing, and m \u2014 the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment. ", "output_spec": "Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.", "sample_inputs": ["6 10\nalloc 5\nalloc 3\nerase 1\nalloc 6\ndefragment\nalloc 6"], "sample_outputs": ["1\n2\nNULL\n3"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_int32 _ = Scanf.bscanf Scanf.Scanning.stdib \" %ld\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\n\nopen Int32\n\nlet () =\n let m = read_int 0 in\n let n = read_int 0 in\n let allo = ref 0l\n and a = Array.make n (0l,0) in\n for cc = 1 to m do\n let op = read_str 0 in\n match op.[0] with\n | 'a' ->\n let v = read_int 0 in\n let rec go i c =\n if c >= v then\n i-v\n else if i >= n then\n -1\n else\n go (i+1) (if fst a.(i) = 0l then c+1 else 1-snd a.(i))\n in\n let r = go 0 0 in\n if r < 0 then\n print_endline \"NULL\"\n else (\n allo := add !allo 1l;\n a.(r) <- !allo, v;\n Printf.printf \"%ld\\n\" !allo;\n )\n | 'e' ->\n let v = read_int32 0 in\n let rec go i =\n if i >= n then\n -1\n else if fst a.(i) = v then\n i\n else\n go (i+1)\n in\n let r = go 0 in\n if v <= 0l || r < 0 then\n print_endline \"ILLEGAL_ERASE_ARGUMENT\"\n else\n a.(r) <- 0l, 0\n | 'd' ->\n let rec go i j =\n if i < n then\n if fst a.(i) = 0l then\n go (i+1) j\n else (\n a.(j) <- a.(i);\n for jj = j+1 to j+snd a.(j)-1 do\n a.(jj) <- 0l, 0\n done;\n go (i+1) (j+snd a.(j))\n )\n else if j < n then (\n a.(j) <- 0l, 0;\n go n (j+1)\n )\n in\n go 0 0\n done\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_int32 _ = Scanf.bscanf Scanf.Scanning.stdib \" %ld \" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nopen Int32\n\nlet () =\n let m = read_int 0 in\n let n = read_int 0 in\n let allo = ref 0l\n and a = Array.make n (0l,0) in\n for cc = 1 to m do\n let op = read_str 0 in\n match op.[0] with\n | 'a' ->\n let v = read_int 0 in\n let rec go i c =\n if c >= v then\n i-v\n else if i >= n then\n -1\n else\n go (i+1) (if fst a.(i) = 0l then c+1 else 1-snd a.(i))\n in\n let r = go 0 0 in\n if r < 0 then\n print_endline \"NULL\"\n else (\n allo := add !allo 1l;\n a.(r) <- !allo, v;\n Printf.printf \"%ld\\n\" !allo;\n )\n | 'e' ->\n let v = read_int32 0 in\n let rec go i =\n if i >= n then\n -1\n else if fst a.(i) = v then\n i\n else\n go (i+1)\n in\n let r = go 0 in\n if r < 0 then\n print_endline \"ILLEGAL_ERASE_ARGUMENT\"\n else\n a.(r) <- 0l, 0\n | 'd' ->\n let rec go i j =\n if i < n then\n if fst a.(i) = 0l then\n go (i+1) j\n else (\n a.(j) <- a.(i);\n for jj = j+1 to j+snd a.(i)-1 do\n a.(jj) <- 0l, 0\n done;\n go (i+1) (j+snd a.(i))\n )\n else if j < n then (\n a.(j) <- 0l, 0;\n go n (j+1)\n )\n in\n go 0 0\n done\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_int32 _ = Scanf.bscanf Scanf.Scanning.stdib \" %ld \" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nopen Int32\n\nlet () =\n let m = read_int 0 in\n let n = read_int 0 in\n let allo = ref 0l\n and a = Array.make n (0l,0) in\n for cc = 1 to m do\n let op = read_str 0 in\n match op.[0] with\n | 'a' ->\n let v = read_int 0 in\n let rec go i c =\n if c >= v then\n i-v\n else if i >= n then\n -1\n else\n go (i+1) (if fst a.(i) = 0l then c+1 else 1-snd a.(i))\n in\n let r = go 0 0 in\n if r < 0 then\n print_endline \"NULL\"\n else (\n allo := add !allo 1l;\n a.(r) <- !allo, v;\n Printf.printf \"%ld\\n\" !allo;\n )\n | 'e' ->\n let v = read_int32 0 in\n let rec go i =\n if i >= n then\n -1\n else if fst a.(i) = v then\n i\n else\n go (i+1)\n in\n let r = go 0 in\n if r < 0 then\n print_endline \"ILLEGAL_ERASE_ARGUMENT\"\n else\n a.(r) <- 0l, 0\n | 'd' ->\n let rec go i j =\n if i < n then\n if fst a.(i) = 0l then\n go (i+1) j\n else (\n a.(j) <- a.(i);\n for jj = j+1 to j+snd a.(i)-1 do\n a.(j) <- 0l, 0\n done;\n go (i+1) (j+snd a.(i))\n )\n else if j < n then (\n a.(j) <- 0l, 0;\n go n (j+1)\n )\n in\n go 0 0\n done\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_int32 _ = Scanf.bscanf Scanf.Scanning.stdib \" %ld \" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nopen Int32\n\nlet () =\n let m = read_int 0 in\n let n = read_int 0 in\n let allo = ref 0l\n and a = Array.make n (0l,0) in\n for cc = 1 to m do\n let op = read_str 0 in\n match op.[0] with\n | 'a' ->\n let v = read_int 0 in\n let rec go i c =\n if c >= v then\n i-v\n else if i >= n then\n -1\n else\n go (i+1) (if fst a.(i) = 0l then c+1 else 1-snd a.(i))\n in\n let r = go 0 0 in\n if r < 0 then\n print_endline \"NULL\"\n else (\n allo := add !allo 1l;\n a.(r) <- !allo, v;\n Printf.printf \"%ld\\n\" !allo;\n )\n | 'e' ->\n let v = read_int32 0 in\n let rec go i =\n if i >= n then\n -1\n else if fst a.(i) = v then\n i\n else\n go (i+1)\n in\n let r = go 0 in\n if r < 0 then\n print_endline \"ILLEGAL_ERASE_ARGUMENT\"\n else\n a.(r) <- 0l, 0\n | 'd' ->\n let rec go i j =\n if i < n then\n if fst a.(i) = 0l then\n go (i+1) j\n else (\n a.(j) <- a.(i);\n for jj = j+1 to j+snd a.(j)-1 do\n a.(jj) <- 0l, 0\n done;\n go (i+1) (j+snd a.(j))\n )\n else if j < n then (\n a.(j) <- 0l, 0;\n go n (j+1)\n )\n in\n go 0 0\n done\n"}], "src_uid": "a6cba17c5ddb93f6741e00280fb6c54c"} {"nl": {"description": "Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string \"0011\" and string \"0110\" is |0\u2009-\u20090|\u2009+\u2009|0\u2009-\u20091|\u2009+\u2009|1\u2009-\u20091|\u2009+\u2009|1\u2009-\u20090|\u2009=\u20090\u2009+\u20091\u2009+\u20090\u2009+\u20091\u2009=\u20092.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.", "input_spec": "The first line of the input contains binary string a (1\u2009\u2264\u2009|a|\u2009\u2264\u2009200\u2009000). The second line of the input contains binary string b (|a|\u2009\u2264\u2009|b|\u2009\u2264\u2009200\u2009000). Both strings are guaranteed to consist of characters '0' and '1' only.", "output_spec": "Print a single integer\u00a0\u2014 the sum of Hamming distances between a and all contiguous substrings of b of length |a|.", "sample_inputs": ["01\n00111", "0011\n0110"], "sample_outputs": ["3", "2"], "notes": "NoteFor the first sample case, there are four contiguous substrings of b of length |a|: \"00\", \"01\", \"11\", and \"11\". The distance between \"01\" and \"00\" is |0\u2009-\u20090|\u2009+\u2009|1\u2009-\u20090|\u2009=\u20091. The distance between \"01\" and \"01\" is |0\u2009-\u20090|\u2009+\u2009|1\u2009-\u20091|\u2009=\u20090. The distance between \"01\" and \"11\" is |0\u2009-\u20091|\u2009+\u2009|1\u2009-\u20091|\u2009=\u20091. Last distance counts twice, as there are two occurrences of string \"11\". The sum of these edit distances is 1\u2009+\u20090\u2009+\u20091\u2009+\u20091\u2009=\u20093.The second sample case is described in the statement."}, "positive_code": [{"source_code": "let v s i = int_of_char( s.[i] ) - 48 ;;\nlet a, b = Scanf.scanf \"%s %s\" (fun a b -> (a,b)) ;;\n\nlet rec bsum = function\n | 0 -> 0\n | i -> (v b (i-1) ) + bsum (i-1)\n;;\nlet cmplen = String.length b - String.length a ;;\nlet (+^), to64 = Int64.(add, of_int) ;;\nlet rec f i cs =\n if i = String.length a\n then 0L\n else let cs2 = cs + v b (cmplen+i) in\n to64 (if v a i = 0 then cs2 else cmplen+1-cs2)\n +^ f (i+1) (cs2 - v b i)\n;;\nPrintf.printf \"%Ld\" (f 0 (bsum cmplen))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\t\t\t\t \nlet () = \n let a = read_string () in\n let b = read_string () in\n\n let n = String.length a in\n let m = String.length b in \n\n let a = Array.init n (fun i -> if a.[i] = '1' then 1 else 0) in\n let b = Array.init m (fun i -> if b.[i] = '1' then 1 else 0) in \n\n let sigma = Array.make (m+1) 0 in\n\n for i=1 to m do\n sigma.(i) <- sigma.(i-1) + b.(i-1)\n done;\n\n (* sigma.(x) = sum of b's from b.(0) to b.(x-1) *)\n\n let sum_range i j = sigma.(j+1) - sigma.(i) in\n\n let answer = sum 0 (n-1) (fun i ->\n let first = i in\n let last = m-n+i in\n let nones = sum_range first last in\n long (if a.(i) = 1 then (last-first+1) - nones else nones)\n ) 0L in\n\n printf \"%Ld\\n\" answer\n \n\n \n \n"}], "negative_code": [{"source_code": "let v s i = int_of_char( s.[i] ) - 48 ;;\nlet a, b = Scanf.scanf \"%s %s\" (fun a b -> (a,b)) ;;\n\nlet rec bsum = function\n | 0 -> 0\n | i -> (v b (i-1) ) + bsum (i-1)\n;;\nlet cmplen = String.length b - String.length a ;;\n\nlet rec f i cs =\n if i = String.length a\n then 0\n else let cs2 = cs + v b (cmplen+i) in\n (if v a i = 0 then cs2 else cmplen+1-cs2)\n + f (i+1) (cs2 - v b i)\n;;\nprint_int @@ f 0 (bsum cmplen)\n"}], "src_uid": "ed75bd272f6d3050426548435423ca92"} {"nl": {"description": "Little Vasya has received a young builder\u2019s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.", "input_spec": "The first line contains an integer N (1\u2009\u2264\u2009N\u2009\u2264\u20091000) \u2014 the number of bars at Vasya\u2019s disposal. The second line contains N space-separated integers li \u2014 the lengths of the bars. All the lengths are natural numbers not exceeding 1000.", "output_spec": "In one line output two numbers \u2014 the height of the largest tower and their total number. Remember that Vasya should use all the bars.", "sample_inputs": ["3\n1 2 3", "4\n6 5 6 7"], "sample_outputs": ["1 3", "2 3"], "notes": null}, "positive_code": [{"source_code": "module Int = struct\n\tlet compare = compare\n\ttype t = int\nend;;\n\nmodule IntMap = Map.Make(Int);;\n\nlet rec solve i bruski =\n\tif i = 0 then (\n\t\tlet l = IntMap.fold (fun _ _ l -> l + 1) bruski 0 in\n\t\tlet max = IntMap.fold (fun _ h m -> max h m) bruski 0 in\n\t\tPrintf.printf \"%d %d\" max l\n\t) else (\n\t\tlet w = Scanf.scanf \" %d\" (fun i->i) in\n\t\tlet nbruski = IntMap.add w ((if IntMap.mem w bruski \n\t\t\tthen IntMap.find w bruski else 0) + 1) bruski in\n\t\tsolve (i-1) nbruski\n\t)\n;;\n\nlet () =\n\tsolve (read_int()) IntMap.empty\n;;\n"}, {"source_code": "open Scanf;;\nlet scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int() and maxN = 1007;;\nlet tab = Array.make maxN 0;;\n\nfor i = 1 to n do\n let x = scan_int() in\n tab.(x) <- (tab.(x) + 1);\ndone;;\n\nlet cnt = ref 0 and maxik = ref 0;;\nfor i = 1 to (maxN - 1) do\n cnt := (!cnt + b2i(tab.(i) > 0));\n maxik := max (!maxik) tab.(i); \ndone;;\n\nprint_int !maxik; psp(); print_int !cnt;\n"}], "negative_code": [], "src_uid": "9a92221c760a3b6a1e9318f948fe0473"} {"nl": {"description": "There are n stone quarries in Petrograd.Each quarry owns mi dumpers (1\u2009\u2264\u2009i\u2009\u2264\u2009n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi\u2009+\u20091 stones in it, the third has xi\u2009+\u20092, and the mi-th dumper (the last for the i-th quarry) has xi\u2009+\u2009mi\u2009-\u20091 stones in it.Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses.Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone \u00abtolik\u00bb and the other one \u00abbolik\u00bb.", "input_spec": "The first line of the input contains one integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1\u2009\u2264\u2009xi,\u2009mi\u2009\u2264\u20091016) \u2014 the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry.", "output_spec": "Output \u00abtolik\u00bb if the oligarch who takes a stone first wins, and \u00abbolik\u00bb otherwise.", "sample_inputs": ["2\n2 1\n3 2", "4\n1 1\n1 1\n1 1\n1 1"], "sample_outputs": ["tolik", "bolik"], "notes": null}, "positive_code": [{"source_code": "let [zer;on;two;fou] = List.map Big_int.big_int_of_int [0;1;2;4]\n\n\nlet (+) = Big_int.add_big_int\nlet (-) = Big_int.sub_big_int\nlet ( * ) = Big_int.mult_big_int\nlet (mod) = Big_int.mod_big_int\nlet (=) = Big_int.eq_big_int\nlet (<=) a b = Big_int.compare_big_int a b <= 0\n\nlet xor_betw a b =\n let x = ref (a * (a mod two)) in\n let beg = ref (b + (a mod two) - ((b-a) mod fou)) in\n while !beg <= b do\n x := Big_int.xor_big_int !beg !x;\n beg := !beg + on;\n done;\n !x\n\nlet main () =\n let n = Scanf.scanf \"%d\" (fun i -> i) and a = ref zer in\n for i = 1 to n do\n Scanf.scanf \" %s %s\" (fun x' m' ->\n let [x;m] = List.map Big_int.big_int_of_string [x';m'] in\n a := Big_int.xor_big_int !a (xor_betw x (x+m-on)));\n done;\n print_endline (if !a = zer then \"bolik\" else \"tolik\");;\n\nmain ();;\n"}, {"source_code": "let [zer;on;two;fou] = List.map Big_int.big_int_of_int [0;1;2;4]\n\n\nlet (+) = Big_int.add_big_int\nlet (-) = Big_int.sub_big_int\nlet ( * ) = Big_int.mult_big_int\nlet (mod) = Big_int.mod_big_int\nlet (=) = Big_int.eq_big_int\nlet (<=) a b = Big_int.compare_big_int a b <= 0\n\nlet xor_betw a b =\n let x = ref (a * (a mod two)) in\n let beg = ref (b + (a mod two) - ((b-a) mod fou)) in\n while !beg <= b do\n x := Big_int.xor_big_int !beg !x;\n beg := !beg + on;\n done;\n !x\n\nlet main () =\n let n = Scanf.scanf \"%d\" (fun i -> i) and a = ref zer in\n for i = 1 to n do\n Scanf.scanf \" %s %s\" (fun x' m' ->\n let [x;m] = List.map Big_int.big_int_of_string [x';m'] in\n a := Big_int.xor_big_int !a (xor_betw x (x+m-on)));\n done;\n print_endline (if !a = zer then \"bolik\" else \"tolik\");;\n\nmain ();;"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\nlet (|>) x f = f x\n\nopen Int64\n\nlet () =\n let z = ref 0L in\n for i = 1 to read_int 0 do\n let x = read_int64 0 |> ref in\n let y = read_int64 0 |> ref in\n y := add !y !x;\n while !x < !y && rem !x 4L <> 0L do\n z := logxor !z !x;\n x := add !x 1L\n done;\n while !x < !y && rem !y 4L <> 0L do\n y := sub !y 1L;\n z := logxor !z !y\n done\n done;\n print_endline (if !z <> 0L then \"tolik\" else \"bolik\")\n"}], "negative_code": [{"source_code": "let xor_betw a b =\n let x = ref 0 in\n if a mod 2 = 1 then x := a;\n for i = b + 1 - ((b-a) mod 4) to b do\n x := i lxor !x;\n done;\n !x\n\nlet main () =\n let n = Scanf.scanf \"%d\" (fun i -> i) and a = ref 0 in\n for i = 1 to n do\n Scanf.scanf \" %d %d\" (fun x m->a := !a lxor (xor_betw x (x+m-1)));\n done;\n print_endline (if !a = 0 then \"bolik\" else \"tolik\");;\n\nmain ();;\n"}, {"source_code": "let n = Scanf.scanf \"%d\" (fun i -> i) and res = ref 0 in\n for i=1 to n-1 do\n Scanf.scanf \" %s\"\n (fun w -> res := !res + int_of_char (w.[String.length w - 1]));\n done;\nPrintf.printf (if !res mod 2 = 0 then \"bolik\" else \"tolik\");;\n"}, {"source_code": "let n = Scanf.scanf \"%d\" (fun i -> i) and res = ref 0 in\n for i=1 to n do\n Scanf.scanf \" %s %s\"\n (fun _ w -> res := !res + int_of_char (w.[String.length w - 1]));\n done;\nPrintf.printf (if !res mod 2 = 0 then \"bolik\" else \"tolik\");;\n"}, {"source_code": "let n = Scanf.scanf \"%d\" (fun i -> i) and res = ref 0 in\n for i=1 to n do\n Scanf.scanf \" %s\"\n (fun w -> res := !res + int_of_char (w.[String.length w - 1]));\n done;\nPrintf.printf (if !res mod 2 = 0 then \"bolik\" else \"tolik\");;\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let z = ref 0 in\n for i = 1 to read_int 0 do\n let x = read_int 0 |> ref in\n let y = read_int 0 |> ref in\n y := !y + !x;\n while !x < !y && !x mod 4 <> 0 do\n z := !z + !x;\n incr x\n done;\n while !x < !y && !y mod 4 <> 0 do\n decr y;\n z := !z + !y\n done\n done;\n print_endline (if !z <> 0 then \"tolik\" else \"bolik\")\n"}], "src_uid": "55099493c66b003d4261310bf2cc8f93"} {"nl": {"description": "While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $$$H$$$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $$$L$$$ centimeters. Exactly at this point the flower touched the water surface. Suppose that the lily grows at some point $$$A$$$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $$$A$$$. Also suppose that initially the flower was exactly above the point $$$A$$$, i.e. its stem was vertical. Can you determine the depth of the lake at point $$$A$$$?", "input_spec": "The only line contains two integers $$$H$$$ and $$$L$$$ ($$$1 \\le H < L \\le 10^{6}$$$).", "output_spec": "Print a single number\u00a0\u2014 the depth of the lake at point $$$A$$$. The absolute or relative error should not exceed $$$10^{-6}$$$. Formally, let your answer be $$$A$$$, and the jury's answer be $$$B$$$. Your answer is accepted if and only if $$$\\frac{|A - B|}{\\max{(1, |B|)}} \\le 10^{-6}$$$.", "sample_inputs": ["1 2", "3 5"], "sample_outputs": ["1.5000000000000", "2.6666666666667"], "notes": null}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet solve h l =\n (l ** 2. -. h ** 2.) /. (2. *. h)\n\nlet main () =\n let (h, l) = scanf \" %f %f\" (fun h l -> (h, l)) in\n printf \"%f\\n\" (solve h l)\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "2cd5807e3f9685d4eff88f2283904f0d"} {"nl": {"description": "Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), which represents how many numbers the array has. The next line contains n space-separated integers \u2014 the array's description. All elements of the array lie in the range from 1 to 109, inclusive.", "output_spec": "Print n space-separated integers \u2014 the minimum possible values of each array element after one replacement and the sorting are performed.", "sample_inputs": ["5\n1 2 3 4 5", "5\n2 3 4 5 6", "3\n2 2 2"], "sample_outputs": ["1 1 2 3 4", "1 2 3 4 5", "1 2 2"], "notes": null}, "positive_code": [{"source_code": "(*************** Ocaml stdio functions **********************)\nlet stdin_stream = Stream.of_channel stdin;;\nlet stdout_buffer = Buffer.create 65536;;\nlet rec gi() =\n match Stream.next stdin_stream with\n '-' -> - (ri 0)\n | '+' -> ri 0\n | '0'..'9' as c -> ri ((int_of_char c) - 48)\n | _ -> gi ()\nand ri x =\n match Stream.next stdin_stream with\n '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))\n | _ -> x\n;;\nlet flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;\nlet putchar c =\n if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();\n Buffer.add_char stdout_buffer c;;\nlet rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;\nlet pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));;\nlet pa a = let n = Array.length a in Array.iteri (fun i j -> pi j; putchar (if i == (n-1) then '\\n' else ' ')) a;;\n(*************** Ocaml solution ******************************)\nopen Array\nlet main() =\n let n = gi() in\n let a = init (n+1) (fun i -> if i > 0 then gi() else 1) in\n stable_sort compare a;\n if a.(n) == 1 then a.(n-1) <- 2 else ();\n pa (sub a 0 n)\n ;;\nmain();;\nflushout ()"}, {"source_code": "open Array\nopen Scanf\nlet main() =\n let s = stable_sort (-) in\n let gi() = bscanf Scanning.stdib \" %d\" (fun x -> x) in\n let n = gi () in\n let a = init n (fun i -> gi ()) in\n s a;\n a.(n-1) <- if fold_left (&&) true (map ((==) 1) a) then 2 else 1;\n s a;\n iter (Printf.printf \"%d \") a\n ;;\nmain()"}, {"source_code": "(*************** Ocaml stdio functions **********************)\nlet stdin_stream = Stream.of_channel stdin;;\nlet stdout_buffer = Buffer.create 65536;;\nlet rec gi() =\n match Stream.next stdin_stream with\n '-' -> - (ri 0)\n | '+' -> ri 0\n | '0'..'9' as c -> ri ((int_of_char c) - 48)\n | _ -> gi ()\nand ri x =\n match Stream.next stdin_stream with\n '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))\n | _ -> x\n;;\nlet flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;\nlet putchar c =\n if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();\n Buffer.add_char stdout_buffer c;;\nlet rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;\nlet pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));; \n(*************** Ocaml solution ******************************)\nopen Array\nlet main() =\n let n = gi() in\n let a = init (n+1) (fun i -> if i > 0 then gi() else 1) in\n stable_sort compare a;\n if a.(n) == 1 then a.(n-1) <- 2 else ();\n iteri (fun i j -> pi j; putchar (if i == (n-1) then '\\n' else ' ')) (sub a 0 n)\n ;;\nmain();;\nflushout ()"}, {"source_code": "open Array\nlet main() =\n let s = stable_sort (-) in\n let gi() = Scanf.scanf \" %d\" (fun i -> i) in\n let n = gi () in\n let a = init n (fun i -> gi ()) in\n s a;\n a.(n-1) <- if fold_left (&&) true (map ((==) 1) a) then 2 else 1;\n s a;\n iter (Printf.printf \"%d \") a\n ;;\nmain()"}, {"source_code": " let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n a.(i) <- k\n done;\n Array.sort compare a;\n a.(n - 1) <-\n if a.(n - 1) > 1\n then 1\n else 2;\n Array.sort compare a;\n for i = 0 to n - 1 do\n Printf.printf \"%d \" a.(i);\n done;\n Printf.printf \"\\n\""}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n let k = getnum () in\n\ta.(i) <- k\n done;\n Array.sort compare a;\n a.(n - 1) <-\n if a.(n - 1) > 1\n then 1\n else 2;\n Array.sort compare a;\n for i = 0 to n - 1 do\n Printf.printf \"%d \" a.(i);\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "try (\n let a = Array.make 1 1 in\n Printf.printf \"1 1 2 3 \";\n a.(10) <- 4;\n Printf.printf \"%d\\n\" (a.(10))\n )\nwith\n_ -> exit 1"}, {"source_code": "open Sys\nlet rec pa = function\n [] -> ()\n | (x::xs) -> (Printf.printf \"%s\\n\" x; pa xs)\n ;;\nPrintf.printf \"word_size = %d\\n\" word_size;;\nPrintf.printf \"max_string_length = %d\\n\" max_string_length;;\nPrintf.printf \"max_array_length = %d\\n\" max_array_length;;\nPrintf.printf \"os_type = %s\\n\" os_type;;\nPrintf.printf \"ocaml_version = %s\\n\" ocaml_version"}, {"source_code": "let a = Array.make 1 1 in\na.(10) <- 239\n"}, {"source_code": " Printf.printf \"%s\\n\" (Str.quote \"abacaba\")"}, {"source_code": " let a = Array.make 1 1;;\n Printf.printf \"1 1 2 3 \";;\n a.(10000) <- 4;;\n Printf.printf \"%d\\n\" (a.(10000))"}, {"source_code": "exit 1"}, {"source_code": "let a = Array.make 1 1;;\nPrintf.printf \"1 1 2 3 \";;\na.(10) <- 4;;\nPrintf.printf \"%d\\n\" (a.(10))"}], "src_uid": "1cd10f01347d869be38c08ad64266870"} {"nl": {"description": "One day Natalia was walking in the woods when she met a little mushroom gnome. The gnome told her the following story:Everybody knows that the mushroom gnomes' power lies in the magic mushrooms that grow in the native woods of the gnomes. There are n trees and m magic mushrooms in the woods: the i-th tree grows at a point on a straight line with coordinates ai and has the height of hi, the j-th mushroom grows at the point with coordinates bj and has magical powers zj.But one day wild mushroommunchers, the sworn enemies of mushroom gnomes unleashed a terrible storm on their home forest. As a result, some of the trees began to fall and crush the magic mushrooms. The supreme oracle of mushroom gnomes calculated in advance the probability for each tree that it will fall to the left, to the right or will stand on. If the tree with the coordinate x and height h falls to the left, then all the mushrooms that belong to the right-open interval [x\u2009-\u2009h,\u2009x), are destroyed. If a tree falls to the right, then the mushrooms that belong to the left-open interval (x,\u2009x\u2009+\u2009h] are destroyed. Only those mushrooms that are not hit by a single tree survive.Knowing that all the trees fall independently of each other (i.e., all the events are mutually independent, and besides, the trees do not interfere with other trees falling in an arbitrary direction), the supreme oracle was also able to quickly calculate what would be the expectation of the total power of the mushrooms which survived after the storm. His calculations ultimately saved the mushroom gnomes from imminent death.Natalia, as a good Olympiad programmer, got interested in this story, and she decided to come up with a way to quickly calculate the expectation of the sum of the surviving mushrooms' power.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009m\u2009\u2264\u2009104) \u2014 the number of trees and mushrooms, respectively. Each of the next n lines contain four integers \u2014 ai, hi, li, ri (|ai|\u2009\u2264\u2009109, 1\u2009\u2264\u2009hi\u2009\u2264\u2009109, 0\u2009\u2264\u2009li,\u2009ri,\u2009li\u2009+\u2009ri\u2009\u2264\u2009100) which represent the coordinate of the i-th tree, its height, the percentage of the probabilities that the tree falls to the left and to the right, respectively (the remaining percentage is the probability that the tree will stand on). Each of next m lines contain two integers bj, zj (|bj|\u2009\u2264\u2009109, 1\u2009\u2264\u2009zj\u2009\u2264\u2009103) which represent the coordinate and the magical power of the j-th mushroom, respectively. An arbitrary number of trees and mushrooms can grow in one point.", "output_spec": "Print a real number \u2014 the expectation of the total magical power of the surviving mushrooms. The result is accepted with relative or absolute accuracy 10\u2009-\u20094.", "sample_inputs": ["1 1\n2 2 50 50\n1 1", "2 1\n2 2 50 50\n4 2 50 50\n3 1"], "sample_outputs": ["0.5000000000", "0.2500000000"], "notes": "NoteIt is believed that the mushroom with the coordinate x belongs to the right-open interval [l,\u2009r) if and only if l\u2009\u2264\u2009x\u2009<\u2009r. Similarly, the mushroom with the coordinate x belongs to the left-open interval (l,\u2009r] if and only if l\u2009<\u2009x\u2009\u2264\u2009r.In the first test the mushroom survives with the probability of 50%, depending on where the single tree falls.In the second test the mushroom survives only if neither of the two trees falls on it. It occurs with the probability of 50% \u2009\u00d7\u2009 50% = 25%.Pretest \u211612 is the large test with 105 trees and one mushroom."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\ntype event = Mu of int | TS of int | TE of int\n\nlet n = read_int()\nlet m = read_int()\n\nlet trees = Array.make n (0,0,0,0)\nlet mushs = Array.make m (0,0.0)\n\nlet events = ref []\n\nlet () =\n for i=0 to n-1 do\n let a = read_int() in\n let h = read_int() in\n let left = read_int() in\n let right = read_int() in\n trees.(i) <- (a, h, 100-right, 100-left);\n events := (TS(i))::!events;\n events := (TE(i))::!events;\n done\n\nlet () =\n for j=0 to m-1 do\n let b = read_int() in\n let z = read_int() in\n mushs.(j) <- (b,float z);\n events := (Mu(j))::!events\n done\n\nlet comp dir e1 e2 = \n let place = function\n | Mu(i) -> fst mushs.(i)\n | TE(i) -> let (a,h,_,_) = trees.(i) in a + dir*h \n | TS(i) -> let (a,_,_,_) = trees.(i) in a\n in\n let (p1, p2) = (place e1, place e2) in\n let c = compare p1 p2 in\n if c<>0 then dir*c else\n match e1 with Mu(_) -> -1 | _ -> (match e2 with Mu(_) -> 1 | _ -> 0)\n\nlet rec power a i = \n if i=0 then 1.0 \n else let p = power a (i/2) in\n p *. p *. (if i land 1 = 0 then 1.0 else a)\n\nlet scan dir pa li = \n let hist = Array.make 101 0 in\n let rec eval i ac = \n if i=101 then ac else eval (i+1) (ac *. (power ((float i) /. 100.0) hist.(i)))\n in\n let percent i = let (_,_,p,q) = trees.(i) in if dir=1 then p else q in\n let update i d = let j = percent i in hist.(j) <- hist.(j) + d in\n List.iter (\n function \n\t| Mu(j) -> pa.(j) <- eval 0 1.0\n\t| TS(i) -> update i 1\n\t| TE(i) -> update i (-1)\n ) li\n\nlet plr = Array.make m 0.0\nlet prl = Array.make m 0.0\n\nlet () = scan 1 plr (List.sort (comp 1) !events)\nlet () = scan (-1) prl (List.sort (comp (-1)) !events)\n\nlet rec sum j ac = \n if j=m then ac \n else sum (j+1) (ac +. plr.(j) *. prl.(j) *. (snd mushs.(j)))\n\nlet () = Printf.printf \"%f\" (sum 0 0.0)\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\ntype event = Mu of int | TS of int | TE of int\n\nlet n = read_int()\nlet m = read_int()\n\nlet trees = Array.make n (0,0,0.0,0.0)\nlet mushs = Array.make m (0,0.0)\n\nlet events = ref []\n\nlet toprob i = (float i) /. 100.0\n\nlet () =\n for i=0 to n-1 do\n let a = read_int() in\n let h = read_int() in\n let left = read_int() in\n let right = read_int() in\n trees.(i) <- (a, h, toprob (100-right), toprob (100-left));\n events := (TS(i))::!events;\n events := (TE(i))::!events;\n done\n\nlet () =\n for j=0 to m-1 do\n let b = read_int() in\n let z = read_int() in\n mushs.(j) <- (b,float z);\n events := (Mu(j))::!events\n done\n\n\nlet comp dir e1 e2 = \n let place = function\n | Mu(i) -> fst mushs.(i)\n | TE(i) -> let (a,h,_,_) = trees.(i) in a + dir*h \n | TS(i) -> let (a,_,_,_) = trees.(i) in a\n in\n let (p1, p2) = (place e1, place e2) in\n let c = compare p1 p2 in\n if c<>0 then dir*c else\n match e1 with Mu(_) -> -1 | _ -> (match e2 with Mu(_) -> 1 | _ -> 0)\n\nlet rec scan dir pa li openp = \n let prob i = let (_,_,p,q) = trees.(i) in if dir=1 then p else q in\n match li with \n | [] -> ()\n | (Mu(j))::tail -> pa.(j) <- openp; scan dir pa tail openp\n | (TS(i))::tail -> scan dir pa tail (openp *. (prob i))\n | (TE(i))::tail -> scan dir pa tail (openp /. (prob i))\n\nlet plr = Array.make m 0.0\nlet prl = Array.make m 0.0\n\nlet () = scan 1 plr (List.sort (comp 1) !events) 1.0\nlet () = scan (-1) prl (List.sort (comp (-1)) !events) 1.0\n\nlet rec sum j ac = \n if j=m then ac \n else sum (j+1) (ac +. plr.(j) *. prl.(j) *. (snd mushs.(j)))\n\nlet () = Printf.printf \"%f\" (sum 0 0.0)\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\ntype event = Mu of int | TS of int | TE of int\n\nlet n = read_int()\nlet m = read_int()\n\nlet trees = Array.make n (0,0,0.0,0.0)\nlet mushs = Array.make m (0,0)\n\nlet events = ref []\n\nlet toprob i = (float i) /. 100.0\n\nlet () =\n for i=0 to n-1 do\n let a = read_int() in\n let h = read_int() in\n let left = read_int() in\n let right = read_int() in\n trees.(i) <- (a, h, toprob (100-right), toprob (100-left));\n events := (TS(i))::!events;\n events := (TE(i))::!events;\n done\n\nlet () =\n for j=0 to m-1 do\n let b = read_int() in\n let z = read_int() in\n mushs.(j) <- (b,z);\n events := (Mu(j))::!events\n done\n\nlet place dir e = match e with\n | Mu(i) -> fst mushs.(i)\n | TE(i) -> let (a,h,_,_) = trees.(i) in a + dir*h \n | TS(i) -> let (a,h,_,_) = trees.(i) in a\n\nlet comp dir e1 e2 = \n let (p1, p2) = (place dir e1, place dir e2) in\n let c = compare p1 p2 in\n dir * (if c<>0 then c else\n\t match e1 with Mu(_) -> -1 | _ -> (match e2 with Mu(_) -> 1 | _ -> 0))\n\nlet lprob i = let (_,_,p,_) = trees.(i) in p\n\nlet rec scan pa li openp = match li with \n | [] -> ()\n | (Mu(j))::tail -> pa.(j) <- openp; scan pa tail openp\n | (TS(i))::tail -> scan pa tail (openp *. (lprob i))\n | (TE(i))::tail -> scan pa tail (openp /. (lprob i))\n\nlet plr = Array.make m 0.0\nlet prl = Array.make m 0.0\n\nlet () = scan plr (List.sort (comp 1) !events) 1.0\nlet () = scan prl (List.sort (comp (-1)) !events) 1.0\n\nlet rec sum j ac = if j=m then ac else sum (j+1) (ac +. plr.(j) *. prl.(j))\n\nlet () = Printf.printf \"%f\" (sum 0 0.0)\n"}], "src_uid": "a6caa65a2374b458a570128022ab496e"} {"nl": {"description": "I guess there's not much point in reminding you that Nvodsk winters aren't exactly hot. That increased the popularity of the public transport dramatically. The route of bus 62 has exactly n stops (stop 1 goes first on its way and stop n goes last). The stops are positioned on a straight line and their coordinates are 0\u2009=\u2009x1\u2009<\u2009x2\u2009<\u2009...\u2009<\u2009xn. Each day exactly m people use bus 62. For each person we know the number of the stop where he gets on the bus and the number of the stop where he gets off the bus. A ticket from stop a to stop b (a\u2009<\u2009b) costs xb\u2009-\u2009xa rubles. However, the conductor can choose no more than one segment NOT TO SELL a ticket for. We mean that conductor should choose C and D (\u0421 <= D) and sell a ticket for the segments [A, C] and [D, B], or not sell the ticket at all. The conductor and the passenger divide the saved money between themselves equally. The conductor's \"untaxed income\" is sometimes interrupted by inspections that take place as the bus drives on some segment of the route located between two consecutive stops. The inspector fines the conductor by c rubles for each passenger who doesn't have the ticket for this route's segment.You know the coordinated of all stops xi; the numbers of stops where the i-th passenger gets on and off, ai and bi (ai\u2009<\u2009bi); the fine c; and also pi \u2014 the probability of inspection on segment between the i-th and the i\u2009+\u20091-th stop. The conductor asked you to help him make a plan of selling tickets that maximizes the mathematical expectation of his profit.", "input_spec": "The first line contains three integers n, m and c (2\u2009\u2264\u2009n\u2009\u2264\u2009150\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009300\u2009000, 1\u2009\u2264\u2009c\u2009\u2264\u200910\u2009000). The next line contains n integers xi (0\u2009\u2264\u2009xi\u2009\u2264\u2009109, x1\u2009=\u20090, xi\u2009<\u2009xi\u2009+\u20091) \u2014 the coordinates of the stops on the bus's route. The third line contains n\u2009-\u20091 integer pi (0\u2009\u2264\u2009pi\u2009\u2264\u2009100) \u2014 the probability of inspection in percents on the segment between stop i and stop i\u2009+\u20091. Then follow m lines that describe the bus's passengers. Each line contains exactly two integers ai and bi (1\u2009\u2264\u2009ai\u2009<\u2009bi\u2009\u2264\u2009n) \u2014 the numbers of stops where the i-th passenger gets on and off.", "output_spec": "Print the single real number \u2014 the maximum expectation of the conductor's profit. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["3 3 10\n0 10 100\n100 0\n1 2\n2 3\n1 3", "10 8 187\n0 10 30 70 150 310 630 1270 2550 51100\n13 87 65 0 100 44 67 3 4\n1 10\n2 9\n3 8\n1 5\n6 10\n2 7\n4 10\n4 5"], "sample_outputs": ["90.000000000", "76859.990000000"], "notes": "NoteA comment to the first sample:The first and third passengers get tickets from stop 1 to stop 2. The second passenger doesn't get a ticket. There always is inspection on the segment 1-2 but both passengers have the ticket for it. There never is an inspection on the segment 2-3, that's why the second passenger gets away with the cheating. Our total profit is (0\u2009+\u200990\u2009/\u20092\u2009+\u200990\u2009/\u20092)\u2009=\u200990."}, "positive_code": [{"source_code": "module Std = struct\n\n module List = struct\n include List\n module L = List\n let map f lst = L.rev (L.rev_map f lst)\n let map2 f l1 l2 = L.rev (L.rev_map2 f l1 l2)\n let each_cons f lst = L.rev_map2 f (L.tl (L.rev lst)) (L.rev (L.tl lst))\n let append x y = List.rev (List.rev_append x y)\n end\n\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n let ( ~. ) = float_of_int\n let ( ~: ) = int_of_float\n let ( @ ) x y = List.append\n\n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\n let di x = prerr_endline (string_of_int x); x\n let df f = prerr_endline (string_of_float f); f\n let ds s = prerr_endline s; s\n \n let int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let read_int = int\n let float () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n let read_float = float\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\nend\n\nmodule Segtree = struct\n module type Builder = sig \n type data\n val merge : data -> data -> data\n val terminal : int -> data\n end\n\n module Make = functor(B : Builder) -> struct\n type t =\n |\tLeaf of B.data\n | Node of B.data * int * int * t * t\n\n let getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\n let rec make l r =\n if l = r then\n\tLeaf(B.terminal l)\n else\n\tlet mid = (l+r) / 2 in\n\tlet ltree = make l mid in\n\tlet rtree = make (mid+1) r in\n\tlet ldata = getdata ltree in\n\tlet rdata = getdata rtree in\n\t Node(B.merge ldata rdata, l, r, ltree, rtree)\n\n let rec query l r = function\n | Leaf(data) ->\n\t data\n | Node(data, start, finish, ltree, rtree) ->\n\t if l = start && r = finish then\n\t data\n\t else \n\t let mid = (start+finish)/2 in\n\t if r <= mid then\n\t\tquery l r ltree\n\t else if l > mid then \n\t\tquery l r rtree\n\t else \n\t\tlet ldata = query l mid ltree in\n\t\tlet rdata = query (mid+1) r rtree in\n\t\t B.merge ldata rdata\n\n end\n\nend\n\n(* entry point *)\n\nopen Std\nmodule L = List\n\nlet max = L.fold_left max neg_infinity\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\nlet x = n_int n ()\n\nlet p = n_int (n-1) () |> L.map (fun x -> ~.x *. 0.01)\n\nlet ab = L.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\nlet w = \n let s = L.each_cons (fun x y -> y-x) x in\n L.map2 (fun pi si -> ~.si /. 2. -. pi *. ~.c) p s |> Array.of_list \n\nmodule A = struct\n\n type data = { left:float; right:float; between:float; full:float; }\n\n let terminal i = { left = 0.; right = 0.; between = 0.; full = w.(i); }\n\n let merge ldata rdata = {\n left = max [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = max [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = max [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n }\n\nend\n\nmodule MySegtree = Segtree.Make(A)\n\nopen A\n\nlet segtree = MySegtree.make 0 (n-2)\n\nlet to_ans data = max [data.left; data.right; data.between; data.full]\n\nlet () = \n L.map (fun (a,b) -> MySegtree.query a b segtree |> to_ans) ab\n |> L.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "module type ExtremumType =\nsig\n type t\n val extremum : t -> t -> bool\nend\n\nmodule type RMQ =\nsig\n type t\n type elt\n val of_array : elt array -> t\n val rmq : t -> int -> int -> int\nend\n\nmodule type RMQMake =\nsig\n module Make(Ext : ExtremumType) : RMQ with type elt = Ext.t\nend\n\nmodule RMQST =\nstruct\n module Make(Ext : ExtremumType) : RMQ with type elt = Ext.t =\n struct\n type elt = Ext.t\n type t = {a : elt array;\n\t m : int array array}\n let ext = Ext.extremum\n let of_array a =\n let n = Array.length a in\n let k = ref 0\n and d = ref 1 in\n\twhile !d <= n do\n\t d := 2 * !d;\n\t incr k\n\tdone;\n\tlet k = !k in\n\tlet m = Array.make_matrix k n 0 in\n\t for i = 0 to n - 1 do\n\t m.(0).(i) <- i;\n\t done;\n\t for j = 1 to k - 1 do\n\t for i = 0 to n - (1 lsl j) do\n\t let i2 = i + (1 lsl (j - 1)) in\n\t\tm.(j).(i) <-\n\t\t if ext a.(m.(j - 1).(i)) a.(m.(j - 1).(i2))\n\t\t then m.(j - 1).(i)\n\t\t else m.(j - 1).(i2)\n\t done\n\t done;\n\t {a = a;\n\t m = m}\n let rmq data x y =\n let a = data.a\n and m = data.m in\n let l = y - x + 1 in\n let k = ref 0\n and d = ref 1 in\n\twhile !d <= l do\n\t d := 2 * !d;\n\t incr k\n\tdone;\n\tlet k = !k - 1 in\n\tlet i2 = y - (1 lsl k) + 1 in\n\t if ext a.(m.(k).(x)) a.(m.(k).(i2))\n\t then m.(k).(x)\n\t else m.(k).(i2)\n end\nend\n\nmodule RMQSTmin =\n RMQST.Make(\n struct\n type t = float\n let extremum (x : t) (y : t) = x < y\n end\n )\n\nmodule RMQSTmax =\n RMQST.Make(\n struct\n type t = float\n let extremum (x : t) (y : t) = x >= y\n end\n )\n\n\nmodule RMSQ2 =\nstruct\n module Make(RMQ : RMQMake) =\n struct\n module RMQmin =\n RMQ.Make(\n\tstruct\n\t type t = float\n\t let extremum (x : t) (y : t) = x < y\n\tend\n )\n module RMQmax =\n RMQ.Make(\n\tstruct\n\t type t = float\n\t let extremum (x : t) (y : t) = x >= y\n\tend\n )\n type elt = float\n type t = {c : elt array;\n\t p : int array;\n\t m : elt array;\n\t crminq : RMQmin.t;\n\t crmaxq : RMQmax.t;\n\t mrmq : RMQmax.t;\n\t }\n let of_array a =\n let n = Array.length a in\n let c = Array.make (n + 1) 0.0 in\n let p = Array.make n 0 in\n let m = Array.make n 0.0 in\n let l = Array.make n 0 in\n\tfor i = 0 to n - 1 do\n\t c.(i + 1) <- c.(i) +. a.(i);\n\t l.(i) <- i - 1;\n\t p.(i) <- i;\n\t while c.(l.(i) + 1) < c.(i + 1) && l.(i) >= 0 do\n\t if c.(p.(l.(i))) < c.(p.(i))\n\t then p.(i) <- p.(l.(i));\n\t l.(i) <- l.(l.(i));\n\t done;\n\t m.(i) <- c.(i + 1) -. c.(p.(i));\n\tdone;\n\t{c = c;\n\t p = p;\n\t m = m;\n\t crminq = RMQmin.of_array c;\n\t crmaxq = RMQmax.of_array c;\n\t mrmq = RMQmax.of_array m;\n\t}\n let rmsq d i j =\n let x = RMQmax.rmq d.mrmq i j in\n\tif d.p.(x) < i then (\n\t let z = RMQmin.rmq d.crminq i x in\n\t if x + 1 <= j then (\n\t let y = RMQmax.rmq d.mrmq (x + 1) j in\n\t\tif d.c.(x + 1) -. d.c.(z) < d.m.(y)\n\t\tthen (d.p.(y), y)\n\t\telse (z, x)\n\t ) else\n\t (z, x)\n\t) else\n\t (d.p.(x), x)\n let rmsq_sum d i j =\n let (x, y) = rmsq d i j in\n\td.c.(y + 1) -. d.c.(x)\n let rmsq2 d i j k l =\n if j <= k then (\n\tlet x = RMQmin.rmq d.crminq i j in\n\tlet y = RMQmax.rmq d.crmaxq (k + 1) (l + 1) - 1 in\n\t (x, y)\n ) else (\n\tlet x1 = RMQmin.rmq d.crminq i k in\n\tlet y1 = RMQmax.rmq d.crmaxq (k + 1) (l + 1) - 1 in\n\tlet x2 = RMQmin.rmq d.crminq (k + 1) j in\n\tlet y2 = RMQmax.rmq d.crmaxq (j + 1) (l + 1) - 1 in\n\tlet (x3, y3) = rmsq d k j in\n\tlet c1 = d.c.(y1 + 1) -. d.c.(x1) in\n\tlet c2 = d.c.(y2 + 1) -. d.c.(x2) in\n\tlet c3 = d.c.(y3 + 1) -. d.c.(x3) in\n\t if c1 > c2 && c1 > c3\n\t then (x1, y1)\n\t else if c2 > c3\n\t then (x2, y2)\n\t else (x3, y3)\n )\n let rmsq2_sum d i j k l =\n let (x, y) = rmsq2 d i j k l in\n\td.c.(y + 1) -. d.c.(x)\n end\nend\n\n\nmodule RMSQ2ST = RMSQ2.Make(RMQST)\n\n\nlet getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let m = getnum () in\n let c = getnum () in\n let x = Array.make n 0 in\n let p = Array.make (n - 1) 0 in\n let _ =\n for i = 0 to n - 1 do\n x.(i) <- getnum ()\n done;\n for i = 0 to n - 2 do\n p.(i) <- getnum ()\n done;\n in\n let e = Array.make (n - 1) 0.0 in\n let f = Array.make n 0.0 in\n let c = float_of_int c in\n let _ =\n for i = 0 to n - 2 do\n let p = float_of_int p.(i) /. 100.0 in\n\te.(i) <- float_of_int (x.(i + 1) - x.(i)) /. 2.0 *. (1. -. 0.0) -. p *. c;\n\t(*Printf.printf \"asd %d %f\\n\" i e.(i);*)\n\t(*e.(i) <- -. e.(i);*)\n\tf.(i + 1) <- f.(i) +. e.(i)\n done\n in\n let res = ref 0.0 in\n let rmsq = RMSQ2ST.of_array e in\n for i = 1 to m do\n let a = getnum () - 1 in\n let b = getnum () - 1 in\n let g = RMSQ2ST.rmsq_sum rmsq a (b - 1) in\n let g = max g 0.0 in\n\t(*Printf.printf \"rmsq %f\\n\" g;*)\n (*let g = f.(b) -. f.(a) -. g in\n\tPrintf.printf \"asd %f\\n\" g;*)\n\tres := !res +. g;\n done;\n (*res := -. !res;*)\n Printf.printf \"%.6f\\n\" !res\n"}, {"source_code": "let ( |> ) v f = f v\nlet ( <| ) f v = f v\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet rec show_flt_list a = \n match a with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc\n else loop (n - 1) f ( (f n) :: acc)\n \n\ntype data = {ma : float; lv : float; rv : float; sum : float}\ntype range = {l: int; r : int}\n\ntype seg_tree = \n Leaf of data\n| Node of int * int * data * seg_tree * seg_tree\n\n\nlet get_data tr = \n match tr with\n\t Leaf d\n\t| Node (_, _, d, _, _) -> d\n\n\nlet update dlc drc = \n let s = dlc.sum +. drc.sum in\n let l = max dlc.lv (dlc.sum +. drc.lv) in\n let r = max drc.rv (drc.sum +. dlc.rv) in\n let m = max (max dlc.ma drc.ma) (dlc.rv +. drc.lv) in\n {ma = m; lv = l; rv = r; sum = s;}\n;;\n\nlet n = next_int () \nlet m = next_int ()\nlet c = next_flt () \n\nlet d = loop n (fun _ -> next_flt ()) []\nlet p = loop (n - 1) (fun _ -> ((next_flt ()) /. 100.0)) []\n\nlet v = List.map (fun (a, b) -> a -. b) (List.combine (List.tl d) (List.rev (List.tl (List.rev d))))\nlet a = Array.of_list <| List.map (fun (a, b) -> a /. 2.0 -. b *. c) (List.combine v p)\n\n\nlet rec build x y =\n if x = y then Leaf ({ma = max (foi 0) a.(x); lv = a.(x); rv = a.(x); sum = a.(x)})\n else begin\n\tlet mid = (x + y) / 2 in\n\tlet lc = build x mid in\n\tlet rc = build (mid+1) y in\n\tNode (x, y, (update (get_data lc) (get_data rc)), lc, rc)\n end\n\nlet rec query tr x y =\n match tr with\n\t Leaf d -> d\n\t| Node (l, r, d, lc, rc) -> begin\n\t if x <= l && y >= r then d\n\t else\n\t\tlet mid = (l + r) / 2 in\n\t\tlet snt = {ma = -1e20; lv = -1e20; rv = -1e20; sum = -1e20} in\n\t\tlet qlc = if x <= mid then query lc x y else snt in\n\t\tlet qrc = if y > mid then query rc x y else snt in\n\t\tupdate qlc qrc\n\tend\n\nlet tr = build 0 (n - 2)\n\n\nlet () =\n loop m (fun _ -> (let a = next_int() in\n\t\t\t\t\tlet b = next_int() in\n\t\t\t\t\tquery tr (a - 1) (b - 2)).ma) [] \n\t|> List.fold_left (+.) (foi 0) \n\t|> print_float\n \n\n\n"}, {"source_code": "module Std = struct\n\n module List = struct\n include List\n module L = List\n let map f lst = L.rev (L.rev_map f lst)\n let map2 f l1 l2 = L.rev (L.rev_map2 f l1 l2)\n let each_cons f lst = L.rev_map2 f (L.tl (L.rev lst)) (L.rev (L.tl lst))\n let append x y = List.rev (List.rev_append x y)\n end\n\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n let ( ~. ) = float_of_int\n let ( ~: ) = int_of_float\n let ( @ ) x y = List.append\n\n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\n let di x = prerr_endline (string_of_int x); x\n let df f = prerr_endline (string_of_float f); f\n let ds s = prerr_endline s; s\n \n let int () = Scanf.scanf \" %d\" (fun x -> x)\n let read_int = int\n let float () = Scanf.scanf \" %f\" (fun x -> x)\n let read_float = float\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\nend\n\nmodule Segtree = struct\n module type Builder = sig \n type data\n val merge : data -> data -> data\n val terminal : int -> data\n end\n\n module Make = functor(B : Builder) -> struct\n type t =\n |\tLeaf of B.data\n | Node of B.data * int * int * t * t\n\n let getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\n let rec make l r =\n if l = r then\n\tLeaf(B.terminal l)\n else\n\tlet mid = (l+r) / 2 in\n\tlet ltree = make l mid in\n\tlet rtree = make (mid+1) r in\n\tlet ldata = getdata ltree in\n\tlet rdata = getdata rtree in\n\t Node(B.merge ldata rdata, l, r, ltree, rtree)\n\n let rec query l r = function\n | Leaf(data) ->\n\t data\n | Node(data, start, finish, ltree, rtree) ->\n\t if l = start && r = finish then\n\t data\n\t else \n\t let mid = (start+finish)/2 in\n\t if r <= mid then\n\t\tquery l r ltree\n\t else if l > mid then \n\t\tquery l r rtree\n\t else \n\t\tlet ldata = query l mid ltree in\n\t\tlet rdata = query (mid+1) r rtree in\n\t\t B.merge ldata rdata\n\n end\n\nend\n\n(* entry point *)\n\nopen Std\nmodule L = List\n\nlet max = L.fold_left max neg_infinity\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\nlet x = n_int n ()\n\nlet p = n_int (n-1) () |> L.map (fun x -> ~.x *. 0.01)\n\nlet ab = L.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\nlet w = \n let s = L.each_cons (fun x y -> y-x) x in\n L.map2 (fun pi si -> ~.si /. 2. -. pi *. ~.c) p s |> Array.of_list \n\nmodule A = struct\n\n type data = { left:float; right:float; between:float; full:float; }\n\n let terminal i = { left = 0.; right = 0.; between = 0.; full = w.(i); }\n\n let merge ldata rdata = {\n left = max [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = max [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = max [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n }\n\nend\n\nmodule MySegtree = Segtree.Make(A)\n\nopen A\n\nlet segtree = MySegtree.make 0 (n-2)\n\nlet to_ans data = max [data.left; data.right; data.between; data.full]\n\nlet () = \n L.map (fun (a,b) -> MySegtree.query a b segtree |> to_ans) ab\n |> L.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "module Std = struct\n\n module List = struct\n include List\n module L = List\n let map f lst = L.rev (L.rev_map f lst)\n let map2 f l1 l2 = L.rev (L.rev_map2 f l1 l2)\n let each_cons f lst = L.rev_map2 f (L.tl (L.rev lst)) (L.rev (L.tl lst))\n let append x y = List.rev (List.rev_append x y)\n end\n\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n let ( ~. ) = float_of_int\n let ( ~: ) = int_of_float\n let ( @ ) x y = List.append\n\n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\n let di x = prerr_endline (string_of_int x); x\n let df f = prerr_endline (string_of_float f); f\n let ds s = prerr_endline s; s\n \n let int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let read_int = int\n let float () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n let read_float = float\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\nend\n\nopen Std\nmodule L = List\n\nlet max = L.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\nlet x = n_int n ()\n\nlet p = n_int (n-1) () |> L.map (fun x -> ~.x *. 0.01)\n\nlet ab = L.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\nlet w = \n let s = L.each_cons (fun x y -> y-x) x in\n L.map2 (fun pi si -> ~.si /. 2. -. pi *. ~.c) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = max [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = max [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = max [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n | Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\nlet segtree = make_tree 0 (n-2)\n\nlet () = \n L.map (fun (a,b) -> let r = query a b segtree in max [r.left; r.right; r.between; r.full]) ab\n |> L.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "module Std = struct\n\n module List = struct\n include List\n module L = List\n let map f lst = L.rev (L.rev_map f lst)\n let map2 f l1 l2 = L.rev (L.rev_map2 f l1 l2)\n let each_cons f lst = L.rev_map2 f (L.tl (L.rev lst)) (L.rev (L.tl lst))\n let append x y = List.rev (List.rev_append x y)\n end\n\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n let ( ~. ) = float_of_int\n let ( ~: ) = int_of_float\n let ( @ ) x y = List.append\n\n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\n let di x = prerr_endline (string_of_int x); x\n let df f = prerr_endline (string_of_float f); f\n let ds s = prerr_endline s; s\n \n let int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let read_int = int\n let float () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n let read_float = float\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\nend\n\nmodule Segtree = struct\n module type Builder = sig \n type data\n val merge : data -> data -> data\n val terminal : int -> data\n end\n\n module Make = functor(B : Builder) -> struct\n type t =\n |\tLeaf of B.data\n | Node of B.data * int * int * t * t\n\n let getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\n let rec make l r =\n if l = r then\n\tLeaf(B.terminal l)\n else\n\tlet mid = (l+r) / 2 in\n\tlet ltree = make l mid in\n\tlet rtree = make (mid+1) r in\n\tlet ldata = getdata ltree in\n\tlet rdata = getdata rtree in\n\t Node(B.merge ldata rdata, l, r, ltree, rtree)\n\n let rec query l r = function\n | Leaf(data) ->\n\t data\n | Node(data, start, finish, ltree, rtree) ->\n\t if l = start && r = finish then\n\t data\n\t else \n\t let mid = (start+finish)/2 in\n\t if r <= mid then\n\t\tquery l r ltree\n\t else if l > mid then \n\t\tquery l r rtree\n\t else \n\t\tlet ldata = query l mid ltree in\n\t\tlet rdata = query (mid+1) r rtree in\n\t\t B.merge ldata rdata\n\n end\n\nend\n\n(* entry point *)\n\nopen Std\nmodule L = List\n\nlet max = L.fold_left max neg_infinity\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\nlet x = n_int n ()\n\nlet p = n_int (n-1) () |> L.map (fun x -> ~.x *. 0.01)\n\nlet ab = L.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\nlet w = \n let s = L.each_cons (fun x y -> y-x) x in\n L.map2 (fun pi si -> ~.si /. 2. -. pi *. ~.c) p s |> Array.of_list \n\nmodule A = struct\n\n type data = { left:float; right:float; between:float; full:float; }\n\n let terminal i = { left = 0.; right = 0.; between = 0.; full = w.(i); }\n\n let merge ldata rdata = {\n left = max [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = max [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = max [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n }\n\nend\n\nmodule MySegtree = Segtree.Make(A)\n\nopen A\n\nlet segtree = MySegtree.make 0 (n-2)\n\nlet to_ans data = max [data.left; data.right; data.between; data.full]\n\nlet () = \n L.map (fun (a,b) -> MySegtree.query a b segtree |> to_ans) ab\n |> L.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nmodule Std = struct\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n \n let di x = prerr_endline (string_of_int x); x\n let df x = prerr_endline (string_of_float x); x\n \n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n let rec int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let rec float () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\n module List = struct\n include List\n let map f lst = List.rev <| List.rev_map f lst\n let map2 f l1 l2 = List.rev <| List.rev_map2 f l1 l2\n end\nend\n\nopen Std\n\n(* utiliry functions *)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\nlet x = n_int n ()\n\nlet p = n_float (n-1) () |> List.map (fun x -> x *. 0.01)\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\nlet segtree = make_tree 0 (n-2)\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}], "negative_code": [{"source_code": "module type ExtremumType =\nsig\n type t\n val extremum : t -> t -> bool\nend\n\nmodule type RMQ =\nsig\n type t\n type elt\n val of_array : elt array -> t\n val rmq : t -> int -> int -> int\nend\n\nmodule type RMQMake =\nsig\n module Make(Ext : ExtremumType) : RMQ with type elt = Ext.t\nend\n\nmodule RMQST =\nstruct\n module Make(Ext : ExtremumType) : RMQ with type elt = Ext.t =\n struct\n type elt = Ext.t\n type t = {a : elt array;\n\t m : int array array}\n let ext = Ext.extremum\n let of_array a =\n let n = Array.length a in\n let k = ref 0\n and d = ref 1 in\n\twhile !d <= n do\n\t d := 2 * !d;\n\t incr k\n\tdone;\n\tlet k = !k in\n\tlet m = Array.make_matrix k n 0 in\n\t for i = 0 to n - 1 do\n\t m.(0).(i) <- i;\n\t done;\n\t for j = 1 to k - 1 do\n\t for i = 0 to n - (1 lsl j) do\n\t let i2 = i + (1 lsl (j - 1)) in\n\t\tm.(j).(i) <-\n\t\t if ext a.(m.(j - 1).(i)) a.(m.(j - 1).(i2))\n\t\t then m.(j - 1).(i)\n\t\t else m.(j - 1).(i2)\n\t done\n\t done;\n\t {a = a;\n\t m = m}\n let rmq data x y =\n let a = data.a\n and m = data.m in\n let l = y - x + 1 in\n let k = ref 0\n and d = ref 1 in\n\twhile !d <= l do\n\t d := 2 * !d;\n\t incr k\n\tdone;\n\tlet k = !k - 1 in\n\tlet i2 = y - (1 lsl k) + 1 in\n\t if ext a.(m.(k).(x)) a.(m.(k).(i2))\n\t then m.(k).(x)\n\t else m.(k).(i2)\n end\nend\n\nmodule RMQSTmin =\n RMQST.Make(\n struct\n type t = float\n let extremum (x : t) (y : t) = x < y\n end\n )\n\nmodule RMQSTmax =\n RMQST.Make(\n struct\n type t = float\n let extremum (x : t) (y : t) = x >= y\n end\n )\n\n\nmodule RMSQ2 =\nstruct\n module Make(RMQ : RMQMake) =\n struct\n module RMQmin =\n RMQ.Make(\n\tstruct\n\t type t = float\n\t let extremum (x : t) (y : t) = x < y\n\tend\n )\n module RMQmax =\n RMQ.Make(\n\tstruct\n\t type t = float\n\t let extremum (x : t) (y : t) = x >= y\n\tend\n )\n type elt = float\n type t = {c : elt array;\n\t p : int array;\n\t m : elt array;\n\t crminq : RMQmin.t;\n\t crmaxq : RMQmax.t;\n\t mrmq : RMQmax.t;\n\t }\n let of_array a =\n let n = Array.length a in\n let c = Array.make (n + 1) 0.0 in\n let p = Array.make n 0 in\n let m = Array.make n 0.0 in\n let l = Array.make n 0 in\n\tfor i = 0 to n - 1 do\n\t c.(i + 1) <- c.(i) +. a.(i);\n\t l.(i) <- i - 1;\n\t p.(i) <- i;\n\t while c.(l.(i) + 1) < c.(i + 1) && l.(i) >= 0 do\n\t if c.(p.(l.(i))) < c.(p.(i))\n\t then p.(i) <- p.(l.(i));\n\t l.(i) <- l.(l.(i));\n\t done;\n\t m.(i) <- c.(i + 1) -. c.(p.(i));\n\tdone;\n\t{c = c;\n\t p = p;\n\t m = m;\n\t crminq = RMQmin.of_array c;\n\t crmaxq = RMQmax.of_array c;\n\t mrmq = RMQmax.of_array m;\n\t}\n let rmsq d i j =\n let x = RMQmax.rmq d.mrmq i j in\n\tif d.p.(x) < i then (\n\t let z = RMQmin.rmq d.crminq i x in\n\t if x + 1 <= j then (\n\t let y = RMQmax.rmq d.mrmq (x + 1) j in\n\t\tif d.c.(x + 1) -. d.c.(z) < d.m.(y)\n\t\tthen (d.p.(y), y)\n\t\telse (z, x)\n\t ) else\n\t (z, x)\n\t) else\n\t (d.p.(x), x)\n let rmsq_sum d i j =\n let (x, y) = rmsq d i j in\n\td.c.(y + 1) -. d.c.(x)\n let rmsq2 d i j k l =\n if j <= k then (\n\tlet x = RMQmin.rmq d.crminq i j in\n\tlet y = RMQmax.rmq d.crmaxq (k + 1) (l + 1) - 1 in\n\t (x, y)\n ) else (\n\tlet x1 = RMQmin.rmq d.crminq i k in\n\tlet y1 = RMQmax.rmq d.crmaxq (k + 1) (l + 1) - 1 in\n\tlet x2 = RMQmin.rmq d.crminq (k + 1) j in\n\tlet y2 = RMQmax.rmq d.crmaxq (j + 1) (l + 1) - 1 in\n\tlet (x3, y3) = rmsq d k j in\n\tlet c1 = d.c.(y1 + 1) -. d.c.(x1) in\n\tlet c2 = d.c.(y2 + 1) -. d.c.(x2) in\n\tlet c3 = d.c.(y3 + 1) -. d.c.(x3) in\n\t if c1 > c2 && c1 > c3\n\t then (x1, y1)\n\t else if c2 > c3\n\t then (x2, y2)\n\t else (x3, y3)\n )\n let rmsq2_sum d i j k l =\n let (x, y) = rmsq2 d i j k l in\n\td.c.(y + 1) -. d.c.(x)\n end\nend\n\n\nmodule RMSQ2ST = RMSQ2.Make(RMQST)\n\n\nlet getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let m = getnum () in\n let c = getnum () in\n let x = Array.make n 0 in\n let p = Array.make (n - 1) 0 in\n let _ =\n for i = 0 to n - 1 do\n x.(i) <- getnum ()\n done;\n for i = 0 to n - 2 do\n p.(i) <- getnum ()\n done;\n in\n let e = Array.make (n - 1) 0.0 in\n let f = Array.make n 0.0 in\n let c = float_of_int c in\n let _ =\n for i = 0 to n - 2 do\n let p = float_of_int p.(i) /. 100.0 in\n\te.(i) <- float_of_int (x.(i + 1) - x.(i)) /. 2.0 *. (1. -. p) -. p *. c;\n\t(*Printf.printf \"asd %d %f\\n\" i e.(i);*)\n\t(*e.(i) <- -. e.(i);*)\n\tf.(i + 1) <- f.(i) +. e.(i)\n done\n in\n let res = ref 0.0 in\n let rmsq = RMSQ2ST.of_array e in\n for i = 1 to m do\n let a = getnum () - 1 in\n let b = getnum () - 1 in\n let g = RMSQ2ST.rmsq_sum rmsq a (b - 1) in\n let g = max g 0.0 in\n\t(*Printf.printf \"rmsq %f\\n\" g;*)\n (*let g = f.(b) -. f.(a) -. g in\n\tPrintf.printf \"asd %f\\n\" g;*)\n\tres := !res +. g;\n done;\n (*res := -. !res;*)\n Printf.printf \"%.6f\\n\" !res\n"}, {"source_code": "let ( |> ) x f = f x\n\nlet ( <| ) f x = f x\n\nlet rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\nlet df x = prerr_endline (string_of_float x); x\n\nlet separated_input_list = ref []\nlet buffer_line () =\n separated_input_list := (read_line () |> Str.split (Str.regexp \"\\ \"))\nlet get_int_list () =\n !separated_input_list\n |> List.map int_of_string\nlet get_next_int () =\n match !separated_input_list with\n | [] -> (print_endline \"Error\"; assert false)\n | hd :: tl -> separated_input_list := tl; int_of_string hd\n\nlet each_cons f lst =\n List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\n\nlet () = buffer_line ()\nlet n = get_next_int ()\nlet m = get_next_int ()\nlet c = get_next_int ()\n\nlet x = buffer_line (); get_int_list ()\n\nlet p = \n (buffer_line (); get_int_list ())\n |> List.map float_of_int\n |> List.map (fun x -> x /. 100.)\n\nlet ab = \n List.rev\n <| repeat m\n (fun lst -> \n\t let () = buffer_line () in\n\t let a = get_next_int () in\n\t let b = get_next_int () in\n\t (a-1, b-2) :: lst)\n []\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 \n (fun pi si -> si /. 2. -. pi *. float_of_int(c))\n p\n s\n |> Array.of_list \n\n(*\nlet () = prerr_endline \"w=\"\nlet () = Array.iter (fun x -> prerr_float x; prerr_string \", \") w\nlet () = prerr_newline ()\nlet () = prerr_newline ()\n*)\n\ntype gao = {\n left:float;\n right:float;\n between:float;\n full:float;\n}\n\ntype tree = \n | Leaf of gao\n | Node of gao * int * int * tree * tree\n\nlet getgao = function\n | Leaf(gao) -> gao\n | Node(gao,_,_,_,_) -> gao\n\nlet lmax = List.fold_left max neg_infinity\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ \n\t left = 0.; \n\t right = 0.; \n\t between = 0.; \n\t full = w.(l); \n\t })\n else\n let mid = (l+r) / 2 in\n let lnode = make_tree l mid in\n let rnode = make_tree (mid+1) r in\n let ldata = getgao lnode in\n let rdata = getgao rnode in\n Node({ \n\t left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n\t right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n\t between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n\t full = ldata.full +. rdata.full;\n\t },\n\t l,\n\t r,\n\t lnode,\n\t rnode)\n\nlet rec query l r tree =\n match tree with\n Leaf(data) ->\n\tdata\n | Node(data, start, finish, ltree, rtree) ->\n\tif l = start && r = finish then\n\t data\n\telse \n\t let mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t\t{ \n\t\t left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n\t\t right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n\t\t between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n\t\t full = ldata.full +. rdata.full;\n\t\t}\n\nlet segtree = make_tree 0 (n-2)\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nmodule Std = struct\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n \n let di x = prerr_endline (string_of_int x); x\n let df x = prerr_endline (string_of_float x); x\n \n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n let rec int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\nend\n\nopen Std\n\n(* utiliry functions *)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = n_int n ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n begin\n print_endline (string_of_int (List.length x));\n print_endline \"hello, world!\"\n end\n\nlet p = n_int (n-1) () |> List.map float_of_int |> List.map (fun x -> x /. 100.)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nmodule Std = struct\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n \n let di x = prerr_endline (string_of_int x); x\n let df x = prerr_endline (string_of_float x); x\n \n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n let rec int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\nend\n\nopen Std\n\n(* utiliry functions *)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = n_int n ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet pp = n_int (n-1) () \n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet p = pp |> List.map (fun x -> (float_of_int x) *. 0.01)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nmodule Std = struct\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n \n let di x = prerr_endline (string_of_int x); x\n let df x = prerr_endline (string_of_float x); x\n \n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n let rec int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let rec float () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\n module List = struct\n include List\n let map f lst = List.rev <| List.rev_map f lst\n end\nend\n\nopen Std\n\n(* utiliry functions *)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = n_int n ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet pp = n_float (n-1) () \n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\n(*let ppp = pp |> List.map float_of_int *)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet p = pp |> List.map (fun x -> x *. 0.01)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nlet ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet di x = prerr_endline (string_of_int x); x\nlet df x = prerr_endline (string_of_float x); x\n\n(*\nlet separated_input_list = ref []\nlet buffer_line () = separated_input_list := (read_line () |> Str.split (Str.regexp \"\\ \"))\nlet int_list () = !separated_input_list |> List.map int_of_string\nlet int () = match !separated_input_list with [] -> assert false | hd :: tl -> separated_input_list := tl; int_of_string hd\n*)\n\nlet digit c = c >= '0' && c <= '9'\nlet feed c = c = '\\r' || c = '\\n'\nlet whitespace c = c = ' ' || c = '\\t' || feed c\n\nlet rec int' flg x =\n let c = input_char stdin in\n if digit c then\n int' true (x*10+int_of_char(c)-48)\n else if whitespace c then\n if flg then\n\t(x, feed c)\n else\n\tint' false 0\n else failwith \"getInt\"\n\nlet int () = fst (int' false 0)\n\nlet int_list () =\n let rec int_list' () =\n let (x, flg) = int' false 0 in\n if flg then\n\t[x]\n else\n\tx :: int_list' ()\n in\n int_list' ()\n\n(* utiliry functions *)\nlet rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = int_list ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet p = int_list () |> List.map float_of_int |> List.map (fun x -> x /. 100.)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "let ( |> ) x f = f x\n\nlet ( <| ) f x = f x\n\nlet rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\nlet df x = prerr_endline (string_of_float x); x\n\nlet separated_input_list = ref []\nlet buffer_line () =\n separated_input_list := (read_line () |> Str.split (Str.regexp \"\\ \"))\nlet get_int_list () =\n !separated_input_list\n |> List.map int_of_string\nlet get_next_int () =\n match !separated_input_list with\n | [] -> assert false\n | hd :: tl -> separated_input_list := tl; int_of_string hd\n\nlet each_cons f lst =\n List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\n\nlet () = buffer_line ()\nlet n = get_next_int ()\nlet m = get_next_int ()\nlet c = get_next_int ()\n\nlet x = buffer_line (); get_int_list ()\n\nlet p = \n (buffer_line (); get_int_list ())\n |> List.map float_of_int\n |> List.map (fun x -> x /. 100.)\n\nlet ab = \n List.rev\n <| repeat m\n (fun lst -> \n\t let () = buffer_line () in\n\t let a = get_next_int () in\n\t let b = get_next_int () in\n\t (a-1, b-2) :: lst)\n []\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 \n (fun pi si -> (1. -. pi) *. si /. 2. -. pi *. float_of_int(c))\n p\n s\n |> Array.of_list \n\nlet () = prerr_endline \"w=\"\nlet () = Array.iter (fun x -> prerr_float x; prerr_string \", \") w\nlet () = prerr_newline ()\nlet () = prerr_newline ()\n\ntype gao = {\n left:float;\n right:float;\n between:float;\n full:float;\n}\n\ntype tree = \n | Leaf of gao\n | Node of gao * int * int * tree * tree\n\nlet getgao = function\n | Leaf(gao) -> gao\n | Node(gao,_,_,_,_) -> gao\n\nlet lmax = List.fold_left max neg_infinity\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ \n\t left = 0.; \n\t right = 0.; \n\t between = 0.; \n\t full = w.(l); \n\t })\n else\n let mid = (l+r) / 2 in\n let lnode = make_tree l mid in\n let rnode = make_tree (mid+1) r in\n let ldata = getgao lnode in\n let rdata = getgao rnode in\n Node({ \n\t left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n\t right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n\t between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n\t full = ldata.full +. rdata.full;\n\t },\n\t l,\n\t r,\n\t lnode,\n\t rnode)\n\nlet rec query l r tree =\n match tree with\n Leaf(data) ->\n\tdata\n | Node(data, start, finish, ltree, rtree) ->\n\tif l = start && r = finish then\n\t data\n\telse \n\t let mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t\t{ \n\t\t left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n\t\t right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n\t\t between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n\t\t full = ldata.full +. rdata.full;\n\t\t}\n\nlet segtree = make_tree 0 (n-2)\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in df(lmax [r.left; r.right; r.between; r.full])) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nmodule Std = struct\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n \n let di x = prerr_endline (string_of_int x); x\n let df x = prerr_endline (string_of_float x); x\n \n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n let rec int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\nend\n\nopen Std\n\n(* utiliry functions *)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = n_int n ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet pp = n_int (n-1) () \n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ppp = pp |> List.map float_of_int \n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet p = ppp |> List.map (fun x -> x *. 0.01)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nmodule Std = struct\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n \n let di x = prerr_endline (string_of_int x); x\n let df x = prerr_endline (string_of_float x); x\n \n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n let rec int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\nend\n\nopen Std\n\n(* utiliry functions *)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = n_int n ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet pp = n_int (n-1) () \n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet p = pp |> List.map float_of_int |> List.map (fun x -> x /. 100.)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nlet ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet di x = prerr_endline (string_of_int x); x\nlet df x = prerr_endline (string_of_float x); x\n\nlet separated_input_list = ref []\nlet buffer_line () = separated_input_list := (read_line () |> Str.split (Str.regexp \"\\ \"))\nlet int_list () = !separated_input_list |> List.map int_of_string\nlet int () = match !separated_input_list with [] -> assert false | hd :: tl -> separated_input_list := tl; int_of_string hd\n\n(* utiliry functions *)\nlet rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet () = buffer_line ()\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = buffer_line (); int_list ()\n\nlet p = buffer_line (); int_list () |> List.map float_of_int |> List.map (fun x -> x /. 100.)\n\nlet ab = List.rev <| repeat m (fun lst -> buffer_line (); let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "let ( |> ) x f = f x\n\nlet ( <| ) f x = f x\n\nlet rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\nlet df x = prerr_endline (string_of_float x); x\n\nlet separated_input_list = ref []\nlet buffer_line () =\n separated_input_list := (read_line () |> Str.split (Str.regexp \"\\ \"))\nlet get_int_list () =\n !separated_input_list\n |> List.map int_of_string\nlet get_next_int () =\n match !separated_input_list with\n | [] -> assert false\n | hd :: tl -> separated_input_list := tl; int_of_string hd\n\nlet each_cons f lst =\n List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\n\nlet () = buffer_line ()\nlet n = get_next_int ()\nlet m = get_next_int ()\nlet c = get_next_int ()\n\nlet x = buffer_line (); get_int_list ()\n\nlet p = \n (buffer_line (); get_int_list ())\n |> List.map float_of_int\n |> List.map (fun x -> x /. 100.)\n\nlet ab = \n List.rev\n <| repeat m\n (fun lst -> \n\t let () = buffer_line () in\n\t let a = get_next_int () in\n\t let b = get_next_int () in\n\t (a-1, b-2) :: lst)\n []\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 \n (fun pi si -> si /. 2. -. pi *. float_of_int(c))\n p\n s\n |> Array.of_list \n\nlet () = prerr_endline \"w=\"\nlet () = Array.iter (fun x -> prerr_float x; prerr_string \", \") w\nlet () = prerr_newline ()\nlet () = prerr_newline ()\n\ntype gao = {\n left:float;\n right:float;\n between:float;\n full:float;\n}\n\ntype tree = \n | Leaf of gao\n | Node of gao * int * int * tree * tree\n\nlet getgao = function\n | Leaf(gao) -> gao\n | Node(gao,_,_,_,_) -> gao\n\nlet lmax = List.fold_left max neg_infinity\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ \n\t left = 0.; \n\t right = 0.; \n\t between = 0.; \n\t full = w.(l); \n\t })\n else\n let mid = (l+r) / 2 in\n let lnode = make_tree l mid in\n let rnode = make_tree (mid+1) r in\n let ldata = getgao lnode in\n let rdata = getgao rnode in\n Node({ \n\t left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n\t right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n\t between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n\t full = ldata.full +. rdata.full;\n\t },\n\t l,\n\t r,\n\t lnode,\n\t rnode)\n\nlet rec query l r tree =\n match tree with\n Leaf(data) ->\n\tdata\n | Node(data, start, finish, ltree, rtree) ->\n\tif l = start && r = finish then\n\t data\n\telse \n\t let mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t\t{ \n\t\t left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n\t\t right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n\t\t between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n\t\t full = ldata.full +. rdata.full;\n\t\t}\n\nlet segtree = make_tree 0 (n-2)\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in df(lmax [r.left; r.right; r.between; r.full])) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nmodule Std = struct\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n \n let di x = prerr_endline (string_of_int x); x\n let df x = prerr_endline (string_of_float x); x\n \n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n let rec int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let rec float () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\n module List = struct\n include List\n let map f lst = List.rev <| List.rev_map f lst\n let map2 f l1 l2 = List.rev <| List.rev_map2 f l1 l2\n end\nend\n\nopen Std\n\n(* utiliry functions *)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = n_int n ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet pp = n_float (n-1) () \n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\n(*let ppp = pp |> List.map float_of_int *)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet p = pp |> List.map (fun x -> x *. 0.01)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nlet ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet di x = prerr_endline (string_of_int x); x\nlet df x = prerr_endline (string_of_float x); x\n\nlet separated_input_list = ref []\nlet buffer_line () = separated_input_list := (read_line () |> Str.split (Str.regexp \"\\ \"))\nlet int_list () = !separated_input_list |> List.map int_of_string\nlet int () = match !separated_input_list with [] -> assert false | hd :: tl -> separated_input_list := tl; int_of_string hd\n\n(* utiliry functions *)\nlet rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet () = buffer_line ()\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = buffer_line (); int_list ()\n\nlet p = buffer_line (); int_list () |> List.map float_of_int |> List.map (fun x -> x /. 100.)\n\nlet ab = List.rev <| repeat m (fun lst -> buffer_line (); let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n(* if n = 150000 && m = 300000 && c = 209 then *)\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nlet ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet di x = prerr_endline (string_of_int x); x\nlet df x = prerr_endline (string_of_float x); x\n\n(*\nlet separated_input_list = ref []\nlet buffer_line () = separated_input_list := (read_line () |> Str.split (Str.regexp \"\\ \"))\nlet int_list () = !separated_input_list |> List.map int_of_string\nlet int () = match !separated_input_list with [] -> assert false | hd :: tl -> separated_input_list := tl; int_of_string hd\n*)\n\nlet digit c = c >= '0' && c <= '9'\nlet feed c = c = '\\r' || c = '\\n'\nlet whitespace c = c = ' ' || c = '\\t' || feed c\n\nlet rec int' flg x =\n let c = input_char stdin in\n if digit c then\n int' true (x*10+int_of_char(c)-48)\n else if whitespace c then\n if flg then\n\t(x, feed c)\n else\n\tint' false 0\n else failwith \"getInt\"\n\nlet int () = fst (int' false 0)\n\nlet int_list () =\n let rec int_list' () =\n let (x, flg) = int' false 0 in\n if flg then\n\t[x]\n else\n\tx :: int_list' ()\n in\n int_list' ()\n\n(* utiliry functions *)\nlet rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = int_list ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n begin\n print_endline (string_of_int (List.length x));\n print_endline \"hello, world!\"\n end\n\nlet p = int_list () |> List.map float_of_int |> List.map (fun x -> x /. 100.)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nmodule Std = struct\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n \n let di x = prerr_endline (string_of_int x); x\n let df x = prerr_endline (string_of_float x); x\n \n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n let rec int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\n let rec float () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\nend\n\nopen Std\n\n(* utiliry functions *)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = n_int n ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet pp = n_float (n-1) () \n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\n(*let ppp = pp |> List.map float_of_int *)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet p = pp |> List.map (fun x -> x *. 0.01)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nlet ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet di x = prerr_endline (string_of_int x); x\nlet df x = prerr_endline (string_of_float x); x\n\nlet separated_input_list = ref []\nlet buffer_line () = separated_input_list := (read_line () |> Str.split (Str.regexp \"\\ \"))\nlet int_list () = !separated_input_list |> List.map int_of_string\nlet int () = match !separated_input_list with [] -> assert false | hd :: tl -> separated_input_list := tl; int_of_string hd\n\n(* utiliry functions *)\nlet rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet () = buffer_line ()\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet x = buffer_line (); int_list ()\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet p = buffer_line (); int_list () |> List.map float_of_int |> List.map (fun x -> x /. 100.)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet ab = List.rev <| repeat m (fun lst -> buffer_line (); let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r = function\n |Leaf(data) ->\n data\n | Node(data, start, finish, ltree, rtree) ->\n if l = start && r = finish then\n\tdata\n else \n\tlet mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t merge ldata rdata\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet segtree = make_tree 0 (n-2)\n\n(* submit debug.. *)\nlet () =\n if n = 150000 && m = 300000 && c = 209 then\n print_endline \"hello, world!\"\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}, {"source_code": "(* template *)\nlet ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet di x = prerr_endline (string_of_int x); x\nlet df x = prerr_endline (string_of_float x); x\n\nlet separated_input_list = ref []\nlet buffer_line () = separated_input_list := (read_line () |> Str.split (Str.regexp \"\\ \"))\nlet int_list () = !separated_input_list |> List.map int_of_string\nlet int () = match !separated_input_list with [] -> assert false | hd :: tl -> separated_input_list := tl; int_of_string hd\n\n(* utiliry functions *)\nlet rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\nlet each_cons f lst = List.rev_map2 f (List.tl (List.rev lst)) (List.rev (List.tl lst))\nlet lmax = List.fold_left max neg_infinity\n\n(* entry point *)\n\nlet () = buffer_line ()\nlet n = int ()\nlet m = int ()\nlet c = int ()\n\nlet x = buffer_line (); int_list ()\n\nlet p = buffer_line (); int_list () |> List.map float_of_int |> List.map (fun x -> x /. 100.)\n\nlet ab = List.rev <| repeat m (fun lst -> buffer_line (); let a = int () in let b = int () in (a-1, b-2) :: lst) []\n\nlet w = \n let s = each_cons (fun x y -> y-x |> float_of_int) x in\n List.map2 (fun pi si -> si /. 2. -. pi *. float_of_int(c)) p s |> Array.of_list \n\ntype data = { left:float; right:float; between:float; full:float; }\n\ntype tree = \n | Leaf of data\n | Node of data * int * int * tree * tree\n\nlet getdata = function\n | Leaf(data) -> data\n | Node(data,_,_,_,_) -> data\n\nlet merge ldata rdata = {\n left = lmax [ldata.left; ldata.full; (ldata.full +. rdata.left)];\n right = lmax [rdata.right; rdata.full; (rdata.full +. ldata.right)];\n between = lmax [ldata.between; rdata.between; ldata.right; rdata.left; (ldata.right +. rdata.left)];\n full = ldata.full +. rdata.full; \n}\n\nlet rec make_tree l r =\n if l = r then\n Leaf({ left = 0.; right = 0.; between = 0.; full = w.(l); })\n else\n let mid = (l+r) / 2 in\n let ltree = make_tree l mid in\n let rtree = make_tree (mid+1) r in\n let ldata = getdata ltree in\n let rdata = getdata rtree in\n Node(merge ldata rdata, l, r, ltree, rtree)\n\nlet rec query l r tree =\n match tree with\n Leaf(data) ->\n\tdata\n | Node(data, start, finish, ltree, rtree) ->\n\tif l = start && r = finish then\n\t data\n\telse \n\t let mid = (start+finish)/2 in\n\t if r <= mid then\n\t query l r ltree\n\t else if l > mid then \n\t query l r rtree\n\t else \n\t let ldata = query l mid ltree in\n\t let rdata = query (mid+1) r rtree in\n\t\tmerge ldata rdata\n\nlet segtree = make_tree 0 (n-2)\n\nlet () = \n List.map (fun (a,b) -> let r = query a b segtree in lmax [r.left; r.right; r.between; r.full]) ab\n |> List.fold_left (+.) 0.\n |> print_float\n"}], "src_uid": "f7528716ef2cfdbcdc8bf8253fd4966b"} {"nl": {"description": "For the given sequence with n different elements find the number of increasing subsequences with k\u2009+\u20091 elements. It is guaranteed that the answer is not greater than 8\u00b71018.", "input_spec": "First line contain two integer values n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009k\u2009\u2264\u200910) \u2014 the length of sequence and the number of elements in increasing subsequences. Next n lines contains one integer ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) each \u2014 elements of sequence. All values ai are different.", "output_spec": "Print one integer \u2014 the answer to the problem.", "sample_inputs": ["5 2\n1\n2\n3\n5\n4"], "sample_outputs": ["7"], "notes": null}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet g2d n = n land (-n)\n\nlet fenwick_new n =\n Array.make n 0L\n\nlet fenwick_modify ft n x =\n let i = ref (n + 1) in\n while !i <= Array.length ft do\n ft.(!i - 1) <- ft.(!i - 1) +| x;\n i := !i + g2d !i;\n done\n\nlet fenwick_count ft n =\n let i = ref (n + 1) in\n let res = ref 0L in\n while !i > 0 do\n res := !res +| ft.(!i - 1);\n i := !i - g2d !i;\n done;\n !res\n\nlet fenwick_count2 ft m n =\n fenwick_count ft n -| fenwick_count ft (m - 1)\n\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = k + 1 in\n let a = Array.make n 0 in\n let b = Array.make n (0, 0) in\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- x;\n\tb.(i) <- (x, i);\n done;\n Array.sort compare b;\n let ft = Array.init (k + 1) (fun _ -> fenwick_new (n + 1)) in\n fenwick_modify ft.(0) 0 1L;\n for i = 0 to n - 1 do\n\tfor j = k downto 1 do\n\t let c = fenwick_count ft.(j - 1) (a.(i) - 1) in\n\t fenwick_modify ft.(j) a.(i) c\n\tdone\n done;\n let res = fenwick_count ft.(k) n in\n\tPrintf.printf \"%Ld\\n\" res\n"}], "negative_code": [], "src_uid": "33112c5af6e9cfd752ad6ded49b54d78"} {"nl": {"description": "There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played. You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d1 and that of between second and third team will be d2.You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?Note that outcome of a match can not be a draw, it has to be either win or loss.", "input_spec": "The first line of the input contains a single integer corresponding to number of test cases t (1\u2009\u2264\u2009t\u2009\u2264\u2009105). Each of the next t lines will contain four space-separated integers n,\u2009k,\u2009d1,\u2009d2 (1\u2009\u2264\u2009n\u2009\u2264\u20091012;\u00a00\u2009\u2264\u2009k\u2009\u2264\u2009n;\u00a00\u2009\u2264\u2009d1,\u2009d2\u2009\u2264\u2009k) \u2014 data for the current test case.", "output_spec": "For each test case, output a single line containing either \"yes\" if it is possible to have no winner of tournament, or \"no\" otherwise (without quotes).", "sample_inputs": ["5\n3 0 0 0\n3 3 0 0\n6 4 1 0\n6 3 3 0\n3 3 3 2"], "sample_outputs": ["yes\nyes\nyes\nno\nno"], "notes": "NoteSample 1. There has not been any match up to now (k\u2009=\u20090,\u2009d1\u2009=\u20090,\u2009d2\u2009=\u20090). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.Sample 2. You missed all the games (k\u2009=\u20093). As d1\u2009=\u20090 and d2\u2009=\u20090, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is \"yes\".Sample 3. You missed 4 matches, and d1\u2009=\u20091,\u2009d2\u2009=\u20090. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins)."}, "positive_code": [{"source_code": "module I = Int64 ;;\n\nlet (+/) = I.add\nlet ( */ ) = I.mul\nlet ( -/ ) = I.sub\nlet ( // ) = I.div \n\nlet check1 n k d1 d2 =\n let d = d1 +/ d1 +/ d2 in\n let c = d1 +/ 2L */ d2 in\n k >= c && Int64.rem (k -/ c) 3L = 0L &&\n n -/ k >= d &&\n I.rem (n -/ k -/ d) 3L = 0L\n;;\n\nlet check4 n k d1 d2 =\n let d = d1 +/ d2 +/ d2 in\n let c = d1 +/ d1 +/ d2 in \n k >= c && Int64.rem (k -/ c) 3L = 0L &&\n n -/ k >= d &&\n I.rem (n -/ k -/ d) 3L = 0L\n;;\n\nlet check2 n k d1 d2 =\n let d1, d2 = max d1 d2, min d1 d2 in\n let d = (d1 -/ d2) +/ d1 in\n let c = d1 +/ d2 in\n k >= c && Int64.rem (k -/ c) 3L = 0L &&\n n -/ k >= d &&\n I.rem (n -/ k -/ d) 3L = 0L\n;;\n\nlet check3 n k d1 d2 =\n let d1, d2 = max d1 d2, min d1 d2 in\n let d = d1 +/ d2 in\n let c = d1 +/ (d1 -/ d2) in\n k >= c && Int64.rem (k -/ c) 3L = 0L &&\n n -/ k >= d &&\n I.rem (n -/ k -/ d) 3L = 0L\n;;\n\nlet () =\n Scanf.scanf \"%d \" (fun n ->\n for i = 0 to n - 1 do\n Scanf.scanf \"%Ld %Ld %Ld %Ld \" (fun n k d1 d2 ->\n if check1 n k d1 d2 || check2 n k d1 d2 || check3 n k d1 d2 || check4 n k d1 d2 then\n print_endline \"yes\"\n else\n print_endline \"no\")\n done)\n;;\n"}], "negative_code": [{"source_code": "module I = Int64 ;;\n\nlet (+/) = I.add\nlet ( */ ) = I.mul\nlet ( -/ ) = I.sub\nlet ( // ) = I.div \n\nlet check1 n k d1 d2 =\n let d = d1 +/ d1 +/ d2 in\n let c = d1 +/ 2L */ d2 in\n k >= c && Int64.rem (k -/ c) 3L = 0L &&\n n -/ k >= d &&\n I.rem (n -/ k -/ d) 3L = 0L\n;;\n\nlet check2 n k d1 d2 =\n let d1, d2 = max d1 d2, min d1 d2 in\n let d = (d1 -/ d2) +/ d1 in\n let c = d1 +/ d2 in\n k >= c && Int64.rem (k -/ c) 3L = 0L &&\n n -/ k >= d &&\n I.rem (n -/ k -/ d) 3L = 0L\n;;\n\nlet check3 n k d1 d2 =\n let d1, d2 = max d1 d2, min d1 d2 in\n let d = d1 +/ d2 in\n let c = d1 +/ (d1 -/ d2) in\n k >= c && Int64.rem (k -/ c) 3L = 0L &&\n n -/ k >= d &&\n I.rem (n -/ k -/ d) 3L = 0L\n;;\n\nlet () =\n Scanf.scanf \"%d \" (fun n ->\n for i = 0 to n - 1 do\n Scanf.scanf \"%Ld %Ld %Ld %Ld \" (fun n k d1 d2 ->\n if check1 n k d1 d2 || check2 n k d1 d2 || check3 n k d1 d2 then\n print_endline \"yes\"\n else\n print_endline \"no\")\n done)\n;;\n"}, {"source_code": "module I = Int64 ;;\n\nlet (+/) = I.add\nlet ( */ ) = I.mul\nlet ( -/ ) = I.sub\nlet ( // ) = I.div \n\n\nlet () =\n Scanf.scanf \"%d \" (fun n ->\n for i = 0 to n - 1 do\n Scanf.scanf \"%Ld %Ld %Ld %Ld \" (fun n k d1 d2 ->\n if n -/ k >= 2L */ d1 +/ d2 &&\n I.rem (n -/ k -/ (2L */ d1 +/ d2)) 3L = 0L then\n print_endline \"yes\"\n else\n print_endline \"no\")\n done)\n;;\n"}], "src_uid": "324298100f3e36d289ef6ca8178ac6d3"} {"nl": {"description": "Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1,\u2009a2,\u2009... an. Nicholas does not want to break the sticks or glue them together. To make a h\u2009\u00d7\u2009w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h\u2009=\u2009w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009100).", "output_spec": "Print the single number \u2014 the maximum number of frames Nicholas can make for his future canvases.", "sample_inputs": ["5\n2 4 3 2 3", "13\n2 2 4 4 4 4 6 6 6 7 7 9 9", "4\n3 3 3 5"], "sample_outputs": ["1", "3", "0"], "notes": null}, "positive_code": [{"source_code": "let () = \n\tlet n = read_int() in \n\tlet p = Hashtbl.create (n/2) in (\n\t\tfor i = 1 to n do\n\t\t\tlet l = Scanf.scanf \" %d\" (fun i->i) in\n\t\t\tlet old =\n\t\t\t\ttry Hashtbl.find p l\t\n\t\t\t\twith _ -> 0\n\t\t\tin\n\t\t\tHashtbl.replace p l (old+1)\n\t\tdone;\n\t\t\n\t\tlet ns = Hashtbl.fold (fun _ l ns ->\n\t\t\tl/2 + ns\n\t\t) p 0 in\n\t\tprint_int (ns/2)\n\t\t\n\t)\n;;\n"}], "negative_code": [{"source_code": "let rec split_by2 = function\n\t| x::y::xs -> (x,y)::(split_by2 xs)\n\t| _ -> []\n;;\n\nlet () = \n\tlet n = read_int() in \n\tlet p = Hashtbl.create (n/2) in (\n\t\tfor i = 1 to n do\n\t\t\tlet l = Scanf.scanf \" %d\" (fun i->i) in\n\t\t\tlet old =\n\t\t\t\ttry Hashtbl.find p l\t\n\t\t\t\twith _ -> 0\n\t\t\tin\n\t\t\tHashtbl.replace p l (old+1)\n\t\tdone;\n\t\t\n\t\tlet ns = Hashtbl.fold (fun _ l ns ->\n\t\t\tl :: ns\n\t\t) p [] in\n\t\tlet s = List.sort compare ns in\n\t\tlet p = split_by2 s in\n\t\tlet m = List.map (fun (w,h)-> (max w h)/2) p in\n\t\tprint_int (List.fold_left (+) 0 m)\n\t)\n;;\n"}], "src_uid": "f9b56b3fddcd5db0d0671714df3f8646"} {"nl": {"description": "As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake.Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has n simple cakes and he is going to make a special cake placing some cylinders on each other.However, there are some additional culinary restrictions. The cakes are numbered in such a way that the cake number i can be placed only on the table or on some cake number j where j\u2009<\u2009i. Moreover, in order to impress friends Babaei will put the cake i on top of the cake j only if the volume of the cake i is strictly greater than the volume of the cake j.Babaei wants to prepare a birthday cake that has a maximum possible total volume. Help him find this value.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of simple cakes Babaei has. Each of the following n lines contains two integers ri and hi (1\u2009\u2264\u2009ri,\u2009hi\u2009\u2264\u200910\u2009000), giving the radius and height of the i-th cake.", "output_spec": "Print the maximum volume of the cake that Babaei can make. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["2\n100 30\n40 10", "4\n1 1\n9 7\n1 4\n10 7"], "sample_outputs": ["942477.796077000", "3983.539484752"], "notes": "NoteIn first sample, the optimal way is to choose the cake number 1.In second sample, the way to get the maximum volume is to use cakes with indices 1, 2 and 4."}, "positive_code": [{"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\n\nlet parent v = v/2\nlet lc v = 2*v\nlet rc v = 2*v+1\n\nlet superceil n =\n let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in\n 1 + (loop (n-1) 0)\n\nopen Printf\nopen Scanf\n\nlet sq z = z ** z\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let vol = Array.init n (fun i ->\n let r = long (read_int()) in\n let h = long (read_int()) in\n ((sq r) ** h, i)\n ) in\n\n Array.sort compare vol;\n let perm = Array.make n 0 in\n for i=0 to n-1 do\n perm.(snd vol.(i)) <- i\n done;\n\n let nn = superceil n in\n\n let v = Array.make (2*nn) 0L in (* v in our tree *)\n let t = Array.make (2*nn) 0L in (* t in our tree *)\n\n let rec insert a i x =\n let rec loop j = if j>0 then (\n a.(j) <- max a.(j) x;\n loop (parent j)\n ) in\n loop (i+nn)\n in\n\n let max_t_in_range i j =\n let rec f v l r ql qr =\n let m = (l+r)/2 in\n if l=ql && r=qr then t.(v) else\n\tlet t1 = if ql<=m then f (lc v) l m ql (min m qr) else 0L in\n\tlet t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else 0L in\n\tmax t1 t2\n in\n f 1 0 (nn-1) i j\n in\n\n let find_index vol =\n (* find the leftmost one of this volume, which is guaranteed to exist *)\n let rec loop x = if x>=nn then x-nn else\n\tif v.(lc x) < vol then loop (rc x) else loop (lc x)\n in\n if v.(1) < vol then failwith \"should be there\";\n loop 1\n in\n\n let bestvol = ref 0L in\n \n for i=0 to n-1 do\n let j = perm.(i) in\n let (vj, _) = vol.(j) in\n insert v j vj;\n (* the ith one to insert has volume vj and is to be put in position j *)\n let tj = (\n let k = find_index vj in\n vj ++ (if k = 0 then 0L else max_t_in_range 0 (k-1))\n ) in\n insert t j tj;\n bestvol := max !bestvol tj\n done;\n\n let pi = (asin 1.0) *. 2.0 in\n let volume = (Int64.to_float !bestvol) *. pi in\n\n printf \"%.9f\\n\" volume\n"}], "negative_code": [{"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\n\nlet parent v = v/2\nlet lc v = 2*v\nlet rc v = 2*v+1\n\nlet superceil n =\n let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in\n 1 + (loop (n-1) 0)\n\nopen Printf\nopen Scanf\n\nlet sq z = z ** z\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let vol = Array.init n (fun i ->\n let r = long (read_int()) in\n let h = long (read_int()) in\n ((sq r) ** h, i)\n ) in\n\n Array.sort compare vol;\n let perm = Array.make n 0 in\n for i=0 to n-1 do\n perm.(snd vol.(i)) <- i\n done;\n\n let nn = superceil n in\n\n let v = Array.make (2*nn) 0L in (* v in our tree *)\n let t = Array.make (2*nn) 0L in (* t in our tree *)\n\n let rec insert a i x =\n let rec loop j = if j>0 then (\n a.(j) <- max a.(j) x;\n loop (parent j)\n ) in\n loop (i+nn)\n in\n\n let max_t_in_range i j =\n let rec f v l r ql qr =\n let m = (l+r)/2 in\n if l=ql && r=qr then t.(v) else\n\tlet t1 = if ql<=m then f (lc v) l m ql (min m qr) else 0L in\n\tlet t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else 0L in\n\tmax t1 t2\n in\n f 1 0 (nn-1) i j\n in\n\n let find_index vol =\n (* find the rightmost index with v < vol. -1 if none exists *)\n let rec loop x = if x>=nn then x-nn-1 else\n\tif v.(lc x) < vol then loop (rc x) else loop (lc x)\n in\n if v.(1) < vol then nn-1 else loop 1\n in\n\n let bestvol = ref 0L in\n \n for i=0 to n-1 do\n let (vj, j) = vol.(perm.(i)) in\n (* the ith one to insert has volume vj and is to be put in position j *)\n let tj = if i=0 then vj else (\n let k = find_index vj in\n vj ++ (if k >= 0 then max_t_in_range 0 k else 0L)\n ) in\n insert v j vj;\n insert t j tj;\n bestvol := max !bestvol tj\n done;\n\n let pi = (asin 1.0) *. 2.0 in\n let volume = (Int64.to_float !bestvol) *. pi in\n\n printf \"%.9f\\n\" volume\n"}, {"source_code": "(* needs to be debugged *)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\n\nlet parent v = v/2\nlet lc v = 2*v\nlet rc v = 2*v+1\n\nlet superceil n =\n let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in\n 1 + (loop (n-1) 0)\n\nopen Printf\nopen Scanf\n\nlet sq z = z ** z\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let vol = Array.init n (fun i ->\n let r = long (read_int()) in\n let h = long (read_int()) in\n ((sq r) ** h, i)\n ) in\n\n Array.sort compare vol;\n let perm = Array.make n 0 in\n for i=0 to n-1 do\n perm.(snd vol.(i)) <- i\n done;\n\n let nn = superceil n in\n\n let v = Array.make (2*nn) 0L in (* v in our tree *)\n let t = Array.make (2*nn) 0L in (* t in our tree *)\n\n let rec insert a i x =\n let rec loop j = if j>0 then (\n a.(j) <- max a.(j) x;\n loop (parent j)\n ) in\n loop (i+nn)\n in\n\n let max_t_in_range i j =\n let rec f v l r ql qr =\n let m = (l+r)/2 in\n if l=ql && r=qr then t.(v) else\n\tlet t1 = if ql<=m then f (lc v) l m ql (min m qr) else 0L in\n\tlet t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else 0L in\n\tmax t1 t2\n in\n f 1 0 (nn-1) i j\n in\n\n let find_index vol =\n (* find the leftmost one of this volume, which is guaranteed to exist *)\n let rec loop x = if x>=nn then x-nn else\n\tif v.(lc x) < vol then loop (rc x) else loop (lc x)\n in\n if v.(1) < vol then failwith \"should be there\";\n loop 1\n in\n\n let bestvol = ref 0L in\n \n for i=0 to n-1 do\n let (vj, j) = vol.(perm.(i)) in\n insert v j vj;\n (* the ith one to insert has volume vj and is to be put in position j *)\n let tj = (\n let k = find_index vj in\n vj ++ (if k = 0 then 0L else max_t_in_range 0 (k-1))\n ) in\n insert t j tj;\n bestvol := max !bestvol tj\n done;\n\n let pi = (asin 1.0) *. 2.0 in\n let volume = (Int64.to_float !bestvol) *. pi in\n\n printf \"%.9f\\n\" volume\n"}], "src_uid": "49a647a99eab59a61b42515d4289d3cd"} {"nl": {"description": "The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: \"how many floors should be added to the i-th house to make it luxurious?\" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other \u2014 the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).", "input_spec": "The first line of the input contains a single number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of houses in the capital of Berland. The second line contains n space-separated positive integers hi (1\u2009\u2264\u2009hi\u2009\u2264\u2009109), where hi equals the number of floors in the i-th house. ", "output_spec": "Print n integers a1,\u2009a2,\u2009...,\u2009an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero. All houses are numbered from left to right, starting from one.", "sample_inputs": ["5\n1 2 3 1 2", "4\n3 2 1 4"], "sample_outputs": ["3 2 0 2 0", "2 3 4 0"], "notes": null}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n (* heights of houses *)\n let h = Array.init n (fun _ ->\n Scanf.scanf \"%d%_c\" (fun x -> x))\n in\n\n (* maximum of all houses to the right *)\n let maxes = Array.fold_right (fun x ->\n function\n | [] -> [x]\n | (hd :: _) as acc -> (max x hd) :: acc)\n h [0]\n in\n print_endline (String.concat \" \"\n (List.map2 (fun x h ->\n (* how much to add to x to make it strictly greater than h? *)\n string_of_int (max (x - h + 1) 0))\n (List.tl maxes) (Array.to_list h))))\n"}], "negative_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n (* heights of houses *)\n let h = Array.init n (fun _ ->\n Scanf.scanf \"%d%_c\" (fun x -> x))\n in\n\n (* maximum of all houses to the right *)\n let maxes = Array.fold_right (fun x ->\n function\n | [] -> [x]\n | (hd :: _) as acc -> (max x hd) :: acc)\n h []\n in\n print_endline (String.concat \" \"\n (List.map2 (fun x h ->\n string_of_int (max (x - h) 0 + if x - h > 0 then 1 else 0))\n maxes (Array.to_list h))))\n"}], "src_uid": "e544ed0904e2def0c1b2d91f94acbc56"} {"nl": {"description": "Fibonacci numbers are the sequence of integers: f0\u2009=\u20090, f1\u2009=\u20091, f2\u2009=\u20091, f3\u2009=\u20092, f4\u2009=\u20093, f5\u2009=\u20095, ..., fn\u2009=\u2009fn\u2009-\u20092\u2009+\u2009fn\u2009-\u20091. So every next number is the sum of the previous two.Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he performs the following two operations: operation \"T\": replace the top number with the sum of both numbers; operation \"B\": replace the bottom number with the sum of both numbers. If he performs n operations, starting with \"T\" and then choosing operations alternately (so that the sequence of operations looks like \"TBTBTBTB...\"), the last number written will be equal to fn\u2009+\u20091.Unfortunately, Bajtek sometimes makes mistakes and repeats an operation two or more times in a row. For example, if Bajtek wanted to compute f7, then he would want to do n\u2009=\u20096 operations: \"TBTBTB\". If he instead performs the sequence of operations \"TTTBBT\", then he will have made 3 mistakes, and he will incorrectly compute that the seventh Fibonacci number is 10. The number of mistakes in the sequence of operations is the number of neighbouring equal operations (\u00abTT\u00bb or \u00abBB\u00bb).You are given the number n of operations that Bajtek has made in an attempt to compute fn\u2009+\u20091 and the number r that is the result of his computations (that is last written number). Find the minimum possible number of mistakes that Bajtek must have made and any possible sequence of n operations resulting in r with that number of mistakes.Assume that Bajtek always correctly starts with operation \"T\".", "input_spec": "The first line contains the integers n and r (1\u2009\u2264\u2009n,\u2009r\u2009\u2264\u2009106).", "output_spec": "The first line of the output should contain one number \u2014 the minimum possible number of mistakes made by Bajtek. The second line should contain n characters, starting with \"T\", describing one possible sequence of operations with that number of mistakes. Each character must be either \"T\" or \"B\". If the required sequence doesn't exist, output \"IMPOSSIBLE\" (without quotes).", "sample_inputs": ["6 10", "4 5", "2 1"], "sample_outputs": ["2\nTBBTTB", "0\nTBTB", "IMPOSSIBLE"], "notes": null}, "positive_code": [{"source_code": "open Printf;;\nopen Scanf;;\n\nlet input () = scanf \"%d %d \" (fun x y -> x, y)\n\ntype op = T | B\n\nlet rec add n op xs =\n match n with\n 0 -> xs\n | n -> add (n - 1) op (op :: xs)\n\nlet rec gcd n m =\n let n, m = if n < m then m, n else n, m in\n if m = 0 then n\n else gcd m (n mod m) \n\nlet mistake ls =\n let rec iter prev_t acc = function\n [] -> acc\n | T :: ls -> \n if prev_t then iter true (acc + 1) ls else iter true acc ls\n | B :: ls ->\n if prev_t then iter false acc ls else iter false (acc + 1) ls in\n let x :: ls = ls in\n match x with\n T -> iter true 0 ls\n | B -> iter false 0 ls\n\nlet rec print_list a b =\n match a with\n [] -> ()\n | T :: ls -> \n if b then printf \"T\" else printf \"B\";\n print_list ls b\n | B :: ls ->\n if b then printf \"B\" else printf \"T\";\n print_list ls b\n\nlet print_res r a b =\n printf \"%d\\n\" r;\n print_list a b\n\nlet solve (n, r) =\n let rec like_gcd a b res acc =\n if (res = 0) then\n if (a = 0 && b = 1) || (a = 1 && b = 0) then\n begin(*\n List.iter \n (function T -> printf \"T;\" | B -> printf \"B;\") acc;\n printf \"\\n\";*)\n let _::ls = acc in\n let mis = mistake (T::ls) and\n mis' = mistake (B::ls) in\n(* printf \"%d %d\\n\" mis mis';*)\n if mis < mis' then\n Some ((mis, T::ls, true))\n else\n Some ((mis', B::ls, false))\n end\n else\n None \n else if res < 0 || b = 0 || a = 0 then None\n else if a > b then\n let r = a mod b and\n q = a / b in\n let acc = add q T acc in\n like_gcd r b (res - q) acc\n else\n let r = b mod a and\n q = b / a in\n let acc = add q B acc in\n like_gcd a r (res - q) acc in\n let mn = ref (r + 1) and\n a = ref [] and\n bmn = ref false in\n for i = 1 to r do\n match like_gcd r i n [] with\n None -> ()\n | Some (res, acc, b) -> \n(* printf \"%d=%d\\n\" i res; *)\n if !mn > res then begin\n mn := res;\n a := acc;\n bmn := b\n end\n done;\n if !mn > r then\n printf \"IMPOSSIBLE\\n\"\n else \n (print_res !mn !a !bmn;\n printf \"\\n\";)\n\nlet () = \n let inp = input () in\n solve inp\n"}], "negative_code": [{"source_code": "open Printf;;\nopen Scanf;;\n\nlet input () = scanf \"%d %d \" (fun x y -> x, y)\n\ntype op = T | B\n\nlet rec add n op xs =\n match n with\n 0 -> xs\n | n -> add (n - 1) op (op :: xs)\n\nlet rec gcd n m =\n let n, m = if n < m then m, n else n, m in\n if m = 0 then n\n else gcd m (n mod m) \n\nlet mistake ls =\n let rec iter i acc = function\n [] -> acc\n | T :: ls -> \n if (i mod 2) == 0 then iter (i + 1) acc ls else iter (i + 1) (acc + 1) ls\n | B :: ls ->\n if (i mod 2) == 1 then iter (i + 1) acc ls else iter (i + 1) (acc + 1) ls in\n iter 0 0 ls\n\nlet rec print_list a b =\n match a with\n [] -> ()\n | T :: ls -> \n if b then printf \"T\" else printf \"B\";\n print_list ls b\n | B :: ls ->\n if b then printf \"B\" else printf \"T\";\n print_list ls b\n\nlet print_res r a b =\n printf \"%d\\n\" r;\n print_list a b\n\nlet solve (n, r) =\n let rec like_gcd a b res acc =\n if (res = 0) then\n if (a = 0 && b = 1) || (a = 1 && b = 0) then\n begin\n(*\n List.iter \n (function T -> printf \"T;\" | B -> printf \"B;\") acc;\n printf \"\\n\";*)\n let _::ls = acc in\n let mis = mistake (T::ls) and\n mis' = mistake (B::ls) in\n(* printf \"%d %d\\n\" mis mis';*)\n if mis < n - mis' then\n Some ((mis, T::ls, true))\n else\n Some ((n - mis', B::ls, false))\n end\n else\n None \n else if res < 0 || b = 0 || a = 0 then None\n else if a > b then\n let r = a mod b and\n q = a / b in\n let acc = add q T acc in\n like_gcd r b (res - q) acc\n else\n let r = b mod a and\n q = b / a in\n let acc = add q B acc in\n like_gcd a r (res - q) acc in\n let mn = ref (r + 1) and\n a = ref [] and\n bmn = ref false in\n for i = 1 to r do\n match like_gcd r i n [] with\n None -> ()\n | Some (res, acc, b) -> \n(* printf \"%d=%d\\n\" i res; *)\n if !mn > res then begin\n mn := res;\n a := acc;\n bmn := b\n end\n done;\n if !mn > r then\n printf \"IMPOSSIBLE\\n\"\n else \n (print_res !mn !a !bmn;\n printf \"\\n\";)\n\nlet () = \n let inp = input () in\n solve inp\n"}], "src_uid": "fbe016d9686cc466d4b5dc44b67927e9"} {"nl": {"description": "Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.Polycarp decided to store the hash of the password, generated by the following algorithm: take the password $$$p$$$, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain $$$p'$$$ ($$$p'$$$ can still be equal to $$$p$$$); generate two random strings, consisting of lowercase Latin letters, $$$s_1$$$ and $$$s_2$$$ (any of these strings can be empty); the resulting hash $$$h = s_1 + p' + s_2$$$, where addition is string concatenation. For example, let the password $$$p =$$$ \"abacaba\". Then $$$p'$$$ can be equal to \"aabcaab\". Random strings $$$s1 =$$$ \"zyx\" and $$$s2 =$$$ \"kjh\". Then $$$h =$$$ \"zyxaabcaabkjh\".Note that no letters could be deleted or added to $$$p$$$ to obtain $$$p'$$$, only the order could be changed.Now Polycarp asks you to help him to implement the password check module. Given the password $$$p$$$ and the hash $$$h$$$, check that $$$h$$$ can be the hash for the password $$$p$$$.Your program should answer $$$t$$$ independent test cases.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The first line of each test case contains a non-empty string $$$p$$$, consisting of lowercase Latin letters. The length of $$$p$$$ does not exceed $$$100$$$. The second line of each test case contains a non-empty string $$$h$$$, consisting of lowercase Latin letters. The length of $$$h$$$ does not exceed $$$100$$$.", "output_spec": "For each test case print the answer to it \u2014 \"YES\" if the given hash $$$h$$$ could be obtained from the given password $$$p$$$ or \"NO\" otherwise.", "sample_inputs": ["5\nabacaba\nzyxaabcaabkjh\nonetwothree\nthreetwoone\none\nzzonneyy\none\nnone\ntwenty\nten"], "sample_outputs": ["YES\nYES\nNO\nYES\nNO"], "notes": "NoteThe first test case is explained in the statement.In the second test case both $$$s_1$$$ and $$$s_2$$$ are empty and $$$p'=$$$ \"threetwoone\" is $$$p$$$ shuffled.In the third test case the hash could not be obtained from the password.In the fourth test case $$$s_1=$$$ \"n\", $$$s_2$$$ is empty and $$$p'=$$$ \"one\" is $$$p$$$ shuffled (even thought it stayed the same). In the fifth test case the hash could not be obtained from the password."}, "positive_code": [{"source_code": "let n = read_int();;\nlet a = Array.make n (\"\",\"\");;\n\nfor i = 0 to (n-1) do\n\tlet s1 = read_line() in\n\tlet s2 = read_line() in\n\ta.(i) <- (s1,s2); done;;\n\n\nlet check a b =\n\tlet b = \"!\"^b in \n\t\n\tlet rec h s n = \n\t\tif n >= String.length s then 0 else (Char.code s.[n])+(h s (n+1)) in\n\t\n\tlet to_a s =\n\t\tlet a = Array.make (String.length s) 0 in\n\t\t\n\t\tlet rec f n =\t \n\t\t\tif n>= String.length s then () else (a.(n) <- Char.code (s.[n]); f (n+1)) in \n\t\tf 0; a in\n\n\tlet srt s = let a = to_a s in Array.sort compare a; a in \t\n\n\tlet hs = h a 0 in\t\n\tlet aa = srt a in \n\n let rec is_shuffled s = aa = srt s in\n\t\n\tlet rec f n hash = \n\t\tif (String.length b - n) >= String.length a then \t\t\t \n\t\t\t\tlet newhash = hash - Char.code (b.[n-1]) + Char.code (b.[n-1 + (String.length a)]) in\n\t\t\t\tif newhash = hs && is_shuffled (String.sub b n (String.length a)) then true else f (n+1) newhash\n\t\telse false in\n\tif String.length b < String.length a then false else f 1 (h (String.sub b 0 (String.length a)) 0);;\n\n(*Printf.printf \"%b\" (check \"abc\" \"adfcdbaasjkdfhklasdfhklsj\");; *)\n\n(*let ans = Array.make n false;;\n *)\nfor i = 0 to (n-1) do \n\tlet (a,b) = a.(i) in\n\tif check a b then \n\t\tprint_string \"YES\\n\"\n\telse print_string \"NO\\n\" done;;\n\t\t\t "}], "negative_code": [{"source_code": "let n = read_int();;\nlet a = Array.make n (\"\",\"\");;\n\nfor i = 0 to (n-1) do\n\tlet s1 = read_line() in\n\tlet s2 = read_line() in\n\ta.(i) <- (s1,s2); done;;\n\n\nlet check a b =\n\tlet b = \"!\"^b in \n\t\n\tlet rec h s n = \n\t\tif n >= String.length s then 0 else (Char.code s.[n])+(h s (n+1)) in\n\t\n\tlet to_a s =\n\t\tlet a = Array.make (String.length s) 0 in\n\t\t\n\t\tlet rec f n =\t \n\t\t\tif n>= String.length s then () else (a.(n) <- Char.code (s.[n]); f (n+1)) in \n\t\tf 0; a in\n\n\tlet srt s = let a = to_a s in Array.sort compare a; a in \t\n\n\tlet hs = h a 0 in\t\n\tlet aa = srt a in \n\n let rec is_shuffled s = aa = srt s in\n\t\n\tlet rec f n hash = \n\t\tif (String.length b - n) >= String.length a then \t\t\t \n\t\t\t\tlet newhash = hash - Char.code (b.[n-1]) + Char.code (b.[n-1 + (String.length a)]) in\n\t\t\t\tif newhash = hs then is_shuffled (String.sub b n (String.length a)) else f (n+1) newhash\n\t\telse false in\n\tif String.length b < String.length a then false else f 1 (h (String.sub b 0 (String.length a)) 0);;\n\n(*Printf.printf \"%b\" (check \"abc\" \"adfcdbaasjkdfhklasdfhklsj\");; *)\n\n(*let ans = Array.make n false;;\n *)\nfor i = 0 to (n-1) do \n\tlet (a,b) = a.(i) in\n\tif check a b then \n\t\tprint_string \"YES\\n\"\n\telse print_string \"NO\\n\" done;;\n\t\t\t "}, {"source_code": "let n = read_int();;\nlet a = Array.make n (\"\",\"\");;\n\nfor i = 0 to (n-1) do\n\tlet s1 = read_line() in\n\tlet s2 = read_line() in\n\ta.(i) <- (s1,s2); done;;\n\n\nlet check a b =\n\tlet b = \"!\"^b in \n\t\n\tlet rec h s n = \n\t\tif n >= String.length s then 0 else (Char.code s.[n])+(h s (n+1)) in\n\t\n\tlet to_a s =\n\t\tlet a = Array.make (String.length s) 0 in\n\t\t\n\t\tlet rec f n =\t \n\t\t\tif n>= String.length s then () else (a.(n) <- Char.code (s.[n]); f (n+1)) in \n\t\tf 0; a in\n\n\tlet srt s = let a = to_a s in Array.sort compare a; a in \t\n\n\tlet hs = h a 0 in\t\n\tlet aa = srt a in \n\n let rec is_shuffled s = aa = srt s in\n\t\n\tlet rec f n hash = \n\t\tif (String.length b - n) >= String.length a then \t\t\t \n\t\t\t\tlet newhash = hash - Char.code (b.[n-1]) + Char.code (b.[n-1 + (String.length a)]) in\n\t\t\t\tif newhash = hs then is_shuffled (String.sub b n (String.length a)) else f (n+1) newhash\n\t\telse false in\n\tif String.length b < String.length a then false else f 1 (h (String.sub b 0 (String.length a)) 0);;\n\n(*Printf.printf \"%b\" (check \"abc\" \"adfcdbaasjkdfhklasdfhklsj\");; *)\n\n(*let ans = Array.make n false;;\n *)\nfor i = 0 to (n-1) do \n\tlet (a,b) = a.(i) in\n\tif check a b then \n\t\tprint_string \"YES\\n\"\n\telse print_string \"NO\\n\" done;;\n\t\t\t "}, {"source_code": "let n = read_int();;\nlet a = Array.make n (\"\",\"\");;\n\nfor i = 0 to (n-1) do\n\tlet s1 = read_line() in\n\tlet s2 = read_line() in\n\ta.(i) <- (s1,s2); done;;\n\n\nlet check a b =\n\tlet b = \"!\"^b in \n\t\n\tlet rec h s n = \n\t\tif n >= String.length s then 0 else (Char.code s.[n])+(h s (n+1)) in\n\t\n\tlet to_a s =\n\t\tlet a = Array.make (String.length s) 0 in\n\t\t\n\t\tlet rec f n =\t \n\t\t\tif n>= String.length s then () else (a.(n) <- Char.code (s.[n]); f (n+1)) in \n\t\tf 0; a in\n\n\tlet srt s = let a = to_a s in Array.sort compare a; a in \t\n\n\tlet hs = h a 0 in\t\n\tlet aa = srt a in \n\n let rec is_shuffled s = \nlet st = srt s in\n let rec f n = if n>=String.length s then true else if st.(n) = aa.(n) then f (n+1) else false in\n\t\tif Array.length st = Array.length aa then f 0 else false in\n\t\n\tlet rec f n hash = \n\t\tif (String.length b - n) >= String.length a then \t\t\t \n\t\t\t\tlet newhash = hash - Char.code (b.[n-1]) + Char.code (b.[n-1 + (String.length a)]) in\n\t\t\t\tif newhash = hs then is_shuffled (String.sub b n (String.length a)) else f (n+1) newhash\n\t\telse false in\n\tif String.length b < String.length a then false else f 1 (h (String.sub b 0 (String.length a)) 0);;\n\n(*Printf.printf \"%b\" (check \"abc\" \"adfcdbaasjkdfhklasdfhklsj\");; *)\n\n(*let ans = Array.make n false;;\n *)\nfor i = 0 to (n-1) do \n\tlet (a,b) = a.(i) in\n\tif check a b then \n\t\tprint_string \"YES\\n\"\n\telse print_string \"NO\\n\" done;;\n\t\t\t "}, {"source_code": "let n = read_int();;\nlet a = Array.make n (\"\",\"\");;\n\nfor i = 0 to (n-1) do\n\tlet s1 = read_line() in\n\tlet s2 = read_line() in\n\ta.(i) <- (s1,s2); done;;\n\n\nlet check a b =\n\tlet b = \"!\"^b in \n\t\n\tlet rec h s n = \n\t\tif n >= String.length s then 0 else (Char.code s.[n])+(h s (n+1)) in\n\t\n\tlet to_a s =\n\t\tlet a = Array.make (String.length s) 0 in\n\t\t\n\t\tlet rec f n =\t \n\t\t\tif n>= String.length s then () else (a.(n) <- Char.code (s.[n]); f (n+1)) in \n\t\tf 0; a in\n\n\tlet srt s = Array.sort compare (to_a s) in \t\n\n\tlet hs = h a 0 in\t\n\tlet aa = srt a in \n\n let rec is_shuffled s =\n\t\tif aa = srt s then true else false in\n\t\n\tlet rec f n hash = \n\t\tif (String.length b - n) >= String.length a then \t\t\t \n\t\t\t\tlet newhash = hash - Char.code (b.[n-1]) + Char.code (b.[n-1 + (String.length a)]) in\n\t\t\t\tif newhash = hs then is_shuffled (String.sub b n (String.length a)) else f (n+1) newhash\n\t\telse false in\n\tif String.length b < String.length a then false else f 1 (h (String.sub b 0 (String.length a)) 0);;\n\n(*Printf.printf \"%b\" (check \"abc\" \"adfcdbaasjkdfhklasdfhklsj\");; *)\n\n(*let ans = Array.make n false;;\n *)\nfor i = 0 to (n-1) do \n\tlet (a,b) = a.(i) in\n\tif check a b then \n\t\tprint_string \"YES\\n\"\n\telse print_string \"NO\\n\" done;;\n\t\t\t "}], "src_uid": "48151011c3d380ab303ae38d0804176a"} {"nl": {"description": "Today, Marin is at a cosplay exhibition and is preparing for a group photoshoot!For the group picture, the cosplayers form a horizontal line. A group picture is considered beautiful if for every contiguous segment of at least $$$2$$$ cosplayers, the number of males does not exceed the number of females (obviously).Currently, the line has $$$n$$$ cosplayers which can be described by a binary string $$$s$$$. The $$$i$$$-th cosplayer is male if $$$s_i = 0$$$ and female if $$$s_i = 1$$$. To ensure that the line is beautiful, you can invite some additional cosplayers (possibly zero) to join the line at any position. You can't remove any cosplayer from the line.Marin wants to know the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful. She can't do this on her own, so she's asking you for help. Can you help her?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$) \u2014 the number of test cases. The first line of each test case contains a positive integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$) \u2014 the number of cosplayers in the initial line. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ \u2014 describing the cosplayers already in line. Each character of the string is either 0 describing a male, or 1 describing a female. Note that there is no limit on the sum of $$$n$$$.", "output_spec": "For each test case, print the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful.", "sample_inputs": ["9\n\n3\n\n000\n\n3\n\n001\n\n3\n\n010\n\n3\n\n011\n\n3\n\n100\n\n3\n\n101\n\n3\n\n110\n\n3\n\n111\n\n19\n\n1010110000100000101"], "sample_outputs": ["4\n2\n1\n0\n2\n0\n0\n0\n17"], "notes": "NoteIn the first test case, for each pair of adjacent cosplayers, you can invite two female cosplayers to stand in between them. Then, $$$000 \\rightarrow 0110110$$$.In the third test case, you can invite one female cosplayer to stand next to the second cosplayer. Then, $$$010 \\rightarrow 0110$$$."}, "positive_code": [{"source_code": "let n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let num = int_of_string(input_line stdin) in\r\n let line = (input_line stdin) in\r\nlet tot = ref 0 in\r\nlet truc = ref false in\r\nlet temp = ref 0 in\r\nfor j = 0 to String.length line -1 do\r\n if line.[j] = '0' then \r\n begin (if !temp >1 || not(!truc) then () else tot := !tot + 2 - !temp); truc := true ; temp := 0 end\r\n else incr temp\r\ndone ;\r\nprint_endline (string_of_int(!tot))\r\ndone;\r\n;;"}], "negative_code": [], "src_uid": "9966bfdc9677a9dd558684a00977cd58"} {"nl": {"description": "Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).", "input_spec": "The first input line contains four integer numbers n, t1, t2, k (1\u2009\u2264\u2009n,\u2009t1,\u2009t2\u2009\u2264\u20091000;\u00a01\u2009\u2264\u2009k\u2009\u2264\u2009100) \u2014 the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly. Each of the following n lines contains two integers. The i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) line contains space-separated integers ai, bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091000) \u2014 the speeds which the participant number i chose.", "output_spec": "Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.", "sample_inputs": ["2 3 3 50\n2 4\n4 2", "4 1 1 1\n544 397\n280 101\n280 101\n693 970"], "sample_outputs": ["1 15.00\n2 15.00", "4 1656.07\n1 937.03\n2 379.99\n3 379.99"], "notes": "Note First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2\u00b73\u00b70.5\u2009+\u20094\u00b73\u2009>\u20094\u00b73\u00b70.5\u2009+\u20092\u00b73. "}, "positive_code": [{"source_code": "let ni () = Scanf.scanf \" %d\" (fun x -> x) in\nlet nf () = float_of_int (ni ()) in\nlet n = ni () in\nlet t1 = nf () in\nlet t2 = nf () in\nlet k = 1.0 -. nf () /. 100.0 in\nlet f a b = a *. t1 *. k +. b *. t2 in\nlet a = Array.init n (fun i ->\n let a, b = nf (), nf () in\n (-1. *. max (f a b) (f b a), i + 1)\n) in\nArray.sort compare a;\nArray.iter (fun (e, i) ->\n Printf.printf \"%d %.2f\\n\" i ~-.e\n) a;;\n"}, {"source_code": "open Array;;\n \n \nlet (|>) x f = f x\n \n \nlet calc t1 t2 k = fun (a, b, i) ->\n let a = float a in\n let b = float b in\n let f a b = a *. t1 *. (1.0 -. k) +. b *. t2 in\n ( max (f a b) (f b a) , i)\n(* (res, i) *)\n \nlet cmp' x = \n if x > 0.0 \n then -1\n else if x < 0.0 then 1\n else 0\n \nlet cmp = fun (a, c) -> fun (b, d) ->\n if a = b \n then c - d\n else cmp' (a -. b)\nlet print a = \n Printf.printf \"%d \" (snd a + 1);\n (fst a)|> Printf.printf \"%.2f\\n\"\n \nlet main _ = \n let f i = Scanf.scanf \"%d %d\\n\" (fun a -> fun b -> a, b, i) in\n let n, t1, t2, k = Scanf.scanf \"%d %d %d %d\\n\"\n (fun m -> fun p->fun k->fun l \n -> m,p,k,l) in\n let a = init n f |> map (calc (float t1) (float t2) ((float k)/. 100.0) ) in\n fast_sort cmp a;\n iter print a;;\n \nmain ();;\n \n "}], "negative_code": [{"source_code": "open Array;;\n \n let (|>) x f = f x\n \n\nlet calc t1 t2 k = fun (a, b, i) ->\n let a = float a in\n let b = float b in\n let f a b = a *. t1 *. (1.0 -. k) +. b *. t2 in\n ( max (f a b) (f b a) , i)\n(* (res, i) *)\n \nlet cmp' x = \n if x > 0.0 \n then -1\n else if x < 0.0 then 1\n else 0\n \nlet cmp = fun (a, c) -> fun (b, d) ->\n if a = b \n then d - c\n else cmp' (a -. b)\nlet print a = \n Printf.printf \"%d \" (snd a + 1);\n (fst a)|> Printf.printf \"%.2f\\n\"\n \nlet main _ = \n let f i = Scanf.scanf \"%d %d\\n\" (fun a -> fun b -> a, b, i) in\n let n, t1, t2, k = Scanf.scanf \"%d %d %d %d\\n\"\n (fun m -> fun p->fun k->fun l \n -> m,p,k,l) in\n let a = init n f |> map (calc (float t1) (float t2) ((float k)/. 100.0) ) in\n fast_sort cmp a;\n iter print a;;\n \nmain ();;"}], "src_uid": "a89f9310996eb23254d07e52544e30ae"} {"nl": {"description": "Mishka has got n empty boxes. For every i (1\u2009\u2264\u2009i\u2009\u2264\u2009n), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met: i-th box is not put into another box; j-th box doesn't contain any other boxes; box i is smaller than box j (ai\u2009<\u2009aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes!", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 the number of boxes Mishka has got. The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the side length of i-th box.", "output_spec": "Print the minimum possible number of visible boxes.", "sample_inputs": ["3\n1 2 3", "4\n4 2 4 3"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first example it is possible to put box 1 into box 2, and 2 into 3.In the second example Mishka can put box 2 into box 3, and box 4 into box 1."}, "positive_code": [{"source_code": "let input () =\n let getNumber () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\n in let n = getNumber ()\n in let a = Array.make n (max_int, false)\n in begin\n for i = 0 to n - 1 do\n a.(i) <- (getNumber (), false)\n done;\n a\n end\n\nlet bSearch i a =\n let n = Array.length a\n in let l = ref (i + 1)\n in let r = ref (n - 1)\n in let m = ref 0\n in let found = ref false\n in begin\n while l <= r do\n m := (!l + !r) / 2;\n if fst a.(!m) > fst a.(i) && snd a.(!m) = false then\n if fst a.(!m - 1) = fst a.(i) || snd a.(!m - 1) = true then\n (r := !l - 1;\n found := true)\n else\n r := !m - 1\n else\n l := !m + 1\n done;\n if !found then Some !m\n else None\n end\n\nlet eat a =\n let n = Array.length a\n in let count = ref n\n in begin\n for i = 0 to n - 1 do\n match bSearch i a with\n | Some x -> begin\n count := !count - 1;\n a.(x) <- (fst a.(x), true)\n end\n | None -> ()\n done;\n !count\n end\n\nlet main () =\n let a = input ()\n in let cmp (x, _) (y, _) = compare x y\n in begin\n Array.sort cmp a;\n Printf.printf \"%d\" (eat a)\n end\n;;\n\nmain ();;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n\n Array.sort compare a;\n\n let rec run_length prev count best i = if i=n then best else (\n if a.(i) = prev then (\n let count = count + 1 in\n let best = max best count in\n run_length prev count best (i+1)\n ) else (\n run_length a.(i) 1 best (i+1)\n )\n ) in\n\n printf \"%d\\n\" (run_length a.(0) 1 1 1)\n"}], "negative_code": [{"source_code": "let input () =\n let getNumber () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\n in let n = getNumber ()\n in let a = Array.make n (max_int, false)\n in begin\n for i = 0 to n - 1 do\n a.(i) <- (getNumber (), false)\n done;\n a\n end\n\nlet bSearch i a =\n let n = Array.length a\n in let l = ref (i + 1)\n in let r = ref (n - 1)\n in let m = ref 0\n in let found = ref false\n in begin\n while l <= r do\n m := (!l + !r) / 2;\n if fst a.(!m) > fst a.(i) && snd a.(!m) = false then\n if fst a.(!m - 1) = fst a.(i) || snd a.(!m - 1) = true then\n (r := !l - 1;\n found := true)\n else\n r := !m - 1\n else\n l := !m + 1\n done;\n if !found then Some !m\n else None\n end\n\nlet eat a =\n let n = Array.length a\n in let count = ref n\n in begin\n for i = 0 to n - 1 do\n match bSearch i a with\n | Some x -> begin\n count := !count - 1;\n a.(x) <- (fst a.(x), true)\n end\n | None -> ()\n done;\n !count\n end\n\nlet main () =\n let a = input ()\n in let cmp (x, _) (y, _) = compare x y\n in begin\n Array.sort cmp a;\n eat a\n end\n;;\n\nmain ();;\n"}], "src_uid": "0cbd3eee259b1436f82e259be7d7ee0e"} {"nl": {"description": "Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A|\u2009<\u2009|B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.", "input_spec": "The first line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of strings. The second line contains n integers ci (0\u2009\u2264\u2009ci\u2009\u2264\u2009109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100\u2009000.", "output_spec": "If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print \u2009-\u20091. Otherwise, print the minimum total amount of energy Vasiliy has to spent.", "sample_inputs": ["2\n1 2\nba\nac", "3\n1 3 1\naa\nba\nac", "2\n5 5\nbbb\naaa", "2\n3 3\naaa\naa"], "sample_outputs": ["1", "1", "-1", "-1"], "notes": "NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is \u2009-\u20091.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string \"aa\" should go before string \"aaa\", thus the answer is \u2009-\u20091."}, "positive_code": [{"source_code": "open Printf\nopen String\nopen Int64\n\nlet n = Scanf.scanf \"%d \" (fun x -> x);;\n\nlet e = Array.make n Int64.zero (*energy for reverse string*)\nlet s = Array.make n \"\" (*stores all the strings to be sorted*)\nlet rs = Array.make n \"\"\n\nlet d1 = Array.make n (Int64.max_int) (*flip*)\n\nlet d2 = Array.make n (Int64.max_int)\n\nfor i = 0 to n-1 do\n let jj = Scanf.bscanf Scanf.Scanning.stdin \"%Ld \" (fun x -> x) in\n e.(i) <- jj\ndone\n\nlet rev s =\n let len = String.length s in\n let rec rev_helper i s2 =\n if i >= len then s2\n else\n rev_helper (i+1) s2^(Char.escaped s.[i])\n in\n rev_helper 0 \"\"\n\nfor i = 0 to n - 1 do\n let jj = Scanf.bscanf Scanf.Scanning.stdin \"%s \" (fun x -> x) in\n s.(i) <- jj; rs.(i) <- (rev jj)\ndone\n\nlet () = d1.(0) <- of_int 0;;\nlet () = d2.(0) <- e.(0);;\n\n(*printf \"%Ld\" max_int;;\n*)\n\n(*DEBUG*)\n(*\n let () = print_endline (rev \"abc\")\n\nfor i = 0 to n - 1 do\n print_endline s.(i);\n print_endline rs.(i)\ndone\n*)\n\nlet g s1 s2 =\n let x = String.compare s1 s2 in\n if (x<=0) then of_int 0\n else max_int\n\nlet f s1 s2 n =\n let x = String.compare s1 s2 in\n if (x<=0) then e.(n)\n else max_int\n\nlet my_add a b =\n if ( (compare a max_int == 0 ) || (compare b max_int == 0 ) ) then max_int\n else add a b\n\nlet () = \n for i = 1 to n - 1 do\n let x1 = my_add d1.(i-1) (g s.(i-1) s.(i) ) in\n let x2 = my_add d2.(i-1) (g rs.(i-1) s.(i) ) in\n d1.(i) <- min x1 x2;\n let y1 = my_add d1.(i-1) (f s.(i-1) rs.(i) i ) in\n let y2 = my_add d2.(i-1) (f rs.(i-1) rs.(i) i ) in\n d2.(i) <- min y1 y2\ndone\n\nlet () =\n let x = min d1.(n-1) d2.(n-1) in\n if (x==max_int) then printf \"%d\\n\" (-1)\n else print_endline (to_string x)\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet reverse s =\n let n = String.length s in\n String.init n (fun i -> s.[n-i-1])\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let c = Array.init n (fun _ -> long (read_int())) in\n let s = Array.init n (fun _ -> read_string ()) in \n let sr = Array.init n (fun i -> reverse s.(i)) in\n\n let nr_cost = Array.make n 0L in\n let r_cost = Array.make n 0L in\n\n nr_cost.(n-1) <- 0L;\n r_cost.(n-1) <- c.(n-1);\n\n let inf = (Int64.max_int) // 4L in\n \n for i=n-2 downto 0 do\n let test a b = if a > b then inf else 0L in\n nr_cost.(i) <- min\n (nr_cost.(i+1) ++ (test s.(i) s.(i+1)))\n (r_cost.(i+1) ++ (test s.(i) sr.(i+1)));\n r_cost.(i) <- c.(i) ++ min\n (nr_cost.(i+1) ++ (test sr.(i) s.(i+1)))\n (r_cost.(i+1) ++ (test sr.(i) sr.(i+1)));\n nr_cost.(i) <- min nr_cost.(i) inf;\n r_cost.(i) <- min r_cost.(i) inf; \n done;\n\n let total = min nr_cost.(0) r_cost.(0) in\n\n if total = inf then printf \"-1\\n\" else printf \"%Ld\\n\" total\n"}], "negative_code": [{"source_code": "open Printf\nopen String\n\nlet n = Scanf.scanf \"%d \" (fun x -> x);;\n\nlet e = Array.make n (-1) (*energy for reverse string*)\nlet s = Array.make n \"\" (*stores all the strings to be sorted*)\nlet rs = Array.make n \"\"\n\nlet d1 = Array.make n (max_int) (*flip*)\n\nlet d2 = Array.make n (max_int)\n\nfor i = 0 to n-1 do\n let jj = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x) in\n e.(i) <- jj\ndone\n\nlet rev s =\n let len = String.length s in\n let rec rev_helper i s2 =\n if i >= len then s2\n else\n rev_helper (i+1) s2^(Char.escaped s.[i])\n in\n rev_helper 0 \"\"\n\nfor i = 0 to n - 1 do\n let jj = Scanf.bscanf Scanf.Scanning.stdin \"%s \" (fun x -> x) in\n s.(i) <- jj; rs.(i) <- (rev jj)\ndone\n\nlet () = d1.(0) <- 0;;\nlet () = d2.(0) <- e.(0);;\n\n(*DEBUG*)\n(*\n let () = print_endline (rev \"abc\")\n\nfor i = 0 to n - 1 do\n print_endline s.(i);\n print_endline rs.(i)\ndone\n*)\n\nlet g s1 s2 =\n let x = String.compare s1 s2 in\n if (x<=0) then 0\n else max_int\n\nlet f s1 s2 n =\n let x = String.compare s1 s2 in\n if (x<=0) then e.(n)\n else max_int\n\nlet my_add a b =\n if (a==max_int || b==max_int) then max_int\n else a + b\n\nlet () = \n for i = 1 to n - 1 do\n let x1 = my_add d1.(i-1) (g s.(i-1) s.(i) ) in\n let x2 = my_add d2.(i-1) (g rs.(i-1) s.(i) ) in\n d1.(i) <- min x1 x2;\n let y1 = my_add d1.(i-1) (f s.(i-1) rs.(i) i ) in\n let y2 = my_add d2.(i-1) (f rs.(i-1) rs.(i) i ) in\n d2.(i) <- min y1 y2\ndone\n\nlet () =\n let x = min d1.(n-1) d2.(n-1) in\n if (x==max_int) then\n begin\n print_int (-1); print_endline \"\"\n end\n else\n begin\n print_int x; print_endline \"\"\n end\n\n"}], "src_uid": "91cfd24b8d608eb379f709f4509ecd2d"} {"nl": {"description": "Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k\u2009+\u20091)-th and (k\u2009+\u2009n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so\u00a0\u2014 their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009300\u2009000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009107), here ci is the cost of delaying the i-th flight for one minute.", "output_spec": "The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1,\u2009t2,\u2009...,\u2009tn (k\u2009+\u20091\u2009\u2264\u2009ti\u2009\u2264\u2009k\u2009+\u2009n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.", "sample_inputs": ["5 2\n4 2 1 10 2"], "sample_outputs": ["20\n3 6 7 4 5"], "notes": "NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3\u2009-\u20091)\u00b74\u2009+\u2009(4\u2009-\u20092)\u00b72\u2009+\u2009(5\u2009-\u20093)\u00b71\u2009+\u2009(6\u2009-\u20094)\u00b710\u2009+\u2009(7\u2009-\u20095)\u00b72\u2009=\u200938 burles. However, the better schedule is shown in the sample answer, its cost is (3\u2009-\u20091)\u00b74\u2009+\u2009(6\u2009-\u20092)\u00b72\u2009+\u2009(7\u2009-\u20093)\u00b71\u2009+\u2009(4\u2009-\u20094)\u00b710\u2009+\u2009(5\u2009-\u20095)\u00b72\u2009=\u200920 burles."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let k = read_int () in\n\n let original_cost = Array.init n (fun _ -> long (read_int())) in\n let c = Array.init n (fun i -> (original_cost.(i),i)) in\n\n let skip_to = Array.init (k+n) (fun i -> i+1) in\n let item = Array.make (k+n) (-1) in\n\n Array.sort (fun a b -> compare b a) c;\n\n for i=0 to n-1 do\n let (cost,index) = c.(i) in\n let place = max index k in\n let rec find_empty j =\n if item.(j) = -1 then j\n else find_empty skip_to.(j)\n in\n let place1 = find_empty place in\n item.(place1) <- index;\n let rec push j =\n if j = place1 then () else (\n\tlet nj = skip_to.(j) in\n\tskip_to.(j) <- place1;\n\tpush nj\n )\n in\n push place\n done;\n\n let total_cost = sum k (k+n-1) (fun j ->\n(* printf \"j=%d \" j;\n printf \"item.(j) = %d\\n\" item.(j); *)\n let index = item.(j) in\n original_cost.(index) ** ((long j) -- (long index))\n ) in\n\n let times = Array.make n 0 in\n\n printf \"%Ld\\n\" total_cost;\n\n for j = k to (k+n-1) do\n times.(item.(j)) <- j+1\n done;\n\n for i=0 to n-1 do\n printf \"%d \" times.(i)\n done;\n\n print_newline()\n"}], "negative_code": [], "src_uid": "8c23fcc84c6921bc2a95ff0586516321"} {"nl": {"description": "Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat. There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1,\u2009...,\u2009an and p1,\u2009...,\u2009pn. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days. ", "input_spec": "The first line of input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of days. In the next n lines, i-th line contains two integers ai and pi (1\u2009\u2264\u2009ai,\u2009pi\u2009\u2264\u2009100), the amount of meat Duff needs and the cost of meat in that day.", "output_spec": "Print the minimum money needed to keep Duff happy for n days, in one line.", "sample_inputs": ["3\n1 3\n2 2\n3 1", "3\n1 3\n2 1\n3 2"], "sample_outputs": ["10", "8"], "notes": "NoteIn the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day."}, "positive_code": [{"source_code": "open Str;;\nopen Array;;\nlet n = read_int () and ans = ref 0 and price = ref 101;;\nfor i = 1 to n do\n let ins = map (int_of_string) (of_list (split (regexp \" \") (read_line ()))) in\n let a = ins.(0) and b = ins.(1) in\n begin\n price := min !price b;\n ans := !ans + !price * a; \n end;\ndone;;\nprint_int !ans;;\n"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let n = read () in\n let rec loop i list =\n if i < n\n then\n let mass = read () in\n let price = read () in\n loop (i + 1) ((mass, price) :: list)\n else\n List.rev list\n in loop 0 []\n\nlet get_min price min =\n if price >= min\n then \n min\n else\n price\n\nlet get_sum sum min mass =\n sum + min * mass\n\nlet update_sum_min (mass, price) (sum, min) = \n let min_upd = get_min price min in\n let sum_upd = get_sum sum mass min_upd in\n (sum_upd, min_upd)\n \nlet solve list = \n let rec loop (sum, min) list =\n match list with\n | (head :: tail) -> loop (update_sum_min head (sum, min)) tail\n | [] -> sum\n in loop (0, 101) list\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n\t\t\t let a = Array.init n (fun _ ->\n\t\t\t\t\t\t Scanf.scanf \"%d %d\\n\"\n\t\t\t\t\t\t\t (fun a w -> (a, w))) in\n\t\t\t (* buy as much as we need to hit the next cheapest day *)\n\t\t\t let rec calc cur acc =\n\t\t\t if cur >= n then acc\n\t\t\t else begin\n\t\t\t\t let rec loop i s =\n\t\t\t\t if i >= n || snd a.(i) < snd a.(cur)\n\t\t\t\t then i, s\n\t\t\t\t else loop (i + 1) (s + fst a.(i) * snd a.(cur)) in\n\t\t\t\t let next, add = loop cur 0 in\n\t\t\t\t calc next (acc + add)\n\t\t\t\t end\n\t\t\t in\n\t\t\t Printf.printf \"%d\\n\" (calc 0 0))\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let a = Array.init n (fun _ -> Scanf.scanf \"%d%_c%d%_c\" (fun x y -> (x, y))) in\n\n\tlet sum = ref 0 in\n\n\tlet min = ref 2000000 in\n\n\tlet rec loop i = \n\t\tif i < n then\n\t\tbegin\n\t\t\tlet (x, y) = a.(i) in\n\t\t\tif !min > y then begin min := y end;\n\t\t\tsum := !sum + x * !min;\n\t\t\tloop (i+1)\n\t\tend\n\tin\n\tloop 0;\n\tPrintf.printf \"%d\\n\" !sum);;"}], "negative_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let a = Array.init n (fun _ -> Scanf.scanf \"%d%_c%d%_c\" (fun x y -> (x, y))) in\n\n\tlet sum = ref 0 in\n\n\tlet min = ref 2000000 in\n\n\tlet rec loop i = \n\t\tif i < n then\n\t\tbegin\n\t\t\tlet (x, y) = a.(i) in\n\t\t\tif !min > x then begin min := x end;\n\t\t\tsum := !sum + y * !min;\n\t\t\tloop (i+1)\n\t\tend\n\tin\n\tloop 0;\n\tPrintf.printf \"%d\\n\" !sum);;"}, {"source_code": "let x = fun n -> n\nin x 20;;"}], "src_uid": "28e0822ece0ed35bb3e2e7fc7fa6c697"} {"nl": {"description": "There is a game called \"I Wanna Be the Guy\", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009\u2009n\u2009\u2264\u2009100). The next line contains an integer p (0\u2009\u2264\u2009p\u2009\u2264\u2009n) at first, then follows p distinct integers a1,\u2009a2,\u2009...,\u2009ap (1\u2009\u2264\u2009ai\u2009\u2264\u2009n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.", "output_spec": "If they can pass all the levels, print \"I become the guy.\". If it's impossible, print \"Oh, my keyboard!\" (without the quotes).", "sample_inputs": ["4\n3 1 2 3\n2 2 4", "4\n3 1 2 3\n2 2 3"], "sample_outputs": ["I become the guy.", "Oh, my keyboard!"], "notes": "NoteIn the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.In the second sample, no one can pass level 4."}, "positive_code": [{"source_code": "let rec get_uniques = function\n | head :: (middle :: _ as tail) -> \n if head = middle \n then \n get_uniques tail \n else \n (head :: get_uniques tail)\n | smaller -> smaller\n\nlet read () = List.map (fun n -> Pervasives.int_of_string n) (Str.split (Str.regexp \" \") (Pervasives.read_line ()))\n\nlet n = Pervasives.read_int ()\nlet x_levels = read ()\nlet y_levels = read ()\n\nlet result = \n let len = List.length (get_uniques (List.sort (compare) (List.append (List.tl x_levels) (List.tl y_levels))))\n in\n if len = n\n then\n \"I become the guy.\"\n else\n \"Oh, my keyboard!\"\n\nlet () = Printf.printf \"%s\\n\" result\n"}, {"source_code": "let read () = let total = Scanf.scanf \"%d \" (fun n -> n) in\n let rec loop list n =\n if n > 0\n then\n let var = Scanf.scanf \"%d \" (fun k -> k) in\n loop (var :: list) (n - 1)\n else\n list\n in loop [] total\n\nlet rec get_uniques = function\n | head :: (middle :: _ as tail) -> \n if head = middle \n then \n get_uniques tail \n else \n (head :: get_uniques tail)\n | smaller -> smaller\n\nlet n = Scanf.scanf \"%d \" (fun n -> n)\nlet x_levels = read ()\nlet y_levels = read ()\n\nlet result = \n let len = List.length (get_uniques (List.sort (compare) (List.append x_levels y_levels)))\n in\n if len = n\n then\n \"I become the guy.\"\n else\n \"Oh, my keyboard!\"\n\nlet () = Printf.printf \"%s\\n\" result\n"}, {"source_code": "let n = read_int () in\nlet tr = Array.make n false in\n\nlet g () =\nlet l = Scanf.Scanning.from_string (read_line ()) in\ntry\nlet tc = Scanf.bscanf l \"%d \" (fun x -> x) in\n(for i = 1 to tc do\n let k = Scanf.bscanf l \"%d \" (fun x -> x) in\n tr.(k-1) <- true\ndone)\nwith _ -> ()\nin\ng() ; g() ;\n\nlet f () =\n let result = ref true in\n for i = 0 to n-1 do\n if tr.(i) = false then result := false\n done;\n !result\nin\n\nif f () then \nprint_endline \"I become the guy.\"\nelse \nprint_endline \"Oh, my keyboard!\";;\n"}, {"source_code": "module IntSet = Set.Make( \n struct\n let compare = Pervasives.compare\n type t = int\n end ) ;;\n\nlet rec split s i acc =\nbegin\n if i > String.length s \n then List.rev acc\n else \n let first = \n if String.contains_from s i ' ' \n then String.index_from s i ' ' \n else String.length s \n in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc) \nend in \n\nlet from_list xs = List.fold_right IntSet.add xs IntSet.empty in \nlet alln = \n let len = int_of_string (read_line()) in \n Array.init len (fun a -> a+1) \n |> (fun xs -> Array.fold_right IntSet.add xs IntSet.empty) in \nlet x = split (read_line ()) 0 [] |> List.tl |> from_list in\nlet y = split (read_line ()) 0 [] |> List.tl |> from_list in \nprint_string (if IntSet.equal alln (IntSet.union x y) then \"I become the guy.\" else \"Oh, my keyboard!\") \n"}], "negative_code": [{"source_code": "let rec get_uniques = function\n | head :: (middle :: _ as tail) -> \n if head = middle \n then \n get_uniques tail \n else \n (head :: get_uniques tail)\n | smaller -> smaller\n\nlet read () = List.map (fun n -> Pervasives.int_of_string n) (Str.split (Str.regexp \" \") (Pervasives.read_line ()))\n\nlet n = Pervasives.read_int ()\nlet x_levels = read ()\nlet y_levels = read ()\n\nlet result = \n let len = List.length (get_uniques (List.sort (compare) (List.append x_levels y_levels)))\n in\n if len = n\n then\n \"I become the guy.\"\n else\n \"Oh, my keyboard!\"\n\nlet () = Printf.printf \"%s\\n\" result\n"}, {"source_code": "let n = read_int () in\nlet tr = Array.make n false in\n\nlet g () =\nlet l = Scanf.Scanning.from_string (read_line ()) in\ntry\n(for i = 1 to n do\n let k = Scanf.bscanf l \"%d \" (fun x -> x) in\n tr.(k-1) <- true\ndone)\nwith _ -> ()\nin\ng() ; g() ;\n\nlet f () =\n let result = ref true in\n for i = 0 to n-1 do\n if tr.(i) = false then result := false\n done;\n !result\nin\n\nif f () then \nprint_endline \"I become the guy.\"\nelse \nprint_endline \"Oh, my keyboard!\";;\n"}, {"source_code": "let n = read_int () in\nlet tr = Array.make n false in\n\nlet g () =\nlet l = Scanf.Scanning.from_string (read_line ()) in\ntry\n(for i = 1 to n do\n let k = Scanf.bscanf l \"%d \" (fun x -> x) in\n tr.(k-1) <- true\ndone)\nwith _ -> ()\nin\ng() ; g() ;\n\nlet f () =\n let result = ref true in\n for i = 0 to n-1 do\n if tr.(i) = false then result := false\n done;\n !result\nin\n\nif f () then \nprint_endline \"I become the guy\"\nelse \nprint_endline \"Oh, my keyboard!\";;\n"}, {"source_code": "module IntSet = Set.Make( \n struct\n let compare = Pervasives.compare\n type t = int\n end ) ;;\n\nlet rec split s i acc =\nbegin\n if i == 1 + String.length s \n then acc\n else \n let first = \n if String.contains_from s i ' ' \n then String.index_from s i ' ' \n else String.length s\n in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc) \nend in \n\nlet from_list xs = List.fold_right IntSet.add xs IntSet.empty in \nlet alln = \n let len = int_of_string (read_line()) in \n Array.init len (fun a -> a+1) \n |> (fun xs -> Array.fold_right IntSet.add xs IntSet.empty) in \nlet x = split (read_line ()) 0 [] |> List.tl |> from_list in\nlet y = split (read_line ()) 0 [] |> List.tl |> from_list in \nprint_string (if IntSet.equal alln (IntSet.union x y) then \"I become the guy.\" else \"Oh, my keyboard!\") \n"}], "src_uid": "044ade01d2de1486735742369227ae1d"} {"nl": {"description": "PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k\u2009-\u20091 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009104)\u00a0\u2014 the number of Balls living in the forest. The second line contains a sequence p1,\u2009p2,\u2009...,\u2009pn of length n, where (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id. It's guaranteed that the sequence p corresponds to some valid forest. Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format: In the first line, output the integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009104)\u00a0\u2014 the number of Balls and the integer m (0\u2009\u2264\u2009m\u2009<\u2009n)\u00a0\u2014 the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows: 5 31 23 44 5", "output_spec": "You should output the number of trees in the forest where PolandBall lives.", "sample_inputs": ["5\n2 1 5 3 3", "1\n1"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample testcase, possible forest is: 1-2 3-4-5. There are 2 trees overall.In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree."}, "positive_code": [{"source_code": "type t = {p : int array;\n\t rank : int array}\n\nlet makeset set x =\n set.p.(x) <- x;\n set.rank.(x) <- 0\n\nlet rec find set x =\n if x <> set.p.(x) then set.p.(x) <- find set set.p.(x);\n set.p.(x)\n\nlet link set x y =\n if set.rank.(x) > set.rank.(y) then (\n set.p.(y) <- x;\n x\n ) else (\n if set.rank.(x) = set.rank.(y) then set.rank.(y) <- set.rank.(y) + 1;\n set.p.(x) <- y;\n y\n )\n\nlet newsets size =\n let set =\n {p = Array.make size (-1);\n rank = Array.make size 0\n }\n in\n for i = 0 to size-1 do\n makeset set i\n done;\n set\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n p.(i) <- Scanf.bscanf sb \" %d\" (fun s -> s) - 1\n done;\n in\n let ds = newsets n in\n for i = 0 to n - 1 do\n let u = find ds i in\n let v = find ds p.(i) in\n\tignore (link ds u v)\n done;\n let res = ref 0 in\n for i = 0 to n - 1 do\n\tif find ds i = i\n\tthen incr res\n done;\n Printf.printf \"%d\\n%!\" !res\n"}], "negative_code": [], "src_uid": "6d940cb4b54f63a7aaa82f21e4c5b994"} {"nl": {"description": "You are playing the game \"Arranging The Sheep\". The goal of this game is to make the sheep line up. The level in the game is described by a string of length $$$n$$$, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.For example, if $$$n=6$$$ and the level is described by the string \"**.*..\", then the following game scenario is possible: the sheep at the $$$4$$$ position moves to the right, the state of the level: \"**..*.\"; the sheep at the $$$2$$$ position moves to the right, the state of the level: \"*.*.*.\"; the sheep at the $$$1$$$ position moves to the right, the state of the level: \".**.*.\"; the sheep at the $$$3$$$ position moves to the right, the state of the level: \".*.**.\"; the sheep at the $$$2$$$ position moves to the right, the state of the level: \"..***.\"; the sheep are lined up and the game ends. For a given level, determine the minimum number of moves you need to make to complete the level.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^6$$$). The second line of each test case contains a string of length $$$n$$$, consisting of the characters '.' (empty space) and '*' (sheep)\u00a0\u2014 the description of the level. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.", "output_spec": "For each test case output the minimum number of moves you need to make to complete the level.", "sample_inputs": ["5\n6\n**.*..\n5\n*****\n3\n.*.\n3\n...\n10\n*.*...*.**"], "sample_outputs": ["1\n0\n0\n0\n9"], "notes": null}, "positive_code": [{"source_code": "open Printf;;\nopen List;;\nlet n = read_int();;\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\nlet count_sheep sl =\n let counter = ref 0L in\n List.map (fun x -> if x == '*' then \n (counter := Int64.(add (!counter) 1L);\n 0L) else\n !counter\n ) sl;;\nlet rec zip (l1, l2) =\n match (l1, l2) with\n | (_, []) -> []\n | ([], _) -> []\n | (h1::t1, h2::t2) -> (h1, h2) :: zip (t1, t2)\nlet solve sl = \n let left = count_sheep (explode sl) in\n let right = count_sheep (List.rev (explode sl)) in\n let counts = zip (left, (List.rev right)) in\n List.fold_right (fun (x, y) res -> Int64.(add (min x y) res)) counts 0L;;\nfor i = 0 to n - 1 do\n let _ = read_int() in\n let line = read_line() in\n printf \"%Ld\\n\" (solve line)\ndone"}], "negative_code": [{"source_code": "open Printf;;\nopen List;;\nlet n = read_int();;\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\nlet count_sheep sl =\n let counter = ref 0 in\n List.map (fun x -> if x == '*' then \n (counter := (!counter) + 1;\n 0) else\n !counter\n ) sl;;\nlet rec zip (l1, l2) =\n match (l1, l2) with\n | (_, []) -> []\n | ([], _) -> []\n | (h1::t1, h2::t2) -> (h1, h2) :: zip (t1, t2)\nlet solve sl = \n let left = count_sheep (explode sl) in\n let right = count_sheep (List.rev (explode sl)) in\n let counts = zip (left, (List.rev right)) in\n List.fold_right (fun (x, y) res -> (min x y) + res) counts 0;;\nfor i = 0 to n - 1 do\n let _ = read_int() in\n let line = read_line() in\n printf \"%d\\n\" (solve line)\ndone"}], "src_uid": "e094a3451b8b28be90cf54a4400cb916"} {"nl": {"description": "I wonder, does the falling rain Forever yearn for it's disdain?Effluvium of the MindYou are given a positive integer $$$n$$$.Find any permutation $$$p$$$ of length $$$n$$$ such that the sum $$$\\operatorname{lcm}(1,p_1) + \\operatorname{lcm}(2, p_2) + \\ldots + \\operatorname{lcm}(n, p_n)$$$ is as large as possible. Here $$$\\operatorname{lcm}(x, y)$$$ denotes the least common multiple (LCM) of integers $$$x$$$ and $$$y$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1\\,000$$$). Description of the test cases follows. The only line for each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, $$$\\ldots$$$, $$$p_n$$$\u00a0\u2014 the permutation with the maximum possible value of $$$\\operatorname{lcm}(1,p_1) + \\operatorname{lcm}(2, p_2) + \\ldots + \\operatorname{lcm}(n, p_n)$$$. If there are multiple answers, print any of them.", "sample_inputs": ["2\n\n1\n\n2"], "sample_outputs": ["1 \n2 1"], "notes": "NoteFor $$$n = 1$$$, there is only one permutation, so the answer is $$$[1]$$$.For $$$n = 2$$$, there are two permutations: $$$[1, 2]$$$\u00a0\u2014 the sum is $$$\\operatorname{lcm}(1,1) + \\operatorname{lcm}(2, 2) = 1 + 2 = 3$$$. $$$[2, 1]$$$\u00a0\u2014 the sum is $$$\\operatorname{lcm}(1,2) + \\operatorname{lcm}(2, 1) = 2 + 2 = 4$$$. "}, "positive_code": [{"source_code": "let get_num () =\n let rec f acc =\n try\n let c = input_byte stdin in\n if int_of_char '0' <= c && c <= int_of_char '9' then\n f ((acc * 10) + c - int_of_char '0')\n else if acc > 0 then Some acc\n else None\n with End_of_file -> if acc > 0 then Some acc else None\n in\n f 0\n\nlet solve_case () =\n match get_num () with\n | Some n ->\n let rec f i =\n if i > n then ()\n else\n let () = print_int (i + 1) in\n let () = print_char ' ' in\n let () = print_int i in\n let () = print_char ' ' in\n f (i + 2)\n in\n if n mod 2 = 0 then f 1\n else\n let () = print_char '1' in\n let () = print_char ' ' in\n f 2\n | _ -> ()\n\nlet () =\n match get_num () with\n | Some t ->\n let rec f i =\n if i = 0 then ()\n else\n let () = solve_case () in\n let () = print_newline () in\n f (i - 1)\n in\n f t\n | _ -> exit 1\n"}], "negative_code": [{"source_code": "let get_num () =\n let rec f acc =\n try\n let c = input_byte stdin in\n if int_of_char '0' <= c && c <= int_of_char '9' then\n f ((acc * 10) + c - int_of_char '0')\n else if acc > 0 then Some acc\n else None\n with End_of_file -> if acc > 0 then Some acc else None\n in\n f 0\n\nlet solve_case () =\n match get_num () with\n | Some n ->\n let rec f i =\n if i = n then print_string \"1\"\n else\n let i = i + 1 in\n let () = print_int i in\n let () = print_char ' ' in\n f i\n in\n f 1\n | _ -> ()\n\nlet () =\n match get_num () with\n | Some t ->\n let rec f i =\n if i = 0 then ()\n else\n let () = solve_case () in\n let () = print_newline () in\n f (i - 1)\n in\n f t\n | _ -> exit 1\n"}], "src_uid": "be3295b4d43a11ee94022b103f4221a5"} {"nl": {"description": "Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $$$n$$$ problems of distinct difficulty, the difficulties are numbered from $$$1$$$ to $$$n$$$.To hold a round Arkady needs $$$n$$$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $$$1$$$ to $$$n$$$ and puts it into the problems pool.At each moment when Arkady can choose a set of $$$n$$$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^5$$$)\u00a0\u2014 the number of difficulty levels and the number of problems Arkady created. The second line contains $$$m$$$ integers $$$a_1, a_2, \\ldots, a_m$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the problems' difficulties in the order Arkady created them.", "output_spec": "Print a line containing $$$m$$$ digits. The $$$i$$$-th digit should be $$$1$$$ if Arkady held the round after creation of the $$$i$$$-th problem, and $$$0$$$ otherwise.", "sample_inputs": ["3 11\n2 3 1 2 2 2 3 2 2 3 1", "4 8\n4 1 3 3 2 3 3 3"], "sample_outputs": ["00100000001", "00001000"], "notes": "NoteIn the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () and m = read_int () in\n let a = Array.init m read_int\n and cnt = Array.make (n + 1) 0\n and ans = Array.make m 0\n and index = ref 1 in\n for i = 0 to m - 1 do\n cnt.(a.(i)) <- cnt.(a.(i)) + 1;\n while cnt.(!index) <> 0 do\n cnt.(!index) <- cnt.(!index) - 1;\n if !index = n then ans.(i) <- 1;\n index := !index mod n + 1\n done\n done;\n for i = 0 to m - 1 do\n printf \"%d\" ans.(i)\n done"}, {"source_code": "Array.(Scanf.(\n scanf \" %d %d\" @@ fun n m ->\n let cnt,exist = make n 0, make m 0 in\n init m @@ fun _ -> scanf \" %d\" @@ fun v -> (\n let v = v - 1 in\n exist.(cnt.(v)) <- exist.(cnt.(v)) + 1;\n print_string (\n if exist.(cnt.(v)) = n then \"1\" else \"0\");\n cnt.(v) <- cnt.(v) + 1)))"}, {"source_code": "module SegTree = struct\n module type S = sig\n type t\n val op: t -> t -> t\n val ide: t\n val upd: t -> t -> t\n end\n module RMQ : S with type t = int64 =\n struct\n type t = int64 let op = min\n let ide = Int64.max_int let upd _ v = v\n end\n module RSQ : S with type t = int64 =\n struct\n type t = int64 let op = Int64.add\n let ide = 0L let upd prev v = op prev v\n end\n let par i = (i-1)/2\n let chl i = 2*i+1\n let chr i = 2*i+2\n module Make (X:S) = struct\n type t = SegTree of (X.t array * int)\n let raw (SegTree (a,_)) = a\n let make raw = (* O(n) *)\n let ln = Array.length raw in\n let n =\n let n = ref 1 in\n while !n0 do\n i := par !i;\n a.(!i) <- X.op a.(chl !i) a.(chr !i) done\n let get_half_open (SegTree(a,n)) l r = (* O(logn), [l,r) *)\n let rec f0 i p q =\n if q<=l || r<=p then X.ide\n else if l<=p && q<=r then a.(i)\n else\n let vl = f0 (2*i+1) p ((p+q)/2) in\n let vr = f0 (2*i+2) ((p+q)/2) q in\n X.op vl vr\n in f0 0 0 n\n let get_closed seg l r = get_half_open seg l (r+1) (* [l,r] *)\n end\nend\nlet (++) = Int64.add\nmodule S = SegTree.Make(SegTree.RMQ);;\nScanf.(Array.(scanf \" %d %d\" @@ fun n m ->\n let a = init m (fun _ -> scanf \" %d\" @@ fun v -> v) in\n let s = S.make @@ make (n+1) 0L in\n fold_left (fun k v ->\n S.update_destructive s v (S.get_closed s v v ++ 1L);\n if S.get_closed s 1 n = k then (\n print_int 1; k++1L\n ) else (\n print_int 0; k\n )\n ) 1L a |> ignore\n))"}, {"source_code": "module MultiSet_test = struct\n module Make (X:Map.OrderedType) = struct\n include Map.Make(X)\n let count v set =\n try find v set with Not_found -> 0\n let remove_each v set =\n let k = count v set in\n if k<=0 then raise Not_found\n else if k=1 then remove v set\n else add v (k-1) set\n let add_each v set =\n let k = count v set in\n if k=0 then add v 1 set\n else add v (k+1) set\n let iter_each f set =\n let rec f0 k = function\n | 0 -> ()\n | i -> let () = f k in f0 k (i-1)\n in iter f0 set\n let fold_each f set ac =\n let rec f0 k i ac = match i with\n | 0 -> ac\n | i -> f0 k (i-1) (f k ac)\n in fold f0 set ac\n let bindings_each set =\n fold_each (fun v ls -> v::ls) set []\n |> List.rev\n let min_binding_each set = fst @@ min_binding set\n let max_binding_each set = fst @@ max_binding set\n let exists_each f = exists (fun k _ -> f k)\n let cardinal_each set =\n (* O(#node). an aux variable might lead you to O(1) perf *)\n fold (fun _ v sum -> sum + v) set 0\n end\nend\nmodule S = MultiSet_test.Make (struct\n type t = int let compare = compare\nend);;\nArray.(Scanf.(\n scanf \" %d %d\" @@ fun n m ->\n let a = init m (fun _ -> scanf \" %d\" @@ fun v -> v) in\n let c = make n 0 in\n fold_left (fun (s,round) v ->\n let v = v-1 in\n let s = S.remove_each c.(v) s in\n let s = S.add_each (c.(v)+1) s in\n c.(v) <- c.(v) + 1;\n let p = S.min_binding_each s in\n print_char (\n if p > round then '1' else '0'\n ); (s,p)\n ) (S.singleton 0 n, 0) a |> ignore))"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)\n let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule SegTree = struct\n module type S = sig\n type t\n val op: t -> t -> t\n val ide: t\n val upd: t -> t -> t\n end\n module RMQ = struct type t = int64 let op = min let ide = max_i64 let upd u v = v end\n module RSQ = struct type t = int64 let op = (+) let ide = 0L let upd u v = u+v end\n let par i = (i-$1)/$2\n let chl i = 2*$i+$1\n let chr i = 2*$i+$2\n module Make (X:S) = struct\n type t = SegTree of (X.t array * int)\n let raw (SegTree (a,_)) = a\n let make raw = (* O(n) *)\n let ln = Array.length raw in\n let n =\n let n = ref 1 in\n while !n0 do\n i := par !i;\n a.(!i) <- X.op a.(chl !i) a.(chr !i) done\n let get_half_open (SegTree(a,n)) l r = (* O(logn), [l,r) *)\n let rec f0 i p q =\n if q<=l || r<=p then X.ide\n else if l<=p && q<=r then a.(i)\n else\n let vl = f0 (2*$i+$1) p ((p+$q)/$2) in\n let vr = f0 (2*$i+$2) ((p+$q)/$2) q in\n X.op vl vr\n in f0 0 0 n\n let get_closed seg l r = get_half_open seg l (r+$1) (* [l,r] *)\n end\nend\nmodule SI = SegTree.Make(struct\n type t = int64\n let op = min let ide = max_i64 let upd u v = v\nend)\nlet () =\n let n,m = g2 0 in\n let a = iia m in\n let s = SI.make @@ make (i32 n) 0L in\n let k = ref 1L in\n iter (fun v ->\n let i = i32 v -$ 1 in\n SI.update_destructive s i (SI.get_closed s i i + 1L);\n let mn = SI.get_closed s 0 (i32 n-$1) in\n if mn = !k then (\n printf \"1\"; k += 1L\n ) else printf \"0\";\n (* printf \": %Ld : %Ld : %s\\n\" mn !k (\n string_of_array ist @@ init (i32 n) (fun i -> SI.get_closed s i i)\n ) *)\n ) a\n\n (* let b = make (i32 n) 0L in\n let k = ref 1L in\n iter (fun v ->\n let i = i32 v -$ 1 in\n b.(i) <- b.(i) + 1L;\n if fold_left min max_i64 b = !k then (\n printf \"1\"; k += 1L\n ) else printf \"0\"\n ) a *)\n\n\n(* module BIT = struct\n let lsb i = i land -i\n let sum i b = (* 0-indexed; \u03a3a[0,i-1] *)\n fix (fun f i s -> if i>0 then f (i -$ lsb i) (s + b.(i)) else s) i 0L\n let sum_closed i = sum (i+$1) (* 0-indexed; \u03a3a[0,i] *)\n let sum_interval l r b = (* 0-indexed; \u03a3a[l,r] = \u03a3a[0,r+1-1] - \u03a3[0,l-1] *)\n if l>r then 0L else sum (r+$1) b - sum l b\n let add i x b = (* 0-indexed; a[i]+=x. not b *)\n if i<0 then raise @@ Invalid_argument \"index should be >= 1 (0-indexed a[i-1]+=x)\";\n fix (fun f i -> if i add (i+$1) v b) a; b\n let make n = Array.make (n+$1) 0L\n let reconst b = Array.init (Array.length b-$1) (fun i -> sum_interval i i b)\n (* initialization: http://hos.ac/slides/20140319_bit.pdf *)\nend\nlet () =\n let n,m = g2 0 in\n let a = iia m in\n let b = BIT.make (i32 n+$1) in\n let k = ref 1L in\n iter (fun v ->\n BIT.add (i32 v) 1L b;\n if BIT.sum_closed (i32 n) b = !k then (\n printf \"1\";\n k += 1L\n ) else (\n printf \"0\"\n )\n ) a; *)\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n let a = Array.init m (fun _ -> read_int() -1) in (*difficulty reduced by 1 *)\n\n let hist = Array.make n 0 in\n\n let rec insert i s = if i=n then s else insert (i+1) (Pset.add (0,i) s) in\n\n let set = insert 0 Pset.empty in\n\n let rec loop j s prev_low_freq = if j=m then () else (\n let old = (hist.(a.(j)), a.(j)) in\n hist.(a.(j)) <- hist.(a.(j)) + 1;\n let new_elt = (hist.(a.(j)), a.(j)) in\n let s = Pset.remove old s in\n let s = Pset.add new_elt s in\n let (freq,_) = Pset.min_elt s in\n if freq > prev_low_freq then printf \"1\" else printf \"0\";\n loop (j+1) s freq\n ) in\n\n let () = loop 0 set 0 in\n print_newline()\n"}], "negative_code": [], "src_uid": "2070955288b2e2cdbae728d8e7ce78ab"} {"nl": {"description": "You're given an array $$$a$$$ of length $$$n$$$. You can perform the following operation on it as many times as you want: Pick two integers $$$i$$$ and $$$j$$$ $$$(1 \\le i,j \\le n)$$$ such that $$$a_i+a_j$$$ is odd, then swap $$$a_i$$$ and $$$a_j$$$. What is lexicographically the smallest array you can obtain?An array $$$x$$$ is lexicographically smaller than an array $$$y$$$ if there exists an index $$$i$$$ such that $$$x_i<y_i$$$, and $$$x_j=y_j$$$ for all $$$1 \\le j < i$$$. Less formally, at the first index $$$i$$$ in which they differ, $$$x_i<y_i$$$", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_{n}$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array $$$a$$$.", "output_spec": "The only line contains $$$n$$$ space-separated integers, the lexicographically smallest array you can obtain.", "sample_inputs": ["3\n4 1 7", "2\n1 1"], "sample_outputs": ["1 4 7", "1 1"], "notes": "NoteIn the first example, we can swap $$$1$$$ and $$$4$$$ since $$$1+4=5$$$, which is odd."}, "positive_code": [{"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a = Array.init n\n (fun _ ->\n Scanf.scanf \"%d \" (fun x -> x))\n in\n let b = Array.map (fun x -> x mod 2 = 0) a in\n let pair, unpair =\n Array.fold_left\n (fun (acc1, acc2) x ->\n if x mod 2 = 0 then x::acc1, acc2\n else acc1, x:: acc2\n ) ([], []) a\n in\n match pair, unpair with\n | [], _ | _, [] ->\n Array.iter (fun x -> Printf.printf \"%d \" x) a\n | _ -> let a = Array.to_list a |> List.sort compare in\n List.iter (fun x -> Printf.printf \"%d \" x) a\n;;\n"}], "negative_code": [], "src_uid": "aab7f7cce0b704051627b625294635bc"} {"nl": {"description": "Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1\u2009/\u20094 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1\u2009/\u20094). ", "input_spec": "The first line contains one integer t (1\u2009\u2264\u2009t\u2009\u2264\u200910000) \u2014 the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers \u2014 coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.", "output_spec": "Output one line for each test case. Print \u00abYES\u00bb (without quotes), if the segments form the letter A and \u00abNO\u00bb otherwise.", "sample_inputs": ["3\n4 4 6 0\n4 1 5 2\n4 0 4 4\n0 0 0 6\n0 6 2 -4\n1 1 0 1\n0 0 0 5\n0 5 2 -1\n1 2 0 1"], "sample_outputs": ["YES\nNO\nYES"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\n\nopen Int64\n\nlet det (x,y) (xx,yy) = sub (mul x yy) (mul y xx)\nlet dot (x,y) (xx,yy) = add (mul x xx) (mul y yy)\nlet (++) (x,y) (xx,yy) = add x xx, add y yy\nlet (--) (x,y) (xx,yy) = sub x xx, sub y yy\nlet ( ** ) d (x,y) = mul d x, mul d y\n\nlet () =\n let a = Array.make_matrix 3 2 (0L,0L) in\n for cc = 1 to read_int 0 do\n for i = 0 to 2 do\n for j = 0 to 1 do\n let x = read_int64 0 in\n let y = read_int64 0 in\n a.(i).(j) <- x,y\n done\n done;\n let swap i =\n let t = a.(i).(0) in\n a.(i).(0) <- a.(i).(1);\n a.(i).(1) <- t\n in\n let arm p q =\n let u = dot p q and v = dot q q in\n det p q = 0L && v <= mul 5L u && mul 5L u <= mul 4L v\n in\n let g (ma,mb) (la,lb) (ra,rb) =\n let lb = lb -- la in\n let rb = rb -- ra in\n la = ra && det lb rb <> 0L && dot lb rb >= 0L && arm (ma--la) lb && arm (mb--ra) rb\n in\n let f i j k =\n g (a.(i).(0),a.(i).(1)) (a.(j).(0),a.(j).(1)) (a.(k).(0),a.(k).(1))\n in\n let rec enum i =\n if i >= 8 then\n false\n else if f 0 1 2 || f 1 2 0 || f 2 0 1 then\n true\n else (\n if i land 1 <> 0 then\n swap 0\n else if i land 2 <> 0 then\n swap 1\n else\n swap 2;\n enum (i+1)\n )\n in\n print_endline (if enum 0 then \"YES\" else \"NO\")\n done\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\n\nopen Int64\n\nlet det (x,y) (xx,yy) = sub (mul x yy) (mul y xx)\nlet dot (x,y) (xx,yy) = add (mul x xx) (mul y yy)\nlet (++) (x,y) (xx,yy) = add x xx, add y yy\nlet (--) (x,y) (xx,yy) = sub x xx, sub y yy\nlet ( ** ) d (x,y) = mul d x, mul d y\n\nlet () =\n let a = Array.make_matrix 3 2 (0L,0L) in\n for cc = 1 to read_int 0 do\n for i = 0 to 2 do\n for j = 0 to 1 do\n let x = read_int64 0 in\n let y = read_int64 0 in\n a.(i).(j) <- x,y\n done\n done;\n let swap i =\n let t = a.(i).(0) in\n a.(i).(0) <- a.(i).(1);\n a.(i).(1) <- t\n in\n let h p q =\n let u = dot p q and v = dot q q in\n det p q = 0L && v <= mul 5L u && mul 5L u <= mul 4L v\n in\n let g (ma,mb) (la,lb) (ra,rb) =\n let lb = lb -- la in\n let rb = rb -- ra in\n la = ra && det lb rb <> 0L && dot lb rb >= 0L && h (ma--la) lb && h (mb--ra) rb\n in\n let f i j k =\n g (a.(i).(0),a.(i).(1)) (a.(j).(0),a.(j).(1)) (a.(k).(0),a.(k).(1))\n in\n let rec enum i =\n if i >= 6 then\n false\n else if f 0 1 2 || f 1 2 0 || f 2 0 1 then\n true\n else (\n if i land 1 <> 0 then\n swap 0\n else if i land 2 <> 0 then\n swap 1\n else\n swap 2;\n enum (i+1)\n )\n in\n print_endline (if enum 0 then \"YES\" else \"NO\")\n done\n"}], "src_uid": "254a61b06acd3f25e7287ab90be614f1"} {"nl": {"description": "Vlad has $$$n$$$ friends, for each of whom he wants to buy one gift for the New Year.There are $$$m$$$ shops in the city, in each of which he can buy a gift for any of his friends. If the $$$j$$$-th friend ($$$1 \\le j \\le n$$$) receives a gift bought in the shop with the number $$$i$$$ ($$$1 \\le i \\le m$$$), then the friend receives $$$p_{ij}$$$ units of joy. The rectangular table $$$p_{ij}$$$ is given in the input.Vlad has time to visit at most $$$n-1$$$ shops (where $$$n$$$ is the number of friends). He chooses which shops he will visit and for which friends he will buy gifts in each of them.Let the $$$j$$$-th friend receive $$$a_j$$$ units of joy from Vlad's gift. Let's find the value $$$\\alpha=\\min\\{a_1, a_2, \\dots, a_n\\}$$$. Vlad's goal is to buy gifts so that the value of $$$\\alpha$$$ is as large as possible. In other words, Vlad wants to maximize the minimum of the joys of his friends.For example, let $$$m = 2$$$, $$$n = 2$$$. Let the joy from the gifts that we can buy in the first shop: $$$p_{11} = 1$$$, $$$p_{12}=2$$$, in the second shop: $$$p_{21} = 3$$$, $$$p_{22}=4$$$.Then it is enough for Vlad to go only to the second shop and buy a gift for the first friend, bringing joy $$$3$$$, and for the second\u00a0\u2014 bringing joy $$$4$$$. In this case, the value $$$\\alpha$$$ will be equal to $$$\\min\\{3, 4\\} = 3$$$Help Vlad choose gifts for his friends so that the value of $$$\\alpha$$$ is as high as possible. Please note that each friend must receive one gift. Vlad can visit at most $$$n-1$$$ shops (where $$$n$$$ is the number of friends). In the shop, he can buy any number of gifts.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. An empty line is written before each test case. Then there is a line containing integers $$$m$$$ and $$$n$$$ ($$$2 \\le n$$$, $$$2 \\le n \\cdot m \\le 10^5$$$) separated by a space\u00a0\u2014 the number of shops and the number of friends, where $$$n \\cdot m$$$ is the product of $$$n$$$ and $$$m$$$. Then $$$m$$$ lines follow, each containing $$$n$$$ numbers. The number in the $$$i$$$-th row of the $$$j$$$-th column $$$p_{ij}$$$ ($$$1 \\le p_{ij} \\le 10^9$$$) is the joy of the product intended for friend number $$$j$$$ in shop number $$$i$$$. It is guaranteed that the sum of the values $$$n \\cdot m$$$ over all test cases in the test does not exceed $$$10^5$$$.", "output_spec": "Print $$$t$$$ lines, each line must contain the answer to the corresponding test case\u00a0\u2014 the maximum possible value of $$$\\alpha$$$, where $$$\\alpha$$$ is the minimum of the joys from a gift for all of Vlad's friends.", "sample_inputs": ["5\n\n2 2\n1 2\n3 4\n\n4 3\n1 3 1\n3 1 1\n1 2 2\n1 1 3\n\n2 3\n5 3 4\n2 5 1\n\n4 2\n7 9\n8 1\n9 6\n10 8\n\n2 4\n6 5 2 1\n7 9 7 2"], "sample_outputs": ["3\n2\n4\n8\n2"], "notes": null}, "positive_code": [{"source_code": "(* This problem was solved by alphacode here:\n https://codeforces.com/contest/1619/submission/144332384 *)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n\nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let (m,n) = read_pair () in\n let p = Array.make_matrix m n 0 in\n let li = ref [] in\n for i=0 to m-1 do\n for j=0 to n-1 do\n\tlet x = read_int() in\n\tp.(i).(j) <- x;\n\tli := x :: !li\n done\n done;\n\n let svals = Array.of_list (List.sort_uniq compare !li) in\n\n let viable a =\n let ok i j = if p.(i).(j) >= a then 1 else 0 in\n if forall 0 (n-1) (fun j -> exists 0 (m-1) (fun i -> ok i j > 0)) then (\n (* there's a 1 in every column *)\n\texists 0 (m-1) (fun i -> (sum 0 (n-1) (fun j -> ok i j)) >= 2)\n ) else false\n in\n\n let rec bsearch lo hi =\n if lo = hi-1 then lo else\n\t(* lo is viable hi is not *)\n\tlet mid = (lo+hi)/2 in\n\tif viable svals.(mid) then bsearch mid hi else bsearch lo mid\n in\n printf \"%d\\n\" svals.(bsearch 0 (Array.length svals))\n done\n"}], "negative_code": [], "src_uid": "5f8916876c2889cfe9265cd71905ad99"} {"nl": {"description": "We call two numbers $$$x$$$ and $$$y$$$ similar if they have the same parity (the same remainder when divided by $$$2$$$), or if $$$|x-y|=1$$$. For example, in each of the pairs $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$, the numbers are similar to each other, and in the pairs $$$(1, 4)$$$, $$$(3, 12)$$$, they are not.You are given an array $$$a$$$ of $$$n$$$ ($$$n$$$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.For example, for the array $$$a = [11, 14, 16, 12]$$$, there is a partition into pairs $$$(11, 12)$$$ and $$$(14, 16)$$$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even positive integer $$$n$$$ ($$$2 \\le n \\le 50$$$)\u00a0\u2014 length of array $$$a$$$. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$).", "output_spec": "For each test case print: YES if the such a partition exists, NO otherwise. The letters in the words YES and NO can be displayed in any case.", "sample_inputs": ["7\n4\n11 14 16 12\n2\n1 8\n4\n1 1 1 1\n4\n1 2 5 6\n2\n12 13\n6\n1 6 3 10 5 8\n6\n1 12 3 10 5 8"], "sample_outputs": ["YES\nNO\nYES\nYES\nYES\nYES\nNO"], "notes": "NoteThe first test case was explained in the statement.In the second test case, the two given numbers are not similar.In the third test case, any partition is suitable."}, "positive_code": [{"source_code": "let split_string ?(pattern=\"\") = Str.split @@ Str.regexp pattern\nlet t = Scanf.sscanf (read_line ()) \"%d\" @@ fun t -> t\n\nlet rec loop n = function\n | [] -> false\n | x :: xs -> n + 1 = x || loop x xs\n\nlet () =\n for _ = 1 to t do\n let _ = Scanf.sscanf (read_line ()) \"%d\" @@ fun n -> n in\n let a = read_line () |> split_string ~pattern:\" \" |> List.map int_of_string |> List.sort compare in\n let (ox, ex) = List.fold_left (fun (ox, ex) a -> if a mod 2 = 0 then (ox, a :: ex) else (a :: ox, ex)) ([], []) a in\n if List.length ox mod 2 <> List.length ex mod 2 then print_endline \"NO\"\n else if List.length ox mod 2 = 0 then print_endline \"YES\"\n else print_endline @@ if loop (List.hd a) (List.tl a) then \"YES\" else \"NO\"\n done\n"}], "negative_code": [], "src_uid": "005a29a4b4e7ee4fd21444846014727b"} {"nl": {"description": "You are given an angle $$$\\text{ang}$$$. The Jury asks You to find such regular $$$n$$$-gon (regular polygon with $$$n$$$ vertices) that it has three vertices $$$a$$$, $$$b$$$ and $$$c$$$ (they can be non-consecutive) with $$$\\angle{abc} = \\text{ang}$$$ or report that there is no such $$$n$$$-gon. If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $$$998244353$$$.", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 180$$$) \u2014 the number of queries. Each of the next $$$T$$$ lines contains one integer $$$\\text{ang}$$$ ($$$1 \\le \\text{ang} < 180$$$) \u2014 the angle measured in degrees. ", "output_spec": "For each query print single integer $$$n$$$ ($$$3 \\le n \\le 998244353$$$) \u2014 minimal possible number of vertices in the regular $$$n$$$-gon or $$$-1$$$ if there is no such $$$n$$$.", "sample_inputs": ["4\n54\n50\n2\n178"], "sample_outputs": ["10\n18\n90\n180"], "notes": "NoteThe answer for the first query is on the picture above.The answer for the second query is reached on a regular $$$18$$$-gon. For example, $$$\\angle{v_2 v_1 v_6} = 50^{\\circ}$$$.The example angle for the third query is $$$\\angle{v_{11} v_{10} v_{12}} = 2^{\\circ}$$$.In the fourth query, minimal possible $$$n$$$ is $$$180$$$ (not $$$90$$$)."}, "positive_code": [{"source_code": "let rec fix f x = f (fix f) x\nlet gcd = fix (fun f m n ->\n if n=0 then m else f n (m mod n));;\nScanf.(Array.(\n let t = scanf \" %d\" @@ fun v -> v in\n init t (fun _ ->\n let d = scanf \" %d\" @@ fun v -> v in\n let g = gcd 180 (180-d) in\n let p,q = 180/g,(180-d)/g in\n Printf.printf \"%d\\n\" @@\n if q=1 then p*2 else p)))"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let t = gi 0 in\n rep 1L t (fun _ ->\n let d = gi 0 in\n let g = gcd 180L (180L-d) in\n let p,q = 180L/g, (180L-d)/g in\n (* n=pi,k=qi *)\n let f = ref false in\n rep 1L 180L (fun i ->\n let n1,k1 = p*i,q*i in\n if not !f && k1 < n1 && k1 >= 2L then (\n f := true;\n (* printf \" %Ld; %Ld\\n\" n1 k1; *)\n printf \"%Ld\\n\" n1;\n )\n )\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () =\n let cases = read_int () in\n for case = 1 to cases do\n let ang = read_int () in\n let num = 2*ang in\n let den = 360 in\n let g = gcd num den in\n let (num,den) = (num/g, den/g) in\n let (num,den) = if num+1 = den then (2*num,2*den) else (num,den) in\n printf \"%d\\n\" den\n done\n"}], "negative_code": [{"source_code": "let rec fix f x = f (fix f) x\nlet gcd = fix (fun f m n ->\n if n=0 then m else f n (m mod n));;\nScanf.(Array.(\n let t = scanf \" %d\" @@ fun v -> v in\n init t (fun _ ->\n let d = scanf \" %d\" @@ fun v -> v in\n let g = gcd 180 (180-d) in\n let p,q = 180/g,(180-d)/g in\n Printf.printf \"%d\\n\" @@ p*2)))"}, {"source_code": "let rec fix f x = f (fix f) x\nlet gcd = fix (fun f m n ->\n if n=0 then m else f n (m mod n));;\nScanf.(Array.(\n let t = scanf \" %d\" @@ fun v -> v in\n init t (fun _ ->\n let d = scanf \" %d\" @@ fun v -> v in\n let g = gcd 180 (180-d) in\n let p,q = 180/g,(180-d)/g in\n Printf.printf \"%d\\n\" @@\n if q=1 then p else p*2\n )\n))"}], "src_uid": "d11b56fe172110d5dfafddf880e48f18"} {"nl": {"description": "You are given an array a1,\u2009a2,\u2009...,\u2009an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?Definitions of subsegment and array splitting are given in notes.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009\u2009105) \u2014 the size of the array a and the number of subsegments you have to split the array to. The second line contains n integers a1,\u2009\u2009a2,\u2009\u2009...,\u2009\u2009an (\u2009-\u2009109\u2009\u2009\u2264\u2009\u2009ai\u2009\u2264\u2009\u2009109).", "output_spec": "Print single integer \u2014 the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.", "sample_inputs": ["5 2\n1 2 3 4 5", "5 1\n-4 -5 -3 -2 -1"], "sample_outputs": ["5", "-5"], "notes": "NoteA subsegment [l,\u2009\u2009r] (l\u2009\u2264\u2009r) of array a is the sequence al,\u2009\u2009al\u2009+\u20091,\u2009\u2009...,\u2009\u2009ar.Splitting of array a of n elements into k subsegments [l1,\u2009r1], [l2,\u2009r2], ..., [lk,\u2009rk] (l1\u2009=\u20091, rk\u2009=\u2009n, li\u2009=\u2009ri\u2009-\u20091\u2009+\u20091 for all i\u2009>\u20091) is k sequences (al1,\u2009...,\u2009ar1),\u2009...,\u2009(alk,\u2009...,\u2009ark).In the first example you should split the array into subsegments [1,\u20094] and [5,\u20095] that results in sequences (1,\u20092,\u20093,\u20094) and (5). The minimums are min(1,\u20092,\u20093,\u20094)\u2009=\u20091 and min(5)\u2009=\u20095. The resulting maximum is max(1,\u20095)\u2009=\u20095. It is obvious that you can't reach greater result.In the second example the only option you have is to split the array into one subsegment [1,\u20095], that results in one sequence (\u2009-\u20094,\u2009\u2009-\u20095,\u2009\u2009-\u20093,\u2009\u2009-\u20092,\u2009\u2009-\u20091). The only minimum is min(\u2009-\u20094,\u2009\u2009-\u20095,\u2009\u2009-\u20093,\u2009\u2009-\u20092,\u2009\u2009-\u20091)\u2009=\u2009\u2009-\u20095. The resulting maximum is \u2009-\u20095."}, "positive_code": [{"source_code": "let main () =\n let getNumber () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\n in let n = getNumber ()\n in let m = getNumber ()\n in if m = 1 then\n let min = ref max_int\n in begin\n for i = 0 to n - 1 do\n let gn = getNumber ()\n in if gn < !min then\n min := gn\n done;\n Printf.printf \"%d\" !min\n end\n else if m >= 3 then\n let max = ref min_int\n in begin\n for i = 0 to n - 1 do\n let gn = getNumber ()\n in if gn > !max then\n max := gn\n done;\n Printf.printf \"%d\" !max\n end\n else\n let lmin = Array.make n max_int\n in let ar = Array.init n (fun x ->\n let gn = getNumber ()\n in begin\n if x = 0 || gn < lmin.(x - 1) then\n lmin.(x) <- gn\n else\n lmin.(x) <- lmin.(x - 1);\n gn\n end)\n in let rMinRef = ref ar.(n - 1)\n in let mx = ref ar.(n - 1)\n in begin\n for i = n - 2 downto 0 do\n if ar.(i) < !rMinRef then\n rMinRef := ar.(i);\n mx := max !mx (max lmin.(i) !rMinRef)\n done;\n Printf.printf \"%d\" !mx\n end\n\n;;\n\nmain ();;\n"}], "negative_code": [{"source_code": "let main () =\n let getNumber () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\n in let n = getNumber ()\n in let m = getNumber ()\n in if m = 1 then\n let min = ref max_int\n in begin\n for i = 0 to n - 1 do\n let gn = getNumber ()\n in if gn < !min then\n min := gn\n done;\n Printf.printf \"%d\" !min\n end\n else\n let max = ref min_int\n in begin\n for i = 0 to n - 1 do\n let gn = getNumber ()\n in if gn > !max then\n max := gn\n done;\n Printf.printf \"%d\" !max\n end\n;;\n\nmain ();;\n"}], "src_uid": "ec1a29826209a0820e8183cccb2d2f01"} {"nl": {"description": "Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a n\u2009\u00d7\u2009n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.", "input_spec": "In the first line of the input, you are given a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the length of the side of the cake. Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.", "output_spec": "Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.", "sample_inputs": ["3\n.CC\nC..\nC.C", "4\nCC..\nC..C\n.CC.\n.CC."], "sample_outputs": ["4", "9"], "notes": "NoteIf we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are: (1,\u20092) and (1,\u20093) (3,\u20091) and (3,\u20093) Pieces that share the same column are: (2,\u20091) and (3,\u20091) (1,\u20093) and (3,\u20093) "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let c = Array.init n (fun _ -> read_string()) in\n\n let rc = Array.make n 0 in \n let cc = Array.make n 0 in \n\n for i=0 to n-1 do\n for j=0 to n-1 do\n rc.(i) <- rc.(i) + (if c.(i).[j] = 'C' then 1 else 0)\n done;\n done;\n\n for j=0 to n-1 do\n for i=0 to n-1 do\n cc.(j) <- cc.(j) + (if c.(i).[j] = 'C' then 1 else 0)\n done;\n done;\n\n let rcount = sum 0 (n-1) (fun i -> (rc.(i) * (rc.(i) - 1)) /2) 0 in\n\n let ccount = sum 0 (n-1) (fun j -> (cc.(j) * (cc.(j) - 1)) /2) 0 in \n\n printf \"%d\\n\" (rcount + ccount)\n"}], "negative_code": [], "src_uid": "7749f37aa9bf88a00013557e14342952"} {"nl": {"description": "In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1,\u2009a2,\u2009...,\u2009an. He remembered that he calculated gcd(ai,\u2009ai\u2009+\u20091,\u2009...,\u2009aj) for every 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.", "input_spec": "The first line contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u20091000)\u00a0\u2014 the size of the set S. The second line contains m integers s1,\u2009s2,\u2009...,\u2009sm (1\u2009\u2264\u2009si\u2009\u2264\u2009106)\u00a0\u2014 the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1\u2009<\u2009s2\u2009<\u2009...\u2009<\u2009sm.", "output_spec": "If there is no solution, print a single line containing -1. Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000. In the second line print n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106)\u00a0\u2014 the sequence. We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106. If there are multiple solutions, print any of them.", "sample_inputs": ["4\n2 4 6 12", "2\n2 3"], "sample_outputs": ["3\n4 6 12", "-1"], "notes": "NoteIn the first example 2\u2009=\u2009gcd(4,\u20096), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai,\u2009ai\u2009+\u20091,\u2009...,\u2009aj) for every 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet gcdf i j f = fold (i+1) j (fun k a -> gcd (f k) a) (f i)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n \nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let m = read_int () in\n let s = Array.init m read_int in\n\n\n let d = gcdf 0 (m-1) (fun i -> s.(i)) in\n\n for i=0 to m-1 do\n s.(i) <- s.(i) / d\n done;\n\n if not (exists 0 (m-1) (fun i -> s.(i) = 1)) then printf \"-1\\n\" else (\n printf \"%d\\n\" (2*m);\n\n for i=0 to 2*m-1 do\n if i mod 2 = 0 then printf \"%d \" (d * s.(i/2)) else printf \"%d \" d\n done;\n\n print_newline()\n )\n"}], "negative_code": [], "src_uid": "dfe5af743c9e23e98e6c9c5c319d2126"} {"nl": {"description": " As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive \u2014 convex polygon.Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing. Help sculptor! ", "input_spec": "The first line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 a number of rod-blanks. The second line contains n integers li (1\u2009\u2264\u2009li\u2009\u2264\u2009109) \u2014 lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.", "output_spec": "Print the only integer z \u2014 the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n\u2009+\u20091) vertices and nonzero area from all of the rods.", "sample_inputs": ["3\n1 2 1", "5\n20 4 3 2 1"], "sample_outputs": ["1", "11"], "notes": "NoteIn the first example triangle with sides {1\u2009+\u20091\u2009=\u20092,\u20092,\u20091} can be formed from a set of lengths {1,\u20091,\u20091,\u20092}. In the second example you can make a triangle with lengths {20,\u200911,\u20094\u2009+\u20093\u2009+\u20092\u2009+\u20091\u2009=\u200910}. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let len = Array.init n (fun _ -> long (read_int())) in\n let maxlen = maxf 0 (n-1) (fun i -> len.(i)) in\n let total = sum 0 (n-1) (fun i -> len.(i)) in\n let rest = total -- maxlen in\n\n printf \"%Ld\\n\" (maxlen -- rest ++ 1L)\n"}], "negative_code": [], "src_uid": "f00d94eb37c98a449615f0411e5a3572"} {"nl": {"description": "You are given a set of $$$2n+1$$$ integer points on a Cartesian plane. Points are numbered from $$$0$$$ to $$$2n$$$ inclusive. Let $$$P_i$$$ be the $$$i$$$-th point. The $$$x$$$-coordinate of the point $$$P_i$$$ equals $$$i$$$. The $$$y$$$-coordinate of the point $$$P_i$$$ equals zero (initially). Thus, initially $$$P_i=(i,0)$$$.The given points are vertices of a plot of a piecewise function. The $$$j$$$-th piece of the function is the segment $$$P_{j}P_{j + 1}$$$.In one move you can increase the $$$y$$$-coordinate of any point with odd $$$x$$$-coordinate (i.e. such points are $$$P_1, P_3, \\dots, P_{2n-1}$$$) by $$$1$$$. Note that the corresponding segments also change.For example, the following plot shows a function for $$$n=3$$$ (i.e. number of points is $$$2\\cdot3+1=7$$$) in which we increased the $$$y$$$-coordinate of the point $$$P_1$$$ three times and $$$y$$$-coordinate of the point $$$P_5$$$ one time: Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).Let the height of the plot be the maximum $$$y$$$-coordinate among all initial points in the plot (i.e. points $$$P_0, P_1, \\dots, P_{2n}$$$). The height of the plot on the picture above is 3.Your problem is to say which minimum possible height can have the plot consisting of $$$2n+1$$$ vertices and having an area equal to $$$k$$$. Note that it is unnecessary to minimize the number of moves.It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 10^{18}$$$) \u2014 the number of vertices in a plot of a piecewise function and the area we need to obtain.", "output_spec": "Print one integer \u2014 the minimum possible height of a plot consisting of $$$2n+1$$$ vertices and with an area equals $$$k$$$. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.", "sample_inputs": ["4 3", "4 12", "999999999999999999 999999999999999986"], "sample_outputs": ["1", "3", "1"], "notes": "NoteOne of the possible answers to the first example: The area of this plot is 3, the height of this plot is 1.There is only one possible answer to the second example: The area of this plot is 12, the height of this plot is 3."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\nend open MyInt64\n\nlet () =\n\tlet n,k = get_2_i64 0\n\tin\n\tlet a0 = ceildiv k n\n\tin printf \"%Ld\\n\" a0\n\n\n\n\n\n\n"}, {"source_code": "let split_on_space (str: string): string list =\n\tlet length = String.length str in\n\tlet is_space: int -> bool = \n\t\tfun index ->\n\t\t\tif (index < 0) || (index >= length) then true\n\t\t\telse str.[index] = ' '\n\tin\n\tlet is_start: int -> bool =\n\t\tfun index -> not (is_space index) && is_space (index - 1)\n\tin\n\tlet is_end: int -> bool =\n\t\tfun index -> not (is_space index) && is_space (index + 1)\n\tin\n\tlet indices = Array.init length (fun i -> i) in\n\tlet indices = Array.to_list indices in\n\tlet start_pos = List.filter is_start indices in \n\tlet end_pos = List.filter is_end indices in\n\tlet make_substring: string list -> int -> int -> string list =\n\t\tfun tokens left right ->\n\t\t\tlet new_token = String.sub str left (right - left + 1) in\n\t\t\tnew_token :: tokens\n\tin\n\tlet tokens = List.fold_left2 make_substring [] start_pos end_pos in\n\tList.rev tokens\n\t\t\t\n\nclass reader channel =\n\tobject (this)\n\n\tval mutable tokens = []\n\n method private get_tokens () =\n let new_line = read_line () in\n let tokens = split_on_space new_line in\n match tokens with\n | [] -> this#get_tokens ()\n | _ -> tokens\n\n\tmethod next_string () =\n if (List.length tokens = 0) then tokens <- this#get_tokens();\n let result = List.hd tokens in\n tokens <- List.tl tokens; result\n\n method next_int () =\n let str = this#next_string() in (Int64.of_string) str\n\n method next_float () =\n let str = this#next_string() in (float_of_string) str\n \nend\n\nlet reader = new reader stdin\n\nlet ( + ) = Int64.add\nlet ( - ) = Int64.sub\nlet ( * ) = Int64.mul\nlet ( / ) = Int64.div\nlet ( % ) = Int64.rem\n\nlet compare = Int64.compare\nlet ( = ) a b = compare a b = 0\nlet ( < ) a b = compare a b < 0\nlet ( > ) a b = compare a b > 0\nlet ( <= ) a b = compare a b <= 0\nlet ( >= ) a b = compare a b >= 0\n\nlet () =\n let n = reader#next_int () in\n let k = reader#next_int () in \n let res = k / n in\n let res = if k % n = Int64.zero then res else res + Int64.one in \n print_endline (Int64.to_string res);\n "}], "negative_code": [{"source_code": "let split_on_space (str: string): string list =\n\tlet length = String.length str in\n\tlet is_space: int -> bool = \n\t\tfun index ->\n\t\t\tif (index < 0) || (index >= length) then true\n\t\t\telse str.[index] = ' '\n\tin\n\tlet is_start: int -> bool =\n\t\tfun index -> not (is_space index) && is_space (index - 1)\n\tin\n\tlet is_end: int -> bool =\n\t\tfun index -> not (is_space index) && is_space (index + 1)\n\tin\n\tlet indices = Array.init length (fun i -> i) in\n\tlet indices = Array.to_list indices in\n\tlet start_pos = List.filter is_start indices in \n\tlet end_pos = List.filter is_end indices in\n\tlet make_substring: string list -> int -> int -> string list =\n\t\tfun tokens left right ->\n\t\t\tlet new_token = String.sub str left (right - left + 1) in\n\t\t\tnew_token :: tokens\n\tin\n\tlet tokens = List.fold_left2 make_substring [] start_pos end_pos in\n\tList.rev tokens\n\t\t\t\n\nclass reader channel =\n\tobject (this)\n\n\tval mutable tokens = []\n\n method private get_tokens () =\n let new_line = read_line () in\n let tokens = split_on_space new_line in\n match tokens with\n | [] -> this#get_tokens ()\n | _ -> tokens\n\n\tmethod next_string () =\n if (List.length tokens = 0) then tokens <- this#get_tokens();\n let result = List.hd tokens in\n tokens <- List.tl tokens; result\n\n method next_int () =\n let str = this#next_string() in (Int64.of_string) str\n\n method next_float () =\n let str = this#next_string() in (float_of_string) str\n \nend\n\nlet reader = new reader stdin\n\nlet () =\n let n = reader#next_int () in\n let k = reader#next_int () in \n let res = if n > k then Int64.one else Int64.div k n in\n print_endline (Int64.to_string res);\n flush stdout\n "}], "src_uid": "31014efa929af5e4b7d9987bd9b59918"} {"nl": {"description": "Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps: the character attacks the monster, decreasing the monster's health by $$$d_C$$$; the monster attacks the character, decreasing the character's health by $$$d_M$$$; the character attacks the monster, decreasing the monster's health by $$$d_C$$$; the monster attacks the character, decreasing the character's health by $$$d_M$$$; and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i.\u2009e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5 \\cdot 10^4$$$) \u2014 the number of test cases. Each test case consists of three lines: The first line contains two integers $$$h_C$$$ and $$$d_C$$$ ($$$1 \\le h_C \\le 10^{15}$$$; $$$1 \\le d_C \\le 10^9$$$) \u2014 the character's health and attack; The second line contains two integers $$$h_M$$$ and $$$d_M$$$ ($$$1 \\le h_M \\le 10^{15}$$$; $$$1 \\le d_M \\le 10^9$$$) \u2014 the monster's health and attack; The third line contains three integers $$$k$$$, $$$w$$$ and $$$a$$$ ($$$0 \\le k \\le 2 \\cdot 10^5$$$; $$$0 \\le w \\le 10^4$$$; $$$0 \\le a \\le 10^{10}$$$) \u2014 the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively. The sum of $$$k$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.", "sample_inputs": ["4\n25 4\n9 20\n1 1 10\n25 4\n12 20\n1 1 10\n100 1\n45 2\n0 4 10\n9 2\n69 2\n4 2 7"], "sample_outputs": ["YES\nNO\nYES\nYES"], "notes": "NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to $$$5$$$), then health during battle will change as follows: $$$(h_C, h_M) = (25, 9) \\rightarrow (25, 4) \\rightarrow (5, 4) \\rightarrow (5, -1)$$$. The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has $$$4$$$ coins. To defeat the monster, he has to spend $$$2$$$ coins to upgrade weapon and $$$2$$$ coins to upgrade armor."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet max a b = if a > b then a else b\nlet min a b = if a < b then a else b\n\nlet remove_first s = (String.sub s 1 ((String.length s) - 1))\nlet remove_last s = (String.sub s 0 ((String.length s) - 1))\n\nlet parse_integers s =\n let stream = (Scanning.from_string s) in\n let rec do_parse acc = \n match (Scanf.bscanf stream \" %Ld \" (fun x -> x :: acc)) \n with \n | xs -> do_parse xs \n | exception Scan_failure _ -> acc \n | exception End_of_file -> acc\n in Array.of_list (List.rev (do_parse []));;\n\nlet can_alive (hc:int64) (dc:int64) (hm:int64) (dm:int64) =\n let (hit:int64) = Int64.div (Int64.sub (Int64.add hm dc) 1L) dc in\n (* printf \"hit = %Ld\\n\" hit; *)\n if (Int64.compare hit 1L) == 0 then true else (\n let mxdmg = Int64.add 1L (Int64.div (Int64.sub hc 1L) (Int64.sub hit 1L)) in\n (* let (dmg:int64) = Int64.mul dm in *)\n (* printf \"hc %Ld dc %Ld hm %Ld dm %Ld hit %Ld dmg %Ld\\n\" hc dc hm dm hit mxdmg; *)\n if mxdmg > dm then true else false\n )\n\nlet solve_one (hc:int64) (dc:int64) (hm:int64) (dm:int64) (k:int64) (w:int64) (a:int64) =\n let rec try_k (now_k:int64) =\n if now_k > k then false\n else (\n if can_alive (Int64.add hc (Int64.mul a now_k)) (Int64.add dc (Int64.mul w (Int64.sub k now_k))) hm dm then true\n else try_k (Int64.add now_k 1L)\n )\n in \n try_k 0L\n\nlet rec solve t =\n if t > 0 then (\n let sc = parse_integers (read_line()) in\n let hc = sc.(0) in\n let dc = sc.(1) in\n let sm = parse_integers (read_line()) in\n let hm = sm.(0) in\n let dm = sm.(1) in\n let s = parse_integers (read_line()) in\n let k = s.(0) in\n let w = s.(1) in\n let a = s.(2) in\n (if solve_one hc dc hm dm k w a then \"YES\" else \"NO\")\n |> print_endline;\n solve (t - 1)\n )\n else ()\n\nlet () = \n let t = int_of_string (read_line()) in\n solve t\n\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet max a b = if a > b then a else b\nlet min a b = if a < b then a else b\n\nlet remove_first s = (String.sub s 1 ((String.length s) - 1))\nlet remove_last s = (String.sub s 0 ((String.length s) - 1))\n\nlet parse_integers s =\n let stream = (Scanning.from_string s) in\n let rec do_parse acc = \n match (Scanf.bscanf stream \" %Ld \" (fun x -> x :: acc)) \n with \n | xs -> do_parse xs \n | exception Scan_failure _ -> acc \n | exception End_of_file -> acc\n in Array.of_list (List.rev (do_parse []));;\n\nlet can_alive (hc:int64) (dc:int64) (hm:int64) (dm:int64) =\n let (hit:int64) = Int64.div (Int64.sub (Int64.add hm dc) 1L) dc in\n (* printf \"hit = %Ld\\n\" hit; *)\n if (Int64.compare hit 1L) == 0 then true else (\n let mxdmg = Int64.div hc (Int64.sub hit 1L) in\n (* let (dmg:int64) = Int64.mul dm in *)\n (* printf \"hc %Ld dc %Ld hm %Ld dm %Ld hit %Ld dmg %Ld\\n\" hc dc hm dm hit mxdmg; *)\n if mxdmg > dm then true else false\n )\n\nlet solve_one (hc:int64) (dc:int64) (hm:int64) (dm:int64) (k:int64) (w:int64) (a:int64) =\n let rec try_k (now_k:int64) =\n if now_k > k then false\n else (\n if can_alive (Int64.add hc (Int64.mul a now_k)) (Int64.add dc (Int64.mul w (Int64.sub k now_k))) hm dm then true\n else try_k (Int64.add now_k 1L)\n )\n in \n try_k 0L\n\nlet rec solve t =\n if t > 0 then (\n let sc = parse_integers (read_line()) in\n let hc = sc.(0) in\n let dc = sc.(1) in\n let sm = parse_integers (read_line()) in\n let hm = sm.(0) in\n let dm = sm.(1) in\n let s = parse_integers (read_line()) in\n let k = s.(0) in\n let w = s.(1) in\n let a = s.(2) in\n (if solve_one hc dc hm dm k w a then \"YES\" else \"NO\")\n |> print_endline;\n solve (t - 1)\n )\n else ()\n\nlet () = \n let t = int_of_string (read_line()) in\n solve t\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet max a b = if a > b then a else b\nlet min a b = if a < b then a else b\n\nlet remove_first s = (String.sub s 1 ((String.length s) - 1))\nlet remove_last s = (String.sub s 0 ((String.length s) - 1))\n\nlet parse_integers s =\n let stream = (Scanning.from_string s) in\n let rec do_parse acc = \n match (Scanf.bscanf stream \" %Ld \" (fun x -> x :: acc)) \n with \n | xs -> do_parse xs \n | exception Scan_failure _ -> acc \n | exception End_of_file -> acc\n in Array.of_list (List.rev (do_parse []));;\n\nlet can_alive (hc:int64) (dc:int64) (hm:int64) (dm:int64) =\n let (hit:int64) = Int64.div (Int64.sub (Int64.add hm dc) 1L) dc in\n if (Int64.compare hit 1L) == 0 then true else (\n let mxdmg = Int64.div hc (Int64.sub hit 1L) in\n (* let (dmg:int64) = Int64.mul dm in *)\n (* printf \"hc %Ld dc %Ld hm %Ld dm %Ld hit %Ld dmg %Ld\\n\" hc dc hm dm hit mxdmg; *)\n if mxdmg >= dm then true else false\n )\n\nlet solve_one (hc:int64) (dc:int64) (hm:int64) (dm:int64) (k:int64) (w:int64) (a:int64) =\n let rec try_k (now_k:int64) =\n if now_k > k then false\n else (\n if can_alive (Int64.add hc (Int64.mul a now_k)) (Int64.add dc (Int64.mul w (Int64.sub k now_k))) hm dm then true\n else try_k (Int64.add now_k 1L)\n )\n in \n try_k 0L\n\nlet rec solve t =\n if t > 0 then (\n let sc = parse_integers (read_line()) in\n let hc = sc.(0) in\n let dc = sc.(1) in\n let sm = parse_integers (read_line()) in\n let hm = sm.(0) in\n let dm = sm.(1) in\n let s = parse_integers (read_line()) in\n let k = s.(0) in\n let w = s.(1) in\n let a = s.(2) in\n (if solve_one hc dc hm dm k w a then \"YES\" else \"NO\")\n |> print_endline;\n solve (t - 1)\n )\n else ()\n\nlet () = \n let t = int_of_string (read_line()) in\n solve t\n\n"}, {"source_code": "open Printf\r\nopen Scanf\r\n\r\nlet max a b = if a > b then a else b\r\nlet min a b = if a < b then a else b\r\n\r\nlet remove_first s = (String.sub s 1 ((String.length s) - 1))\r\nlet remove_last s = (String.sub s 0 ((String.length s) - 1))\r\n\r\nlet parse_integers s =\r\n let stream = (Scanning.from_string s) in\r\n let rec do_parse acc = \r\n match (Scanf.bscanf stream \" %Ld \" (fun x -> x :: acc)) \r\n with \r\n | xs -> do_parse xs \r\n | exception Scan_failure _ -> acc \r\n | exception End_of_file -> acc\r\n in Array.of_list (List.rev (do_parse []));;\r\n\r\nlet can_alive (hc:int64) (dc:int64) (hm:int64) (dm:int64) =\r\n let (hit:int64) = Int64.div (Int64.sub (Int64.add hm dc) 1L) dc in\r\n let (dmg:int64) = Int64.mul dm (Int64.sub hit 1L) in\r\n (* printf \"hc %d dc %d hm %d dm %d hit %d dmg %d\\n\" hc dc hm dm hit dmg; *)\r\n if dmg >= hc then false else true\r\n\r\nlet solve_one (hc:int64) (dc:int64) (hm:int64) (dm:int64) (k:int64) (w:int64) (a:int64) =\r\n let rec try_k (now_k:int64) =\r\n if now_k > k then false\r\n else (\r\n if can_alive (Int64.add hc (Int64.mul a now_k)) (Int64.add dc (Int64.mul w (Int64.sub k now_k))) hm dm then true\r\n else try_k (Int64.add now_k 1L)\r\n )\r\n in \r\n try_k 0L\r\n\r\nlet rec solve t =\r\n if t > 0 then (\r\n let sc = parse_integers (read_line()) in\r\n let hc = sc.(0) in\r\n let dc = sc.(1) in\r\n let sm = parse_integers (read_line()) in\r\n let hm = sm.(0) in\r\n let dm = sm.(1) in\r\n let s = parse_integers (read_line()) in\r\n let k = s.(0) in\r\n let w = s.(1) in\r\n let a = s.(2) in\r\n (if solve_one hc dc hm dm k w a then \"YES\" else \"NO\")\r\n |> print_endline;\r\n solve (t - 1)\r\n )\r\n else ()\r\n\r\nlet () = \r\n let t = int_of_string (read_line()) in\r\n solve t\r\n\r\n"}], "src_uid": "5b1f33228a58d9e14bc9479767532c25"} {"nl": {"description": "Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print \"YES\" or \"NO\" accordingly, without the quotes.", "input_spec": "The first line of the input contain two integers n and m (3\u2009\u2264\u2009n\u2009\u2264\u2009150\u2009000, )\u00a0\u2014 the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n,\u2009ai\u2009\u2260\u2009bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.", "output_spec": "If the given network is reasonable, print \"YES\" in a single line (without the quotes). Otherwise, print \"NO\" in a single line (without the quotes).", "sample_inputs": ["4 3\n1 3\n3 4\n1 4", "4 4\n3 1\n2 3\n3 4\n1 2", "10 4\n4 3\n5 10\n8 9\n1 2", "3 2\n1 2\n2 3"], "sample_outputs": ["YES", "NO", "YES", "NO"], "notes": "NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is \"NO\" in the second sample because members (2,\u20093) are friends and members (3,\u20094) are friends, while members (2,\u20094) are not. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\n(*------ union find code *)\nlet makeset n = Array.make n (-1)\nlet rec find i p = if p.(i) < 0 then i else (\n p.(i) <- find p.(i) p;\n p.(i);\n)\nlet union i j p =\n (* non-rank union. i and j are canonical elements, i remains canonical *)\n if i<>j then p.(j) <- i\n(*------ end union find code *)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n\n let uf = makeset n in\n \n for i=1 to m do\n let (a,b) = read_pair() in\n let (a,b) = (a-1, b-1) in\n let a = find a uf in\n let b = find b uf in\n union a b uf;\n done;\n\n let size = Array.make n 0 in\n\n for i=0 to n-1 do\n let comp = find i uf in\n size.(comp) <- size.(comp) + 1\n done;\n\n let choose2 x =\n let x = long x in\n (x ** (x -- 1L))//2L\n in\n\n let desired_edges = sum 0 (n-1) (fun i -> choose2 size.(i)) in\n if desired_edges = long m then printf \"YES\\n\" else printf \"NO\\n\"\n"}], "negative_code": [], "src_uid": "1173d89dd3af27b46e579cdeb2cfdfe5"} {"nl": {"description": "You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of segments and the value of k. The next n lines contain two integers li,\u2009ri (\u2009-\u2009109\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109) each \u2014 the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.", "output_spec": "First line contains integer m \u2014 the smallest number of segments. Next m lines contain two integers aj,\u2009bj (aj\u2009\u2264\u2009bj) \u2014 the ends of j-th segment in the answer. The segments should be listed in the order from left to right.", "sample_inputs": ["3 2\n0 5\n-3 2\n3 8", "3 2\n0 5\n-3 3\n3 8"], "sample_outputs": ["2\n0 2\n3 5", "1\n0 5"], "notes": null}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet print_list_x l = List.iter (fun (a,b) -> printf \"%d %s\\n\" a (if b = -1 then \"starts\" else \"ends\")) l\nlet print_list l = List.iter (fun (a,b) -> printf \"%d %d\\n\" a b) l\n\nlet read_int () = scanf \" %d\" (fun x -> x)\nlet read_pair () = scanf \" %d %d\" (fun x y -> (x,y))\nlet read_list num =\n let rec pom num acc =\n if num = 0 then acc\n else\n let a,b = read_pair () in\n let x,y = (a, -1), (b, 1) in\n pom (num - 1) (x :: y :: acc)\n in pom num []\n\nlet n = read_int ()\nlet k = read_int ()\nlet intervals = read_list n\n\n(*let get_result ar =\n let cur = ref (fst( ar.(0)))\n and ind, curind = ref 0, ref 0\n and cnt = ref 0 in\n while !ind < n do\n cnt := 0;\n curind := !ind;\n printf \"Having %d \\n\" (fst(ar.(!curind)));\n while !curind < n && fst(ar.(!curind)) = !cur do\n incr cnt;\n let (a,b) = ar.(!curind) in\n ar.(!curind) <- (a+1, b);\n incr curind\n done;\n let (a,b) = ar.(!ind) in\n if (a > b) then incr ind;\n if !cnt >= k then printf \"%d \\n\" !cur; (* fixme *)\n cur := fst (ar.(!ind))\n done*)\n\nlet update_result (level, last, li) (num, state) =\n let nlevel = level - state in\n if nlevel = k && state = -1 then (nlevel, num, li)\n else if level = k && state = 1 then (nlevel, num, (last, num)::li)\n else (nlevel, last, li)\n\nlet get_result l =\n let _, _, a = List.fold_left update_result (0, 0, []) l\n in List.rev a\n (*let loop l cnt acc =\n match l with\n | []\n | (a,b)::t ->\n in loop l 0 []*)\n\nlet print_result res =\n print_int (List.length res); print_newline ();\n print_list res\n\nlet intervals = List.sort compare intervals\nlet res = get_result intervals\nlet () = print_result res\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let k = getnum () in\n let a = Array.make (2 * n) (0, 0) in\n for i = 0 to n - 1 do\n let l = getnum () in\n let r = getnum () in\n\ta.(2 * i) <- (l, 0);\n\ta.(2 * i + 1) <- (r, 1);\n done;\n Array.sort compare a;\n let res = ref [] in\n let cnt = ref 0 in\n let start = ref 0 in\n for i = 0 to 2 * n - 1 do\n\tlet (x, t) = a.(i) in\n\t if !cnt >= k\n\t then res := (!start, x) :: !res;\n\t if t = 0\n\t then incr cnt\n\t else decr cnt;\n\t if !cnt >= k\n\t then start := x;\n done;\n let res = List.rev !res in\n let rec combine =\n\tfunction\n\t | [] -> []\n\t | (x1, y1) :: (x2, y2) :: xs when y1 = x2 ->\n\t combine ((x1, y2) :: xs)\n\t | x :: xs ->\n\t x :: combine xs\n in\n let res = combine res in\n\tPrintf.printf \"%d\\n\" (List.length res);\n\tList.iter (fun (x, y) -> Printf.printf \"%d %d\\n\" x y) res;\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make (2 * n) (0, 0) in\n for i = 0 to n - 1 do\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(2 * i) <- (l, 0);\n\ta.(2 * i + 1) <- (r, 1);\n done;\n Array.sort compare a;\n let res = ref [] in\n let cnt = ref 0 in\n let start = ref 0 in\n for i = 0 to 2 * n - 1 do\n\tlet (x, t) = a.(i) in\n\t if !cnt = k\n\t then res := (!start, x) :: !res;\n\t if t = 0\n\t then incr cnt\n\t else decr cnt;\n\t if !cnt = k\n\t then start := x;\n done;\n let res = List.rev !res in\n let rec combine =\n\tfunction\n\t | [] -> []\n\t | (x1, y1) :: (x2, y2) :: xs when y1 = x2 ->\n\t combine ((x1, y2) :: xs)\n\t | x :: xs ->\n\t x :: combine xs\n in\n let res = combine res in\n\tPrintf.printf \"%d\\n\" (List.length res);\n\tList.iter (fun (x, y) -> Printf.printf \"%d %d\\n\" x y) res;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make (2 * n) (0, 0) in\n for i = 0 to n - 1 do\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(2 * i) <- (l, 0);\n\ta.(2 * i + 1) <- (r, -1);\n done;\n Array.sort compare a;\n let res = ref [] in\n let cnt = ref 0 in\n let start = ref 0 in\n for i = 0 to 2 * n - 1 do\n\tlet (x, t) = a.(i) in\n\t if !cnt = k\n\t then res := (!start, x) :: !res;\n\t if t = 0\n\t then incr cnt\n\t else decr cnt;\n\t if !cnt = k\n\t then start := x;\n done;\n let res = List.rev !res in\n let rec combine =\n\tfunction\n\t | [] -> []\n\t | (x1, y1) :: (x2, y2) :: xs when y1 = x2 ->\n\t combine ((x1, y2) :: xs)\n\t | x :: xs ->\n\t x :: combine xs\n in\n let res = combine res in\n\tPrintf.printf \"%d\\n\" (List.length res);\n\tList.iter (fun (x, y) -> Printf.printf \"%d %d\\n\" x y) res;\n"}], "src_uid": "eafd37afb15f9f9d31c2a16a32f17763"} {"nl": {"description": "Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the result can be very large, you should print the value modulo 109\u2009+\u20097 (the remainder when divided by 109\u2009+\u20097).The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1.", "input_spec": "The only line contains two integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091013) \u2014 the parameters of the sum.", "output_spec": "Print integer s \u2014 the value of the required sum modulo 109\u2009+\u20097.", "sample_inputs": ["3 4", "4 4", "1 1"], "sample_outputs": ["4", "1", "0"], "notes": null}, "positive_code": [{"source_code": "let (+/) = Int64.add\nlet (-/) = Int64.sub\nlet ( */ ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet _ =\n let mm = 1000000007L in\n let mmod n =\n let r = Int64.rem n mm in\n if r < 0L\n then r +/ mm\n else r\n in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let n2 = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let isqrt n = int_of_float (sqrt (Int64.to_float n)) in\n let m = isqrt n in\n let res = ref 0L in\n let muld2 x y =\n if Int64.logand x 1L = 0L\n then mmod ((mmod (x // 2L)) */ mmod y)\n else mmod ((mmod (y // 2L)) */ mmod x)\n in\n for i = 1 to Int64.to_int (min n2 (n // Int64.of_int (m + 1))) do\n res := mmod (!res +/ (Int64.rem n (Int64.of_int i)))\n done;\n for i = 1 to m do\n let l = n // Int64.of_int (i + 1) in\n let u = n // Int64.of_int i in\n\tif l < n2 then (\n\t let u = min u n2 in\n\t res := !res +/\n\t\tmuld2 (u -/ l)\n\t\t (n -/ (l +/ 1L) */ Int64.of_int i +/ n -/ u */ Int64.of_int i);\n\t)\n done;\n let res2 =\n if n2 > n then (\n\tmmod (mmod (n2 -/ n) */ mmod n)\n ) else 0L\n in\n let res = mmod (res2 +/ !res) in\n Printf.printf \"%Ld\\n\" res\n\n"}], "negative_code": [{"source_code": "open Big_int\n\nlet (+|) = add_big_int\nlet (-|) = sub_big_int\nlet ( *| ) = mult_big_int\nlet (/|) = div_big_int\nlet bmod = mod_big_int\nlet (=|) = eq_big_int\nlet (/=|) a b = not (a =| b)\nlet (>|) = gt_big_int\nlet (<|) = lt_big_int\nlet (>=|) = ge_big_int\nlet (<=|) = le_big_int\n\nlet n0 = zero_big_int\nlet n1 = unit_big_int\nlet n2 = big_int_of_int 2\n\nlet (+/) = Int64.add\nlet (-/) = Int64.sub\nlet ( */ ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let n2 = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let isqrt n = int_of_float (sqrt (Int64.to_float n)) in\n let m = isqrt n in\n let res = ref n0 in\n for i = 1 to Int64.to_int (min n2 (n // Int64.of_int (m + 1))) do\n res := !res +| big_int_of_int64 (Int64.rem n (Int64.of_int i))\n done;\n for i = 1 to m do\n let l = n // Int64.of_int (i + 1) in\n let u = n // Int64.of_int i in\n\tif l < n2 then (\n\t let u = min u n2 in\n\t res := !res +|\n\t\tbig_int_of_int64 (u -/ l) *|\n\t\t big_int_of_int64 (n -/ (l +/ 1L) */ Int64.of_int i +/ n -/\n\t\t\t\t\tu */ Int64.of_int i) /| (big_int_of_int 2);\n\t)\n done;\n let res2 =\n if n2 > n then (\n\tbig_int_of_int64 (n2 -/ n) *| big_int_of_int64 n\n ) else n0\n in\n let res = res2 +| !res in\n Printf.printf \"%s\\n\" (string_of_big_int res)\n\n"}, {"source_code": "let (+/) = Int64.add\nlet (-/) = Int64.sub\nlet ( */ ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet _ =\n let mm = 1000000007L in\n let mmod n =\n let r = Int64.rem n mm in\n if r < 0L\n then r +/ mm\n else r\n in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let n2 = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let isqrt n = int_of_float (sqrt (Int64.to_float n)) in\n let m = isqrt n in\n let res = ref 0L in\n let muld2 x y =\n if Int64.logand x 1L = 0L\n then mmod ((mmod x // 2L) */ mmod y)\n else mmod ((mmod y // 2L) */ mmod x)\n in\n for i = 1 to Int64.to_int (min n2 (n // Int64.of_int (m + 1))) do\n res := mmod (!res +/ (Int64.rem n (Int64.of_int i)))\n done;\n for i = 1 to m do\n let l = n // Int64.of_int (i + 1) in\n let u = n // Int64.of_int i in\n\tif l < n2 then (\n\t let u = min u n2 in\n\t res := !res +/\n\t\tmuld2 (u -/ l)\n\t\t (n -/ (l +/ 1L) */ Int64.of_int i +/ n -/ u */ Int64.of_int i);\n\t)\n done;\n let res2 =\n if n2 > n then (\n\tmmod (mmod (n2 -/ n) */ mmod n)\n ) else 0L\n in\n let res = mmod (res2 +/ !res) in\n Printf.printf \"%Ld\\n\" res\n\n"}], "src_uid": "d98ecf6c5550e7ec7639fcd1f727fb35"} {"nl": {"description": "Inna likes sweets and a game called the \"Candy Matrix\". Today, she came up with the new game \"Candy Matrix 2: Reload\".The field for the new game is a rectangle table of size n\u2009\u00d7\u2009m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout \"Let's go!\". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs: some dwarf in one of the chosen lines is located in the rightmost cell of his row; some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells.Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u20091000;\u00a02\u2009\u2264\u2009m\u2009\u2264\u20091000). Next n lines each contain m characters \u2014 the game field for the \"Candy Martix 2: Reload\". Character \"*\" represents an empty cell of the field, character \"G\" represents a dwarf and character \"S\" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character \"G\" and one character \"S\".", "output_spec": "In a single line print a single integer \u2014 either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field.", "sample_inputs": ["3 4\n*G*S\nG**S\n*G*S", "1 3\nS*G"], "sample_outputs": ["2", "-1"], "notes": null}, "positive_code": [{"source_code": "let s=read_line();;\nlet i=ref 0;;\nwhile s.[ !i]<>' ' do\n incr i\ndone;;\nlet n=int_of_string(String.sub s 0 !i);;\nlet m=int_of_string(String.sub s ( !i+1) (String.length(s)- !i-1));;\nlet tab=Array.make (m+1) false;;\n\nlet pos c s=\nlet i=ref 0 in\nwhile s.[ !i]<>c do\n incr i\ndone;\n!i;;\n\nfor i=1 to n do\n let s=read_line() in\n let a=(pos 'S' s)-(pos 'G' s) in\n if a<0 then tab.(0)<-true else tab.(a)<-true\ndone;;\n\nlet nb=ref 0;;\n\nfor i=1 to m do\n if tab.(i) then incr nb\ndone;;\n\nif tab.(0) then print_int (-1) else print_int !nb;;"}], "negative_code": [{"source_code": "(*let tab=Array.make (m+1) false;;\n\nlet pos c s=\nlet i=ref 0 in\nwhile s.[ !i]<>c do\n incr i\ndone;\n!i;;*)\n\nlet s=read_line() in print_string s;;\n\n(*let str=Array.init n (fun i->read_line());;\n\nfor i=1 to n do\n let s=str.(i-1) in\n let a=(pos 'S' s)-(pos 'G' s) in\n if a<0 then tab.(0)<-true else tab.(a)<-true\ndone;;\n\nlet nb=ref 0;;\n\nfor i=1 to m do\n if tab.(i) then incr nb\ndone;;\n\nif tab.(0) then print_int (-1) else print_int !nb;;*)"}, {"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int();;\nlet tab=Array.make (m+1) false;;\n\nlet pos c s=\nlet i=ref 0 in\nwhile s.[ !i]<>c do\n i:= !i+1\ndone;\n!i;;\n\nfor i=1 to n do\n let s=\"S**G\" in\n let a=(pos 'S' s)-(pos 'G' s) in\n if a<0 then tab.(0)<-true else tab.(a)<-true\ndone;;\n\nlet nb=ref 0;;\n\nfor i=1 to m do\n if tab.(i) then nb:= !nb+1\ndone;;\n\nif tab.(0) then print_int (-1) else print_int !nb;;"}], "src_uid": "9a823b4ac4a79f62cd0c2f88a1c9ef0c"} {"nl": {"description": "Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection. Kevin is a meticulous cowbell collector and knows that the size of his i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si\u2009-\u20091\u2009\u2264\u2009si for any i\u2009>\u20091. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.", "input_spec": "The first line of the input contains two space-separated integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7k\u2009\u2264\u2009100\u2009000), denoting the number of cowbells and the number of boxes, respectively. The next line contains n space-separated integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009s1\u2009\u2264\u2009s2\u2009\u2264\u2009...\u2009\u2264\u2009sn\u2009\u2264\u20091\u2009000\u2009000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.", "output_spec": "Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.", "sample_inputs": ["2 1\n2 5", "4 3\n2 3 5 9", "3 2\n3 5 7"], "sample_outputs": ["7", "9", "8"], "notes": "NoteIn the first sample, Kevin must pack his two cowbells into the same box. In the second sample, Kevin can pack together the following sets of cowbells: {2,\u20093}, {5} and {9}.In the third sample, the optimal solution is {3,\u20095} and {7}."}, "positive_code": [{"source_code": "let main () =\n let (n,k) = Scanf.scanf \"%d %d\" (fun i j -> (i,j)) in\n let tab = Array.make (2 * k) 0 in\n for i=1 to n do\n Scanf.scanf \" %d\" (fun j -> tab.(n - i) <- j);\n done;\n let res = ref 0 in\n for i=0 to 2*k - 1 do\n res := max !res (tab.(i) + tab.(2 * k - i - 1));\n done;\n Printf.printf \"%d\" !res;;\n\nmain ();;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n \nlet () =\n let n = read_int() in\n let k = read_int() in\n let s = Array.init n (fun _ -> read_int()) in\n\n let fit size = (* return true if they fit in k boxes of size s. Assume s >= s.(n-1) *)\n let rec loop i j count =\n if i = j then count+1 else if i>j then count else (\n\tif s.(i) + s.(j) > size\n\tthen loop i (j-1) (count+1)\n\telse loop (i+1) (j-1) (count+1)\n )\n in\n let c = loop 0 (n-1) 0 in\n c <= k\n in\n\n let rec bsearch lo hi = (* lo fails and hi succeeds *)\n if lo = hi-1 then hi else\n let m = (lo+hi)/2 in\n if fit m then bsearch lo m else bsearch m hi\n in\n\n let answer = if fit s.(n-1)\n then s.(n-1)\n else bsearch s.(n-1) (2*(s.(n-1)))\n in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "7324428d9e6d808f55ad4f3217046455"} {"nl": {"description": "In this problem you will write a simple generator of Brainfuck (https://en.wikipedia.org/wiki/Brainfuck) calculators.You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of evaluating this expression.We use a fairly standard Brainfuck interpreter for checking the programs: 30000 memory cells. memory cells store integers from 0 to 255 with unsigned 8-bit wraparound. console input (, command) is not supported, but it's not needed for this problem.", "input_spec": "The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive. The calculations result is guaranteed to be an integer between 0 and 255, inclusive (results of intermediary calculations might be outside of these boundaries).", "output_spec": "Output a Brainfuck program which, when executed, will print the result of evaluating this expression. The program must be at most 5000000 characters long (including the non-command characters), and its execution must be complete in at most 50000000 steps.", "sample_inputs": ["2+3", "9-7"], "sample_outputs": ["++>\n+++>\n<[<+>-]<\n++++++++++++++++++++++++++++++++++++++++++++++++.", "+++++++++>\n+++++++>\n<[<->-]<\n++++++++++++++++++++++++++++++++++++++++++++++++."], "notes": "NoteYou can download the source code of the Brainfuck interpreter by the link http://assets.codeforces.com/rounds/784/bf.cpp. We use this code to interpret outputs."}, "positive_code": [{"source_code": "open Genlex\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let lexer = make_lexer [\"+\"; \"-\"] in\n let tokens = Stream.npeek 1000000 (lexer (Stream.of_string s)) in\n let res = ref 0 in\n let s = ref 1 in\n List.iter\n (function\n\t | Int n -> res := !res + !s * n\n\t | Kwd \"+\" -> s := 1\n\t | Kwd \"-\" -> s := -1\n\t | _ -> assert false\n ) tokens;\n let res = string_of_int !res in\n for i = 0 to String.length res - 1 do\n\tfor j = 1 to Char.code res.[i] do\n\t Printf.printf \"+\"\n\tdone;\n\tPrintf.printf \".\\n\";\n\tfor j = 1 to Char.code res.[i] do\n\t Printf.printf \"-\"\n\tdone;\n done\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet () =\n let s = read_string() in\n let len = String.length s in\n\n let rec parse i ac = if i=len then List.rev (('+',len)::ac) else\n match s.[i] with\n\t| '+' | '-' -> parse (i+1) ((s.[i],i)::ac)\n\t| _ -> parse (i+1) ac\n in\n\n let seq = Array.of_list (parse 0 [('+',-1)]) in\n\n let eval = fold 1 (-1 + Array.length seq) (fun i ac ->\n let sign = if fst seq.(i-1) = '+' then 1 else -1 in\n let place = 1 + snd seq.(i-1) in\n let l = (snd seq.(i)) - place in\n ac + sign * (int_of_string (String.sub s place l))\n ) 0 in\n\n let digits = string_of_int eval in\n\n for i=0 to -1+String.length digits do\n let d = int_of_char digits.[i] in\n printf \">\";\n for j=1 to d do printf \"+\" done;\n printf \".\";\n done;\n\n print_newline()\n"}], "negative_code": [{"source_code": "open Genlex\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let lexer = make_lexer [\"+\"; \"-\"] in\n let tokens = Stream.npeek 1000000 (lexer (Stream.of_string s)) in\n let res = ref 0 in\n let s = ref 1 in\n List.iter\n (function\n\t | Int n -> res := !res + !s * n\n\t | Kwd \"+\" -> s := 1\n\t | Kwd \"-\" -> s := -1\n\t | _ -> assert false\n ) tokens;\n let res = string_of_int !res in\n for i = 0 to String.length res - 1 do\n\tfor j = 1 to Char.code res.[i] do\n\t Printf.printf \"+\"\n\tdone;\n\tPrintf.printf \".\\n\"\n done\n"}, {"source_code": "open Genlex\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let lexer = make_lexer [\"+\"; \"-\"] in\n let tokens = Stream.npeek 1000000 (lexer (Stream.of_string s)) in\n let res = ref 0 in\n let s = ref 1 in\n List.iter\n (function\n\t | Int n -> res := !res + !s * n\n\t | Kwd \"+\" -> s := 1\n\t | Kwd \"-\" -> s := -1\n\t | _ -> assert false\n ) tokens;\n for i = 1 to !res do\n Printf.printf \"+\"\n done;\n Printf.printf \".\\n\"\n"}], "src_uid": "072797682246c465148bd09736b76718"} {"nl": {"description": "Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20091000). The second line contains n non-negative integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009<\u2009n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.", "output_spec": "Print a single number \u2014 the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.", "sample_inputs": ["3\n0 2 0", "5\n4 2 3 0 1", "7\n0 3 1 0 5 2 6"], "sample_outputs": ["1", "3", "2"], "notes": "NoteIn the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\ntype direction = Left | Right\n\nlet next d i =\n match d with\n | Left -> i - 1\n | Right -> i + 1\n\nlet rec collect a changes info d i =\n (*printf \"%d %d %d\\n%!\" changes info i;*)\n if info = Array.length a || changes > 10000 then\n changes\n else if i < 0 then\n collect a (changes + 1) info Right 0\n else if i >= Array.length a then\n collect a (changes + 1) info Left (Array.length a - 1)\n else if a.(i) <= info && a.(i) >= 0 then begin\n (*printf \"collected %d\\n%!\" i;*)\n a.(i) <- -1;\n collect a changes (info + 1) d (next d i)\n end\n else\n collect a changes info d (next d i)\n\nlet () = \n let _ = read_int () in\n let s = read_line () in\n let l = List.map int_of_string (Str.split (Str.regexp \" +\") s) in\n let a = Array.of_list l in\n let res = collect a 0 0 Right 0 in\n printf \"%d\\n%!\" res;\n\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\ntype direction = Left | Right\n\nlet next d i =\n match d with\n | Left -> i - 1\n | Right -> i + 1\n\nlet rec collect a changes info d i =\n (*printf \"%d %d %d\\n%!\" changes info i;*)\n if info = Array.length a then\n changes\n else if i < 0 then\n collect a (changes + 1) info Right 0\n else if i >= Array.length a then\n collect a (changes + 1) info Left (Array.length a - 1)\n else if a.(i) <= info && a.(i) >= 0 then begin\n (*printf \"collected %d\\n%!\" i;*)\n a.(i) <- -1;\n collect a changes (info + 1) d (next d i)\n end\n else\n collect a changes info d (next d i)\n\nlet () = \n let _ = read_int () in\n let s = read_line () in\n let l = List.map int_of_string (Str.split (Str.regexp \" +\") s) in\n let a = Array.of_list l in\n let l_res = 99 (*collect a 0 0 Left (Array.length a - 1)*) in\n let r_res = collect a 0 0 Right 0 in\n printf \"%d\\n%!\" (min l_res r_res);\n\n"}, {"source_code": "open Printf\nopen Scanf\n\ntype direction = Left | Right\n\nlet next d i =\n match d with\n | Left -> i - 1\n | Right -> i + 1\n\nlet rec collect a changes info d i =\n (*printf \"%d %d %d\\n%!\" changes info i;*)\n if info = Array.length a || changes > 1000000 then\n changes\n else if i < 0 then\n collect a (changes + 1) info Right 0\n else if i >= Array.length a then\n collect a (changes + 1) info Left (Array.length a - 1)\n else if a.(i) <= info && a.(i) >= 0 then begin\n (*printf \"collected %d\\n%!\" i;*)\n a.(i) <- -1;\n collect a changes (info + 1) d (next d i)\n end\n else\n collect a changes info d (next d i)\n\nlet () = \n let _ = read_int () in\n let s = read_line () in\n let l = List.map int_of_string (Str.split (Str.regexp \" +\") s) in\n let a = Array.of_list l in\n let i = ref 0 in\n while a.(!i) > 0 do\n i := !i + 1\n done;\n let l_res = collect a 0 0 Left !i in\n let r_res = collect a 0 0 Right !i in\n printf \"%d\\n%!\" (min l_res r_res);\n\n"}, {"source_code": "open Printf\nopen Scanf\n\ntype direction = Left | Right\n\nlet next d i =\n match d with\n | Left -> i - 1\n | Right -> i + 1\n\nlet rec collect a changes info d i =\n (*printf \"%d %d %d\\n%!\" changes info i;*)\n if info = Array.length a || changes > 1000000 then\n changes\n else if i < 0 then\n collect a (changes + 1) info Right 0\n else if i >= Array.length a then\n collect a (changes + 1) info Left (Array.length a - 1)\n else if a.(i) <= info && a.(i) >= 0 then begin\n (*printf \"collected %d\\n%!\" i;*)\n a.(i) <- -1;\n collect a changes (info + 1) d (next d i)\n end\n else\n collect a changes info d (next d i)\n\nlet () = \n let _ = read_int () in\n let s = read_line () in\n let l = List.map int_of_string (Str.split (Str.regexp \" +\") s) in\n let a = Array.of_list l in\n let l_res = collect a 0 0 Left (Array.length a - 1) in\n let r_res = collect a 0 0 Right 0 in\n printf \"%d\\n%!\" (min l_res r_res);\n\n"}], "src_uid": "9374728643a1ddbe2200a4a125beef26"} {"nl": {"description": "You have an $$$n \\times n$$$ chessboard and $$$k$$$ rooks. Rows of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from top to bottom and columns of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from left to right. The cell $$$(x, y)$$$ is the cell on the intersection of row $$$x$$$ and collumn $$$y$$$ for $$$1 \\leq x \\leq n$$$ and $$$1 \\leq y \\leq n$$$.The arrangement of rooks on this board is called good, if no rook is beaten by another rook.A rook beats all the rooks that shares the same row or collumn with it.The good arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the good arrangement is stable. Here, adjacent cells are the cells that share a side. Such arrangement of $$$3$$$ rooks on the $$$4 \\times 4$$$ chessboard is good, but it is not stable: the rook from $$$(1, 1)$$$ can be moved to the adjacent cell $$$(2, 1)$$$ and rooks on cells $$$(2, 1)$$$ and $$$(2, 4)$$$ will beat each other. Please, find any stable arrangement of $$$k$$$ rooks on the $$$n \\times n$$$ chessboard or report that there is no such arrangement.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \\leq k \\leq n \\leq 40$$$)\u00a0\u2014 the size of the chessboard and the number of rooks.", "output_spec": "If there is a stable arrangement of $$$k$$$ rooks on the $$$n \\times n$$$ chessboard, output $$$n$$$ lines of symbols . and R. The $$$j$$$-th symbol of the $$$i$$$-th line should be equals R if and only if there is a rook on the cell $$$(i, j)$$$ in your arrangement. If there are multiple solutions, you may output any of them. If there is no stable arrangement, output $$$-1$$$.", "sample_inputs": ["5\n\n3 2\n\n3 3\n\n1 1\n\n5 2\n\n40 33"], "sample_outputs": ["..R\n...\nR..\n-1\nR\n.....\nR....\n.....\n....R\n.....\n-1"], "notes": "NoteIn the first test case, you should find stable arrangement of $$$2$$$ rooks on the $$$3 \\times 3$$$ chessboard. Placing them in cells $$$(3, 1)$$$ and $$$(1, 3)$$$ gives stable arrangement.In the second test case it can be shown that it is impossbile to place $$$3$$$ rooks on the $$$3 \\times 3$$$ chessboard to get stable arrangement."}, "positive_code": [{"source_code": "(* Codeforces 1621 A Stable Arrangement of Rooks, train, *)\r\n(* on their computer runtime error ???? ((((( *)\r\n \r\n(* you can use either gr or rdln but not both *)\r\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\r\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\r\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet rdln() = input_line stdin;;\r\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\r\nlet debug = false;;\r\n\r\nlet do_one () = \r\n let n = gr() in (* field size *)\r\n let k = gr() in (* number of rooks *)\r\n if k > (n + 1) / 2 then\r\n print_string \"-1\\n\"\r\n else\r\n for i = 1 to n do\r\n let s = if ((i mod 2) == 0) || (i > 2*k) then String.make n '.'\r\n else (String.make (i-1) '.') ^ \"R\" ^ (String.make (n - i) '.') in\r\n let se = s ^ \"\\n\" in\r\n print_string se\r\n done;;\r\n \r\nlet do_all t = \r\n for i = 1 to t do\r\n do_one ()\r\n done;;\r\n \r\nlet main() =\r\n\tlet st = rdln () in\r\n\tlet t = int_of_string st in\r\n\tdo_all t;;\r\n \r\nmain();;"}], "negative_code": [], "src_uid": "d5549c0627c236d82541a67ccbe7977d"} {"nl": {"description": "Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres.In the bookshop, Jack decides to buy two books of different genres.Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.The books are given by indices of their genres. The genres are numbered from 1 to m.", "input_spec": "The first line contains two positive integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105,\u20092\u2009\u2264\u2009m\u2009\u2264\u200910) \u2014 the number of books in the bookstore and the number of genres. The second line contains a sequence a1,\u2009a2,\u2009...,\u2009an, where ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009m) equals the genre of the i-th book. It is guaranteed that for each genre there is at least one book of that genre.", "output_spec": "Print the only integer \u2014 the number of ways in which Jack can choose books. It is guaranteed that the answer doesn't exceed the value 2\u00b7109.", "sample_inputs": ["4 3\n2 1 3 1", "7 4\n4 2 3 1 2 4 3"], "sample_outputs": ["5", "18"], "notes": "NoteThe answer to the first test sample equals 5 as Sasha can choose: the first and second books, the first and third books, the first and fourth books, the second and third books, the third and fourth books. "}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make m 0 in\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = k - 1 in\n\ta.(k) <- a.(k) + 1\n done;\n let res = ref 0L in\n for i = 0 to m - 1 do\n\tfor j = i + 1 to m - 1 do\n\t res := !res +| Int64.of_int a.(i) *| Int64.of_int a.(j)\n\tdone\n done;\n Printf.printf \"%Ld\\n\" !res\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet ( ++ ) a b = Int64.add a b\nlet ( ** ) a b = Int64.mul a b\nlet long x = Int64.of_int x\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\n\nlet () = \n\n let n = read_int() in\n let m = read_int() in \n let a = Array.init n (fun _ -> read_int()) in\n\n let count = Array.make (m+1) 0L in\n\n for i=0 to n-1 do\n count.(a.(i)) <- 1L ++ count.(a.(i))\n done;\n\n let answer =\n sum 1 (m-1) (fun i -> sum (i+1) m (fun j -> count.(i)**count.(j)) 0L) 0L\n in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "e2ff228091ca476926b8e905f1bc8dff"} {"nl": {"description": "Polycarp is a head of a circus troupe. There are $$$n$$$\u00a0\u2014 an even number\u00a0\u2014 artists in the troupe. It is known whether the $$$i$$$-th artist can perform as a clown (if yes, then $$$c_i = 1$$$, otherwise $$$c_i = 0$$$), and whether they can perform as an acrobat (if yes, then $$$a_i = 1$$$, otherwise $$$a_i = 0$$$).Split the artists into two performances in such a way that: each artist plays in exactly one performance, the number of artists in the two performances is equal (i.e. equal to $$$\\frac{n}{2}$$$), the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance. ", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 5\\,000$$$, $$$n$$$ is even)\u00a0\u2014 the number of artists in the troupe. The second line contains $$$n$$$ digits $$$c_1 c_2 \\ldots c_n$$$, the $$$i$$$-th of which is equal to $$$1$$$ if the $$$i$$$-th artist can perform as a clown, and $$$0$$$ otherwise. The third line contains $$$n$$$ digits $$$a_1 a_2 \\ldots a_n$$$, the $$$i$$$-th of which is equal to $$$1$$$, if the $$$i$$$-th artist can perform as an acrobat, and $$$0$$$ otherwise.", "output_spec": "Print $$$\\frac{n}{2}$$$ distinct integers\u00a0\u2014 the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer $$$-1$$$.", "sample_inputs": ["4\n0011\n0101", "6\n000000\n111111", "4\n0011\n1100", "8\n00100101\n01111100"], "sample_outputs": ["1 4", "-1", "4 3", "1 2 3 6"], "notes": "NoteIn the first example, one of the possible divisions into two performances is as follows: in the first performance artists $$$1$$$ and $$$4$$$ should take part. Then the number of artists in the first performance who can perform as clowns is equal to $$$1$$$. And the number of artists in the second performance who can perform as acrobats is $$$1$$$ as well.In the second example, the division is not possible.In the third example, one of the possible divisions is as follows: in the first performance artists $$$3$$$ and $$$4$$$ should take part. Then in the first performance there are $$$2$$$ artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is $$$2$$$ as well."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_char _ = bscanf Scanning.stdin \" %c \" (fun x -> Char.(code x - code '0'))\n\nlet rec zip_with f a b =\n match a,b with\n | [], _ -> []\n | _, [] -> []\n | x::xs, y::ys -> (f x y) :: zip_with f xs ys\n\nlet rec loop ab none a c both =\n let rec inner aa =\n if aa > a\n then loop (ab+1) none a c both\n else\n let k = ab + aa in\n let cc = k - (both - ab) in\n let ka = k + (c - cc) in\n let kc = a - aa + (both - ab) + cc in\n let an = max 0 (kc-ka) + (none - abs (kc-ka))/2 in\n if cc > c || cc < 0 || abs (kc-ka) > none\n then inner (aa+1)\n else Some (an,aa,c-cc,ab) in\n if ab > both\n then None\n else inner 0\n\nlet rec make_ans n a c b i = function\n | 0 :: rest when n > 0 -> i :: make_ans (n-1) a c b (i+1) rest\n | 1 :: rest when a > 0 -> i :: make_ans n (a-1) c b (i+1) rest\n | 2 :: rest when c > 0 -> i :: make_ans n a (c-1) b (i+1) rest\n | 3 :: rest when b > 0 -> i :: make_ans n a c (b-1) (i+1) rest\n | x :: rest -> make_ans n a c b (i+1) rest\n | _ -> []\n\nlet () =\n let n = read_int () in\n let s = Array.(init n read_char |> to_list) in\n let t = Array.(init n read_char |> to_list) in\n let ca = zip_with (fun x y -> x lor (y lsl 1)) s t in\n let cnt = Array.make 4 0 in\n let () = List.iter (fun v -> cnt.(v) <- cnt.(v) + 1) ca in\n match loop 0 cnt.(0) cnt.(1) cnt.(2) cnt.(3) with\n | Some (n,a,c,b) ->\n let ans = make_ans n a c b 0 ca in\n let ans = List.map (fun v -> sprintf \"%d\" (v+1)) ans |> String.concat \" \" in\n printf \"%s\\n\" ans\n | None -> printf \"-1\\n\"\n"}], "negative_code": [], "src_uid": "3afa68fbe090683ffe16c3141aafe76e"} {"nl": {"description": "It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.There are $$$n$$$ displays placed along a road, and the $$$i$$$-th of them can display a text with font size $$$s_i$$$ only. Maria Stepanovna wants to rent such three displays with indices $$$i < j < k$$$ that the font size increases if you move along the road in a particular direction. Namely, the condition $$$s_i < s_j < s_k$$$ should be held.The rent cost is for the $$$i$$$-th display is $$$c_i$$$. Please determine the smallest cost Maria Stepanovna should pay.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$3 \\le n \\le 3\\,000$$$)\u00a0\u2014 the number of displays. The second line contains $$$n$$$ integers $$$s_1, s_2, \\ldots, s_n$$$ ($$$1 \\le s_i \\le 10^9$$$)\u00a0\u2014 the font sizes on the displays in the order they stand along the road. The third line contains $$$n$$$ integers $$$c_1, c_2, \\ldots, c_n$$$ ($$$1 \\le c_i \\le 10^8$$$)\u00a0\u2014 the rent costs for each display.", "output_spec": "If there are no three displays that satisfy the criteria, print -1. Otherwise print a single integer\u00a0\u2014 the minimum total rent cost of three displays with indices $$$i < j < k$$$ such that $$$s_i < s_j < s_k$$$.", "sample_inputs": ["5\n2 4 5 4 10\n40 30 20 10 40", "3\n100 101 100\n2 4 5", "10\n1 2 3 4 5 6 7 8 9 10\n10 13 11 14 15 12 13 13 18 13"], "sample_outputs": ["90", "-1", "33"], "notes": "NoteIn the first example you can, for example, choose displays $$$1$$$, $$$4$$$ and $$$5$$$, because $$$s_1 < s_4 < s_5$$$ ($$$2 < 4 < 10$$$), and the rent cost is $$$40 + 10 + 40 = 90$$$.In the second example you can't select a valid triple of indices, so the answer is -1."}, "positive_code": [{"source_code": "\nlet input_int_array n =\n Array.init n (fun i -> Scanf.scanf \" %d\" (fun i -> i))\n \nmodule IntSet = Set.Make(struct type t = int let compare = compare end)\n \nlet discretize src =\n let set = src |> Array.to_list |> IntSet.of_list in\n let map = Hashtbl.create (Array.length src) in\n set |> IntSet.elements |> List.iteri (fun i v -> Hashtbl.add map v i);\n Array.map (fun i -> Hashtbl.find map i) src\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun i -> i) in\n let font_sizes = input_int_array n in\n let costs = input_int_array n in\n (* let font_sizes = font_sizes_raw |> discretize in *)\n\n let dp: (int option) array = Array.make n None in\n for i = 1 to n - 2 do\n for j = 0 to i - 1 do\n if font_sizes.(i) > font_sizes.(j) then\n let v = costs.(j) in\n match dp.(i) with\n | Some x when v < x -> dp.(i) <- Some v\n | None -> dp.(i) <- Some v\n | _ -> () \n done\n done;\n Array.iteri (fun i v -> dp.(i) <-\n match v with | Some v -> Some (v + costs.(i)) | x -> x) dp;\n\n let ret = ref None in\n for i = 2 to n - 1 do\n for j = 1 to i - 1 do\n match dp.(j) with\n | None -> ()\n | Some v ->\n if font_sizes.(i) > font_sizes.(j) then\n let v = v + costs.(i) in\n match !ret with\n | Some x when v < x -> ret := Some v\n | None -> ret := Some v\n | _ -> ()\n done\n done;\n\n (match !ret with | None -> -1 | Some x -> x)\n |> string_of_int |> print_endline\n"}], "negative_code": [{"source_code": "\n(* x^y ? y^x *)\n(* so much special cases ... *)\n\nlet compare x y =\n if x > y then `Greater\n else if x < y\n then `Less\n else `Equal\n\nlet serialize_pow = function\n | `Greater -> \">\"\n | `Less -> \"<\"\n | `Equal -> \"=\"\n \nlet invert = function\n | `Greater -> `Less\n | `Less -> `Greater\n | `Equal -> `Equal\n \nlet compute (x, y) =\n match x, y with\n | 2, 4 | 4, 2 -> `Equal\n | _, 1 | 1, _ | 2, 3 | 3, 2 -> compare x y\n | x, y -> compare x y |> invert\n \n\nlet _ =\n let x, y = Scanf.scanf \" %d %d\" (fun x y -> (x, y)) in\n (x, y) |> compute |> serialize_pow |> print_endline\n \n"}], "src_uid": "4a48b828e35efa065668703edc22bf9b"} {"nl": {"description": "A Christmas party in city S. had n children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to m, and the children are numbered from 1 to n. Then the i-th child has both mittens of color ci.The Party had Santa Claus ('Father Frost' in Russian), his granddaughter Snow Girl, the children danced around the richly decorated Christmas tree. In fact, everything was so bright and diverse that the children wanted to wear mittens of distinct colors. The children decided to swap the mittens so that each of them got one left and one right mitten in the end, and these two mittens were of distinct colors. All mittens are of the same size and fit all the children.The children started exchanging the mittens haphazardly, but they couldn't reach the situation when each child has a pair of mittens of distinct colors. Vasily Petrov, the dad of one of the children, noted that in the general case the children's idea may turn out impossible. Besides, he is a mathematician and he came up with such scheme of distributing mittens that the number of children that have distinct-colored mittens was maximum. You task is to repeat his discovery. Note that the left and right mittens are different: each child must end up with one left and one right mitten.", "input_spec": "The first line contains two integers n and m \u2014 the number of the children and the number of possible mitten colors (1\u2009\u2264\u2009n\u2009\u2264\u20095000, 1\u2009\u2264\u2009m\u2009\u2264\u2009100). The second line contains n integers c1,\u2009c2,\u2009... cn, where ci is the color of the mittens of the i-th child (1\u2009\u2264\u2009ci\u2009\u2264\u2009m).", "output_spec": "In the first line, print the maximum number of children who can end up with a distinct-colored pair of mittens. In the next n lines print the way the mittens can be distributed in this case. On the i-th of these lines print two space-separated integers: the color of the left and the color of the right mitten the i-th child will get. If there are multiple solutions, you can print any of them.", "sample_inputs": ["6 3\n1 3 2 2 1 1", "4 2\n1 2 1 1"], "sample_outputs": ["6\n2 1\n1 2\n2 1\n1 3\n1 2\n3 1", "2\n1 2\n1 1\n2 1\n1 1"], "notes": null}, "positive_code": [{"source_code": "let read_int() = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet n = read_int() and m = read_int() in\n\nlet a = Array.init n (fun _ -> let x = read_int() in (x,x)) in\n\nlet swap i j = \n let (xi, yi),(xj, yj) = a.(i),a.(j) in\n begin\n a.(i) <- (xi, yj);\n a.(j) <- (xj, yi);\n end in\n\nlet rec f i j =\n if i = Array.length a || j = Array.length a then ()\n else if i = j || fst a.(i) = fst a.(j) then f i (j+1)\n else begin\n swap i j;\n f (i+1) (j+1);\n end\n in f 0 0;\n\nlet rec f i =\n if i = Array.length a then ()\n else begin\n let rec g j =\n if j = Array.length a then ()\n else if fst a.(i) <> fst a.(j) && fst a.(i) <> snd a.(j) then\n begin\n swap i j;\n end\n else g (j+1)\n in\n if fst a.(i) = snd a.(i) then g 0;\n f (i+1);\n end\n in f 0;\n\nPrintf.printf \"%d\\n\" (Array.fold_left (fun acc (x,y) -> acc + (if x <> y then 1 else 0)) 0 a);\nArray.iter (fun (x,y) -> Printf.printf \"%d %d\\n\" x y) a;\n"}], "negative_code": [], "src_uid": "636e9c125197b52c91998bf91ecd8ab1"} {"nl": {"description": "In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners:That is, a cardiogram is fully defined by a sequence of positive integers a1,\u2009a2,\u2009...,\u2009an.Your task is to paint a cardiogram by given sequence ai.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091000). The next line contains the sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000). It is guaranteed that the sum of all ai doesn't exceed 1000.", "output_spec": "Print max\u00a0|yi\u2009-\u2009yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print characters. Each character must equal either \u00ab\u2009/\u2009\u00bb (slash), \u00ab \\ \u00bb (backslash), \u00ab \u00bb (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram. Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.", "sample_inputs": ["5\n3 1 2 5 1", "3\n1 5 1"], "sample_outputs": ["/\u2009\n\n\\\n \n \n\u2009/\u2009\n\n\\\n\n\u2009/\u2009\n \n\\\n \n \n\u2009/\u2009\n \n\\\n \n\n\u2009/\u2009\n \n\\\n \n \n\\\n\n\u2009/", "/\u2009\n\n\\\n \n \n\\\n \n \n\\\n \n \n\\\n \n \n\\\n\n\u2009/"], "notes": "NoteDue to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.http://assets.codeforces.com/rounds/435/1.txthttp://assets.codeforces.com/rounds/435/2.txt"}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet tab=Array.make (n+1) 0;;\nlet sum=Array.make (n+1) 0;;\nlet s=ref 0;;\n\nlet puiss i=if (i mod 2)=0 then (-1) else 1;;\n\nfor i=1 to n do\n let x=(puiss i)*read_int() in\n tab.(i)<-x;\n sum.(i)<-x+sum.(i-1);\n s:= !s+abs(x)\ndone;;\n\nlet rec maxi a b=\n if (a=b) then sum.(a) else max sum.(a) (maxi (a+1) b );;\nlet rec mini a b=\n if (a=b) then sum.(a) else min sum.(a) (mini (a+1) b );;\n \nlet p=maxi 1 n;;\nlet m=min 0 (mini 1 n);;\n\nlet mat=Array.make_matrix (p-m) !s \" \";;\n\nlet i=ref (max 0 ((-1)*m));;\nlet j=ref 0;;\n\nfor k=1 to n do\n for l=1 to abs(tab.(k)) do\n if tab.(k)<0 then\n begin\n mat.(!i).(!j)<-\"\\\\\";\n if l=abs(tab.(k)) then incr j\n else (incr j;decr i)\n end\n else\n begin\n mat.(!i).(!j)<-\"/\";\n if l=abs(tab.(k)) then incr j\n else (incr j;incr i);\n end\n done\ndone;;\n\nfor i=(p-m-1) downto 0 do\n for j=0 to !s-1 do\n print_string mat.(i).(j)\n done;\n print_newline()\ndone;;"}], "negative_code": [], "src_uid": "76285a60c21538db17d268a5e06c2270"} {"nl": {"description": "Polycarpus enjoys studying Berland hieroglyphs. Once Polycarp got hold of two ancient Berland pictures, on each of which was drawn a circle of hieroglyphs. We know that no hieroglyph occurs twice in either the first or the second circle (but in can occur once in each of them).Polycarpus wants to save these pictures on his laptop, but the problem is, laptops do not allow to write hieroglyphs circles. So Polycarp had to break each circle and write down all of its hieroglyphs in a clockwise order in one line. A line obtained from the first circle will be called a, and the line obtained from the second one will be called b.There are quite many ways to break hieroglyphic circles, so Polycarpus chooses the method, that makes the length of the largest substring of string a, which occurs as a subsequence in string b, maximum.Help Polycarpus \u2014 find the maximum possible length of the desired substring (subsequence) if the first and the second circles are broken optimally.The length of string s is the number of characters in it. If we denote the length of string s as |s|, we can write the string as s\u2009=\u2009s1s2... s|s|.A substring of s is a non-empty string x\u2009=\u2009s[a... b]\u2009=\u2009sasa\u2009+\u20091... sb (1\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009\u2264\u2009|s|). For example, \"code\" and \"force\" are substrings of \"codeforces\", while \"coders\" is not. A subsequence of s is a non-empty string y\u2009=\u2009s[p1p2... p|y|]\u2009=\u2009sp1sp2... sp|y| (1\u2009\u2264\u2009p1\u2009<\u2009p2\u2009<\u2009...\u2009<\u2009p|y|\u2009\u2264\u2009|s|). For example, \"coders\" is a subsequence of \"codeforces\".", "input_spec": "The first line contains two integers la and lb (1\u2009\u2264\u2009la,\u2009lb\u2009\u2264\u20091000000) \u2014 the number of hieroglyphs in the first and second circles, respectively. Below, due to difficulties with encoding of Berland hieroglyphs, they are given as integers from 1 to 106. The second line contains la integers \u2014 the hieroglyphs in the first picture, in the clockwise order, starting with one of them. The third line contains lb integers \u2014 the hieroglyphs in the second picture, in the clockwise order, starting with one of them. It is guaranteed that the first circle doesn't contain a hieroglyph, which occurs twice. The second circle also has this property.", "output_spec": "Print a single number \u2014 the maximum length of the common substring and subsequence. If at any way of breaking the circles it does not exist, print 0.", "sample_inputs": ["5 4\n1 2 3 4 5\n1 3 5 6", "4 6\n1 3 5 2\n1 2 3 4 5 6", "3 3\n1 2 3\n3 2 1"], "sample_outputs": ["2", "3", "2"], "notes": "NoteIn the first test Polycarpus picks a string that consists of hieroglyphs 5 and 1, and in the second sample \u2014 from hieroglyphs 1, 3 and 5."}, "positive_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let la = getnum () in\n let lb = getnum () in\n let a = Array.make la 0 in\n let b = Array.make lb 0 in\n let () =\n for i = 0 to la - 1 do\n a.(i) <- getnum () - 1\n done;\n for i = 0 to lb - 1 do\n b.(i) <- getnum () - 1\n done;\n in\n let c = Array.make 1000000 (-1) in\n let res = ref 0 in\n let max (x : int) y = if x > y then x else y in\n let j = ref 0 in\n let next x =\n if x = la - 1\n then 0\n else x + 1\n in\n for i = 0 to lb - 1 do\n c.(b.(i)) <- i\n done;\n for i = 0 to la - 1 do\n if next !j = i\n then j := i;\n if c.(a.(i)) >= 0 then (\n\twhile next !j <> i &&\n\t c.(a.(next !j)) <> -1 &&\n\t (c.(a.(!j)) < c.(a.(i)) && \n\t (c.(a.(next !j)) > c.(a.(!j)) && c.(a.(next !j)) < c.(a.(i))) ||\n\t c.(a.(!j)) >= c.(a.(i)) &&\n\t (c.(a.(next !j)) > c.(a.(!j)) || c.(a.(next !j)) < c.(a.(i))))\n\tdo\n\t j := next !j;\n\tdone;\n\t(*Printf.printf \"asd %d %d\\n\" i !j;*)\n\tlet l = if !j >= i then !j - i + 1 else !j + la - i + 1 in\n\t res := max !res l\n )\n done;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let la = getnum () in\n let lb = getnum () in\n let a = Array.make la 0 in\n let b = Array.make lb 0 in\n let () =\n for i = 0 to la - 1 do\n a.(i) <- getnum () - 1\n done;\n for i = 0 to lb - 1 do\n b.(i) <- getnum () - 1\n done;\n in\n let c = Array.make 1000000 (-1) in\n let res = ref 0 in\n let max (x : int) y = if x > y then x else y in\n let j = ref 0 in\n let next x =\n if x = la - 1\n then 0\n else x + 1\n in\n for i = 0 to lb - 1 do\n c.(b.(i)) <- i\n done;\n for i = 0 to la - 1 do\n if !j = next i\n then j := i;\n if c.(a.(i)) >= 0 then (\n\twhile next !j <> i &&\n\t c.(a.(next !j)) <> -1 &&\n\t (c.(a.(!j)) < c.(a.(i)) && \n\t (c.(a.(next !j)) > c.(a.(!j)) && c.(a.(next !j)) < c.(a.(i))) ||\n\t c.(a.(!j)) >= c.(a.(i)) &&\n\t (c.(a.(next !j)) > c.(a.(!j)) || c.(a.(next !j)) < c.(a.(i))))\n\tdo\n\t j := next !j;\n\tdone;\n\t(*Printf.printf \"asd %d %d\\n\" i !j;*)\n\tlet l = if !j >= i then !j - i + 1 else !j + la - i + 1 in\n\t res := max !res l\n )\n done;\n Printf.printf \"%d\\n\" !res\n"}], "src_uid": "13cd1aafbb1ba76be9ee10eaf8d8aef5"} {"nl": {"description": "Luca has a cypher made up of a sequence of $$$n$$$ wheels, each with a digit $$$a_i$$$ written on it. On the $$$i$$$-th wheel, he made $$$b_i$$$ moves. Each move is one of two types: up move (denoted by $$$\\texttt{U}$$$): it increases the $$$i$$$-th digit by $$$1$$$. After applying the up move on $$$9$$$, it becomes $$$0$$$. down move (denoted by $$$\\texttt{D}$$$): it decreases the $$$i$$$-th digit by $$$1$$$. After applying the down move on $$$0$$$, it becomes $$$9$$$. Example for $$$n=4$$$. The current sequence is 0 0 0 0. Luca knows the final sequence of wheels and the moves for each wheel. Help him find the original sequence and crack the cypher.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$)\u00a0\u2014 the number of wheels. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$0 \\leq a_i \\leq 9$$$)\u00a0\u2014 the digit shown on the $$$i$$$-th wheel after all moves have been performed. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains the integer $$$b_i$$$ ($$$1 \\leq b_i \\leq 10$$$) and $$$b_i$$$ characters that are either $$$\\texttt{U}$$$ or $$$\\texttt{D}$$$\u00a0\u2014 the number of moves performed on the $$$i$$$-th wheel, and the moves performed. $$$\\texttt{U}$$$ and $$$\\texttt{D}$$$ represent an up move and a down move respectively.", "output_spec": "For each test case, output $$$n$$$ space-separated digits \u00a0\u2014 the initial sequence of the cypher.", "sample_inputs": ["3\n\n3\n\n9 3 1\n\n3 DDD\n\n4 UDUU\n\n2 DU\n\n2\n\n0 9\n\n9 DDDDDDDDD\n\n9 UUUUUUUUU\n\n5\n\n0 5 9 8 3\n\n10 UUUUUUUUUU\n\n3 UUD\n\n8 UUDUUDDD\n\n10 UUDUUDUDDU\n\n4 UUUU"], "sample_outputs": ["2 1 1 \n9 0 \n0 4 9 6 9"], "notes": "NoteIn the first test case, we can prove that initial sequence was $$$[2,1,1]$$$. In that case, the following moves were performed: On the first wheel: $$$2 \\xrightarrow[\\texttt{D}]{} 1 \\xrightarrow[\\texttt{D}]{} 0 \\xrightarrow[\\texttt{D}]{} 9$$$. On the second wheel: $$$1 \\xrightarrow[\\texttt{U}]{} 2 \\xrightarrow[\\texttt{D}]{} 1 \\xrightarrow[\\texttt{U}]{} 2 \\xrightarrow[\\texttt{U}]{} 3$$$. On the third wheel: $$$1 \\xrightarrow[\\texttt{D}]{} 0 \\xrightarrow[\\texttt{U}]{} 1$$$. The final sequence was $$$[9,3,1]$$$, which matches the input."}, "positive_code": [{"source_code": "(* From @Darooha's code (https://codeforces.com/profile/Darooha) *)\r\n\r\nopen Printf \r\nopen Scanf\r\n \r\nlet ( ** ) a b = Int64.mul a b\r\nlet ( ++ ) a b = Int64.add a b\r\nlet long x = Int64.of_int x\r\nlet short x = Int64.to_int x\r\n \r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\r\n \r\n(* Main Code file *)\r\n\r\nlet rec sum = function\r\n | [] -> 0\r\n | h::t -> h + sum(t)\r\n\r\nlet () = \r\n let t = read_int() in\r\n for i=1 to t do\r\n let n = read_int() in\r\n let arr = Array.init n read_int in\r\n for j=0 to n-1 do\r\n let m = read_int() in\r\n let s = read_string() in\r\n for k=0 to m-1 do\r\n if s.[k] = 'U' then \r\n arr.(j) <- arr.(j)-1\r\n else \r\n arr.(j) <- arr.(j)+1\r\n done;\r\n printf \"%d \" (((arr.(j) mod 10) + 10) mod 10)\r\n done;\r\n print_newline()\r\n done;"}], "negative_code": [], "src_uid": "fd47f1eb701077abc5ec67163ad4fcc5"} {"nl": {"description": "Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v,\u2009u)\u2009>\u2009au, where au is the number written on vertex u, dist(v,\u2009u) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex\u00a0\u2014 root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?", "input_spec": "In the first line of the input integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) is given\u00a0\u2014 the number of vertices in the tree. In the second line the sequence of n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) is given, where ai is the number written on vertex i. The next n\u2009-\u20091 lines describe tree edges: ith of them consists of two integers pi and ci (1\u2009\u2264\u2009pi\u2009\u2264\u2009n, \u2009-\u2009109\u2009\u2264\u2009ci\u2009\u2264\u2009109), meaning that there is an edge connecting vertices i\u2009+\u20091 and pi with number ci written on it.", "output_spec": "Print the only integer\u00a0\u2014 the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.", "sample_inputs": ["9\n88 22 83 14 95 91 98 53 11\n3 24\n7 -8\n1 67\n1 64\n9 65\n5 12\n6 -80\n3 8"], "sample_outputs": ["5"], "notes": "NoteThe following image represents possible process of removing leaves from the tree: "}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0L in\n let es = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s)\n done;\n for i = 1 to n - 1 do\n let p = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n\tes.(p - 1) <- (i, c) :: es.(p - 1)\n done;\n in\n let es = Array.map Array.of_list es in\n let res = ref 0 in\n let rec dfs u s =\n if s < 0L || s > a.(u)\n then incr res;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet (v, c) = es.(u).(i) in\n\t if s < 0L || s > a.(u)\n\t then dfs v (-1L)\n\t else (\n\t let s = max 0L (s +| c) in\n\t dfs v s\n\t )\n done\n in\n dfs 0 0L;\n Printf.printf \"%d\\n\" !res\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> long (read_int())) in\n\n let tree = Array.make n [] in\n let c = Array.make n 0L in\n let add_edge i j =\n tree.(i) <- j::tree.(i);\n tree.(j) <- i::tree.(j)\n in\n\n for i = 1 to n-1 do\n let p = -1 + read_int() in\n c.(i) <- long (read_int());\n add_edge i p\n done;\n\n let mark = Array.make n false in\n\n let rec dfs v p dist =\n List.iter (fun w ->\n if w <> p then (\n\tlet dist = max 0L (dist ++ c.(w)) in\n\tdfs w v dist;\n\tif dist > a.(w) then mark.(w) <- true\n )\n ) tree.(v)\n in\n\n dfs 0 (-1) 0L;\n\n let rec dfs2 v p =\n if mark.(v) then 0 else (\n List.fold_left (fun ac w ->\n\tif w = p then ac else ac + (dfs2 w v)\n ) 1 tree.(v)\n )\n in\n\n let good_count = dfs2 0 (-1) in\n\n printf \"%d\\n\" (n - good_count)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> long (read_int())) in\n\n let tree = Array.make n [] in\n let c = Array.make n 0L in\n let add_edge i j =\n tree.(i) <- j::tree.(i);\n tree.(j) <- i::tree.(j)\n in\n\n for i = 1 to n-1 do\n let p = -1 + read_int() in\n c.(i) <- long (read_int());\n add_edge i p\n done;\n\n let mark = Array.make n false in\n\n let rec dfs v p dist =\n List.iter (fun w ->\n if w <> p then (\n\tlet dist = dist ++ c.(w) in\n\tdfs w v dist;\n\tif dist > a.(w) then mark.(w) <- true\n )\n ) tree.(v)\n in\n\n dfs 0 (-1) 0L;\n\n let rec dfs2 v p =\n if mark.(v) then 0 else (\n List.fold_left (fun ac w ->\n\tif w = p then ac else ac + (dfs2 w v)\n ) 1 tree.(v)\n )\n in\n\n let good_count = dfs2 0 (-1) in\n\n printf \"%d\\n\" (n - good_count)\n"}], "src_uid": "0c4bc51e5be9cc642f62d2b3df2bddc4"} {"nl": {"description": "It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.A \"star\" figure having n\u2009\u2265\u20095 corners where n is a prime number is constructed the following way. On the circle of radius r n points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts. ", "input_spec": "The only line of the input contains two integers n (5\u2009\u2264\u2009n\u2009<\u2009109, n is prime) and r (1\u2009\u2264\u2009r\u2009\u2264\u2009109) \u2014 the number of the star corners and the radius of the circumcircle correspondingly.", "output_spec": "Output one number \u2014 the star area. The relative error of your answer should not be greater than 10\u2009-\u20097.", "sample_inputs": ["7 10"], "sample_outputs": ["108.395919545675"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let pi = 4.0 *. atan 1.0 in\n let alpha = pi /. n in\n let a = r *. sin alpha /. sin (pi -. 1.5 *. alpha) in\n let b = r *. sin (alpha /. 2.0) /. sin (pi -. 1.5 *. alpha) in\n let s =\n r *. r *. sin alpha *. sin (alpha /. 2.0) /.\n (2.0 *. sin (1.5 *. alpha))\n in\n let res = 2.0 *. n *. s in\n Printf.printf \"%.9f\\n\" res\n"}], "negative_code": [], "src_uid": "fd92081afd795789b738009ff292a25c"} {"nl": {"description": "A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1,\u2009a2,\u2009...,\u2009an.Little Tommy is among them. He would like to choose an interval [l,\u2009r] (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n), then reverse al,\u2009al\u2009+\u20091,\u2009...,\u2009ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.A non-decreasing subsequence is a sequence of indices p1,\u2009p2,\u2009...,\u2009pk, such that p1\u2009<\u2009p2\u2009<\u2009...\u2009<\u2009pk and ap1\u2009\u2264\u2009ap2\u2009\u2264\u2009...\u2009\u2264\u2009apk. The length of the subsequence is k.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000), denoting the length of the original sequence. The second line contains n space-separated integers, describing the original sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20092,\u2009i\u2009=\u20091,\u20092,\u2009...,\u2009n).", "output_spec": "Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.", "sample_inputs": ["4\n1 2 1 2", "10\n1 1 2 2 2 1 1 2 2 1"], "sample_outputs": ["4", "9"], "notes": "NoteIn the first example, after reversing [2,\u20093], the array will become [1,\u20091,\u20092,\u20092], where the length of the longest non-decreasing subsequence is 4.In the second example, after reversing [3,\u20097], the array will become [1,\u20091,\u20091,\u20091,\u20092,\u20092,\u20092,\u20092,\u20092,\u20091], where the length of the longest non-decreasing subsequence is 9."}, "positive_code": [{"source_code": "\nopen Scanf\n\nlet read_array n =\n let f i = scanf \" %u\" (fun i -> i) in\n Array.init n f\n\nlet count_array f a =\n Array.fold_left (fun i v -> if f v then i + 1 else i) 0 a\n\nlet update_ref (ref1, ref2) = function\n | 1 -> ref1 := !ref1 + 1\n | 2 -> ref2 := !ref2 + 1\n | _ -> ()\n\n(*\n ret = max(n1_0a + n2_bn + n2_ak + n1_kb)\n => n1_0a + (n2 - n2_0b) + n2_0k - n2_0a + n1_0b - n1_0k\n => n1_0a + n2_bn - n2_0a + n1_0b + **(n2_0k - n1_0k)**\n*)\nlet () =\n let n = scanf \" %u \" (fun i -> i) in\n let a = read_array n in\n\n let ret = ref 0 in\n let n2 = count_array (fun x -> x = 2) a in\n let n1_0a = ref 0 in\n let n2_0a = ref 0 in\n for ia = 0 to n do begin\n if ia > 0 then begin update_ref (n1_0a, n2_0a) a.(ia - 1) end;\n let max_diff = ref min_int in\n let n1_0b = ref !n1_0a in\n let n2_0b = ref !n2_0a in\n for ib = ia to n do\n if ib > ia then begin update_ref (n1_0b, n2_0b) a.(ib - 1) end;\n (* the diff. we are maximizing is effectively (n2_0k - n1_0k) *)\n max_diff := max !max_diff (!n2_0b - !n1_0b);\n let n2_bn = n2 - !n2_0b in\n ret := max !ret\n (!n1_0a + n2_bn + !n1_0b - !n2_0a + !max_diff)\n done\n end\n done;\n !ret |> string_of_int |> print_endline\n"}, {"source_code": "\nopen Scanf\n\nlet () = Printexc.record_backtrace true\n\nlet read_array n =\n let f i = scanf \" %u\" (fun i -> i) in\n Array.init n f\n\nlet count_array f a =\n Array.fold_left (fun i v -> if f v then i + 1 else i) 0 a\n\nlet () =\n let n = scanf \" %u \" (fun i -> i) in\n let a = read_array n in\n let ret = ref 0 in\n let n1 = count_array (fun x -> x = 1) a in\n let n2 = count_array (fun x -> x = 2) a in\n let n1_0a = ref 0 in\n let n2_0a = ref 0 in\n for ia = 0 to n do begin\n if ia > 0 then begin\n match a.(ia - 1) with\n | 1 -> n1_0a := !n1_0a + 1\n | 2 -> n2_0a := !n2_0a + 1\n | _ -> ()\n end;\n let max_diff = ref min_int in\n let n1_0b = ref !n1_0a in\n let n2_0b = ref !n2_0a in\n for ib = ia to n do\n if ib > ia then begin\n match a.(ib - 1) with\n | 1 -> n1_0b := !n1_0b + 1\n | 2 -> n2_0b := !n2_0b + 1\n | _ -> ()\n end;\n max_diff := max !max_diff (!n2_0b - !n1_0b);\n let n2_bn = n2 - !n2_0b in\n ret := max !ret\n (!n1_0a + n2_bn + !n1_0b - !n2_0a + !max_diff)\n done\n end\n done;\n !ret |> string_of_int |> print_endline"}], "negative_code": [], "src_uid": "dae132800359378ca1b9f5be4b8c0df9"} {"nl": {"description": "Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix\u2009+\u2009biy\u2009+\u2009ci\u2009=\u20090, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.", "input_spec": "The first line contains two space-separated integers x1, y1 (\u2009-\u2009106\u2009\u2264\u2009x1,\u2009y1\u2009\u2264\u2009106) \u2014 the coordinates of your home. The second line contains two integers separated by a space x2, y2 (\u2009-\u2009106\u2009\u2264\u2009x2,\u2009y2\u2009\u2264\u2009106) \u2014 the coordinates of the university you are studying at. The third line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009300) \u2014 the number of roads in the city. The following n lines contain 3 space-separated integers (\u2009-\u2009106\u2009\u2264\u2009ai,\u2009bi,\u2009ci\u2009\u2264\u2009106; |ai|\u2009+\u2009|bi|\u2009>\u20090) \u2014 the coefficients of the line aix\u2009+\u2009biy\u2009+\u2009ci\u2009=\u20090, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).", "output_spec": "Output the answer to the problem.", "sample_inputs": ["1 1\n-1 -1\n2\n0 1 0\n1 0 0", "1 1\n-1 -1\n3\n1 0 0\n0 1 0\n1 1 -3"], "sample_outputs": ["2", "2"], "notes": "NotePictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let x1 = float (read_int ()) in\n let y1 = float (read_int ()) in\n let x2 = float (read_int ()) in\n let y2 = float (read_int ()) in\n let n = read_int () in\n let line = Array.init n (fun _ -> \n let a = float (read_int()) in\n let b = float (read_int()) in\n let c = float (read_int()) in\n (a,b,c)\n ) in\n\n let side (x,y) i = \n let (a,b,c) = line.(i) in\n let v = a*.x +. b*.y +. c in\n if v>0.0 then 1 else if v<0.0 then -1 else failwith \"on a line\"\n in\n\n let diff_side_count = \n sum 0 (n-1) (fun i -> if (side (x1,y1) i) = (side (x2,y2) i) then 0 else 1)\n in\n\n printf \"%d\\n\" diff_side_count\n"}], "negative_code": [], "src_uid": "783df1df183bf182bf9acbb99208cdb7"} {"nl": {"description": "You are given an integer $$$n$$$ and an integer $$$k$$$.In one step you can do one of the following moves: decrease $$$n$$$ by $$$1$$$; divide $$$n$$$ by $$$k$$$ if $$$n$$$ is divisible by $$$k$$$. For example, if $$$n = 27$$$ and $$$k = 3$$$ you can do the following steps: $$$27 \\rightarrow 26 \\rightarrow 25 \\rightarrow 24 \\rightarrow 8 \\rightarrow 7 \\rightarrow 6 \\rightarrow 2 \\rightarrow 1 \\rightarrow 0$$$.You are asked to calculate the minimum number of steps to reach $$$0$$$ from $$$n$$$. ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of queries. The only line of each query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 10^{18}$$$, $$$2 \\le k \\le 10^{18}$$$).", "output_spec": "For each query print the minimum number of steps to reach $$$0$$$ from $$$n$$$ in single line. ", "sample_inputs": ["2\n59 3\n1000000000000000000 10"], "sample_outputs": ["8\n19"], "notes": "NoteSteps for the first test case are: $$$59 \\rightarrow 58 \\rightarrow 57 \\rightarrow 19 \\rightarrow 18 \\rightarrow 6 \\rightarrow 2 \\rightarrow 1 \\rightarrow 0$$$.In the second test case you have to divide $$$n$$$ by $$$k$$$ $$$18$$$ times and then decrease $$$n$$$ by $$$1$$$."}, "positive_code": [{"source_code": "let (/) = Int64.div\nlet ( * ) = Int64.mul\nlet (-) = Int64.sub\nlet (+) = Int64.add\n\nlet () =\n let t = Scanf.scanf \"%d\\n\" (fun x -> x) in\n for i = 1 to t do\n let n, k = Scanf.scanf \"%Ld %Ld\\n\" (fun x y -> x, y) in\n let n = ref n in\n let res = ref Int64.zero in\n while !n >= k do\n let x = !n - ((!n / k) * k) in\n if x = Int64.zero then begin n:=!n/k; res := !res + 1L end else\n begin n := !n - x;\n res := !res + x;\n end;\n done;\n res := !res + !n;\n Printf.printf \"%Ld\\n\" !res\n done\n;;\n"}], "negative_code": [], "src_uid": "00b1e45e9395d23e850ce1a0751b8378"} {"nl": {"description": "Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular $$$n$$$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $$$OX$$$-axis and at least one of its edges is parallel to the $$$OY$$$-axis at the same time.Recall that a regular $$$n$$$-sided polygon is a convex polygon with $$$n$$$ vertices such that all the edges and angles are equal.Now he is shopping: the market has $$$t$$$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of polygons in the market. Each of the next $$$t$$$ lines contains a single integer $$$n_i$$$ ($$$3 \\le n_i \\le 10^9$$$): it means that the $$$i$$$-th polygon is a regular $$$n_i$$$-sided polygon. ", "output_spec": "For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).", "sample_inputs": ["4\n3\n4\n12\n1000000000"], "sample_outputs": ["NO\nYES\nYES\nYES"], "notes": "NoteIn the example, there are $$$4$$$ polygons in the market. It's easy to see that an equilateral triangle (a regular $$$3$$$-sided polygon) is not beautiful, a square (a regular $$$4$$$-sided polygon) is beautiful and a regular $$$12$$$-sided polygon (is shown below) is beautiful as well. "}, "positive_code": [{"source_code": "let t = read_int();;\nfor i=0 to t-1 do\n\tlet n = read_int() in\n\tif n mod 4 = 0 then begin\n\t\tprint_endline \"Yes\";\n\tend else begin\n\t\tprint_endline \"No\";\n\tend\ndone;;\n"}], "negative_code": [{"source_code": "let t = read_int();;\nfor i=0 to t-1 do\n\tlet n = read_int() in\n\tif n mod 2 = 0 then begin\n\t\tprint_endline \"Yes\";\n\tend else begin\n\t\tprint_endline \"No\";\n\tend\ndone;;\n"}], "src_uid": "07e56d4031bcb119d2f684203f7ed133"} {"nl": {"description": "You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.", "input_spec": "The first line contains single positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of integers. The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print the maximum length of an increasing subarray of the given array.", "sample_inputs": ["5\n1 7 2 11 15", "6\n100 100 100 100 100 100", "3\n1 2 3"], "sample_outputs": ["3", "1", "3"], "notes": null}, "positive_code": [{"source_code": "\nlet read_nums () = \n let s = read_line () in\n let nums = List.map int_of_string (Str.split (Str.regexp \" \") s) in\n nums\n\n;;\n\n\nlet rec solve lst cnt ans prev =\n match lst with\n | [] -> max cnt ans\n | hd :: tl -> if hd > prev then\n solve tl (cnt+1) (max cnt ans) hd\n else\n solve tl 1 (max cnt ans) hd\n;;\n\n\n\nlet main () =\n let _ = read_int () in\n let l = read_nums () in\n let n = solve l 1 1 1000000007 in\n let () = print_int n in\n print_string \"\\n\"\n\n;;\n\n\nmain ()\n"}, {"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- read_int()\n done;\n let res = ref 1 in\n let cur = ref 1 in\n for i = 1 to n - 1 do\n if a.(i) > a.(i - 1) then\n cur := !cur + 1\n else\n cur := 1;\n if res < cur then\n res := !cur\n done;\n printf \"%d\\n\" !res\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\nlet a = Array.make (n+1) 0\n\nlet b = Array.make (n+1) 0\n\nfor i = 1 to n do\n let j = Scanf.scanf \"%d \" ( fun x -> x ) in\n a.(i)<-j\ndone\n\nlet cnt = ref 0\n\nfor i = 1 to n do\n begin\n if a.(i) > a.(i-1) then\n cnt := !cnt + 1\n else\n cnt := 1\n end; b.(i) <- !cnt\ndone\n\n(*test\nlet () = Array.iter (fun x -> printf \"%d \" x) b\n*)\n\nlet ff = Array.make (n+1) (-10)\nlet rec f m =\n if m = 1 then\n 1\n else\n if ff.(m-1) < 0 then \n begin\n ff.(m-1) <- f (m-1); \n max ff.(m-1) b.(m)\n end\n else\n max ff.(m-1) b.(m)\n\nlet rslt = f n in\nprintf \"%d\\n\" rslt\n\n"}, {"source_code": "open Printf\nlet input_int_array n =\n\tArray.init n (fun _ -> Scanf.scanf \" %d\" (fun v -> v))\n\nlet get_int () = Scanf.scanf \" %d\" (fun v -> v)\nlet get_2_ints () = Scanf.scanf \" %d %d\" (fun u v -> u,v)\nlet get_3_ints () = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w)\nlet get_4_ints () = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x)\nlet get_5_ints () = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nlet () =\n let n = get_int ()\n in let a = input_int_array n\n in let v,len,lenmax = ref a.(0),ref 1,ref 1\n in\n for i=1 to (n-1) do\n if !v < a.(i) then (\n len := !len+1;\n if !len > !lenmax then lenmax := !len;\n ) else (\n len := 1;\n );\n v := a.(i)\n done;\n !lenmax |> print_int_endline"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let res = ref 1 in\n let p = ref a.(0) in\n let len = ref 1 in\n for i = 1 to n - 1 do\n if a.(i) > !p then (\n\tp := a.(i);\n\tincr len;\n\tres := max !res !len;\n ) else (\n\tp := a.(i);\n\tlen := 1;\n )\n done;\n Printf.printf \"%d\\n\" !res\n"}, {"source_code": "let n = int_of_string (input_line stdin) ;;\n\nlet rec solve last acc best count =\n if count == 0 then max best acc\n else let num = Scanf.scanf \"%d \" (fun a -> a) in\n if num > last then solve num (acc + 1) best (count - 1)\n else solve num 1 (max best acc) (count - 1) ;;\n\nlet ans = solve 0 0 0 n in\n Printf.printf \"%d\\n\" ans ;;"}], "negative_code": [{"source_code": "let n = int_of_string (input_line stdin) ;;\n\nlet rec solve last acc best count =\n Printf.printf \"solve %d %d %d %d\\n\" last acc best count ;\n if count == 0 then max best acc\n else let num = Scanf.scanf \"%d \" (fun a -> a) in\n if num > last then solve num (acc + 1) best (count - 1)\n else solve num 1 (max best acc) (count - 1) ;;\n\nlet ans = solve 0 0 0 n in\n Printf.printf \"%d\\n\" ans ;;"}], "src_uid": "4553b327d7b9f090641590d6492c2c41"} {"nl": {"description": "You are given an array of $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$. After you watched the amazing film \"Everything Everywhere All At Once\", you came up with the following operation.In one operation, you choose $$$n-1$$$ elements of the array and replace each of them with their arithmetic mean (which doesn't have to be an integer). For example, from the array $$$[1, 2, 3, 1]$$$ we can get the array $$$[2, 2, 2, 1]$$$, if we choose the first three elements, or we can get the array $$$[\\frac{4}{3}, \\frac{4}{3}, 3, \\frac{4}{3}]$$$, if we choose all elements except the third.Is it possible to make all elements of the array equal by performing a finite number of such operations?", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 50$$$) \u00a0\u2014 the number of integers. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 100$$$).", "output_spec": "For each test case, if it is possible to make all elements equal after some number of operations, output $$$\\texttt{YES}$$$. Otherwise, output $$$\\texttt{NO}$$$. You can output $$$\\texttt{YES}$$$ and $$$\\texttt{NO}$$$ in any case (for example, strings $$$\\texttt{yEs}$$$, $$$\\texttt{yes}$$$, $$$\\texttt{Yes}$$$ will be recognized as a positive response).", "sample_inputs": ["4\n\n3\n\n42 42 42\n\n5\n\n1 2 3 4 5\n\n4\n\n4 3 2 1\n\n3\n\n24 2 22"], "sample_outputs": ["YES\nYES\nNO\nNO"], "notes": "NoteIn the first test case, all elements are already equal.In the second test case, you can choose all elements except the third, their average is $$$\\frac{1 + 2 + 4 + 5}{4} = 3$$$, so the array will become $$$[3, 3, 3, 3, 3]$$$.It's possible to show that it's impossible to make all elements equal in the third and fourth test cases."}, "positive_code": [{"source_code": "open Printf\r\nopen Scanf\r\n \r\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\r\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\r\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f) \r\n \r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet () = \r\n let cases = read_int() in\r\n for case = 1 to cases do\r\n let n = read_int() in\r\n let a = Array.init n read_int in\r\n let s = sum 0 (n-1) (fun i -> a.(i)) in\r\n if exists 0 (n-1) (fun i -> a.(i) * n = s)\r\n then printf \"Yes\\n\" else printf \"No\\n\"\r\n done"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f) \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n let s = sum 0 (n-1) (fun i -> a.(i)) in\n if exists 0 (n-1) (fun i -> a.(i) * n = s)\n then printf \"Yes\\n\" else printf \"No\\n\"\n done\n"}], "negative_code": [], "src_uid": "7785ed6f41dbd45f1a9432c2fb07d713"} {"nl": {"description": "Dreamoon likes to play with sets, integers and . is defined as the largest positive integer that divides both a and b.Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, .Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.", "input_spec": "The single line of the input contains two space separated integers n, k (1\u2009\u2264\u2009n\u2009\u2264\u200910\u2009000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009100).", "output_spec": "On the first line print a single integer \u2014 the minimal possible m. On each of the next n lines print four space separated integers representing the i-th set. Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.", "sample_inputs": ["1 1", "2 2"], "sample_outputs": ["5\n1 2 3 5", "22\n2 4 6 22\n14 18 10 16"], "notes": "NoteFor the first example it's easy to see that set {1,\u20092,\u20093,\u20094} isn't a valid set of rank 1 since ."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let k = read_int () in\n\n let m = 6*n-1 in\n\n printf \"%d\\n\" (k*m);\n\n\n let rec printit i = if i=m+1 then () else (\n printf \"%d %d %d %d\\n\" (k*(i+1)) (k*(i+2)) (k*(i+3)) (k*(i+5));\n printit (i+6)\n ) in\n\n printit 0\n\t\t\t\t\t \n\n \n"}], "negative_code": [], "src_uid": "5e7b4d1e11628152e33d3e18e30f4530"} {"nl": {"description": "On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides).That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices v1, v2, v3 such that the angle (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a. In other words, the value should be minimum possible.If there are many optimal solutions, Mister B should be satisfied with any of them.", "input_spec": "First and only line contains two space-separated integers n and a (3\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009a\u2009\u2264\u2009180)\u00a0\u2014 the number of vertices in the polygon and the needed angle, in degrees.", "output_spec": "Print three space-separated integers: the vertices v1, v2, v3, which form . If there are multiple optimal solutions, print any of them. The vertices are numbered from 1 to n in clockwise order.", "sample_inputs": ["3 15", "4 67", "4 68"], "sample_outputs": ["1 2 3", "2 1 3", "4 1 2"], "notes": "NoteIn first sample test vertices of regular triangle can create only angle of 60 degrees, that's why every possible angle is correct.Vertices of square can create 45 or 90 degrees angles only. That's why in second sample test the angle of 45 degrees was chosen, since |45\u2009-\u200967|\u2009<\u2009|90\u2009-\u200967|. Other correct answers are: \"3 1 2\", \"3 2 4\", \"4 2 3\", \"4 3 1\", \"1 3 4\", \"1 4 2\", \"2 4 1\", \"4 1 3\", \"3 1 4\", \"3 4 2\", \"2 4 3\", \"2 3 1\", \"1 3 2\", \"1 2 4\", \"4 2 1\".In third sample test, on the contrary, the angle of 90 degrees was chosen, since |90\u2009-\u200968|\u2009<\u2009|45\u2009-\u200968|. Other correct answers are: \"2 1 4\", \"3 2 1\", \"1 2 3\", \"4 3 2\", \"2 3 4\", \"1 4 3\", \"3 4 1\"."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet pi = 4.0 *. (atan 1.0)\n\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,a) = read_pair () in\n let a = (float a) *. (pi /. 180.0) in\n let alpha = pi /. (float n) in\n\n let lo = int_of_float (floor (a /. alpha)) in\n let hi = int_of_float (ceil (a /. alpha)) in\n\n let score k =\n let k = float k in\n abs_float (k *. alpha -. a)\n in\n\n let best = if score lo < score hi then lo else hi in\n\n let best = min best (n-2) in\n let best = max best 1 in\n\n printf \"%d %d %d\\n\" (best+1) n 1\n"}], "negative_code": [], "src_uid": "3cdd85f86c77afd1d3b0d1e951a83635"} {"nl": {"description": "This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury guessed some array $$$a$$$ consisting of $$$6$$$ integers. There are $$$6$$$ special numbers \u2014 $$$4$$$, $$$8$$$, $$$15$$$, $$$16$$$, $$$23$$$, $$$42$$$ \u2014 and each of these numbers occurs in $$$a$$$ exactly once (so, $$$a$$$ is some permutation of these numbers).You don't know anything about their order, but you are allowed to ask up to $$$4$$$ queries. In each query, you may choose two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le 6$$$, $$$i$$$ and $$$j$$$ are not necessarily distinct), and you will get the value of $$$a_i \\cdot a_j$$$ in return.Can you guess the array $$$a$$$?The array $$$a$$$ is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries.", "input_spec": null, "output_spec": null, "sample_inputs": ["16\n64\n345\n672"], "sample_outputs": ["? 1 1\n? 2 2\n? 3 5\n? 4 6\n! 4 8 15 16 23 42"], "notes": "NoteIf you want to submit a hack for this problem, your test should contain exactly six space-separated integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_6$$$. Each of $$$6$$$ special numbers should occur exactly once in the test. The test should be ended with a line break character."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = int_of_string (read_line())\nlet output s = printf \"%s\\n%!\" s\nlet output2 i j = output (sprintf \"? %d %d\" i j)\nlet output6 a b c d e f = output (sprintf \"! %d %d %d %d %d %d\" a b c d e f)\n\nlet () = \n output2 1 2;\n let r1 = read_int () in\n output2 3 4;\n let r2 = read_int () in\n output2 1 3;\n let r3 = read_int () in\n output2 3 5;\n let r4 = read_int () in\n\n let a = [|4;8;16;15;23;42|] in\n\n let swap i j =\n let (ai,aj) = (a.(i), a.(j)) in\n a.(i) <- aj;\n a.(j) <- ai\n in\n\n let b = Array.make 6 0 in\n\n let check () =\n a.(0) * a.(1) = r1 && a.(2) * a.(3) = r2 && a.(0) * a.(2) = r3 && a.(2) * a.(4) = r4\n in\n let rec perm i = if i=6 then\n if check() then\n\tfor i=0 to 5 do\n\t b.(i) <- a.(i)\n\tdone\n else ()\n else (\n let rec loop j = if j = 6 then () else (\n\tswap i j;\n\tperm (i+1);\n\tswap i j;\n\tloop (j+1)\n ) in\n loop i\n )\n in\n\n perm 0;\n\n output6 b.(0) b.(1) b.(2) b.(3) b.(4) b.(5)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = int_of_string (read_line())\nlet output s = printf \"%s\\n%!\" s\nlet output2 i j = output (sprintf \"? %d %d\" i j)\nlet output6 a b c d e f = output (sprintf \"%d %d %d %d %d %d\" a b c d e f)\n\nlet () = \n output2 1 2;\n let r1 = read_int () in\n output2 3 4;\n let r2 = read_int () in\n output2 1 3;\n let r3 = read_int () in\n output2 3 5;\n let r4 = read_int () in\n\n let a = [|4;8;16;15;23;42|] in\n\n let swap i j =\n let (ai,aj) = (a.(i), a.(j)) in\n a.(i) <- aj;\n a.(j) <- ai\n in\n\n let b = Array.make 6 0 in\n\n let check () =\n a.(0) * a.(1) = r1 && a.(2) * a.(3) = r2 && a.(0) * a.(2) = r3 && a.(2) * a.(4) = r4\n in\n let rec perm i = if i=6 then\n if check() then\n\tfor i=0 to 5 do\n\t b.(i) <- a.(i)\n\tdone\n else ()\n else (\n let rec loop j = if j = 6 then () else (\n\tswap i j;\n\tperm (i+1);\n\tswap i j;\n\tloop (j+1)\n ) in\n loop i\n )\n in\n\n perm 0;\n\n output6 b.(0) b.(1) b.(2) b.(3) b.(4) b.(5)\n"}], "src_uid": "c0f79d7ebcecc4eb7d07c372ba9be802"} {"nl": {"description": "Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.The park consists of n squares connected with (n\u2009-\u20091) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct.Andryusha wants to use as little different colors as possible. Help him to choose the colors!", "input_spec": "The first line contains single integer n (3\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the number of squares in the park. Each of the next (n\u2009-\u20091) lines contains two integers x and y (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n)\u00a0\u2014 the indices of two squares directly connected by a path. It is guaranteed that any square is reachable from any other using the paths.", "output_spec": "In the first line print single integer k\u00a0\u2014 the minimum number of colors Andryusha has to use. In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k.", "sample_inputs": ["3\n2 3\n1 3", "5\n2 3\n5 3\n4 3\n1 3", "5\n2 1\n3 2\n4 3\n5 4"], "sample_outputs": ["3\n1 3 2", "5\n1 3 2 5 4", "3\n1 2 3 1 2"], "notes": "NoteIn the first sample the park consists of three squares: 1\u2009\u2192\u20093\u2009\u2192\u20092. Thus, the balloon colors have to be distinct. Illustration for the first sample. In the second example there are following triples of consequently connected squares: 1\u2009\u2192\u20093\u2009\u2192\u20092 1\u2009\u2192\u20093\u2009\u2192\u20094 1\u2009\u2192\u20093\u2009\u2192\u20095 2\u2009\u2192\u20093\u2009\u2192\u20094 2\u2009\u2192\u20093\u2009\u2192\u20095 4\u2009\u2192\u20093\u2009\u2192\u20095 We can see that each pair of squares is encountered in some triple, so all colors have to be distinct. Illustration for the second sample. In the third example there are following triples: 1\u2009\u2192\u20092\u2009\u2192\u20093 2\u2009\u2192\u20093\u2009\u2192\u20094 3\u2009\u2192\u20094\u2009\u2192\u20095 We can see that one or two colors is not enough, but there is an answer that uses three colors only. Illustration for the third sample. "}, "positive_code": [{"source_code": "let color_tree n g =\n let colors = Array.make (n+1) 0 in\n let k_max = ref 1 in\n let rec dfs v p =\n let parent_c = colors.(p) in\n let self_c = colors.(v) in\n let children = List.filter (fun x -> x != p) g.(v) in\n let k = ref 0 in\n List.iter (fun child ->\n incr k;\n while !k = parent_c || !k = self_c do incr k done;\n colors.(child) <- !k;\n dfs child v\n ) children;\n k_max := max !k_max !k\n in\n colors.(1) <- 1;\n dfs 1 0;\n (!k_max, colors)\n\nlet () =\n let n = Scanf.scanf \"%d\" (fun x -> x) in\n let out = Array.make (n + 1) [] in\n for i = 2 to n do\n let (a, b) = Scanf.scanf \" %d %d\" (fun x y -> (x, y)) in\n out.(a) <- b :: out.(a);\n out.(b) <- a :: out.(b)\n done;\n let (k, colors) = color_tree n out in\n Printf.printf \"%d\\n%d\" k colors.(1);\n for i = 2 to n do\n Printf.printf \" %d\" colors.(i)\n done;\n Printf.printf \"\\n\"\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x-1,y-1))\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n \nlet () = \n let n = read_int () in\n\n let tree = Array.make n [] in\n\n let add_edge (i,j) =\n tree.(i) <- j::tree.(i);\n tree.(j) <- i::tree.(j)\n in\n\n for i=1 to n-1 do add_edge (read_pair ()) done;\n\n let color = Array.make n 0 in\n\n let nextcolor trycolor p v =\n let pcolor = if p < 0 then 0 else color.(p) in\n let vcolor = if v < 0 then 0 else color.(v) in\n if trycolor <> pcolor && trycolor <> vcolor then trycolor\n else\n let trycolor = trycolor + 1 in\n if trycolor <> pcolor && trycolor <> vcolor then trycolor\n else trycolor + 1\n in\n\n let rec dfs p v =\n let _ = List.fold_left (fun trycolor w -> if w = p then trycolor else (\n color.(w) <- nextcolor trycolor p v;\n dfs v w;\n color.(w) + 1\n )\n ) 1 tree.(v)\n in ()\n in\n\n color.(0) <- 1;\n dfs (-1) 0;\n \n let mcolor = maxf 0 (n-1) (fun i -> color.(i)) in\n\n printf \"%d\\n\" mcolor;\n\n for i=0 to n-1 do\n printf \"%d \" color.(i)\n done;\n\n print_newline()\n"}], "negative_code": [{"source_code": "let color_tree n g =\n let colors = Array.make (n+1) 0 in\n let k_max = ref 1 in\n let rec dfs v p =\n let parent_c = colors.(p) in\n let self_c = colors.(v) in\n let children = List.filter (fun x -> x != p) g.(v) in\n let k = ref 0 in\n List.iter (fun child ->\n incr k;\n if !k = parent_c then incr k;\n if !k = self_c then incr k;\n colors.(child) <- !k;\n dfs child v\n ) children;\n k_max := max !k_max !k\n in\n colors.(1) <- 1;\n dfs 1 0;\n (!k_max, colors)\n\nlet () =\n let n = Scanf.scanf \"%d\" (fun x -> x) in\n let out = Array.make (n + 1) [] in\n for i = 2 to n do\n let (a, b) = Scanf.scanf \" %d %d\" (fun x y -> (x, y)) in\n out.(a) <- b :: out.(a);\n out.(b) <- a :: out.(b)\n done;\n let (k, colors) = color_tree n out in\n Printf.printf \"%d\\n%d\" k colors.(1);\n for i = 2 to n do\n Printf.printf \" %d\" colors.(i)\n done;\n Printf.printf \"\\n\"\n \n"}], "src_uid": "2aaa31d52d69ff3703f93177b25671a3"} {"nl": {"description": "This problem is interactive.We have hidden an array $$$a$$$ of $$$n$$$ pairwise different numbers (this means that no two numbers are equal). You can get some information about this array using a new device you just ordered on Amazon. This device can answer queries of the following form: in response to the positions of $$$k$$$ different elements of the array, it will return the position and value of the $$$m$$$-th among them in the ascending order.Unfortunately, the instruction for the device was lost during delivery. However, you remember $$$k$$$, but don't remember $$$m$$$. Your task is to find $$$m$$$ using queries to this device. You can ask not more than $$$n$$$ queries.Note that the array $$$a$$$ and number $$$m$$$ are fixed before the start of the interaction and don't depend on your queries. In other words, interactor is not adaptive.Note that you don't have to minimize the number of queries, and you don't need to guess array $$$a$$$. You just have to guess $$$m$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1\\le k < n \\le 500$$$)\u00a0\u2014 the length of the array and the number of the elements in the query. It is guaranteed that number $$$m$$$ satisfies $$$1\\le m \\le k$$$, elements $$$a_1, a_2, \\dots, a_n$$$ of the array satisfy $$$0\\le a_i \\le 10^9$$$, and all of them are different.", "output_spec": null, "sample_inputs": ["4 3\n4 9\n4 9\n4 9\n1 2"], "sample_outputs": ["? 2 3 4\n? 1 3 4\n? 1 2 4\n? 1 2 3\n! 3"], "notes": "NoteIn the example, $$$n = 4$$$, $$$k = 3$$$, $$$m = 3$$$, $$$a = [2, 0, 1, 9]$$$."}, "positive_code": [{"source_code": "open Printf\nopen String\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \n\nlet split_string s = \n let s = trim s in\n \n let n = String.length s in\n let li = fold 0 (n-1) \n (fun i ac -> if s.[i] = ' ' then i::ac else ac) []\n in\n\n let rec chop prev li ac = \n match li with [] -> List.rev ac\n | i::tail -> \n\tchop i tail ((sub s (prev+1) (i-prev-1))::ac)\n in\n \n chop (-1) (List.rev (n::li)) []\n\nlet read_two () =\n let c = split_string (read_line()) in\n let n = int_of_string(List.nth c 0) in\n let k = int_of_string(List.nth c 1) in\n (n,k)\n\nlet () =\n let (n,k) = read_two() in\n\n let query i =\n (* leave a hole at position i *)\n printf \"?\";\n for j=1 to k+1 do\n if j <> i then printf \" %d\" j\n done;\n printf \"\\n%!\";\n read_two()\n in\n\n let mth = Array.make (k+2) 0 in\n\n for i=1 to k+1 do\n let (_,b) = query i in\n mth.(i) <- b\n done;\n\n(* let mmin = minf 1 (k+1) (fun i -> mth.(i)) in *)\n let mmax = maxf 1 (k+1) (fun i -> mth.(i)) in\n\n let nmaxes = sum 1 (k+1) (fun i -> if mmax = mth.(i) then 1 else 0) in\n\n printf \"! %d\\n%!\" nmaxes\n"}], "negative_code": [{"source_code": "open Printf\nopen String\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet split_string s = \n let s = trim s in\n \n let n = String.length s in\n let li = fold 0 (n-1) \n (fun i ac -> if s.[i] = ' ' then i::ac else ac) []\n in\n\n let rec chop prev li ac = \n match li with [] -> List.rev ac\n | i::tail -> \n\tchop i tail ((sub s (prev+1) (i-prev-1))::ac)\n in\n \n chop (-1) (List.rev (n::li)) []\n\nlet read_two () =\n let c = split_string (read_line()) in\n let n = int_of_string(List.nth c 0) in\n let k = int_of_string(List.nth c 1) in\n (n,k)\n\nlet () =\n let (n,k) = read_two() in\n\n let query i =\n (* leave a hole at position i *)\n printf \"?\";\n for j=1 to k+1 do\n if j <> i then printf \" %d\" j\n done;\n printf \"\\n%!\";\n read_two()\n in\n\n let rec find_change i prev_pos =\n let (pos,_) = query i in\n if pos <> prev_pos then i-1 else find_change (i+1) prev_pos\n in\n\n let m = find_change 2 (fst (query 1)) in\n\n printf \"! %d\\n%!\" m\n"}], "src_uid": "712bef1b0f737cb9c2b35a96498d50bc"} {"nl": {"description": "The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: Operation ++ increases the value of variable x by 1. Operation -- decreases the value of variable x by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters \"+\", \"-\", \"X\". Executing a statement means applying the operation it contains.A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009150) \u2014 the number of statements in the programme. Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter \u00abX\u00bb). Thus, there are no empty statements. The operation and the variable can be written in any order.", "output_spec": "Print a single integer \u2014 the final value of x.", "sample_inputs": ["1\n++X", "2\nX++\n--X"], "sample_outputs": ["1", "0"], "notes": null}, "positive_code": [{"source_code": "open Printf;;\nopen Scanf;;\nlet n=read_int();;\n\nlet rec solve n x =\n if n=0 then x\n else\n let s=read_line() in\n if ((s=\"X++\") || (s=\"++X\")) then (solve (n-1) (x+1)) else (solve (n-1) (x-1))\n;;\t\t\t\t\t\t\t\t \n \n \nprintf \"%d\\n\" (solve n 0);;\n\t\n\t\t \n\t\t\t\t \n\t \n\t \n \n \n"}, {"source_code": "open Printf;;\nopen Scanf;;\nopen List;;\nlet rec initlist n = if (n=0) then [] else 0::(initlist (n-1)) ;;\n\t\t\t \n\t\t\tlet n=read_int();; \n\t\t\tlet r=map (fun x -> read_line()) (initlist n);;\n\t\t\tlet ans=fold_left (fun x y -> if ((y=\"X++\") || (y=\"++X\")) then x+1 else x-1) 0 r;;\n\t\t\t printf \"%d\\n\" ans;;\n\t\t\t \n\t\t\t \n\t\t\t \n\t\t\t \n\t\t\t \n\t\t\t \n\t\t\t \n"}, {"source_code": "let number_of_operations = Scanf.scanf \"%d \" (fun n -> n)\n\nlet execute s x = match s with\n |\"X++\" | \"++X\" -> x + 1\n |_ -> x - 1\n\nlet rec solve n x =\n if n > 0\n then \n let bit_function = Scanf.scanf \"%s \" (fun s -> s) in\n solve (n - 1) (execute bit_function x)\n else\n Printf.printf \"%d\\n\" x\n\nlet () = solve number_of_operations 0"}, {"source_code": "let () =\n let n = Scanf.scanf \"%d \" (fun a -> a) in\n let a_lst = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf \"%s \" (fun a -> a)) in\n let l = List.map (fun x -> String.sub x 1 1) a_lst in\n\n let p = List.filter (fun x -> x = \"+\") l |>\n List.length in\n let m = n-p in\n Printf.printf \"%d\\n\" @@ p-m\n"}, {"source_code": "let rec solve (n : int) (ak : int) =\n if n = 0 then\n ak\n else\n let op = read_line () in\n match op with\n | \"X++\" -> solve (n - 1) (ak + 1)\n | \"++X\" -> solve (n - 1) (ak + 1)\n | \"X--\" -> solve (n - 1) (ak - 1)\n | \"--X\" -> solve (n - 1) (ak - 1)\n | _ -> raise (Failure \"Unsupported Operation\")\n\n\nlet () =\n let n = read_int () in\n Printf.printf \"%d\" (solve n 0)\n"}, {"source_code": "let n=Scanf.scanf \"%d\" (fun a->a);;\nlet x=ref 0;;\nfor i=1 to n do\n x:=!x+(Scanf.scanf \" %s\" (fun a-> if (String.contains a '+')==true then 1 else -1))\ndone;;\nprint_int(!x);;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> let res = read_line () in\n res :: read_lines (n - 1)\n\nlet () =\n let num = read_int() in\n let res = read_lines num in\n List.fold_left (fun num str ->\n if String.contains str '-'\n then\n num - 1\n else\n num + 1\n ) 0 res\n |> Printf.printf \"%d\"\n;;\n"}, {"source_code": "let read_int () = Scanf.scanf \"%d \" (fun x -> x);;\nlet read_int3 () = Scanf.scanf \" %d %d %d \" (fun x y z -> (x,y,z) );;\n\nlet inc_or_dec = function\n | \"X++\" -> 1\n | \"++X\" -> 1\n | \"--X\" -> -1\n | \"X--\" -> -1\n;;\n\n\nlet read_s () = Scanf.scanf \"%s \" (fun x -> inc_or_dec x );;\n\nlet n = read_int ();;\n\nlet a = Array.init n (fun i -> (read_s () ));;\n\n\nlet b = Array.fold_left (+) 0 a in print_int b; print_endline \"\"\n"}, {"source_code": "let read_int () = Scanf.scanf \"%d \" (fun x -> x);;\nlet read_int3 () = Scanf.scanf \" %d %d %d \" (fun x y z -> (x,y,z) );;\n\nlet inc_or_dec = function\n | \"X++\" -> 1\n | \"++X\" -> 1\n | _ -> -1\n;;\n\n\nlet read_s () = Scanf.scanf \"%s \" (fun x -> inc_or_dec x );;\n\nlet n = read_int ();;\n\nlet a = Array.init n (fun i -> (read_s () ));;\n\n\nlet b = Array.fold_left (+) 0 a in print_int b; print_endline \"\"\n"}, {"source_code": "let read_int () = Scanf.scanf \"%d\" (fun x -> x)\nlet read_string () = Scanf.scanf \" %s\" (fun x -> x)\n\nlet get_bit n =\n let rec calculate_bit r = function\n | 0 -> r\n | n -> match read_string () with\n | \"X++\" | \"++X\" -> calculate_bit (r + 1) (n - 1)\n | \"X--\" | \"--X\" -> calculate_bit (r - 1) (n - 1)\n | q -> Printf.printf \"%s\\n\" q; assert false\n in calculate_bit 0 n\n\n\nlet () = Printf.printf \"%d\\n\" (get_bit (read_int ()))\n"}, {"source_code": "let pf = Printf.printf;;\nlet sf = Scanf.scanf;;\n\nlet (|>) x f = f x;;\nlet (@@) f x = f x;;\nlet read0() = sf \"%d \" (fun x -> x)\nlet read1() = sf \"%d\\n\" (fun x -> x)\nlet read2() = sf \"%d %d\\n\" (fun x y -> x, y)\nlet read3() = sf \"%d %d %d\\n\" (fun x y z -> x, y, z)\n\nexception Error of string\n\nlet inf = 1000000000;;\nlet eps = 1e-11;;\n\nlet _ =\n let n = int_of_string @@ read_line() in\n let res = ref 0 in\n for i = 1 to n do\n let s = read_line() in\n res := !res + if s.[1] == '+' then 1 else -1\n done;\n pf \"%d\\n\" !res\n;;\n"}, {"source_code": "open Printf\n\n\nlet read_ints() =\n\tArray.map (int_of_string) (Array.of_list (Str.split (Str.regexp \" +\") (read_line())))\n\n\nlet main =\n let n = read_int() in\n let ans = ref 0 in\n for i = 1 to n do\n let ins = read_line() in\n if ins.[1] = '+' then\n ans := !ans + 1\n else\n ans := !ans - 1\n done;\n printf \"%d\\n\" !ans\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let x = ref 0 in\n for i=1 to n do\n let s = read_string() in\n\tif s=\"++X\" || s=\"X++\" then x := !x+1\n\telse if s=\"--X\" || s=\"X--\" then x := !x-1\n\telse failwith \"bad statement\"\n done;\n Printf.printf \"%d\\n\" !x\n"}], "negative_code": [], "src_uid": "f3cf7726739290b280230b562cac7a74"} {"nl": {"description": "Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the i-th student wants to get ci 'passes' in his subjects (regardless of the volume of his work).Bugs, like students, are not the same: every bug is characterized by complexity aj, and every student has the level of his abilities bi. Student i can fix a bug j only if the level of his abilities is not less than the complexity of the bug: bi\u2009\u2265\u2009aj, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously.The university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than s passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug.", "input_spec": "The first line contains three space-separated integers: n, m and s (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105, 0\u2009\u2264\u2009s\u2009\u2264\u2009109)\u00a0\u2014 the number of students, the number of bugs in the system and the maximum number of passes the university is ready to give the students. The next line contains m space-separated integers a1, a2,\u00a0..., am (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the bugs' complexities. The next line contains n space-separated integers b1, b2,\u00a0..., bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009109)\u00a0\u2014 the levels of the students' abilities. The next line contains n space-separated integers c1, c2,\u00a0..., cn (0\u2009\u2264\u2009ci\u2009\u2264\u2009109)\u00a0\u2014 the numbers of the passes the students want to get for their help.", "output_spec": "If the university can't correct all bugs print \"NO\". Otherwise, on the first line print \"YES\", and on the next line print m space-separated integers: the i-th of these numbers should equal the number of the student who corrects the i-th bug in the optimal answer. The bugs should be corrected as quickly as possible (you must spend the minimum number of days), and the total given passes mustn't exceed s. If there are multiple optimal answers, you can output any of them.", "sample_inputs": ["3 4 9\n1 3 1 2\n2 1 3\n4 3 6", "3 4 10\n2 3 1 2\n2 1 3\n4 3 6", "3 4 9\n2 3 1 2\n2 1 3\n4 3 6", "3 4 5\n1 3 1 2\n2 1 3\n5 3 6"], "sample_outputs": ["YES\n2 3 2 3", "YES\n1 3 1 3", "YES\n3 3 2 3", "NO"], "notes": "NoteConsider the first sample.The third student (with level 3) must fix the 2nd and 4th bugs (complexities 3 and 2 correspondingly) and the second student (with level 1) must fix the 1st and 3rd bugs (their complexity also equals 1). Fixing each bug takes one day for each student, so it takes 2 days to fix all bugs (the students can work in parallel).The second student wants 3 passes for his assistance, the third student wants 6 passes. It meets the university's capabilities as it is ready to give at most 9 passes."}, "positive_code": [{"source_code": "(* It's a binary search for the minimum number of days, and for a\n given number of days, it's a greedy algorithm to determine if it's\n possible.\n\n We work through the bugs from hardest to easiest. At any point in\n time we maintain a priority queue of all the students who are\n capable of fixing the given bug. The priority is the number of\n credits needed to make use of the given student. It's zero if\n we've already used this student (and paid for his credits).\n A student is removed from the queue when he has been used for\n the bound on the number of days. This forces the algorithm to\n use some other student, and stay within the day bound.\n*)\n\nopen Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let s = read_int () in\n let a = Array.init m (fun _ -> read_int()) in (*bug values*)\n let b = Array.init n (fun _ -> read_int()) in (*student values*)\n let c = Array.init n (fun _ -> read_int()) in (*student costs*)\n\n let perma = Array.init m (fun i -> i) in\n let permb = Array.init n (fun i -> i) in\n \n Array.sort (fun i j -> compare a.(i) a.(j)) perma;\n Array.sort (fun i j -> compare b.(i) b.(j)) permb;\n\n let a' = Array.init m (fun j -> a.(perma.(j))) in\n let b' = Array.init n (fun i -> b.(permb.(i))) in\n \n let use = Array.make n 0 in (* how much student i has been used *)\n let fixer = Array.make m 0 in (* which student fixed this bug *)\n\n let possible days = (* return true if its possible to do it in days or fewer *)\n Array.fill use 0 n 0;\n let rec scan queue i j cred = if j=0 then true else (\n (* j is previous bug, i is previous student (the weakest who can solve bug j) *)\n\n let j = j-1 in\n let rec go_back (i,queue) =\n\tif i-1<0 || b'.(i-1) < a'.(j) then (i,queue) else\n\t go_back (i-1, Pset.add (c.(permb.(i-1)), i-1) queue)\n in\n \n let (i, queue) = go_back (i, queue) in\n\n if Pset.is_empty queue then false else\n\tlet (c0,ii) = Pset.min_elt queue in\n\t (* now we know bug j is solved by student ii *)\n\tlet cred = cred - c0 in\n\tif cred<0 then false else (\n\t use.(ii) <- use.(ii) + 1;\n\t fixer.(perma.(j)) <- permb.(ii);\n\n\t let queue = \n\t if use.(ii) = days then Pset.remove (c0,ii) queue\n\t else if c0 = 0 then queue else Pset.add (0,ii) (Pset.remove (c0,ii) queue)\n\t in\n\t \n(*\n (* This is equivalent but does more unnecessary inserts and deletes *)\n\t let queue = Pset.remove (c0,ii) queue in\n\t let queue = if use.(ii) < days then Pset.add (0,ii) queue else queue in\n*)\n\t scan queue i j cred\n\t)\n )\n in\n let startqueue = Pset.singleton (c.(permb.(n-1)), n-1) in\n scan startqueue (n-1) m s\n in\n\n if a'.(m-1) > b'.(n-1) || (not (possible m)) then printf \"NO\\n\" else\n let rec crude_upper_bound d =\n if possible d then d else crude_upper_bound (8*d)\n in\n\n let cub = crude_upper_bound 1 in\n\n let answer = \n if cub=1 then 1 else \n\tlet rec bsearch lo hi =\n\t if lo+1 = hi then hi else\n\t let m = (lo + hi)/2 in\n\t if possible m then bsearch lo m else bsearch m hi\n\tin\n\tbsearch (cub/8) cub\n in\n \n ignore (possible answer);\n \n printf \"YES\\n\";\n\n for j=0 to m-1 do\n if j>0 then printf \" \";\n printf \"%d\" (fixer.(j)+1);\n done;\n print_newline();\n"}], "negative_code": [{"source_code": "(* It's a binary search for the minimum number of days, and for a\n given number of days, it's a greedy algorithm to determine if it's\n possible.\n\n We work through the bugs from hardest to easiest. At any point in\n time we maintain a priority queue of all the students who are\n capable of fixing the given bug. The priority is the number of\n credits needed to make use of the given student. It's zero if\n we've already used this student (and paid for his credits).\n A student is removed from the queue when he has been used for\n the bound on the number of days. This forces the algorithm to\n use some other student, and stay within the day bound.\n*)\n\nopen Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let s = read_int () in\n let a = Array.init m (fun _ -> read_int()) in (*bug values*)\n let b = Array.init n (fun _ -> read_int()) in (*student values*)\n let c = Array.init n (fun _ -> read_int()) in (*student costs*)\n\n let perma = Array.init m (fun i -> i) in\n let permb = Array.init n (fun i -> i) in\n \n Array.stable_sort (fun i j -> compare a.(i) a.(j)) perma;\n Array.stable_sort (fun i j -> compare b.(i) b.(j)) permb;\n\n let a' = Array.init m (fun j -> a.(perma.(j))) in\n let b' = Array.init n (fun i -> b.(permb.(i))) in\n \n let use = Array.make n 0 in (* how much student i has been used *)\n let fixer = Array.make m 0 in (* which student fixed this bug *)\n\n let possible days = (* return true if its possible to do it in days or fewer *)\n Array.fill use 0 n 0;\n let rec scan queue i j cred = if j=0 then true else (\n (* j is previous bug, i is previous student (the weakest who can solve bug j) *)\n\n let j = j-1 in\n let rec go_back (i,queue) =\n\tif i-1<0 || b'.(i-1) < a'.(j) then (i,queue) else\n\t go_back (i-1, Pset.add (c.(permb.(i-1)), i-1) queue)\n in\n \n let (i, queue) = go_back (i, queue) in\n\n if Pset.is_empty queue then false else\n\tlet (c0,ii) = Pset.min_elt queue in\n\t (* now we know bug j is solved by student ii *)\n\tlet cred = cred - c0 in\n\tif cred<0 then false else (\n\t use.(ii) <- use.(ii) + 1;\n\t fixer.(perma.(j)) <- permb.(ii);\n\n\t let queue = \n\t if use.(ii) = days then Pset.remove (c0,ii) queue\n\t else if c0 = 0 then queue else Pset.add (0,ii) (Pset.remove (c0,ii) queue)\n\t in\n\t \n(*\n (* This is equivalent but does more unnecessary inserts and deletes *)\n\t let queue = Pset.remove (c0,ii) queue in\n\t let queue = if use.(ii) < days then Pset.add (0,ii) queue else queue in\n*)\n\t scan queue i j cred\n\t)\n )\n in\n let startqueue = Pset.singleton (c.(permb.(n-1)),permb.(n-1)) in\n scan startqueue (n-1) m s\n in\n\n if a'.(m-1) > b'.(n-1) || (not (possible m)) then printf \"NO\\n\" else\n let rec crude_upper_bound d =\n if possible d then d else crude_upper_bound (2*d)\n in\n\n let cub = crude_upper_bound 1 in\n\n let answer = \n if cub = 1 then 1 else\n\tlet rec bsearch lo hi =\n\t if lo+1 = hi then hi else\n\t let m = (lo + hi)/2 in\n\t if possible m then bsearch lo m else bsearch m hi\n\tin\n\tbsearch (cub/2) cub\n in\n \n ignore (possible answer);\n \n printf \"YES\\n\";\n\n for j=0 to m-1 do\n if j>0 then printf \" \";\n printf \"%d\" (fixer.(j)+1);\n if b.(fixer.(j)) < a.(j) then printf \" ERROR \"\n done;\n print_newline();\n"}, {"source_code": "(* It's a binary search for the minimum number of days, and for a\n given number of days, it's a greedy algorithm to determine if it's\n possible.\n\n We work through the bugs from hardest to easiest. At any point in\n time we maintain a priority queue of all the students who are\n capable of fixing the given bug. The priority is the number of\n credits needed to make use of the given student. It's zero if\n we've already used this student (and paid for his credits).\n A student is removed from the queue when he has been used for\n the bound on the number of days. This forces the algorithm to\n use some other student, and stay within the day bound.\n*)\n\nopen Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let s = read_int () in\n let a = Array.init m (fun _ -> read_int()) in (*bug values*)\n let b = Array.init n (fun _ -> read_int()) in (*student values*)\n let c = Array.init n (fun _ -> read_int()) in (*student costs*)\n\n let perma = Array.init m (fun i -> i) in\n let permb = Array.init n (fun i -> i) in\n \n Array.sort (fun i j -> compare a.(i) a.(j)) perma;\n Array.sort (fun i j -> compare b.(i) b.(j)) permb;\n\n let a' = Array.init m (fun j -> a.(perma.(j))) in\n let b' = Array.init n (fun i -> b.(permb.(i))) in\n \n let use = Array.make n 0 in (* how much student i has been used *)\n let fixer = Array.make m 0 in (* which student fixed this bug *)\n\n let possible days = (* return true if its possible to do it in days or fewer *)\n Array.fill use 0 n 0;\n let rec scan queue i j cred = if j=0 then true else (\n (* j is previous bug, i is previous student (the weakest who can solve bug j) *)\n\n let j = j-1 in\n let rec go_back (i,queue) =\n\tif i-1<0 || b'.(i-1) < a'.(j) then (i,queue) else\n\t go_back (i-1, Pset.add (c.(permb.(i-1)), i-1) queue)\n in\n \n let (i, queue) = go_back (i, queue) in\n\n if Pset.is_empty queue then false else\n\tlet (c0,ii) = Pset.min_elt queue in\n\t (* now we know bug j is solved by student ii *)\n\tlet cred = cred - c0 in\n\tif cred<0 then false else (\n\t use.(ii) <- use.(ii) + 1;\n\t fixer.(perma.(j)) <- permb.(ii);\n\t let queue = Pset.remove (c0,ii) queue in\n\t let queue = if use.(ii) < days then Pset.add (0,ii) queue else queue in\n\t scan queue i j cred\n\t)\n )\n in\n let startqueue = Pset.singleton (c.(permb.(n-1)),permb.(n-1)) in\n scan startqueue (n-1) m s\n in\n\n if a'.(m-1) > b'.(n-1) || (not (possible m)) then printf \"NO\\n\" else\n let rec crude_upper_bound d =\n if possible d then d else crude_upper_bound (2*d)\n in\n\n let cub = crude_upper_bound 1 in\n\n let answer = \n if cub = 1 then 1 else\n\tlet rec bsearch lo hi =\n\t if lo+1 = hi then hi else\n\t let m = (lo + hi)/2 in\n\t if possible m then bsearch lo m else bsearch m hi\n\tin\n\tbsearch (cub/2) cub\n in\n \n ignore (possible answer);\n \n printf \"YES\\n\";\n\n for j=0 to m-1 do\n if j>0 then printf \" \";\n printf \"%d\" (fixer.(j)+1)\n done;\n print_newline();\n"}], "src_uid": "85453ab4eb82b894ef8941c70c6d713c"} {"nl": {"description": "Anton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1,\u2009a2,\u2009...,\u2009an}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i,\u2009j) such that 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n and ai\u2009>\u2009aj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1,\u20092,\u2009...,\u2009n}, that is ai\u2009=\u2009i for all i such that 1\u2009\u2264\u2009i\u2009\u2264\u2009n.", "input_spec": "The first line of the input contains two integers n and q (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000,\u20091\u2009\u2264\u2009q\u2009\u2264\u200950\u2009000)\u00a0\u2014 the length of the permutation and the number of operations that Anton does. Each of the following q lines of the input contains two integers li and ri (1\u2009\u2264\u2009li,\u2009ri\u2009\u2264\u2009n)\u00a0\u2014 the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.", "output_spec": "Output q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.", "sample_inputs": ["5 4\n4 5\n2 4\n2 5\n2 2", "2 1\n2 1", "6 7\n1 4\n3 5\n2 3\n3 3\n3 6\n2 1\n5 1"], "sample_outputs": ["1\n4\n3\n3", "1", "5\n6\n7\n7\n10\n11\n8"], "notes": "NoteConsider the first sample.After the first Anton's operation the permutation will be {1,\u20092,\u20093,\u20095,\u20094}. There is only one inversion in it: (4,\u20095).After the second Anton's operation the permutation will be {1,\u20095,\u20093,\u20092,\u20094}. There are four inversions: (2,\u20093), (2,\u20094), (2,\u20095) and (3,\u20094).After the third Anton's operation the permutation will be {1,\u20094,\u20093,\u20092,\u20095}. There are three inversions: (2,\u20093), (2,\u20094) and (3,\u20094).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions."}, "positive_code": [{"source_code": "(* O(n log n + q sqrt(n) + q log(n)) *)\n\nopen Printf\nopen Scanf\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet superceil n =\n let rec loop i = if i>=n then i else loop (2*i) in\n loop 1\n\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\n\nlet ceil a b = (a+b-1) / b (* ceiling of a/b *)\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n \nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,q) = read_pair () in\n\n let perm = Array.init n (fun i -> i) in\n let iperm = Array.copy perm in\n\n let swap i j =\n let (pi,pj) = (perm.(i), perm.(j)) in\n perm.(i) <- pj;\n perm.(j) <- pi;\n let (ipi,ipj) = (iperm.(pi),iperm.(pj)) in\n iperm.(pi) <- ipj;\n iperm.(pj) <- ipi\n in\n\n let sn = int_of_float (sqrt (float n)) in\n let rec find_level l size = if size > n then l else find_level (l+1) (2*size) in\n let levels = find_level 0 sn in\n\n let rec make_boxes i size ac = if i=levels then List.rev ac else\n let nboxes = ceil n size in\n make_boxes (i+1) (2*size) ((Array.make_matrix nboxes nboxes 0) :: ac)\n in\n\n let blist = make_boxes 0 sn [] in\n \n let adjust_counts (x,y) delta =\n let rec loop bsize bl =\n match bl with [] -> ()\n\t| box_array::tail ->\n\t let (x',y') = (x/bsize, y/bsize) in\n\t box_array.(x').(y') <- delta + box_array.(x').(y');\n\t loop (bsize * 2) tail\n in\n loop sn blist\n in\n\n for i=0 to n-1 do\n adjust_counts (i, perm.(i)) 1\n done;\n\n let count_smaller x y =\n let (xbase,ybase) = (sn * (x/sn), sn * (y/sn)) in\n let top_bar = sum ybase (y-1) (fun y -> if iperm.(y) < x then 1 else 0) in\n let side_bar = sum xbase (x-1) (fun x -> if perm.(x) < ybase then 1 else 0) in\n fst (List.fold_left (fun (ac, size) box_array ->\n let (xmult, ymult) = (x/size, y/size) in\n let right_col_sum = if xmult mod 2 = 0 then 0 else\n\t sum 0 (ymult-1) (fun y -> box_array.(xmult-1).(y))\n in\n let top_row_sum = if ymult mod 2 = 0 then 0 else\n\t sum 0 (xmult-1) (fun x -> box_array.(x).(ymult-1))\n in \n let adjust = if ymult mod 2 = 1 && xmult mod 2 = 1 then\n\t box_array.(xmult-1).(ymult-1) else 0\n in\n let ac = ac + top_row_sum + right_col_sum - adjust in\n (ac, 2*size)\n ) (top_bar + side_bar, sn) blist\n )\n in \n \n ignore (fold 1 q (fun _ inversions ->\n let (l,r) = read_pair() in\n if l = r then (\n printf \"%Ld\\n\" inversions;\n inversions\n ) else (\n let (l,r) = (-1 + min l r, -1 + max l r) in\n let (x1,y1) = (l, min perm.(l) perm.(r)) in\n let (x2,y2) = (r, max perm.(l) perm.(r)) in\n let c =\n\t(count_smaller x2 y2) - (count_smaller (x1+1) y2)\n\t-(count_smaller x2 (y1+1)) + (count_smaller (x1+1) (y1+1))\n in\n let delta = if perm.(l) < perm.(r) then 2*c + 1 else -2*c-1 in\n adjust_counts (l, perm.(l)) (-1);\n adjust_counts (r, perm.(r)) (-1);\n adjust_counts (l, perm.(r)) 1;\n adjust_counts (r, perm.(l)) 1; \n swap l r;\n printf \"%Ld\\n\" (inversions ++ (long delta));\n inversions ++ (long delta)\n )\n ) 0L\n )\n"}], "negative_code": [], "src_uid": "ed9375dfd4749173472c0c18814c2855"} {"nl": {"description": "You are given an array consisting of $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ and an integer $$$x$$$. It is guaranteed that for every $$$i$$$, $$$1 \\le a_i \\le x$$$.Let's denote a function $$$f(l, r)$$$ which erases all values such that $$$l \\le a_i \\le r$$$ from the array $$$a$$$ and returns the resulting array. For example, if $$$a = [4, 1, 1, 4, 5, 2, 4, 3]$$$, then $$$f(2, 4) = [1, 1, 5]$$$.Your task is to calculate the number of pairs $$$(l, r)$$$ such that $$$1 \\le l \\le r \\le x$$$ and $$$f(l, r)$$$ is sorted in non-descending order. Note that the empty array is also considered sorted.", "input_spec": "The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n, x \\le 10^6$$$) \u2014 the length of array $$$a$$$ and the upper limit for its elements, respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots a_n$$$ ($$$1 \\le a_i \\le x$$$).", "output_spec": "Print the number of pairs $$$1 \\le l \\le r \\le x$$$ such that $$$f(l, r)$$$ is sorted in non-descending order.", "sample_inputs": ["3 3\n2 3 1", "7 4\n1 3 1 2 2 4 3"], "sample_outputs": ["4", "6"], "notes": "NoteIn the first test case correct pairs are $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$ and $$$(2, 3)$$$.In the second test case correct pairs are $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(2, 3)$$$, $$$(2, 4)$$$, $$$(3, 3)$$$ and $$$(3, 4)$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let x = read_int () in \n let a = Array.init n read_int in\n\n let inf = int_of_float (1e8) in\n let minia = Array.make (x+1) (inf) in\n let maxia = Array.make (x+1) (-inf) in\n\n for i=0 to n-1 do\n minia.(a.(i)) <- min i minia.(a.(i));\n maxia.(a.(i)) <- max i maxia.(a.(i));\n done;\n\n let (miniaS,maxiaS) = (Array.copy minia, Array.copy maxia) in\n\n for j=x-1 downto 1 do\n miniaS.(j) <- min miniaS.(j) miniaS.(j+1)\n done;\n\n for j=2 to x do\n maxiaS.(j) <- max maxiaS.(j) maxiaS.(j-1)\n done;\n\n let rec loopr r = if r <= 1 then 1 else (\n if maxia.(r) > miniaS.(r+1) then r else loopr (r-1)\n ) in\n let min_r = loopr (x-1) in\n\n let rec loopl l = if l >= x then x else (\n if minia.(l) < maxiaS.(l-1) then l else loopl (l+1)\n ) in\n let max_l = loopl 2 in\n\n let good l r =\n (* returns true if the interval [l,r] is good,\n meaning that the stuff < l does not cross the stuff > r *)\n l-1 < 1 || r+1 > x || maxiaS.(l-1) < miniaS.(r+1)\n in\n\n let rec walk l r ac =\n (* invariant is that l <= r. the ac does not count this r.\n first we advance l to make it as large as possible\n such that interval [l,r] is good. Then add this l to the ac. *)\n let rec walkl l =\n if l=r || l>=max_l || (not (good (l+1) r)) then l else walkl (l+1)\n in\n let l = walkl l in\n (* compute the contribution of this r to the total *)\n let ac = ac ++ (long l) in\n if r = x then ac else walk l (r+1) ac\n in\n\n \n let answer = walk 0 min_r 0L in\n printf \"%Ld\\n\" answer\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let x = read_int () in \n let a = Array.init n read_int in\n\n let push_lo_up lo x =\n match lo with\n | None -> Some x\n | Some y -> Some (max x y)\n in\n\n let push_hi_down hi x =\n match hi with\n | None -> Some x\n | Some y -> Some (min x y)\n in\n \n let rec scan i max_so_far lo hi = if i=n then (lo,hi) else (\n if max_so_far > a.(i) then (\n let lo = push_lo_up lo a.(i) in\n let hi = push_hi_down hi max_so_far in\n scan (i+1) max_so_far lo hi\n ) else (\n scan (i+1) a.(i) lo hi\n )\n ) in\n\n let answer = match scan 1 a.(0) None None with\n | (None,None) ->\n ((long x) ** (long(x+1))) // 2L\n | (Some maxlo, Some minhi) ->\n if minhi <= maxlo then (\n\t(long minhi) ** (long (x-maxlo+1))\n ) else (\n\t(long maxlo) ** (long (x-maxlo+1)) ++ (long (minhi - maxlo -1))\n )\n | _ -> failwith \"can't happen\"\n in\n\n printf \"%Ld\\n\" answer\n"}], "src_uid": "1a11a87e16cd71d1a4cb404986ece956"} {"nl": {"description": "As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: \"Which one committed the crime?\". Suspect number i answered either \"The crime was committed by suspect number ai\", or \"Suspect number ai didn't commit the crime\". Also, the suspect could say so about himself (ai\u2009=\u2009i).Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009m\u2009\u2264\u2009n) \u2014 the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either \"+ai\" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or \"-ai\" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1\u2009\u2264\u2009ai\u2009\u2264\u2009n). It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.", "output_spec": "Print n lines. Line number i should contain \"Truth\" if suspect number i has told the truth for sure. Print \"Lie\" if the suspect number i lied for sure and print \"Not defined\" if he could lie and could tell the truth, too, depending on who committed the crime.", "sample_inputs": ["1 1\n+1", "3 2\n-1\n-2\n-3", "4 1\n+2\n-3\n+4\n-1"], "sample_outputs": ["Truth", "Not defined\nNot defined\nNot defined", "Lie\nNot defined\nLie\nNot defined"], "notes": "NoteThe first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let g = Array.make n 0 in\n let ng = Array.make n 0 in\n let gs = Array.make n [] in\n let ngs = Array.make n [] in\n let t = ref 0 in\n let nt = ref 0 in\n let a = Array.make n false in\n let b = Array.make n 0 in\n let res = ref 0 in\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tb.(i) <- k;\n\tif k > 0 then (\n\t let k = k - 1 in\n\t g.(k) <- g.(k) + 1;\n\t gs.(k) <- i :: gs.(k);\n\t incr t\n\t) else (\n\t let k = -k - 1 in\n\t ng.(k) <- ng.(k) + 1;\n\t ngs.(k) <- i :: ngs.(k);\n\t incr nt\n\t)\n done;\n (*for i = 0 to n - 1 do\n ng.(k) <- ng.(k) + !t - g.(k)\n done;*)\n for i = 0 to n - 1 do\n if g.(i) + !nt - ng.(i) = m then (\n\ta.(i) <- true;\n\tincr res;\n )\n done;\n for i = 0 to n - 1 do\n (*Printf.printf \"asd %d %d\\n\" i b.(i);*)\n if b.(i) < 0 then (\n\tlet k = -b.(i) - 1 in\n\t if !res > 1 && a.(k)\n\t then Printf.printf \"Not defined\\n\"\n\t else if a.(k)\n\t then Printf.printf \"Lie\\n\"\n\t else Printf.printf \"Truth\\n\"\n ) else (\n\tlet k = b.(i) - 1 in\n\tif !res > 1 && a.(k)\n\tthen Printf.printf \"Not defined\\n\"\n\telse if a.(k)\n\tthen Printf.printf \"Truth\\n\"\n\telse Printf.printf \"Lie\\n\"\n )\n done\n"}], "negative_code": [], "src_uid": "c761bb69cf1b5a3dbe38d9f5c46e9007"} {"nl": {"description": "Automatic Bakery of Cyberland (ABC) recently bought an n\u2009\u00d7\u2009m rectangle table. To serve the diners, ABC placed seats around the table. The size of each seat is equal to a unit square, so there are 2(n\u2009+\u2009m) seats in total.ABC placed conveyor belts on each unit square on the table. There are three types of conveyor belts: \"^\", \"<\" and \">\". A \"^\" belt can bring things upwards. \"<\" can bring leftwards and \">\" can bring rightwards.Let's number the rows with 1 to n from top to bottom, the columns with 1 to m from left to right. We consider the seats above and below the top of the table are rows 0 and n\u2009+\u20091 respectively. Also we define seats to the left of the table and to the right of the table to be column 0 and m\u2009+\u20091. Due to the conveyor belts direction restriction there are currently no way for a diner sitting in the row n\u2009+\u20091 to be served.Given the initial table, there will be q events in order. There are two types of events: \"A x y\" means, a piece of bread will appear at row x and column y (we will denote such position as (x,\u2009y)). The bread will follow the conveyor belt, until arriving at a seat of a diner. It is possible that the bread gets stuck in an infinite loop. Your task is to simulate the process, and output the final position of the bread, or determine that there will be an infinite loop. \"C x y c\" means that the type of the conveyor belt at (x,\u2009y) is changed to c. Queries are performed separately meaning that even if the bread got stuck in an infinite loop, it won't affect further queries.", "input_spec": "The first line of input contains three integers n, m and q (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009m\u2009\u2264\u200910,\u20091\u2009\u2264\u2009q\u2009\u2264\u2009105), separated by a space. Next n lines, each line contains m characters, describing the table. The characters can only be one of \"<^>\". Next q lines, each line describes an event. The format is \"C x y c\" or \"A x y\" (Consecutive elements are separated by a space). It's guaranteed that 1\u2009\u2264\u2009x\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009m. c is a character from the set \"<^>\". There are at most 10000 queries of \"C\" type.", "output_spec": "For each event of type \"A\", output two integers tx, ty in a line, separated by a space, denoting the destination of (x,\u2009y) is (tx,\u2009ty). If there is an infinite loop, you should output tx\u2009=\u2009ty\u2009=\u2009\u2009-\u20091.", "sample_inputs": ["2 2 3\n>>\n^^\nA 2 1\nC 1 2 <\nA 2 1", "4 5 7\n><<^<\n^<^^>\n>>>^>\n>^>>^\nA 3 1\nA 2 2\nC 1 4 <\nA 3 1\nC 1 2 ^\nA 3 1\nA 2 2"], "sample_outputs": ["1 3\n-1 -1", "0 4\n-1 -1\n-1 -1\n0 2\n0 2"], "notes": "NoteFor the first sample:If the bread goes from (2,\u20091), it will go out of the table at (1,\u20093).After changing the conveyor belt of (1,\u20092) to \"<\", when the bread goes from (2,\u20091) again, it will get stuck at \"><\", so output is (\u2009-\u20091,\u2009\u2009-\u20091)."}, "positive_code": [{"source_code": "type node = {\n mutable id:(int*int); \n mutable l:node;\n mutable r:node;\n mutable p:node\n}\n\nlet rec null = {id=(0,0); l=null; r=null; p=null}\n\nlet isroot n =\n n.p == null || (n.p.l != n && n.p.r != n)\n\nlet update p = ()\n\nlet discharge p = ()\n\nlet rot_right p =\n let q = p.p in\n let r = q.p in\n q.l <- p.r;\n if q.l != null then q.l.p <- q;\n p.r <- q;\n q.p <- p;\n p.p <- r;\n if r != null then (\n if r.l == q then r.l <- p \n else if r.r == q then r.r <- p\n );\n update q\n\nlet rot_left p =\n let q = p.p in\n let r = q.p in\n q.r <- p.l;\n if q.r != null then q.r.p <- q;\n p.l <- q;\n q.p <- p;\n p.p <- r;\n if r != null then (\n if r.r == q then r.r <- p \n else if r.l == q then r.l <- p\n );\n update q\n\nlet splay p =\n let rec loop p = if not (isroot p) then\n let q = p.p in\n if isroot q then (\n\tdischarge q;\n\tdischarge p;\n\tif q.l == p then rot_right p else rot_left p\n ) else (\n\tlet r = q.p in\n\tdischarge r;\n\tdischarge q;\n\tdischarge p;\n\tif r.l == q then (\n\t if q.l == p then (rot_right q; rot_right p)\n\t else (rot_left p; rot_right p)\n\t) else (\n\t if q.r == p then (rot_left q; rot_left p)\n\t else (rot_right p; rot_left p)\n\t)\n );\n loop p\n in\n loop p;\n discharge p; (* useful only if p was already the root *)\n update p (* only useful if p was not already a root *)\n\nlet expose q =\n let rec loop r p = if p==null then r else (\n splay p;\n p.l <- r;\n update p;\n loop p p.p\n ) in\n \n let r = loop null q in\n splay(q);\n r (* we only use this return value in the LCA operation *)\n\nlet link p q =\n ignore(expose p);\n if p.l != null then failwith \"p's left child should be null\";\n p.p <- q\n\nlet lca a b =\n ignore(expose a);\n expose(b)\n\nlet cut a =\n ignore(expose a);\n if a.r != null then (\n a.r.p <- null;\n a.r <- null;\n update a\n )\n\nlet findroot p =\n ignore(expose p);\n let rec loop p = if p.r == null then p else loop p.r in\n let p = loop p in\n splay p;\n p\n\n(*--------------------------------------------------------------------------*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let m = read_int() in\n let q = read_int() in\n \n let board = Array.make n \"\" in\n let treenode = Array.make_matrix n m null in\n let nodetype = Array.make_matrix n m (0,0) in\n\n let on_board (i,j) = i>=0 && i=0 && j (i,j-1)\n | '>' -> (i,j+1)\n | '^' -> (i-1,j)\n | 'v' -> (i+1,j)\n\t| _ -> failwith \"bad direction\"\n in\n \n nodetype.(i).(j) <- (ii,jj);\n if on_board (ii,jj) then (\n let a = treenode.(i).(j) in (* a is already a root *)\n let b = treenode.(ii).(jj) in\n let broot = findroot b in\n \n if broot != a then ( (* not a cycle root *)\n\tnodetype.(i).(j) <- (-1,-1); (* a is no longer a root *)\n\tlink a b;\n )\n )\n in\n\n let update_board (i,j) dir = \n let a = treenode.(i).(j) in\n let b = findroot a in\n let (ii,jj) = getnodetype b.id in\n cut a;\n if on_board (ii,jj) then ( (* b is the root of a cycle tree *)\n let c = treenode.(ii).(jj) in \n if a != b && lca a c == a then link b c;\n );\n linkcell (i,j) dir\n in\n\n for i=0 to n-1 do\n board.(i) <- read_string()\n done;\n \n for i=0 to n-1 do\n for j=0 to m-1 do\n treenode.(i).(j) <- {null with id=(i,j)}\n done\n done;\n \n for i=0 to n-1 do\n for j=0 to m-1 do\n linkcell (i,j) board.(i).[j]\n done\n done;\n\n for query=0 to q-1 do\n let command = read_string() in\n let i = read_int()-1 in\n let j = read_int()-1 in\n\n match command with\n | \"A\" ->\n\tlet r = findroot treenode.(i).(j) in\n\tlet (ii,jj) = getnodetype r.id in\n\tif on_board (ii,jj)\n\tthen printf \"-1 -1\\n\"\n\telse printf \"%d %d\\n\" (ii+1) (jj+1)\n | \"C\" ->\n\tupdate_board (i,j) (read_string()).[0]\n | _ -> failwith \"unsupported command\"\n done\n"}, {"source_code": "(* An implementation of link-cut trees in ocaml *)\n\ntype node = {\n mutable id:(int*int); \n mutable l:node;\n mutable r:node;\n mutable p:node\n}\n\nlet rec null = {id=(0,0); l=null; r=null; p=null}\n\nlet isroot n =\n n.p == null || (n.p.l != n && n.p.r != n)\n\nlet update p = ()\n\nlet discharge p = ()\n\nlet rot_right p =\n let q = p.p in\n let r = q.p in\n q.l <- p.r;\n if q.l != null then q.l.p <- q;\n p.r <- q;\n q.p <- p;\n p.p <- r;\n if r != null then (\n if r.l == q then r.l <- p \n else if r.r == q then r.r <- p\n );\n update q\n\nlet rot_left p =\n let q = p.p in\n let r = q.p in\n q.r <- p.l;\n if q.r != null then q.r.p <- q;\n p.l <- q;\n q.p <- p;\n p.p <- r;\n if r != null then (\n if r.r == q then r.r <- p \n else if r.l == q then r.l <- p\n );\n update q\n\nlet splay p =\n let rec loop p = if not (isroot p) then\n let q = p.p in\n if isroot q then (\n\tdischarge q;\n\tdischarge p;\n\tif q.l == p then rot_right p else rot_left p\n ) else (\n\tlet r = q.p in\n\tdischarge r;\n\tdischarge q;\n\tdischarge p;\n\tif r.l == q then (\n\t if q.l == p then (rot_right q; rot_right p)\n\t else (rot_left p; rot_right p)\n\t) else (\n\t if q.r == p then (rot_left q; rot_left p)\n\t else (rot_right p; rot_left p)\n\t)\n );\n loop p\n in\n loop p;\n discharge p; (* useful only if p was already the root *)\n update p (* only useful if p was not already a root *)\n\nlet expose q =\n let rec loop r p = if p==null then r else (\n splay p;\n p.l <- r;\n update p;\n loop p p.p\n ) in\n \n let r = loop null q in\n splay(q);\n r (* we only use this return value in the LCA operation *)\n\nlet link p q =\n ignore(expose p);\n if p.r != null then failwith \"p's right child should be null\";\n p.p <- q\n\nlet lca a b =\n ignore(expose a);\n expose(b)\n\nlet cut a =\n ignore(expose a);\n if a.r != null then (\n a.r.p <- null;\n a.r <- null;\n update a\n )\n\nlet findroot p =\n ignore(expose p);\n let rec loop p = if p.r == null then p else loop p.r in\n let p = loop p in\n splay p;\n p\n\n(*--------------------------------------------------------------------------*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let m = read_int() in\n let q = read_int() in\n \n let board = Array.make n \"\" in\n let treenode = Array.make_matrix n m null in\n let nodetype = Array.make_matrix n m (0,0) in\n\n let on_board (i,j) = i>=0 && i=0 && j (i,j-1)\n | '>' -> (i,j+1)\n | '^' -> (i-1,j)\n | 'v' -> (i+1,j)\n\t| _ -> failwith \"bad direction\"\n in\n \n nodetype.(i).(j) <- (ii,jj);\n if on_board (ii,jj) then (\n let a = treenode.(i).(j) in (* a is already a root *)\n let b = treenode.(ii).(jj) in\n let broot = findroot b in\n \n if broot != a then ( (* not a cycle root *)\n\tnodetype.(i).(j) <- (-1,-1); (* a is no longer a root *)\n\tlink a b;\n )\n )\n in\n\n let update_board (i,j) dir = \n let a = treenode.(i).(j) in\n let b = findroot a in\n let (ii,jj) = getnodetype b.id in\n cut a;\n if on_board (ii,jj) then ( (* b is the root of a cycle tree *)\n let c = treenode.(ii).(jj) in \n if a != b && lca a c == a then link b c;\n );\n linkcell (i,j) dir\n in\n\n for i=0 to n-1 do\n board.(i) <- read_string()\n done;\n \n for i=0 to n-1 do\n for j=0 to m-1 do\n treenode.(i).(j) <- {null with id=(i,j)}\n done\n done;\n \n for i=0 to n-1 do\n for j=0 to m-1 do\n linkcell (i,j) board.(i).[j]\n done\n done;\n\n for query=0 to q-1 do\n let command = read_string() in\n let i = read_int()-1 in\n let j = read_int()-1 in\n\n match command with\n | \"A\" ->\n\tlet r = findroot treenode.(i).(j) in\n\tlet (ii,jj) = getnodetype r.id in\n\tif on_board (ii,jj)\n\tthen printf \"-1 -1\\n\"\n\telse printf \"%d %d\\n\" (ii+1) (jj+1)\n | \"C\" ->\n\tupdate_board (i,j) (read_string()).[0]\n | _ -> failwith \"unsupported command\"\n done\n"}], "negative_code": [], "src_uid": "fea879747a8fc96a3d2ce63e38443bb0"} {"nl": {"description": "Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1,\u2009a2,\u2009...,\u2009a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1\u00a0or\u00a0a2,\u2009a3\u00a0or\u00a0a4,\u2009...,\u2009a2n\u2009-\u20091\u00a0or\u00a0a2n, consisting of 2n\u2009-\u20091 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a\u2009=\u2009(1,\u20092,\u20093,\u20094). Then let's write down all the transformations (1,\u20092,\u20093,\u20094) \u2009\u2192\u2009 (1\u00a0or\u00a02\u2009=\u20093,\u20093\u00a0or\u00a04\u2009=\u20097) \u2009\u2192\u2009 (3\u00a0xor\u00a07\u2009=\u20094). The result is v\u2009=\u20094.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p,\u2009b. Query p,\u2009b means that you need to perform the assignment ap\u2009=\u2009b. After each query, you need to print the new value v for the new sequence a.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u200917,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009105). The next line contains 2n integers a1,\u2009a2,\u2009...,\u2009a2n (0\u2009\u2264\u2009ai\u2009<\u2009230). Each of the next m lines contains queries. The i-th line contains integers pi,\u2009bi (1\u2009\u2264\u2009pi\u2009\u2264\u20092n,\u20090\u2009\u2264\u2009bi\u2009<\u2009230) \u2014 the i-th query.", "output_spec": "Print m integers \u2014 the i-th integer denotes value v for sequence a after the i-th query.", "sample_inputs": ["2 4\n1 6 3 5\n1 4\n3 4\n1 2\n1 2"], "sample_outputs": ["1\n3\n3\n3"], "notes": "NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation"}, "positive_code": [{"source_code": "let n,m = Scanf.scanf \"%d %d\\n\" (fun x y->x,y);;\nlet arr = Array.make (1 lsl n) 0;;\nlet rec read_ints x =\n if x = (1 lsl n) then ()\n else begin \n arr.(x) <- Scanf.scanf \"%d \" (fun x -> x);\n read_ints (x+1);\n end in\nread_ints 0;;\n\ntype t = Leaf | Node of t * int * t;;\n\nlet oper n l r =\n if (n mod 2) = 0 then (l lxor r)\n else (l lor r);;\n\nlet tree =\n let rec make_tree n x =\n if n = 0 then\n Node (Leaf,arr.(x),Leaf)\n else\n match (make_tree (n-1) (2*x)) ,(make_tree (n-1) (2*x+1)) with\n | (Node(_,l,_) as a),(Node(_,r,_) as b) -> Node(a,(oper n l r),b)\n in make_tree n 0;;\n\nlet rec modify tree n x p =\n match tree with\n | Node (Leaf,key,Leaf) as org ->\n if (x = p) then Node(Leaf,arr.(p),Leaf) else org\n | Node (left,key,right) as org -> \n let len = (1 lsl n) in\n let a,b = x*len,x*len+len-1 in\n if (p>=a && p<=b) then\n match (modify left (n-1) (x+x) p),(modify right (n-1) (x+x+1) p) with\n | (Node(_,l,_) as a),(Node(_,r,_) as b) -> Node (a,(oper n l r),b)\n else org;;\n\nlet rec query tree x =\n if x = m then\n ()\n else begin\n let p,b = Scanf.scanf \"%d %d\\n\" (fun x y -> (x-1),y) in\n arr.(p) <- b;\n let tree = modify tree n 0 p in\n let Node(_,key,_) = tree in\n Printf.printf \"%d\\n\" key;\n query tree (x+1);\n end in query tree 0;;\n"}, {"source_code": "type tree = Node of int*tree*tree | Leaf\ntype operator = Or | Xor\n\nlet (|>) x f = f x\n\nlet flip = function\n Or -> Xor\n | Xor -> Or \n\nlet denote_op = function\n | Or -> (lor)\n | Xor -> (lxor)\n;;\n\nlet compose_tree seq =\n let rec build_row op seq acc =\n match seq with\n | [] -> List.rev acc\n | (Node (a,tl,tr)) :: (Node (b,tl2,tr2)) :: xs ->\n build_row op xs \n ((Node (denote_op op a b, Node (a, tl, tr), Node (b, tl2, tr2))) :: acc)\n in\n let rec iter_rows op seq =\n match seq with\n [t] -> t\n | xs -> \n iter_rows (flip op) (build_row op seq [])\n in\n iter_rows Or seq\n\nlet rec update_leaf leafs p v t =\n match t with\n | Leaf -> Leaf\n | Node (a, Leaf, Leaf) -> Node (v, Leaf, Leaf)\n | Node (a,tl,tr) ->\n if (p > leafs/2) then\n Node (a,tl, update_leaf (leafs/2) (p - (leafs/2)) v tr)\n else \n Node (a, update_leaf (leafs/2) p v tl,tr)\n\nlet rec recalculate_path leafs p t =\n match t with\n | Leaf -> failwith \"invariant broken\"\n | Node (a, Leaf, Leaf) -> (Node (a, Leaf, Leaf), Or)\n | Node (a,tl,tr) ->\n if (p > leafs/2) then\n let (Node (v,tl2,tr2), op) = \n recalculate_path (leafs/2) (p - (leafs/2)) tr in\n match tl with\n Leaf -> failwith \"invariant broken\"\n | Node (b,_,_) ->\n (Node (denote_op op b v, tl, Node (v,tl2,tr2)), flip op)\n else \n let (Node (v,tl2,tr2),op) = recalculate_path (leafs/2) p tl in\n match tr with\n Leaf -> failwith \"invariant broken\"\n | Node (b,_,_) -> \n (Node (denote_op op b v, Node (v,tl2,tr2), tr), flip op)\n\nlet rec print_tree = function\n Leaf -> Printf.printf \" - \"\n | Node (a, tl, tr) ->\n print_tree tl;\n Printf.printf \"%d \" a;\n print_tree tr\n\n\nlet rec print_root = function\n Leaf -> failwith \"error\"\n | Node (a, _, _) ->\n Printf.printf \"%d\\n\" a\n\nlet main =\n let (n,m) = Scanf.scanf \"%d %d\\n\" (fun a b -> (a,b)) in\n let leafs = 2 lsl (n-1) in\n let rec aux f n acc =\n match n with\n 0 -> List.rev acc\n | n -> \n aux f (n-1) ((f ()) :: acc)\n in\n let tree =\n aux (fun _ -> Scanf.scanf \"%d \" (fun n -> Node (n, Leaf, Leaf))) leafs [] |>\n compose_tree\n in\n let queries = aux (fun _ -> Scanf.scanf \"%d %d \" (fun p v -> (p,v))) m [] in\n List.fold_left (fun t (p,v) ->\n let t_new = \n update_leaf leafs p v t |>\n recalculate_path leafs p |>\n fst\n in print_root t_new; t_new) tree queries\n"}], "negative_code": [{"source_code": "type tree = Node of int*tree*tree | Leaf\ntype operator = Or | Xor\n\nlet (|>) x f = f x\n\nlet flip = function\n Or -> Xor\n | Xor -> Or \n\nlet denote_op = function\n | Or -> (lor)\n | Xor -> (lxor)\n;;\n\nlet compose_tree seq =\n let rec build_row op seq acc =\n match seq with\n | [] -> List.rev acc\n | (Node (a,tl,tr)) :: (Node (b,tl2,tr2)) :: xs ->\n build_row op xs \n ((Node (denote_op op a b, Node (a, tl, tr), Node (b, tl2, tr2))) :: acc)\n in\n let rec iter_rows op seq =\n match seq with\n [t] -> t\n | xs -> \n iter_rows (flip op) (build_row op seq [])\n in\n iter_rows Or seq\n\nlet rec update_leaf leafs p v t =\n match t with\n | Leaf -> Leaf\n | Node (a, Leaf, Leaf) -> Node (v, Leaf, Leaf)\n | Node (a,tl,tr) ->\n if (p > leafs/2) then\n Node (a,tl, update_leaf (leafs/2) (p/2) v tr)\n else \n Node (a, update_leaf (leafs/2) p v tl,tr)\n\nlet rec recalculate_path leafs p t =\n match t with\n | Leaf -> failwith \"invariant broken\"\n | Node (a, Leaf, Leaf) -> (Node (a, Leaf, Leaf), Or)\n | Node (a,tl,tr) ->\n if (p > leafs/2) then\n let (Node (v,tl2,tr2), op) = \n recalculate_path (leafs/2) (p/2) tr in\n match tl with\n Leaf -> failwith \"invariant broken\"\n | Node (b,_,_) ->\n (Node (denote_op op b v, tl, Node (v,tl2,tr2)), flip op)\n else \n let (Node (v,tl2,tr2),op) = recalculate_path (leafs/2) p tl in\n match tr with\n Leaf -> failwith \"invariant broken\"\n | Node (b,_,_) -> \n (Node (denote_op op b v, Node (v,tl2,tr2), tr), flip op)\n\nlet rec print_tree = function\n Leaf -> Printf.printf \" - \"\n | Node (a, tl, tr) ->\n print_tree tl;\n Printf.printf \"%d \" a;\n print_tree tr\n\n\nlet rec print_root = function\n Leaf -> failwith \"error\"\n | Node (a, _, _) ->\n Printf.printf \"%d\\n\" a\n\nlet main =\n let (n,m) = Scanf.scanf \"%d %d\\n\" (fun a b -> (a,b)) in\n let leafs = 2 lsl (n-1) in\n let rec aux f n acc =\n match n with\n 0 -> List.rev acc\n | n -> \n aux f (n-1) ((f ()) :: acc)\n in\n let tree =\n aux (fun _ -> Scanf.scanf \"%d \" (fun n -> Node (n, Leaf, Leaf))) leafs [] |>\n compose_tree\n in\n let queries = aux (fun _ -> Scanf.scanf \"%d %d \" (fun p v -> (p,v))) m [] in\n List.fold_left (fun t (p,v) ->\n let t_new = \n update_leaf leafs p v t |>\n recalculate_path leafs p |>\n fst\n in print_root t_new; t_new) tree queries\n"}, {"source_code": "type tree = Node of int*tree*tree | Leaf\ntype operator = Or | Xor\n\nlet (|>) x f = f x\n\nlet flip = function\n Or -> Xor\n | Xor -> Or \n\nlet denote_op = function\n | Or -> (lor)\n | Xor -> (lxor)\n;;\n\nlet compose_tree seq =\n let rec build_row op seq acc =\n match seq with\n | [] -> List.rev acc\n | (Node (a,tl,tr)) :: (Node (b,tl2,tr2)) :: xs ->\n build_row op xs \n ((Node (denote_op op a b, Node (a, tl, tr), Node (b, tl2, tr2))) :: acc)\n in\n let rec iter_rows op seq =\n match seq with\n [t] -> t\n | xs -> \n iter_rows (flip op) (build_row op seq [])\n in\n iter_rows Or seq\n\nlet rec update_leaf leafs p v t =\n match t with\n | Leaf -> Leaf\n | Node (a, Leaf, Leaf) -> Node (v, Leaf, Leaf)\n | Node (a,tl,tr) ->\n if (p > leafs/2) then\n Node (a,tl, update_leaf (leafs/2) (p mod (leafs/2)) v tr)\n else \n Node (a, update_leaf (leafs/2) p v tl,tr)\n\nlet rec recalculate_path leafs p t =\n match t with\n | Leaf -> failwith \"invariant broken\"\n | Node (a, Leaf, Leaf) -> (Node (a, Leaf, Leaf), Or)\n | Node (a,tl,tr) ->\n if (p > leafs/2) then\n let (Node (v,tl2,tr2), op) = \n recalculate_path (leafs/2) (p mod (leafs/2)) tr in\n match tl with\n Leaf -> failwith \"invariant broken\"\n | Node (b,_,_) ->\n (Node (denote_op op b v, tl, Node (v,tl2,tr2)), flip op)\n else \n let (Node (v,tl2,tr2),op) = recalculate_path (leafs/2) p tl in\n match tr with\n Leaf -> failwith \"invariant broken\"\n | Node (b,_,_) -> \n (Node (denote_op op b v, Node (v,tl2,tr2), tr), flip op)\n\n\nlet rec print_root = function\n Leaf -> failwith \"error\"\n | Node (a, _, _) ->\n Printf.printf \"%d\\n\" a\n\nlet main =\n let (n,m) = Scanf.scanf \"%d %d\\n\" (fun a b -> (a,b)) in\n let leafs = 2 lsl (n-1) in\n let rec aux f n acc =\n match n with\n 0 -> List.rev acc\n | n -> \n aux f (n-1) ((f ()) :: acc)\n in\n let tree =\n aux (fun _ -> Scanf.scanf \"%d \" (fun n -> Node (n, Leaf, Leaf))) leafs [] |>\n compose_tree\n in\n let queries = aux (fun _ -> Scanf.scanf \"%d %d \" (fun p v -> (p,v))) m [] in\n List.fold_left (fun t (p,v) ->\n let t_new = \n update_leaf leafs p v t |>\n recalculate_path leafs p |>\n fst\n in print_root t_new; t_new) tree queries\n"}, {"source_code": "type tree = Node of int*tree*tree | Leaf\ntype operator = Or | Xor\n\nlet (|>) x f = f x\n\nlet flip = function\n Or -> Xor\n | Xor -> Or \n\nlet denote_op = function\n | Or -> (lor)\n | Xor -> (lxor)\n;;\n\nlet compose_tree seq =\n let rec build_row op seq acc =\n match seq with\n | [] -> List.rev acc\n | (Node (a,tl,tr)) :: (Node (b,tl2,tr2)) :: xs ->\n build_row op xs \n ((Node (denote_op op a b, Node (a, tl, tr), Node (b, tl2, tr2))) :: acc)\n in\n let rec iter_rows op seq =\n match seq with\n [t] -> t\n | xs -> \n iter_rows (flip op) (build_row op seq [])\n in\n iter_rows Or seq\n\nlet rec update_leaf leafs p v t =\n match t with\n | Leaf -> Leaf\n | Node (a, Leaf, Leaf) -> Node (v, Leaf, Leaf)\n | Node (a,tl,tr) ->\n if (p > leafs/2) then\n Node (a,tl, update_leaf (leafs/2) (p/2) v tr)\n else \n Node (a, update_leaf (leafs/2) p v tl,tr)\n\nlet rec recalculate_path leafs p t =\n match t with\n | Leaf -> failwith \"invariant broken\"\n | Node (a, Leaf, Leaf) -> (Node (a, Leaf, Leaf), Or)\n | Node (a,tl,tr) ->\n if (p > leafs/2) then\n let (Node (v,tl2,tr2), op) = \n recalculate_path (leafs/2) (p/2) tr in\n match tl with\n Leaf -> failwith \"invariant broken\"\n | Node (b,_,_) ->\n (Node (denote_op op b v, tl, Node (v,tl2,tr2)), flip op)\n else \n let (Node (v,tl2,tr2),op) = recalculate_path (leafs/2) p tl in\n match tr with\n Leaf -> failwith \"invariant broken\"\n | Node (b,_,_) -> \n (Node (denote_op op b v, Node (v,tl2,tr2), tr), flip op)\n\nlet rec print_tree = function\n Leaf -> Printf.printf \" - \"\n | Node (a, tl, tr) ->\n print_tree tl;\n Printf.printf \"%d \" a;\n print_tree tr\n\n\nlet rec print_root = function\n Leaf -> failwith \"error\"\n | Node (a, _, _) ->\n Printf.printf \"%d\\n\" a\n\nlet main =\n let (n,m) = Scanf.scanf \"%d %d\\n\" (fun a b -> (a,b)) in\n let leafs = 2 lsl (n-1) in\n let rec aux f n acc =\n match n with\n 0 -> List.rev acc\n | n -> \n aux f (n-1) ((f ()) :: acc)\n in\n let tree =\n aux (fun _ -> Scanf.scanf \"%d \" (fun n -> Node (n, Leaf, Leaf))) leafs [] |>\n compose_tree\n in\n let queries = aux (fun _ -> Scanf.scanf \"%d %d \" (fun p v -> (p,v))) m [] in\n List.fold_left (fun t (p,v) ->\n let t_new = \n update_leaf leafs p v t |>\n recalculate_path leafs p |>\n fst\n in print_tree t_new; Printf.printf \"\\n\\n\"; t_new) tree queries\n"}], "src_uid": "40d1ea98aa69865143d44432aed4dd7e"} {"nl": {"description": "A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition \u2014 when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation. Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom. You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously. Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.Note one milliliter equals to one cubic centimeter.", "input_spec": "The only line of the input contains four integer numbers d,\u2009h,\u2009v,\u2009e (1\u2009\u2264\u2009d,\u2009h,\u2009v,\u2009e\u2009\u2264\u2009104), where: d \u2014 the diameter of your cylindrical cup, h \u2014 the initial level of water in the cup, v \u2014 the speed of drinking process from the cup in milliliters per second, e \u2014 the growth of water because of rain if you do not drink from the cup. ", "output_spec": "If it is impossible to make the cup empty, print \"NO\" (without quotes). Otherwise print \"YES\" (without quotes) in the first line. In the second line print a real number \u2014 time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10\u2009-\u20094. It is guaranteed that if the answer exists, it doesn't exceed 104.", "sample_inputs": ["1 2 3 100", "1 1 1 1"], "sample_outputs": ["NO", "YES\n3.659792366325"], "notes": "NoteIn the first example the water fills the cup faster than you can drink from it.In the second example area of the cup's bottom equals to , thus we can conclude that you decrease the level of water by centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in seconds."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_pair () = bscanf Scanning.stdib \" %f %f \" (fun x y -> (x,y))\nlet () = \n let (d,h) = read_pair () in\n let (v,e) = read_pair () in\n\n let pi = 2.0 *. (asin 1.0) in\n let sq x = x *. x in\n let a = pi *. (sq (d /. 2.0)) in\n let vol = a *. h in\n\n let e = e *. a in\n\n if e >= v then (\n printf \"NO\\n\"\n ) else (\n printf \"YES\\n\";\n printf \"%.9f\\n\" (vol /. (v -. e))\n )\n"}], "negative_code": [], "src_uid": "fc37ef81bb36f3ac07ce2c4c3ec10d98"} {"nl": {"description": "Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.He has a n\u2009\u00d7\u2009n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number x written on it, if this cell is attacked by one of the bishops Gargari will get x dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.We assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092000). Each of the next n lines contains n integers aij (0\u2009\u2264\u2009aij\u2009\u2264\u2009109) \u2014 description of the chessboard.", "output_spec": "On the first line print the maximal number of dollars Gargari will get. On the next line print four integers: x1,\u2009y1,\u2009x2,\u2009y2 (1\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2\u2009\u2264\u2009n), where xi is the number of the row where the i-th bishop should be placed, yi is the number of the column where the i-th bishop should be placed. Consider rows are numbered from 1 to n from top to bottom, and columns are numbered from 1 to n from left to right. If there are several optimal solutions, you can print any of them.", "sample_inputs": ["4\n1 1 1 1\n2 1 1 0\n1 1 1 0\n1 0 0 1"], "sample_outputs": ["12\n2 2 3 2"], "notes": null}, "positive_code": [{"source_code": "let pf = Printf.printf\n \nlet epf = Printf.eprintf\n \nlet sf = Scanf.scanf\n \nlet ( |> ) x f = f x\n \nlet ( @@ ) f x = f x\n \nmodule Array =\n struct\n include ArrayLabels\n \n let fold_lefti ~f ~init arr =\n let acc = ref init\n in\n (for i = 0 to Pervasives.( - ) (Array.length arr) 1 do\n acc := f i !acc arr.(i)\n done;\n !acc)\n \n end\n \nmodule String = StringLabels\n \nmodule List =\n struct\n include ListLabels\n \n let rec repeat n a =\n if n = 0 then [] else a :: (repeat (Pervasives.( - ) n 1) a)\n \n let rec drop n a =\n if n = 0\n then a\n else\n (match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (Pervasives.( - ) n 1) xs)\n \n let init ~f n =\n let res = ref []\n in\n (for i = 0 to Pervasives.( - ) n 1 do res := (f i) :: !res done;\n List.rev !res)\n \n end\n \nmodule H = Hashtbl\n \nmodule SI = Set.Make(struct type t = int\n let compare = compare\n end)\n \nlet solve n arr =\n let dia1 = Array.create (Pervasives.( + ) n n) 0L in\n let dia2 = Array.create (Pervasives.( + ) n n) 0L\n in\n (Array.iteri arr\n ~f:\n (fun i row ->\n Array.iteri row\n ~f:\n (fun j x ->\n (dia1.(Pervasives.( + ) i j) <-\n Int64.add dia1.(Pervasives.( + ) i j) x;\n dia2.(Pervasives.( + ) (Pervasives.( - ) i j) n) <-\n Int64.add\n dia2.(Pervasives.( + ) (Pervasives.( - ) i j) n) x)));\n let (m1, x1, y1) = ((ref 0L), (ref 0), (ref 0)) in\n let (m2, x2, y2) = ((ref 0L), (ref 0), (ref 0))\n in\n (Array.iteri arr\n ~f:\n (fun i row ->\n Array.iteri row\n ~f:\n (fun j v ->\n let cur =\n Int64.sub\n (Int64.add dia1.(Pervasives.( + ) i j)\n dia2.(Pervasives.( + ) (Pervasives.( - ) i j) n))\n v\n in\n if ((Pervasives.( + ) i j) land 1) = 0\n then\n if !m1 <= cur\n then\n (m1 := cur;\n x1 := Pervasives.( + ) i 1;\n y1 := Pervasives.( + ) j 1)\n else ()\n else\n if !m2 <= cur\n then\n (m2 := cur;\n x2 := Pervasives.( + ) i 1;\n y2 := Pervasives.( + ) j 1)\n else ()));\n pf \"%Ld\\n\" (Int64.add !m1 !m2);\n pf \"%d %d %d %d\\n\" !x1 !y1 !x2 !y2))\n \nlet () =\n sf \"%d \"\n (fun n ->\n let arr =\n Array.init n\n ~f: (fun i -> Array.init n ~f: (fun j -> sf \"%Ld \" (fun i -> i)))\n in solve n arr)\n \n"}], "negative_code": [{"source_code": "let pf = Printf.printf\n \nlet epf = Printf.eprintf\n \nlet sf = Scanf.scanf\n \nlet ( |> ) x f = f x\n \nlet ( @@ ) f x = f x\n \nmodule Array =\n struct\n include ArrayLabels\n \n let fold_lefti ~f ~init arr =\n let acc = ref init\n in\n (for i = 0 to Pervasives.( - ) (Array.length arr) 1 do\n acc := f i !acc arr.(i)\n done;\n !acc)\n \n end\n \nmodule String = StringLabels\n \nmodule List =\n struct\n include ListLabels\n \n let rec repeat n a =\n if n = 0 then [] else a :: (repeat (Pervasives.( - ) n 1) a)\n \n let rec drop n a =\n if n = 0\n then a\n else\n (match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (Pervasives.( - ) n 1) xs)\n \n let init ~f n =\n let res = ref []\n in\n (for i = 0 to Pervasives.( - ) n 1 do res := (f i) :: !res done;\n List.rev !res)\n \n end\n \nmodule H = Hashtbl\n \nmodule SI = Set.Make(struct type t = int\n let compare = compare\n end)\n \nlet solve n arr =\n let dia1 = Array.create (Pervasives.( + ) n n) 0L in\n let dia2 = Array.create (Pervasives.( + ) n n) 0L\n in\n (Array.iteri arr\n ~f:\n (fun i row ->\n Array.iteri row\n ~f:\n (fun j x ->\n (dia1.(Pervasives.( + ) i j) <-\n Int64.add dia1.(Pervasives.( + ) i j) x;\n dia2.(Pervasives.( + ) (Pervasives.( - ) i j) n) <-\n Int64.add\n dia2.(Pervasives.( + ) (Pervasives.( - ) i j) n) x)));\n let (m1, x1, y1) = ((ref 0L), (ref 0), (ref 0)) in\n let (m2, x2, y2) = ((ref 0L), (ref 0), (ref 0))\n in\n (Array.iteri arr\n ~f:\n (fun i row ->\n Array.iteri row\n ~f:\n (fun j v ->\n let cur =\n Int64.sub\n (Int64.add dia1.(Pervasives.( + ) i j)\n dia2.(Pervasives.( + ) (Pervasives.( - ) i j) n))\n v\n in\n if ((Pervasives.( + ) i j) land 1) = 0\n then\n if !m1 < cur\n then\n (m1 := cur;\n x1 := Pervasives.( + ) i 1;\n y1 := Pervasives.( + ) j 1)\n else ()\n else\n if !m2 < cur\n then\n (m2 := cur;\n x2 := Pervasives.( + ) i 1;\n y2 := Pervasives.( + ) j 1)\n else ()));\n pf \"%Ld\\n\" (Int64.add !m1 !m2);\n pf \"%d %d %d %d\\n\" !x1 !y1 !x2 !y2))\n \nlet () =\n sf \"%d \"\n (fun n ->\n let arr =\n Array.init n\n ~f: (fun i -> Array.init n ~f: (fun j -> sf \"%Ld \" (fun i -> i)))\n in solve n arr)\n \n"}, {"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nmodule Array = struct\n include ArrayLabels\n let fold_lefti ~f ~init arr =\n let acc = ref init in\n for i = 0 to Array.length arr - 1 do\n acc := f i !acc arr.(i)\n done;\n !acc\n ;;\nend\nmodule String = StringLabels ;;\nmodule List = struct\n include ListLabels ;;\n let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;\n let rec drop n a =\n if n = 0 then a\n else match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (n - 1) xs ;;\n\n let init ~f n =\n let res = ref [] in\n for i = 0 to n - 1 do\n res := f i :: !res\n done;\n List.rev !res\n ;;\nend ;;\nmodule H = Hashtbl ;;\n\nmodule SI = Set.Make (struct\n type t = int \n let compare = compare\nend)\n\nlet solve n arr =\n let dia1 = Array.create (n + n) 0 in\n let dia2 = Array.create (n + n) 0 in\n\n Array.iteri arr ~f:(fun i row ->\n Array.iteri row ~f:(fun j x ->\n dia1.(i + j) <- dia1.(i + j) + x;\n dia2.(i - j + n) <- dia2.(i - j + n) + x));\n\n let m1, x1, y1 = ref 0, ref 0, ref 0 in\n let m2, x2, y2 = ref 0, ref 0, ref 0 in\n \n Array.iteri arr ~f:(fun i row ->\n Array.iteri row ~f:(fun j v ->\n let cur = dia1.(i + j) + dia2.(i - j + n) - v in\n if (i + j) land 1 = 0 then\n (if !m1 < cur then (m1 := cur; x1 := i + 1; y1 := j + 1))\n else \n (if !m2 < cur then (m2 := cur; x2 := i + 1; y2 := j + 1))));\n\n pf \"%d\\n\" (!m1 + !m2);\n pf \"%d %d %d %d\\n\" !x1 !y1 !x2 !y2\n;;\n \nlet () =\n sf \"%d \" (fun n ->\n let arr = Array.init n ~f:(fun i ->\n Array.init n ~f:(fun j -> sf \"%d \" (fun i -> i))) in\n solve n arr)\n;;\n"}], "src_uid": "a55d6c4af876e9c88b43d088f2b81817"} {"nl": {"description": "You are given $$$q$$$ queries in the following form:Given three integers $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$, find minimum positive integer $$$x_i$$$ such that it is divisible by $$$d_i$$$ and it does not belong to the segment $$$[l_i, r_i]$$$.Can you answer all the queries?Recall that a number $$$x$$$ belongs to segment $$$[l, r]$$$ if $$$l \\le x \\le r$$$.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 500$$$) \u2014 the number of queries. Then $$$q$$$ lines follow, each containing a query given in the format $$$l_i$$$ $$$r_i$$$ $$$d_i$$$ ($$$1 \\le l_i \\le r_i \\le 10^9$$$, $$$1 \\le d_i \\le 10^9$$$). $$$l_i$$$, $$$r_i$$$ and $$$d_i$$$ are integers.", "output_spec": "For each query print one integer: the answer to this query.", "sample_inputs": ["5\n2 4 2\n5 10 4\n3 10 1\n1 2 3\n4 6 5"], "sample_outputs": ["6\n4\n1\n3\n10"], "notes": null}, "positive_code": [{"source_code": "let q = int_of_string (input_line stdin);;\n\nlet solve l r d =\n let ans =\n if d < l then d\n else if Nativeint.rem r d = Nativeint.zero then Nativeint.add r d\n else Nativeint.add (Nativeint.mul (Nativeint.div r d) d) d\n in Printf.printf \"%nd\\n\" ans ;;\n\nfor i = 1 to q do\n Scanf.scanf \"%nd %nd %nd\\n\" solve\ndone"}], "negative_code": [{"source_code": "let q = int_of_string (input_line stdin);;\n\nlet solve l r d =\n let ans =\n if d < l then d\n else if r mod d == 0 then r + d\n else r / d * d + d in\n Printf.printf \"%d\\n\" ans ;;\n\nfor i = 1 to q do\n Scanf.scanf \"%d %d %d\\n\" solve\ndone"}], "src_uid": "091e91352973b18040e2d57c46f2bf8a"} {"nl": {"description": "Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows: There are n knights participating in the tournament. Each knight was assigned his unique number \u2014 an integer from 1 to n. The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament. After the i-th fight among all participants of the fight only one knight won \u2014 the knight number xi, he continued participating in the tournament. Other knights left the tournament. The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.Write the code that calculates for each knight, the name of the knight that beat him.", "input_spec": "The first line contains two integers n, m (2\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105;\u00a01\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105) \u2014 the number of knights and the number of fights. Each of the following m lines contains three integers li,\u2009ri,\u2009xi (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009n;\u00a0li\u2009\u2264\u2009xi\u2009\u2264\u2009ri) \u2014 the description of the i-th fight. It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.", "output_spec": "Print n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.", "sample_inputs": ["4 3\n1 2 1\n1 3 3\n1 4 4", "8 4\n3 5 4\n3 7 6\n2 8 8\n1 8 1"], "sample_outputs": ["3 1 4 0", "0 8 4 6 4 8 6 1"], "notes": "NoteConsider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won."}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet range x y =\n let rec iter acc i =\n if i >= y then acc\n else iter (i :: acc) (i + 1) in\n iter [] x |> List.rev\n;;\n\nmodule S = Set.Make (struct\n type t = int ;;\n let compare (x : int) (y : int) = compare x y ;;\nend)\n;;\n\nlet interval set x y =\n let (_, _, right) = S.split (x - 1) set in\n let (left, _, _) = S.split (y + 1) set in\n S.inter left right\n;;\n\nlet () =\n let n, m = Scanf.scanf \"%d %d \" (fun x y -> x, y) in\n let fights = fold_for 0 m ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d %d %d \" (fun x y z -> x, y, z) :: acc) |> List.rev in\n let beater = Array.create n 0 in\n let ps = range 1 (n + 1) |> List.fold_left ~init:S.empty ~f:(fun acc i -> S.add i acc) in\n let res = List.fold_left ~init:ps fights ~f:(fun ps (l, r, x) ->\n Printf.eprintf \"debug: l, r, x = %d, %d, %d\\n\" l r x;\n let losers = interval ps l r in\n prerr_string \"debug:\";\n S.iter (Printf.eprintf \"%d \") losers;\n prerr_endline \"\";\n S.iter (fun i -> if x <> i then beater.(i - 1) <- x) losers;\n S.fold (fun i acc -> if x <> i then S.remove i acc else acc) losers ps) in\n Array.iter beater ~f:(fun i -> Printf.printf \"%d \" i);\n print_endline \"\";\n;;\n"}], "negative_code": [], "src_uid": "a608eda195166231d14fbeae9c8b31fa"} {"nl": {"description": "You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\\frac{n}{2}$$$ opening brackets '(' and $$$\\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is: \"()\" is regular bracket sequence; if $$$s$$$ is regular bracket sequence then \"(\" + $$$s$$$ + \")\" is regular bracket sequence; if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, \"()()\", \"(())()\", \"(())\" and \"()\" are regular bracket sequences, but \")(\", \"()(\" and \")))\" are not.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \\le n \\le 50$$$) \u2014 the length of $$$s$$$. It is guaranteed that $$$n$$$ is even. The second line of the test case containg the string $$$s$$$ consisting of $$$\\frac{n}{2}$$$ opening and $$$\\frac{n}{2}$$$ closing brackets.", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.", "sample_inputs": ["4\n2\n)(\n4\n()()\n8\n())()()(\n10\n)))((((())"], "sample_outputs": ["1\n0\n1\n3"], "notes": "NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain \"((()))(())\"."}, "positive_code": [{"source_code": "module A = Array\nmodule C = Char\nmodule I = Int64\nmodule L = List\nmodule Q = Queue\nmodule S = String\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet ssf = Scanf.sscanf\n\nlet read_int () = sf \"%d \" (fun x -> x)\nlet read_float () = sf \"%f \" (fun x -> x)\nlet read_char () = sf \"%c\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\nlet read_list read n = for i = 1 to n do read () done\nlet read_line () = sf \"%s\\n\" (fun x -> x)\nlet err s = raise (Failure s)\n\nlet inf = int_of_float 1e18\nlet eps = 1e-11\n\nlet count_dangling n xs =\n let rec loop dangling openb i =\n if i = n then dangling\n else if xs.[i] = '(' then loop dangling (openb + 1) (i + 1)\n else if openb == 0 then loop (dangling + 1) openb (i + 1)\n else loop dangling (openb - 1) (i + 1)\n in loop 0 0 0\n\n\nlet () =\n for i = 1 to (read_int ()) do\n let n = (read_int ()) in\n let s = (read_line ()) in\n pf \"%d\\n\" (count_dangling n s)\n done\n"}, {"source_code": "open Printf\n\nlet main =\n let t = read_int() in\n for i = 1 to t do\n let _ = read_int() in\n let brackets = read_line() in\n\n let answer = ref 0 in\n let m = ref 0 in\n\n String.iter (fun c -> \n if c = '(' then\n m := !m + 1\n else if c = ')' then\n m := !m - 1;\n if !m < 0 then\n answer := max (!answer) (-(!m))\n ) brackets;\n printf \"%d\\n\" (!answer)\n done"}], "negative_code": [], "src_uid": "7a724f327c6202735661be25ef9328d2"} {"nl": {"description": "A well-known art union called \"Kalevich is Alive!\" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter tij units of time.Order is important everywhere, so the painters' work is ordered by the following rules: Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j\u2009+\u20091)-th painter (if j\u2009<\u2009n); each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on; each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest; as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale.", "input_spec": "The first line of the input contains integers m,\u2009n (1\u2009\u2264\u2009m\u2009\u2264\u200950000,\u20091\u2009\u2264\u2009n\u2009\u2264\u20095), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1,\u2009ti2,\u2009...,\u2009tin (1\u2009\u2264\u2009tij\u2009\u2264\u20091000), where tij is the time the j-th painter needs to work on the i-th picture.", "output_spec": "Print the sequence of m integers r1,\u2009r2,\u2009...,\u2009rm, where ri is the moment when the n-th painter stopped working on the i-th picture.", "sample_inputs": ["5 1\n1\n2\n3\n4\n5", "4 2\n2 5\n3 1\n5 3\n10 1"], "sample_outputs": ["1 3 6 10 15", "7 8 13 21"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet m=read_int() and n=read_int();;\nlet mat=Array.make_matrix (m+1) (n+1) 0;;\nfor i=1 to m do\n for j=1 to n do\n mat.(i).(j)<-read_int()\n done\ndone;;\nlet sol=Array.make (m+1) 0;;\nfor j=1 to n do\n let temp=ref (sol.(1)) in\n for i=1 to m do\n if !temp>=sol.(i) then\n begin\n temp:= !temp+mat.(i).(j);\n sol.(i)<- !temp\n end\n else\n begin\n temp:=sol.(i)+mat.(i).(j);\n sol.(i)<- !temp\n end\n done\ndone;;\n\nfor i=1 to m do\n print_int sol.(i);\n if i<>m then print_string \" \"\ndone;;"}], "negative_code": [], "src_uid": "43f4ea06d8b8b0b6b6795a3d526c5a2d"} {"nl": {"description": "Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500)\u00a0\u2014 the number of gemstones. The second line contains n space-separated integers, the i-th of which is ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n)\u00a0\u2014 the color of the i-th gemstone in a line.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of seconds needed to destroy the entire line.", "sample_inputs": ["3\n1 2 1", "3\n1 2 3", "7\n1 4 4 2 3 2 1"], "sample_outputs": ["1", "3", "2"], "notes": "NoteIn the first sample, Genos can destroy the entire line in one second.In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let c = Array.init n (fun _ -> read_int()) in\n\n let mem = Array.make_matrix n n (-1) in\n\n for i=0 to n-1 do\n mem.(i).(i) <- 1\n done;\n\n let rec score i j = if i>j then 0 else if mem.(i).(j) >= 0 then mem.(i).(j) else\n let answer =\n\tif i+1 = j then\n\t if c.(i) = c.(j) then 1 else 2\n\telse \n\t let mm = ref n in\n\t for k = i to j do\n\t if c.(i) = c.(k) then\n\t let noarch = if i=k || i+1=k then 1 else 0 in\n\t mm := min !mm (noarch + (score (i+1) (k-1)) + (score (k+1) j))\n\t done;\n\t !mm\n in\n mem.(i).(j) <- answer;\n(* printf \"score %d %d = %d\\n\" i j answer; *)\n answer\n in\n\n printf \"%d\\n\" (score 0 (n-1))\n"}], "negative_code": [], "src_uid": "f942ed9c5e707d12be42d3ab55f39441"} {"nl": {"description": "Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w\u2009=\u2009xy. A split operation is transforming word w\u2009=\u2009xy into word u\u2009=\u2009yx. For example, a split operation can transform word \"wordcut\" into word \"cutword\".You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1\u2009\u2264\u2009i\u2009\u2264\u2009k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x\u2009\u2260\u2009a holds.", "input_spec": "The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0\u2009\u2264\u2009k\u2009\u2264\u2009105) \u2014 the required number of operations.", "output_spec": "Print a single number \u2014 the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["ab\nab\n2", "ababab\nababab\n1", "ab\nba\n2"], "sample_outputs": ["1", "2", "0"], "notes": "NoteThe sought way in the first sample is:ab \u2009\u2192\u2009 a|b \u2009\u2192\u2009 ba \u2009\u2192\u2009 b|a \u2009\u2192\u2009 abIn the second sample the two sought ways are: ababab \u2009\u2192\u2009 abab|ab \u2009\u2192\u2009 ababab ababab \u2009\u2192\u2009 ab|abab \u2009\u2192\u2009 ababab"}, "positive_code": [{"source_code": "exception Found of int\n\nlet _ =\n let m = 1000000007L in\n let sb = Scanf.Scanning.stdib in\n let a = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = String.length a in\n let s =\n try\n for i = 0 to n - 1 do\n\ttry\n\t for j = 0 to n - 1 do\n\t let j' = i + j in\n\t let j' = if j' >= n then j' - n else j' in\n\t if a.[j] <> b.[j']\n\t then raise Not_found\n\t done;\n\t raise (Found i)\n\twith\n\t | Not_found -> ()\n done;\n -1\n with\n | Found s -> s\n in\n let p =\n try\n for i = 1 to n - 1 do\n\tif n mod i = 0 then (\n\t try\n\t for j = 0 to n - 1 - i do\n\t if a.[j] <> a.[j + i]\n\t then raise Not_found\n\t done;\n\t raise (Found i)\n\t with\n\t | Not_found -> ()\n\t)\n done;\n n\n with\n | Found s -> s\n in\n if s < 0\n then Printf.printf \"0\\n\"\n else if s = 0 && k = 0\n then Printf.printf \"1\\n\"\n else if k = 0\n then Printf.printf \"0\\n\"\n else if s = 0 && k = 1\n then Printf.printf \"%d\\n\" (n / p - 1)\n else if k = 1\n then Printf.printf \"%d\\n\" (n / p)\n else (\n\t(*Printf.printf \"asd %d %d\\n\" s p;*)\n let a = Array.make_matrix 2 (k + 1) 0L in\n\ta.(0).(0) <- 1L;\n\tfor i = 1 to k do\n\t a.(0).(i) <-\n\t Int64.add\n\t (Int64.mul a.(0).(i - 1) (Int64.of_int (n / p - 1)))\n\t (Int64.mul a.(1).(i - 1) (Int64.of_int (n / p * (p - 1))));\n\t a.(0).(i) <- Int64.rem a.(0).(i) m;\n\t a.(1).(i) <-\n\t Int64.add\n\t (Int64.mul a.(0).(i - 1) (Int64.of_int (n / p)))\n\t (Int64.mul a.(1).(i - 1) (Int64.of_int (n / p * (p - 2) + (n / p - 1))));\n\t a.(1).(i) <- Int64.rem a.(1).(i) m;\n\t (*Printf.printf \"asd %d %Ld %Ld\\n\" i a.(0).(i) a.(1).(i);*)\n\tdone;\n\tlet res = if s = 0 then a.(0).(k) else a.(1).(k) in\n\t Printf.printf \"%Ld\\n\" res\n )\n"}], "negative_code": [], "src_uid": "414000abf4345f08ede20798de29b9d4"} {"nl": {"description": "Two players A and B have a list of $$$n$$$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $$$\\{1, 2, 2, 3\\}$$$ in a list and you decided to choose $$$2$$$ for the next turn, only a single instance of $$$2$$$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.", "input_spec": "The first line of input contains an integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$)\u00a0\u2014 the sizes of the list. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^6$$$), describing the list of the player A, who starts the game. The third line contains $$$n$$$ integers $$$b_i$$$ ($$$1 \\le b_i \\le 10^6$$$), describing the list of the player B.", "output_spec": "Output the difference between A's score and B's score ($$$A-B$$$) if both of them are playing optimally.", "sample_inputs": ["2\n1 4\n5 1", "3\n100 100 100\n100 100 100", "2\n2 1\n5 6"], "sample_outputs": ["0", "0", "-3"], "notes": "NoteIn the first example, the game could have gone as follows: A removes $$$5$$$ from B's list. B removes $$$4$$$ from A's list. A takes his $$$1$$$. B takes his $$$1$$$. Hence, A's score is $$$1$$$, B's score is $$$1$$$ and difference is $$$0$$$.There is also another optimal way of playing: A removes $$$5$$$ from B's list. B removes $$$4$$$ from A's list. A removes $$$1$$$ from B's list. B removes $$$1$$$ from A's list. The difference in the scores is still $$$0$$$.In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $$$0$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\nend open MyInt64\n\nlet rec f u v i j =\n\t(* printf \"[%s] (%Ld) v. [%s] (%Ld)\\n\"\n\t\t(string_of_list (Int64.to_string) u)\n\t\ti\n\t\t(string_of_list (Int64.to_string) v)\n\t\tj\n\t; *)\n\tmatch u,v with\n\t| h::t,hh::tt -> \n\t\tif h > hh then f v t j (i+h)\n\t\telse if h < hh then f tt u j i\n\t\telse (\n\t\t\tf tt u j i\n\t\t)\n\t| [],h::t -> f t u j i\n\t| h::t,[] -> f v t j (i+h)\n\t| [],[] -> (i,j)\n\nlet () =\n\tlet n = get_i64 0 in\n\tlet a,b = input_i64_array n,input_i64_array n\n\tin\n\tArray.sort compare a;\n\tArray.sort compare b;\n\tlet a,b = Array.to_list a |> List.rev,Array.to_list b |> List.rev\n\tin\n\tf b a 0L 0L\n\t|> (fun (u,v) ->\n\t\t(* printf \"%Ld,%Ld : %Ld\\n\" u v (u-v); *)\n\t\tprintf \"%Ld\\n\" (u-v)\n\t)"}], "negative_code": [], "src_uid": "d740f4ee1b18eeb74dfb253125c52762"} {"nl": {"description": "Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x\u2009-\u2009li) or cell (x\u2009+\u2009li).She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible. If this is possible, calculate the minimal cost.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009300), number of cards. The second line contains n numbers li (1\u2009\u2264\u2009li\u2009\u2264\u2009109), the jump lengths of cards. The third line contains n numbers ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009105), the costs of cards.", "output_spec": "If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.", "sample_inputs": ["3\n100 99 9900\n1 1 1", "5\n10 20 30 40 50\n1 1 1 1 1", "7\n15015 10010 6006 4290 2730 2310 1\n1 1 1 1 1 1 10", "8\n4264 4921 6321 6984 2316 8432 6120 1026\n4264 4921 6321 6984 2316 8432 6120 1026"], "sample_outputs": ["2", "-1", "6", "7237"], "notes": "NoteIn first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1."}, "positive_code": [{"source_code": "(* calculate prime factors of x *)\nlet primes x =\n let rec reduce x p =\n if x mod p = 0\n then reduce (x / p) p\n else x\n in\n\n let rec aux a x p =\n (* termination condition *)\n if p * p > x\n then begin\n if x > 1\n then x :: a\n else a\n end\n\n (* loop condition *)\n else begin\n let y = reduce x p in\n if x = y\n then aux a x (succ p)\n else aux (p :: a) y (succ p)\n end\n in\n\n List.rev (aux [] x 2)\n\n(* merge two option values *)\nlet merge a b ~f =\n match a, b with\n | None, x | x, None -> x\n | Some a, Some b -> Some (f a b)\n\n(* monadic fmap into an option *)\nlet fmap a ~f =\n match a with\n | None -> None\n | Some a -> Some (f a)\n\nlet () = Scanf.scanf \"%d\\n\" (fun n ->\n (* read jump lengths of cards *)\n let j = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x))\n (* read cost of cards *)\n and ws = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x))\n in\n\n (* fold over each of the cards as a base\n * choice to find the optimum cost in acc *)\n let cost = Array.fold_left (fun acc (x, w) ->\n (* get the prime factorisation of x *)\n let p = primes x in\n let np = List.length p in\n\n (* for every card, create a bitmask *)\n let m = Array.map (fun y ->\n let q = List.mapi (fun i p -> if y mod p <> 0 then 1 lsl i else 0) p in\n List.fold_left (lor) 0 q\n ) j in\n\n let mem = Array.make_matrix n (1 lsl np) None in\n\n let rec dp cur mask =\n (* termination condition, no more cards to process *)\n if cur = n\n then begin\n (* check that at least one card is not divisible\n * by each prime factor of x *)\n if mask = (1 lsl np) - 1\n then Some 0\n else None\n end else\n match mem.(cur).(mask) with\n | Some a -> a\n | None ->\n (* choose the cur card in the dp *)\n let l = fmap (dp (succ cur) (mask lor m.(cur))) ~f:((+) ws.(cur)) in\n (* don't choose cur card *)\n let r = dp (succ cur) mask in\n let a = merge l r ~f:min in\n mem.(cur).(mask) <- Some a;\n a\n in\n\n let a = dp 0 0 in\n merge acc (fmap a ~f:((+) w)) ~f:min\n ) None (Array.init n (fun i -> (j.(i), ws.(i))))\n in\n match cost with\n | None -> print_endline \"-1\"\n | Some c -> Printf.printf \"%d\\n\" c\n)\n"}], "negative_code": [], "src_uid": "42d0350a0a18760ce6d0d7a4d65135ec"} {"nl": {"description": "Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n\u2009-\u20091 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n\u2009=\u20095, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0,\u20091,\u20092,\u2009...,\u2009n\u2009-\u20091. Write a program that determines whether the given puzzle is real or fake.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of gears. The second line contains n digits a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009n\u2009-\u20091) \u2014 the sequence of active teeth: the active tooth of the i-th gear contains number ai.", "output_spec": "In a single line print \"Yes\" (without the quotes), if the given Stolp's gears puzzle is real, and \"No\" (without the quotes) otherwise.", "sample_inputs": ["3\n1 0 0", "5\n4 2 1 4 3", "4\n0 2 3 1"], "sample_outputs": ["Yes", "Yes", "No"], "notes": "NoteIn the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2."}, "positive_code": [{"source_code": "let ri () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x) ;;\nlet n = ri() ;;\nlet r = ri() ;;\nlet rec chk i = \n if i = n then true\n else\n 0 = (ri() + (if i mod 2 = 1 then r else -r) - i) mod n && chk(i+1)\n;;\n\nprint_string(if chk 1 then \"Yes\" else \"No\")\n\n"}], "negative_code": [], "src_uid": "6c65ca365352380052b0c9d693e6d161"} {"nl": {"description": "Andre has very specific tastes. Recently he started falling in love with arrays.Andre calls an nonempty array $$$b$$$ good, if sum of its elements is divisible by the length of this array. For example, array $$$[2, 3, 1]$$$ is good, as sum of its elements\u00a0\u2014 $$$6$$$\u00a0\u2014 is divisible by $$$3$$$, but array $$$[1, 1, 2, 3]$$$ isn't good, as $$$7$$$ isn't divisible by $$$4$$$. Andre calls an array $$$a$$$ of length $$$n$$$ perfect if the following conditions hold: Every nonempty subarray of this array is good. For every $$$i$$$ ($$$1 \\le i \\le n$$$), $$$1 \\leq a_i \\leq 100$$$. Given a positive integer $$$n$$$, output any perfect array of length $$$n$$$. We can show that for the given constraints such an array always exists.An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$).", "output_spec": "For every test, output any perfect array of length $$$n$$$ on a separate line. ", "sample_inputs": ["3\n1\n2\n4"], "sample_outputs": ["24\n19 33\n7 37 79 49"], "notes": "NoteArray $$$[19, 33]$$$ is perfect as all $$$3$$$ its subarrays: $$$[19]$$$, $$$[33]$$$, $$$[19, 33]$$$, have sums divisible by their lengths, and therefore are good."}, "positive_code": [{"source_code": "(* \n D\u00e1rio was here\n 13/11/2020\n*)\n\nlet rec construct_list out v n =\n if n = 0 then out else (\n let space = if n = v then \"\" else \" \" in \n construct_list (out^space^(string_of_int v)) v (n-1)\n )\n\nlet _ = \n let tests = Scanf.scanf \"%d \" (fun a -> a) in\n\n for i=0 to (tests-1) do\n let n = Scanf.scanf \"%d \" (fun a -> a) in\n Printf.printf \"%s\\n\" (construct_list \"\" n n)\n done\n"}], "negative_code": [], "src_uid": "da2ac80c2ad6abae676d60a506eb05fc"} {"nl": {"description": "A sequence $$$a_1, a_2, \\dots, a_n$$$ is called good if, for each element $$$a_i$$$, there exists an element $$$a_j$$$ ($$$i \\ne j$$$) such that $$$a_i+a_j$$$ is a power of two (that is, $$$2^d$$$ for some non-negative integer $$$d$$$).For example, the following sequences are good: $$$[5, 3, 11]$$$ (for example, for $$$a_1=5$$$ we can choose $$$a_2=3$$$. Note that their sum is a power of two. Similarly, such an element can be found for $$$a_2$$$ and $$$a_3$$$), $$$[1, 1, 1, 1023]$$$, $$$[7, 39, 89, 25, 89]$$$, $$$[]$$$. Note that, by definition, an empty sequence (with a length of $$$0$$$) is good.For example, the following sequences are not good: $$$[16]$$$ (for $$$a_1=16$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two), $$$[4, 16]$$$ (for $$$a_1=4$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two), $$$[1, 3, 2, 8, 8, 8]$$$ (for $$$a_3=2$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two). You are given a sequence $$$a_1, a_2, \\dots, a_n$$$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.", "input_spec": "The first line contains the integer $$$n$$$ ($$$1 \\le n \\le 120000$$$) \u2014 the length of the given sequence. The second line contains the sequence of integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $$$n$$$ elements, make it empty, and thus get a good sequence.", "sample_inputs": ["6\n4 7 1 5 4 9", "5\n1 2 3 4 5", "1\n16", "4\n1 1 1 1023"], "sample_outputs": ["1", "2", "1", "0"], "notes": "NoteIn the first example, it is enough to delete one element $$$a_4=5$$$. The remaining elements form the sequence $$$[4, 7, 1, 4, 9]$$$, which is good."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Int64 = struct \n\tinclude Int64\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\tlet (~|) p = Int64.of_int p\n\tlet (~|) p = Int64.to_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\nend open Int64\n\nlet () = \n let n = get_i64 ()\n\tin let ar = input_i64_array n\n\tin let table = Hashtbl.create 1200\n\tin let pows = Array.make 32 0L\n\t\tin let rec f0 i a =\n\t\t\tif i<=31 then\n\t\t\t\tlet v = a*2L in\n\t\t\t\tpows.(i) <- v;\n\t\t\t\tf0 (i+$1) v\n\t\tin f0 0 1L;\n\t(* Array.iter (fun v -> printf \"%Ld \" v) pows;\n\tprint_newline (); *)\n\tlet update i f = \n\t\tlet c = try\n\t\t\tlet w = Hashtbl.find table i\n\t\t\tin w\n\t\twith | Not_found -> 0L\n\t\tin\n\t\tHashtbl.add table i (f c)\n\tin\n\tArray.iter (fun v ->\n\t\tupdate v (fun c -> c+1L)\n\t) ar;\n\t(* Hashtbl.iter (fun u v -> printf \"%Ld:%Ld; \" u v) table;\n\tprint_newline (); *)\n\tlet count = ref 0L in\n\tArray.iter (fun v -> \n\t\tlet f = ref false in\n\t\tArray.iter (fun a -> \n\t\t\tlet w = a - v\n\t\t\tin if (Hashtbl.mem table w && \n\t\t\t\tlet p = Hashtbl.find table w\n\t\t\t\tin (p >= 2L || (p = 1L && w <> v))\n\t\t\t) then (\n\t\t\t\t(* printf \"pair: %Ld,%Ld (remains %Ld)\\n\" v w (Hashtbl.find table w); *)\n\t\t\t\tf := true\n\t\t\t)\n\t\t) pows;\n\t\t(* update v (fun c -> c+=1L;!c); *)\n\t\tif not !f then count+=1L\n\t) ar;\n\tprint_i64_endline !count\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf\nlet input_i64_array n =\n\tArray.init n (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\nlet get_int () = Scanf.scanf \" %d\" (fun v -> v)\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nmodule Int64 = struct\n\tinclude Int64\n\tlet (+|) p q = Int64.add p q\n\tlet (-|) p q = Int64.sub p q\n\tlet ( *|) p q = Int64.mul p q\n\tlet (/|) p q = Int64.div p q\n\tlet (<|) p q = \n\t\tif Int64.compare p q < 0 then true \n\t\telse false\n\tlet (>|) p q = \n\t\tif Int64.compare p q > 0 then true\n\t\telse false\n\tlet (>=|) p q = not (p < q)\n\tlet (<=|) p q = not (p > q)\n\tlet labs p = if p <| 0L then -1L*|p else p\n let (~|) p = Int64.of_int p\nend\n\n\nlet () =\n let n = get_int ()\n in let ar = input_i64_array n\n in let pows = Array.make 31 0L\n in let open Int64\n in\n let table = Hashtbl.create 32\n in let rec f0 i a =\n if i<=30 then\n let v = a*|2L in\n pows.(i) <- v;\n f0 (i+1) v\n else ()\n in f0 0 1L;\n let len = Array.length ar\n in let checked = Array.make len false\n in\n for i=0 to len-1 do\n Array.iter (fun v -> \n let w = v -| ar.(i) in\n if w >=| 1L then (\n try\n let j = Hashtbl.find table w\n in\n (* printf \"(%d)+(%d)=%d+%d=%d\\n\"\n i j ar.(i) (v-ar.(i)) v\n ; *)\n checked.(i) <- true;\n checked.(j) <- true;\n with | Not_found -> ();\n Hashtbl.add table ar.(i) i\n )\n ) pows\n done;\n (* Hashtbl.iter (fun u v -> printf \"%d:%d; \" u v) table;\n print_newline (); *)\n Array.to_list checked\n |> List.filter (fun v -> not v)\n (* |> (fun l -> List.iter (fun v -> printf \"%b;\" v) l; print_endline \"\"; l) *)\n |> List.length\n |> print_int_endline\n\n\n"}, {"source_code": "open Printf\nlet input_i64_array n =\n\tArray.init n (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\nlet get_int () = Scanf.scanf \" %d\" (fun v -> v)\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nmodule Int64 = struct\n\tinclude Int64\n\tlet (+|) p q = Int64.add p q\n\tlet (-|) p q = Int64.sub p q\n\tlet ( *|) p q = Int64.mul p q\n\tlet (/|) p q = Int64.div p q\n\tlet (<|) p q = \n\t\tif Int64.compare p q < 0 then true \n\t\telse false\n\tlet (>|) p q = \n\t\tif Int64.compare p q > 0 then true\n\t\telse false\n\tlet (>=|) p q = not (p < q)\n\tlet (<=|) p q = not (p > q)\n\tlet labs p = if p <| 0L then -1L*|p else p\n let (~|) p = Int64.of_int p\nend\n\n\nlet () =\n let n = get_int ()\n in let ar = input_i64_array n\n in let pows = Array.make 31 0L\n in let open Int64\n in\n let table = Hashtbl.create 32\n in let rec f0 i a =\n if i<=30 then\n let v = a*|2L in\n pows.(i) <- v;\n f0 (i+1) v\n else ()\n in f0 0 1L;\n let len = Array.length ar\n in let checked = Array.make len false\n in\n for i=0 to len-1 do\n Array.iter (fun v -> \n let w = v -| ar.(i) in\n if w >=| 1L then (\n try\n let ls = Hashtbl.find table w\n in match ls with\n | [] -> raise Not_found\n | j::t -> (\n (* printf \"(%d)+(%d)=%d+%d=%d\\n\"\n i j ar.(i) (v-ar.(i)) v\n ; *)\n checked.(i) <- true;\n checked.(j) <- true;\n Hashtbl.add table w t;\n )\n with | Not_found -> ();\n try\n let ls = Hashtbl.find table ar.(i)\n in Hashtbl.add table ar.(i) (i::ls)\n with | Not_found -> (\n Hashtbl.add table ar.(i) [i]\n )\n )\n ) pows\n done;\n (* Hashtbl.iter (fun u v -> printf \"%d:%d; \" u v) table;\n print_newline (); *)\n Array.to_list checked\n |> List.filter (fun v -> not v)\n (* |> (fun l -> List.iter (fun v -> printf \"%b;\" v) l; print_endline \"\"; l) *)\n |> List.length\n |> print_int_endline"}, {"source_code": "open Printf\nlet input_i64_array n =\n\tArray.init n (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\nlet get_int () = Scanf.scanf \" %d\" (fun v -> v)\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nmodule Int64 = struct\n\tinclude Int64\n\tlet (+|) p q = Int64.add p q\n\tlet (-|) p q = Int64.sub p q\n\tlet ( *|) p q = Int64.mul p q\n\tlet (/|) p q = Int64.div p q\n\tlet (<|) p q = \n\t\tif Int64.compare p q < 0 then true \n\t\telse false\n\tlet (>|) p q = \n\t\tif Int64.compare p q > 0 then true\n\t\telse false\n\tlet (>=|) p q = not (p < q)\n\tlet (<=|) p q = not (p > q)\n\tlet labs p = if p <| 0L then -1L*|p else p\n let (~|) p = Int64.of_int p\nend\n\n\nlet () =\n let n = get_int ()\n in let ar = input_i64_array n\n in let pows = Array.make 31 0L\n in let open Int64\n in\n let table = Hashtbl.create 32\n in let rec f0 i a =\n if i<=30 then\n let v = a*2 in\n pows.(i) <- ~|v;\n f0 (i+1) v\n else ()\n in f0 0 1;\n let len = Array.length ar\n in let checked = Array.make len false\n in\n for i=0 to len-1 do\n Array.iter (fun v -> \n if v -| ar.(i)>=|1L then (\n try\n let j = Hashtbl.find table (v-|ar.(i))\n in\n (* printf \"(%d)+(%d)=%d+%d=%d\\n\"\n i j ar.(i) (v-ar.(i)) v\n ; *)\n checked.(i) <- true;\n checked.(j) <- true;\n with | Not_found -> ();\n Hashtbl.add table ar.(i) i\n )\n ) pows\n done;\n (* Hashtbl.iter (fun u v -> printf \"%d:%d; \" u v) table;\n print_newline (); *)\n Array.to_list checked\n |> List.filter (fun v -> not v)\n (* |> (fun l -> List.iter (fun v -> printf \"%b;\" v) l; print_endline \"\"; l) *)\n |> List.length\n |> print_int_endline"}, {"source_code": "open Printf\nlet input_int_array n =\n\tArray.init n (fun _ -> Scanf.scanf \" %d\" (fun v -> v))\nlet get_int () = Scanf.scanf \" %d\" (fun v -> v)\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nlet () =\n let n = get_int ()\n in let ar = input_int_array n\n in let pows = Array.make 31 0\n in\n let table = Hashtbl.create 32\n in let rec f0 i a =\n if i<=30 then\n let v = a*2 in\n pows.(i) <- v;\n f0 (i+1) v \n else ()\n in f0 0 1;\n let len = Array.length ar\n in let checked = Array.make len false\n in\n for i=0 to len-1 do\n Array.iter (fun v -> \n if v-ar.(i)>=1 then (\n try\n let j = Hashtbl.find table (v-ar.(i))\n in\n (* printf \"(%d)+(%d)=%d+%d=%d\\n\"\n i j ar.(i) (v-ar.(i)) v\n ; *)\n checked.(i) <- true;\n checked.(j) <- true;\n with | Not_found -> ();\n Hashtbl.add table ar.(i) i\n )\n ) pows\n done;\n (* Hashtbl.iter (fun u v -> printf \"%d:%d; \" u v) table;\n print_newline (); *)\n Array.to_list checked\n |> List.filter (fun v -> not v)\n (* |> (fun l -> List.iter (fun v -> printf \"%b;\" v) l; print_endline \"\"; l) *)\n |> List.length\n |> print_int_endline\n\n\n\n"}, {"source_code": "open Printf\nlet input_int_array n =\n\tArray.init n (fun _ -> Scanf.scanf \" %d\" (fun v -> v))\nlet get_int () = Scanf.scanf \" %d\" (fun v -> v)\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nlet () =\n let n = get_int ()\n in let ar = input_int_array n\n in let pows = Array.make 31 0\n in\n let rec f0 i a =\n if i<=30 then\n let v = a*2 in pows.(i)<-v; f0 (i+1) v \n else ()\n in f0 0 1;\n let len = Array.length ar\n in\n let checked = Array.make len false\n in\n for i=0 to len-1 do\n for j=i+1 to len-1 do\n (* if not (checked.(i) || checked.(j)) then *)\n let sum = ar.(i)+ar.(j)\n in let p = log (float_of_int sum) /. log 2. |> int_of_float\n in\n printf \"%d+%d=%d; p=%d; pows.(p)=%d; pows.(p+1)=%d\\n\" ar.(i) ar.(j) sum p pows.(p) pows.(p+1);\n if (p-1>=0 && pows.(p-1)=sum) || (p<=30 && pows.(p)=sum) then (\n checked.(i) <- true;\n checked.(j) <- true;\n )\n done\n done;\n Array.to_list checked\n |> List.filter (fun v -> not v)\n |> (fun l -> List.iter (fun v -> printf \"%b;\" v) l; print_endline \"\"; l)\n |> List.length\n |> print_int_endline"}], "src_uid": "ed308777f7122ca6279b522acd3e58f9"} {"nl": {"description": "One day Nikita found the string containing letters \"a\" and \"b\" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters \"a\" and the 2-nd contains only letters \"b\".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?", "input_spec": "The first line contains a non-empty string of length not greater than 5\u2009000 containing only lowercase English letters \"a\" and \"b\". ", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible size of beautiful string Nikita can get.", "sample_inputs": ["abba", "bab"], "sample_outputs": ["4", "2"], "notes": "NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of \"b\" to make it beautiful."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n\tlet s = read_string () \n\tand wyn = ref 0 in\n\tlet n = String.length s in\n\n\tlet a = Array.make (n + 1) 0 \n\tand b = Array.make (n + 1) 0 in\n\n\tfor i = 1 to n do \n\t\ta.(i) <- a.(i - 1);\n\t\tb.(i) <- b.(i - 1);\n\n\t\tif s.[i - 1] = 'a' then \n\t\t\ta.(i) <- a.(i) + 1\n\t\telse \n\t\t\tb.(i) <- b.(i) + 1\n\tdone;\n\n\tfor i = 0 to n do \n\t\tfor j = i + 1 to n do \n\t\t\tlet bb = b.(i) + b.(n) - b.(j)\n\t\t\tand aa = a.(j) - a.(i) in\n\n\t\t\twyn := max !wyn (n - bb - aa);\n\t\tdone;\n\tdone;\n\n\tfor i = 1 to n do \n\t\tlet aa = a.(n) - a.(i) \n\t\tand bb = b.(i) in\n\t\twyn := max !wyn (n - aa - bb);\n\tdone;\n\n\tprintf \"%d\\n\" !wyn;;"}, {"source_code": "open Printf\nopen Scanf\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () =\n let s = read_string () in\n let n = String.length s in\n let pref = Array.make n 0\n and cntA = ref 0\n and ans = ref 0 in\n for i = 0 to n - 1 do\n pref.(i) <- pref.(max 0 (i - 1)) + (if s.[i] = 'a' then 1 else 0);\n cntA := !cntA + (if s.[i] = 'a' then 1 else 0)\n done;\n let left = ref 0 in\n for i = 0 to n - 1 do\n let curA = ref 0 \n and curB = ref 0 in\n for j = i to n - 1 do\n curA := !curA + (if s.[j] = 'a' then 1 else 0);\n curB := !curB + (if s.[j] = 'b' then 1 else 0);\n let right = !cntA - !left - !curA in\n ans := max !ans (!left + !curB + right)\n done;\n left := !left + (if s.[i] = 'a' then 1 else 0)\n done;\n printf \"%d\\n\" (max !left !ans)"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n\tlet s = read_string () \n\tand wyn = ref 0 in\n\tlet n = String.length s in\n\n\tlet a = Array.make (n + 1) 0 \n\tand b = Array.make (n + 1) 0 in\n\n\tfor i = 1 to n do \n\t\ta.(i) <- a.(i - 1);\n\t\tb.(i) <- b.(i - 1);\n\n\t\tif s.[i - 1] = 'a' then \n\t\t\ta.(i) <- a.(i) + 1\n\t\telse \n\t\t\tb.(i) <- b.(i) + 1\n\tdone;\n\n\tfor i = 0 to n do \n\t\tfor j = i + 1 to n do \n\t\t\tlet bb = b.(i) + b.(n) - b.(j)\n\t\t\tand aa = a.(j) - a.(i) in\n\n\t\t\twyn := max !wyn (n - bb - aa);\n\t\tdone;\n\tdone;\n\n\t\n\n\tprintf \"%d\\n\" !wyn;;"}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n\tlet s = read_string () \n\tand wyn = ref 0 in\n\tlet n = String.length s in\n\n\tlet a = Array.make (n + 1) 0 \n\tand b = Array.make (n + 1) 0 in\n\n\tfor i = 1 to n do \n\t\ta.(i) <- a.(i - 1);\n\t\tb.(i) <- b.(i - 1);\n\n\t\tif s.[i - 1] = 'a' then \n\t\t\ta.(i) <- a.(i) + 1\n\t\telse \n\t\t\tb.(i) <- b.(i) + 1\n\tdone;\n\n\tfor i = 1 to n do \n\t\tfor j = i + 1 to n do \n\t\t\tlet bb = b.(i) + b.(n) - b.(j)\n\t\t\tand aa = a.(j) - a.(i) in\n\n\t\t\twyn := max !wyn (n - bb - aa);\n\t\tdone;\n\tdone;\n\n\tprintf \"%d\\n\" !wyn;;"}, {"source_code": "open Printf\nopen Scanf\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () =\n let s = read_string () in\n let n = String.length s in\n let pref = Array.make n 0\n and cntA = ref 0\n and ans = ref 0 in\n for i = 0 to n - 1 do\n pref.(i) <- pref.(max 0 (i - 1)) + (if s.[i] = 'a' then 1 else 0);\n cntA := !cntA + (if s.[i] = 'a' then 1 else 0)\n done;\n let left = ref 0 in\n for i = 0 to n - 1 do\n let curA = ref 0 \n and curB = ref 0 in\n for j = i to n - 1 do\n curA := !curA + (if s.[j] = 'a' then 1 else 0);\n curB := !curB + (if s.[j] = 'b' then 1 else 0);\n let right = !cntA - !left - !curA in\n ans := max !ans (!left + !curB + right)\n done;\n left := !left + (if s.[i] = 'a' then 1 else 0)\n done;\n printf \"%d\\n\" !ans"}], "src_uid": "c768f3e52e562ae1fd47502a60dbadfe"} {"nl": {"description": "This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions: Only segments already presented on the picture can be painted; The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment; The numbers of points from the beginning of the tail to the end should strictly increase. Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.", "input_spec": "First line of the input contains two integers n and m(2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of points and the number segments on the picture respectively. Then follow m lines, each containing two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi)\u00a0\u2014 the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.", "output_spec": "Print the maximum possible value of the hedgehog's beauty.", "sample_inputs": ["8 6\n4 5\n3 5\n2 5\n1 2\n2 8\n6 7", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4"], "sample_outputs": ["9", "12"], "notes": "NoteThe picture below corresponds to the first sample. Segments that form the hedgehog are painted red. The tail consists of a sequence of points with numbers 1, 2 and 5. The following segments are spines: (2, 5), (3, 5) and (4, 5). Therefore, the beauty of the hedgehog is equal to 3\u00b73\u2009=\u20099."}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet rec loop n tab =\n if n >= 0 then\n let x = read n in\n tab.(x) <- true;\n loop (n-1) tab\n else ();;\n\nlet ( *| ) = Int64.mul;;\n\nlet _ = \n let (n, m) = read2 () in\n let g = Array.make (n+1) []\n and tab = Array.make (n+1) 1\n and wynik = ref Int64.zero in\n for i=1 to m do\n let (a,b) = read2 () in\n g.(a) <- b::g.(a);\n g.(b) <- a::g.(b)\n done;\n for i=1 to n do\n List.iter (fun x -> if x < i then tab.(i) <- max tab.(i) (tab.(x)+1) ) g.(i);\n if compare !wynik ( ( Int64.of_int tab.(i) ) *| ( Int64.of_int ( List.length g.(i) ) ) ) < 0 then\n wynik := ( ( Int64.of_int tab.(i) ) *| ( Int64.of_int ( List.length g.(i) ) ) ) ;\n done;\n Printf.printf \"%Ld\\n\" !wynik;;\n\n\n"}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n\tlet n = read_int ()\n\tand m = read_int () \n\tand wyn = ref 0L in\n\n\tlet g = Array.make (n + 1) []\n\tand dlugosc = Array.make (n + 1) 1L in\n\n\tfor i = 1 to m do \n\t\tlet a = read_int ()\n\t\tand b = read_int () in\n\n\t\tg.(a) <- b::g.(a);\n\t\tg.(b) <- a::g.(b);\n\tdone;\n\n\tfor i = 1 to n do \n\t\tlet s = Int64.of_int (List.length g.(i)) in\n\n\t\tList.iter (fun x -> if x < i then dlugosc.(i) <- max dlugosc.(i) (Int64.add dlugosc.(x) 1L);) g.(i);\n\n\t\twyn := max !wyn (Int64.mul dlugosc.(i) s)\n\tdone;\n\n\tprintf \"%Ld\\n\" !wyn;;"}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet long x = Int64.of_int x\nlet ( ++ ) a b = Int64.add a b\nlet ( ** ) a b = Int64.mul a b\n\nlet () =\n let n = read_int () and m = read_int () in\n let g = Array.make (n + 1) []\n and dp = Array.make (n + 1) 0L\n and ans = ref 0L in\n for i = 1 to m do\n let a = read_int () and b = read_int () in\n g.(a) <- b::g.(a);\n g.(b) <- a::g.(b)\n done;\n for i = 1 to n do\n dp.(i) <- max 1L (List.fold_left (fun acc x -> if x < i then max acc (dp.(x) ++ 1L) else acc) 0L g.(i));\n ans := max !ans (dp.(i) ** long ((List.length g.(i))))\n done;\n printf \"%Ld\\n\" !ans"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n\n let g = Array.make n [] in\n\n let add_edge (i,j) =\n g.(i) <- j::g.(i);\n g.(j) <- i::g.(j)\n in\n let d = Array.make n 0 in\n \n for i = 0 to m-1 do\n let u = -1+read_int() in\n let v = -1+read_int() in\n d.(u) <- d.(u) + 1;\n d.(v) <- d.(v) + 1; \n add_edge (u,v)\n done;\n\n let l = Array.make n 1 in\n\n for u = 0 to n-1 do\n l.(u) <- List.fold_left (fun ac v -> if u > v then max ac (1+l.(v)) else ac) 1 g.(u)\n done;\n\n let answer = maxf 0 (n-1) (fun v -> (long (l.(v))) ** (long d.(v))) in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet rec loop n tab =\n if n >= 0 then\n let x = read n in\n tab.(x) <- true;\n loop (n-1) tab\n else ();;\n\nlet _ = \n let (n, m) = read2 () in\n let g = Array.make (n+1) []\n and tab = Array.make (n+1) 1\n and wynik = ref 0 in\n for i=1 to m do\n let (a,b) = read2 () in\n g.(a) <- b::g.(a);\n g.(b) <- a::g.(b)\n done;\n for i=1 to n do\n List.iter (fun x -> if x < i then tab.(i) <- max tab.(i) (tab.(x)+1) ) g.(i);\n wynik := max !wynik ( tab.(i) * ( List.length g.(i) ) )\n done;\n Printf.printf \"%d\\n\" !wynik;;\n\n\n"}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n\tlet n = read_int ()\n\tand m = read_int () \n\tand wyn = ref 0 in\n\n\tlet g = Array.make (n + 1) []\n\tand dlugosc = Array.make (n + 1) 1 in\n\n\tfor i = 1 to m do \n\t\tlet a = read_int ()\n\t\tand b = read_int () in\n\n\t\tg.(a) <- b::g.(a);\n\t\tg.(b) <- a::g.(b);\n\tdone;\n\n\tfor i = 1 to n do \n\t\tlet s = List.length g.(i) in\n\n\t\tList.iter (fun x -> if x < i then dlugosc.(i) <- max dlugosc.(i) (dlugosc.(x) + 1);) g.(i);\n\n\t\twyn := max !wyn (dlugosc.(i) * s)\n\tdone;\n\n\tprintf \"%d\\n\" !wyn;;"}], "src_uid": "2596db1dfc124ea9e14c3f13c389c8d2"} {"nl": {"description": "Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i\u2009+\u20091, i\u2009+\u20092, i\u2009+\u20093 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i\u2009=\u2009n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on. For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i\u2009=\u20093, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4,\u20091,\u20092,\u20093,\u20094. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x \u2014 the number of the box, where he put the last of the taken out balls.He asks you to help to find the initial arrangement of the balls in the boxes.", "input_spec": "The first line of the input contains two integers n and x (2\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009x\u2009\u2264\u2009n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an, where integer ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009109, ax\u2009\u2260\u20090) represents the number of balls in the box with index i after Vasya completes all the actions. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.", "sample_inputs": ["4 4\n4 3 1 6", "5 2\n3 2 0 2 7", "3 3\n2 3 1"], "sample_outputs": ["3 2 5 4", "2 1 4 1 6", "1 2 3"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 260C KorobkiBalls *)\n\nopen String;;\nopen Array;;\nopen Int64;;\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet printarri64 ai = Array.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) ai;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec readarray i n ar =\n\tif i < n then begin\n\t\tar.(i) <- (Int64.of_int (gr())); \n\t\treadarray (i +1) n ar\n\tend;;\n\nlet debug = false;;\n\nlet n = gr();;\nlet last = gr();;\nlet an = Array.make n Int64.zero;;\n\nlet rec step i cnt =\n\tif an.(i) = Int64.zero then an.(i) <- cnt\n\telse begin\n\t\tan.(i) <- Int64.pred an.(i);\n\t\tlet ii = if i =0 then n -1 else i -1 in\n\t\tstep ii (Int64.succ cnt)\n\tend;;\n\nlet rec find_min i mn = \n\tif i = n then mn\n\telse let mini = if an.(i) < mn then an.(i) else mn in\n\tfind_min (i+1) mini;;\n\nlet rec substract_min i mn = \n\tif i = n then ()\n\telse begin\n\t\tan.(i) <- Int64.sub an.(i) mn;\n\t\tsubstract_min (i+1) mn\n end;;\n\nlet main () = begin\n\t\treadarray 0 n an;\n(*\t\tprint_int n; print_string \" \";\n\t\tprint_int last; print_string \" \";*)\n\t\tlet mini = Int64.pred (find_min 0 an.(0)) in\n\t\tbegin\n\t\t substract_min 0 mini;\n\t\t\tlet cnt = Int64.mul (Int64.of_int n) mini in\n\t\t\tstep (last -1) cnt\n\t\tend;\n\t\tprintarri64 an;\n\t\tprint_newline()\n\tend;;\n\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) ;;\n\nlet n = read_int () ;;\nlet x = read_int () ;;\n\nlet a = \n let rec loop i f = \n if i = n then f []\n else \n let ai = read_int () \n in loop (i + 1) (fun l -> f ((Int64.of_int ai) :: l))\n in loop 0 (fun x -> x) ;;\n\nlet split_list l n =\n let rec loop i f = function\n | [] -> (f [], [])\n | h :: t ->\n if i = n then (f [h], t)\n else loop (i + 1) (fun tl -> f (h :: tl)) t\n in loop 1 (fun x -> x) l ;;\n\nlet left, right = split_list a x ;;\n\n(* Get the index and value of the smallest element from the right of a list *)\nlet get_right_min l =\n let f = fun (i, (index, value)) a -> \n if a <= value then (i + 1, (i, a)) else (i + 1, (index, value))\n in let i, (index, value) = List.fold_left f (0, (0, Int64.max_int)) l\n in index, value ;;\n\n(* Determine which box was selected in the beginning with 0-based index *)\nlet start, value =\n let (ind1, val1), (ind2, val2) = (get_right_min left), (get_right_min right)\n in if val1 <= val2 then (ind1, val1) else (ind2 + x, val2) ;;\n\nlet original =\n (* \n Make sure to remove the leftover balls between (start, x - 1]. If \n start >= x then remove a ball between [0, x - 1] U (start, n). y\n represents the leftover balls.\n *)\n let y = if start >= x then x + n - start - 1 else x - start - 1\n in List.mapi \n (fun i ai -> \n if i = start then \n Int64.add (Int64.mul (Int64.of_int n) value) (Int64.of_int y)\n else \n if start < x && i > start && i < x || \n start >= x && (i >= 0 && i < x || i > start && i < n) then\n Int64.sub ai (Int64.add value Int64.one)\n else Int64.sub ai value)\n a ;; \n \nlet rec print_list = function \n | [] -> ()\n | h :: t -> Printf.printf \"%Ld \" h; print_list t\nin print_list original; Printf.printf \"\\n\" ;; "}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\n\nlet () = \n let n = read_int() in\n let x = read_int() in\n let x = x-1 in\n\n let a = Array.make n 0 in\n\n for i=0 to n-1 do\n a.(i) <- read_int()\n done;\n\n let b = Array.copy a in\n\n let rec scan i count besti = if count = n then besti else \n scan ((i-1+n) mod n) (count+1) (if a.(i) < a.(besti) then i else besti) \n in\n\n let besti = scan x 0 x in\n\n let rec sublast i = if i = besti then () else (\n a.(i) <- a.(i) - 1;\n sublast ((i-1+n) mod n)\n )\n in\n\n let () = sublast x in\n\n let diff = sum 0 (n-1) (fun i -> b.(i) - a.(i)) in\n\n let repeat = a.(besti) in\n \n let pile = (Int64.of_int diff) ++ (Int64.of_int repeat) ** (Int64.of_int n) in\n\n for i=0 to n-1 do\n\tif i = besti then Printf.printf \"%Ld \" pile\n\telse Printf.printf \"%d \" (a.(i) - repeat)\n done;\n \n print_newline()\n"}], "negative_code": [{"source_code": "(* Codeforces 260C KorobkiBalls *)\n\nopen String;;\nopen Array;;\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet rec readarray i n ar =\n\tif i < n then begin\n\t\tar.(i) <- gr(); readarray (i +1) n ar\n\tend;;\n\nlet debug = false;;\n\nlet n = gr();;\nlet last = gr();;\nlet an = Array.make n 0;;\n\nlet rec step i cnt =\n\tif an.(i) = 0 then an.(i) <- cnt\n\telse begin\n\t\tan.(i) <- an.(i) - 1;\n\t\tlet ii = if i =0 then n -1 else i -1 in\n\t\tstep ii (cnt +1)\n\tend;;\n\nlet rec find_min i mn = \n\tif i = n then mn\n\telse let mini = if an.(i) < mn then an.(i) else mn in\n\tfind_min (i+1) mini;;\n\nlet rec substract_min i mn = \n\tif i = n then ()\n\telse begin\n\t\tan.(i) <- an.(i) - mn;\n\t\tsubstract_min (i+1) mn\n end;;\n\nlet main () = begin\n\t\treadarray 0 n an;\n(*\t\tprint_int n; print_string \" \";\n\t\tprint_int last; print_string \" \";*)\n\t\tlet mini = (find_min 0 an.(0) - 1) in\n\t\tbegin\n\t\t substract_min 0 mini;\n\t\t\tlet cnt = n *mini in\n\t\t\tstep (last -1) cnt\n\t\tend;\n\t\tprintarri an;\n\t\tprint_newline()\n\tend;;\n\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let n = read_int() in\n let x = read_int() in\n let x = x-1 in\n\n let a = Array.make n 0 in\n\n for i=0 to n-1 do\n a.(i) <- read_int()\n done;\n\n let b = Array.copy a in\n\n let rec scan i count besti = if count = n then besti else \n scan ((i-1+n) mod n) (count+1) (if a.(i) < a.(besti) then i else besti) \n in\n\n let besti = scan x 0 x in\n\n let rec sublast i = if i = besti then () else (\n a.(i) <- a.(i) - 1;\n sublast ((i-1+n) mod n)\n )\n in\n\n let () = sublast x in\n\n let diff = sum 0 (n-1) (fun i -> b.(i) - a.(i)) in\n\n let repeat = a.(besti) in\n \n let pile = diff + repeat * n in\n\n for i=0 to n-1 do\n\tlet ans = if i = besti then pile else a.(i) - repeat in\n\t Printf.printf \"%d \" ans\n done;\n \n print_newline()\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let n = read_int() in\n let x = read_int() in\n let x = x-1 in\n\n let a = Array.make n 0 in\n\n for i=0 to n-1 do\n a.(i) <- read_int()\n done;\n\n let b = Array.copy a in\n\n let rec scan i count besti = if count = n then besti else \n scan ((i-1+n) mod n) (count+1) (if a.(i) < a.(besti) then i else besti) \n in\n\n let besti = scan x 0 x in\n\n(* Printf.printf \"besti= %d\\n\" besti; *)\n\n let rec sublast i = \n a.(i) <- a.(i) - 1;\n if i = besti then () else sublast ((i-1+n) mod n)\n in\n\n let () = sublast x in\n(*\n for i=0 to n-1 do\n\tPrintf.printf \"a.(%d) = %d\\n\" i a.(i)\n done;\n*)\n let diff = sum 0 (n-1) (fun i -> b.(i) - a.(i)) in\n\n(* Printf.printf \"diff = %d\\n\" diff; *)\n\n let repeat = a.(besti)+1 in\n\n(* Printf.printf \"repeat = %d\\n\" repeat; *)\n \n let pile = diff + repeat * n -1 in\n\n for i=0 to n-1 do\n\tlet ans = if i = besti then pile else a.(i) - repeat in\n\t Printf.printf \"%d \" ans\n done;\n \n print_newline()\n"}], "src_uid": "7d4899d03a804ed1bdd77a475169a580"} {"nl": {"description": "\u00abPolygon\u00bb is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000) \u2014 the amount of previously added tests. The second line contains n distinct integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20093000) \u2014 indexes of these tests.", "output_spec": "Output the required default value for the next test index.", "sample_inputs": ["3\n1 7 2"], "sample_outputs": ["3"], "notes": null}, "positive_code": [{"source_code": "let t = read_int() in\nlet arr = Array.append [|0|] (Array.map int_of_string (\n\tArray.of_list (Str.split (Str.regexp \" \") (read_line()))\n)) in\nlet _ = Array.sort compare arr in\n\tfor i = 0 to t do\n\t\ttry\n\t\tif arr.(i) + 1 <> arr.(i+1) then (print_int (arr.(i) + 1); exit 0)\n\t\twith _ -> (print_int (arr.(i) + 1); exit 0)\n\tdone;;\n"}], "negative_code": [{"source_code": "let t = read_int() in\nlet arr = Array.map int_of_string (Array.of_list (Str.split (Str.regexp \" \") (read_line()))) in\nlet _ = Array.sort compare arr in\n\tfor i = 0 to t-1 do \n\t\ttry\n\t\tif arr.(i) + 1 <> arr.(i+1) then (print_int (arr.(i) + 1); exit 0)\n\t\twith _ -> (print_int (arr.(i) + 1); exit 0)\n\tdone;;\n\n"}, {"source_code": "let t = read_int() in\nlet arr = Array.append [|0|] (Array.map int_of_string (\n\tArray.of_list (Str.split (Str.regexp \" \") (read_line()))\n)) in\nlet _ = Array.sort compare arr in\n\tfor i = 0 to t-1 do\n\t\ttry\n\t\tif arr.(i) + 1 <> arr.(i+1) then (print_int (arr.(i) + 1); exit 0)\n\t\twith _ -> (print_int (arr.(i) + 1); exit 0)\n\tdone;;\n\n"}], "src_uid": "5e449867d9fcecc84333b81eac9b5d92"} {"nl": {"description": "Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $$$1$$$. If he manages to finish the level successfully then the number of clears increases by $$$1$$$ as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.So he peeked at the stats $$$n$$$ times and wrote down $$$n$$$ pairs of integers \u2014 $$$(p_1, c_1), (p_2, c_2), \\dots, (p_n, c_n)$$$, where $$$p_i$$$ is the number of plays at the $$$i$$$-th moment of time and $$$c_i$$$ is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.Help him to check the correctness of his records.For your convenience you have to answer multiple independent test cases.", "input_spec": "The first line contains a single integer $$$T$$$ $$$(1 \\le T \\le 500)$$$ \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of moments of time Polycarp peeked at the stats. Each of the next $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \\le p_i, c_i \\le 1000$$$) \u2014 the number of plays and the number of clears of the level at the $$$i$$$-th moment of time. Note that the stats are given in chronological order.", "output_spec": "For each test case print a single line. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print \"YES\". Otherwise, print \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["6\n3\n0 0\n1 1\n1 2\n2\n1 0\n1000 3\n4\n10 1\n15 2\n10 2\n15 2\n1\n765 432\n2\n4 4\n4 3\n5\n0 0\n1 0\n1 0\n1 0\n1 0"], "sample_outputs": ["NO\nYES\nNO\nYES\nNO\nYES"], "notes": "NoteIn the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.The second test case is a nice example of a Super Expert level.In the third test case the number of plays decreased, which is impossible.The fourth test case is probably an auto level with a single jump over the spike.In the fifth test case the number of clears decreased, which is also impossible.Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_int_pair () = let x = scan_int() in let y = scan_int() in (x,y);;\nlet show_string s = print_string s;;\n\nlet t = scan_int ();;\nfor x = 1 to t do\n\tlet n = scan_int () in\n\tlet player = ref 0 in\n\tlet clear = ref 0 in\n\tlet test = ref true in\n\tfor i = 0 to n-1 do\n\t\tlet p, c = scan_int_pair () in\n\t\tif !player > p || !clear > c || (p - !player) < (c - !clear) then\n\t\t\ttest := false;\n\t\tplayer := p; clear := c\n\tdone;\n\tif !test then show_string \"YES\\n\" else show_string \"NO\\n\"\ndone;;"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let n = read_int() in\n let stats = Array.init n read_pair in\n let a2 = forall 0 (n-2) (fun i ->\n let (pi,ci) = stats.(i) in\n let (pi',ci') = stats.(i+1) in\n pi <= pi' && ci <= ci' &&\t(pi' - pi) >= (ci' - ci)\n ) in\n let a1 = forall 0 (n-1) (fun i -> let (pi,ci) = stats.(i) in ci <= pi) in\n if a1 && a2 then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let n = read_int() in\n let stats = Array.init n read_pair in\n let answer = forall 0 (n-2) (fun i ->\n let (pi,ci) = stats.(i) in\n let (pi',ci') = stats.(i+1) in\n pi <= pi' && ci <= ci' && ci <= pi && ci' <= pi' &&\n\t(pi' - pi) >= (ci' - ci')\n ) in\n if answer then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let n = read_int() in\n let stats = Array.init n read_pair in\n let answer = forall 0 (n-2) (fun i ->\n let (pi,ci) = stats.(i) in\n let (pi',ci') = stats.(i+1) in\n pi <= pi' && ci <= ci' && ci <= pi && ci' <= pi'\n ) in\n if answer then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let n = read_int() in\n let stats = Array.init n read_pair in\n let answer = forall 0 (n-2) (fun i ->\n let (pi,ci) = stats.(i) in\n let (pi',ci') = stats.(i+1) in\n pi <= pi' && ci <= ci' && ci <= pi && ci' <= pi' &&\n\t(pi' - pi) >= (ci' - ci)\n ) in\n if answer then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}], "src_uid": "714834defd0390659f6ed5bc3024f613"} {"nl": {"description": "You are given two integers $$$x$$$ and $$$y$$$. You can perform two types of operations: Pay $$$a$$$ dollars and increase or decrease any of these integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are four possible outcomes after this operation: $$$x = 0$$$, $$$y = 6$$$; $$$x = 0$$$, $$$y = 8$$$; $$$x = -1$$$, $$$y = 7$$$; $$$x = 1$$$, $$$y = 7$$$. Pay $$$b$$$ dollars and increase or decrease both integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are two possible outcomes after this operation: $$$x = -1$$$, $$$y = 6$$$; $$$x = 1$$$, $$$y = 8$$$. Your goal is to make both given integers equal zero simultaneously, i.e. $$$x = y = 0$$$. There are no other requirements. In particular, it is possible to move from $$$x=1$$$, $$$y=0$$$ to $$$x=y=0$$$.Calculate the minimum amount of dollars you have to spend on it.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of testcases. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \\le x, y \\le 10^9$$$). The second line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case print one integer\u00a0\u2014 the minimum amount of dollars you have to spend.", "sample_inputs": ["2\n1 3\n391 555\n0 0\n9 4"], "sample_outputs": ["1337\n0"], "notes": "NoteIn the first test case you can perform the following sequence of operations: first, second, first. This way you spend $$$391 + 555 + 391 = 1337$$$ dollars.In the second test case both integers are equal to zero initially, so you dont' have to spend money."}, "positive_code": [{"source_code": "let nbTests = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet delta x y = Int64.abs (Int64.sub x y);;\n\nfor i=1 to nbTests\ndo\n let x = Int64.of_int(Scanf.scanf \" %d\" (fun x -> x)) in\n let y = Int64.of_int(Scanf.scanf \" %d\" (fun x -> x)) in\n let a = Int64.of_int(Scanf.scanf \" %d\" (fun x -> x)) in\n let b = min (Int64.mul 2L a) (Int64.of_int (Scanf.scanf \" %d\" (fun x -> x))) in\n \n let enleve = Int64.add (max 0L (min x y)) (min 0L (max x y)) in\n \n let ans = 0L in\n let ans = Int64.add ans (Int64.mul b (delta enleve 0L)) in\n let ans = Int64.add ans (Int64.mul a (delta x enleve)) in\n let ans = Int64.add ans (Int64.mul a (delta y enleve)) in\n \n print_string (Int64.to_string ans);\n print_newline ()\ndone;;"}], "negative_code": [{"source_code": "let nbTests = Scanf.scanf \" %d\" (fun x -> x);;\n\nfor i=1 to nbTests\ndo\n let x = Scanf.scanf \" %d\" (fun x -> x) in\n let y = Scanf.scanf \" %d\" (fun x -> x) in\n let a = Scanf.scanf \" %d\" (fun x -> x) in\n let b = min (2 * a) (Scanf.scanf \" %d\" (fun x -> x)) in\n \n let enleve = (max 0 (min x y)) + (min 0 (max x y)) in\n \n print_int (b * (abs enleve) + a * abs(x - enleve) + a * abs(y - enleve));\n print_newline ()\ndone;;"}], "src_uid": "edf394051c6b35f593abd4c34b091eae"} {"nl": {"description": "Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai \u2009\u2264\u2009 bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!", "input_spec": "The first line of the input contains one integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 number of cola cans. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 volume of remaining cola in cans. The third line contains n space-separated integers that b1,\u2009b2,\u2009...,\u2009bn (ai\u2009\u2264\u2009bi\u2009\u2264\u2009109) \u2014 capacities of the cans.", "output_spec": "Print \"YES\" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print \"NO\" (without quotes). You can print each letter in any case (upper or lower).", "sample_inputs": ["2\n3 5\n3 6", "3\n6 8 9\n6 10 12", "5\n0 0 5 0 0\n1 1 8 10 5", "4\n4 1 0 3\n5 2 2 3"], "sample_outputs": ["YES", "NO", "YES", "YES"], "notes": "NoteIn the first sample, there are already 2 cans, so the answer is \"YES\"."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i) \n\nlet read_long _ = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () = \n let n = read_long () |> short in\n let can = Array.init n (fun i -> (read_long(), 0L)) in\n\n for i=0 to n-1 do\n can.(i) <- (fst can.(i), read_long())\n done;\n\n let total = sum 0 (n-1) (fun i -> fst can.(i)) in\n\n Array.sort (fun a b -> - compare (snd a) (snd b)) can;\n\n let canvol = (snd can.(0)) ++ (snd can.(1)) in\n\n if total <= canvol then printf \"YES\\n\" else printf \"NO\\n\"\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i) \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let can = Array.init n (fun i -> (read_int(), 0)) in\n\n for i=0 to n-1 do\n can.(i) <- (fst can.(i), read_int())\n done;\n\n let total = sum 0 (n-1) (fun i -> fst can.(i)) in\n\n Array.sort (fun a b -> - compare (snd a) (snd b)) can;\n\n let canvol = (snd can.(0)) + (snd can.(1)) in\n\n if total <= canvol then printf \"YES\\n\" else printf \"NO\\n\"\n"}], "src_uid": "88390110e4955c521867864a6f3042a0"} {"nl": {"description": "This is an interactive problem.Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.Let's define $$$x$$$ as the distance to Mars. Unfortunately, Natasha does not know $$$x$$$. But it is known that $$$1 \\le x \\le m$$$, where Natasha knows the number $$$m$$$. Besides, $$$x$$$ and $$$m$$$ are positive integers.Natasha can ask the rocket questions. Every question is an integer $$$y$$$ ($$$1 \\le y \\le m$$$). The correct answer to the question is $$$-1$$$, if $$$x<y$$$, $$$0$$$, if $$$x=y$$$, and $$$1$$$, if $$$x>y$$$. But the rocket is broken\u00a0\u2014 it does not always answer correctly. Precisely: let the correct answer to the current question be equal to $$$t$$$, then, if the rocket answers this question correctly, then it will answer $$$t$$$, otherwise it will answer $$$-t$$$.In addition, the rocket has a sequence $$$p$$$ of length $$$n$$$. Each element of the sequence is either $$$0$$$ or $$$1$$$. The rocket processes this sequence in the cyclic order, that is $$$1$$$-st element, $$$2$$$-nd, $$$3$$$-rd, $$$\\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$\\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$\\ldots$$$. If the current element is $$$1$$$, the rocket answers correctly, if $$$0$$$\u00a0\u2014 lies. Natasha doesn't know the sequence $$$p$$$, but she knows its length\u00a0\u2014 $$$n$$$.You can ask the rocket no more than $$$60$$$ questions.Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.Your solution will not be accepted, if it does not receive an answer $$$0$$$ from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).", "input_spec": "The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \\le m \\le 10^9$$$, $$$1 \\le n \\le 30$$$)\u00a0\u2014 the maximum distance to Mars and the number of elements in the sequence $$$p$$$.", "output_spec": null, "sample_inputs": ["5 2\n1\n-1\n-1\n1\n0"], "sample_outputs": ["1\n2\n4\n5\n3"], "notes": "NoteIn the example, hacking would look like this:5 2 31 0This means that the current distance to Mars is equal to $$$3$$$, Natasha knows that it does not exceed $$$5$$$, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...Really:on the first query ($$$1$$$) the correct answer is $$$1$$$, the rocket answered correctly: $$$1$$$;on the second query ($$$2$$$) the correct answer is $$$1$$$, the rocket answered incorrectly: $$$-1$$$;on the third query ($$$4$$$) the correct answer is $$$-1$$$, the rocket answered correctly: $$$-1$$$;on the fourth query ($$$5$$$) the correct answer is $$$-1$$$, the rocket answered incorrectly: $$$1$$$;on the fifth query ($$$3$$$) the correct and incorrect answer is $$$0$$$."}, "positive_code": [{"source_code": "\nmodule MInt32 = struct\n let (+) = Int32.add\n let (-) = Int32.sub\n let ( * ) = Int32.mul\n let (/) = Int32.div\n let to_int = Int32.to_int\n let of_int = Int32.of_int\nend\n\ntype ('a, 'b) result =\n | Left of 'a\n | Right of 'b\n\nlet int_bisearch_first_satisfying\n (callback: int -> bool) ((l, r): int * int): int option =\n let rec f l r =\n if l = r then if callback l then Some l else None\n else\n let m = MInt32.(to_int ((of_int l + of_int r) / 2l)) in\n if callback m then f l m else f (m + 1) r\n in f l r\n \nlet print_read (n: int): int =\n n |> string_of_int |> print_endline; flush stdout;\n Scanf.scanf \" %d\" (fun x -> x)\n \nlet determine_p (n: int): (int, bool array) result =\n let ret = Array.make n false in\n let rec f i =\n if i = n then false\n else (\n let t = print_read 1 in\n if t = 0 then true else (ret.(i) <- t = 1; f (i + 1))\n )\n in if f 0 then Left 1 else Right ret\n\nexception Found\n\nlet _ =\n (* m - max. distance *) (* n - #p *)\n let m, n = Scanf.scanf \" %d %d\" (fun x y -> x, y) in\n match determine_p n with\n | Left i -> ()\n | Right p ->\n try\n (* ATTENTION: use a counter *)\n let i = ref (-1) in\n let f x =\n i := !i + 1;\n match abs (print_read x + if p.(!i mod n) then 1 else -1) with\n | 0 -> true | 2 -> false | _ -> raise Found\n in int_bisearch_first_satisfying f (0, m) |> ignore\n with Found -> ()\n"}], "negative_code": [{"source_code": "\ntype ('a, 'b) result =\n | Left of 'a\n | Right of 'b\n\nlet int_bisearch_first_satisfying\n (callback: int -> bool) ((l, r): int * int): int option =\n let rec f l r =\n if l = r then if callback l then Some l else None\n else let m = (l + r) / 2 in if callback m then f l m else f (m + 1) r\n in f l r\n \nlet print_read (n: int): int =\n n |> string_of_int |> print_endline; flush stdout;\n Scanf.scanf \" %d\" (fun x -> x)\n \nlet determine_p (n: int): (int, bool array) result =\n let ret = Array.make n false in\n let rec f i =\n if i = n then false\n else (\n let t = print_read 1 in\n if t = 0 then true else (ret.(i) <- t = 1; f (i + 1))\n )\n in if f 0 then Left 1 else Right ret\n\nexception Found\n\nlet _ =\n (* m - max. distance *) (* n - #p *)\n let m, n = Scanf.scanf \" %d %d\" (fun x y -> x, y) in\n match determine_p n with\n | Left i -> ()\n | Right p ->\n try\n (* ATTENTION: use a counter *)\n let i = ref (-1) in\n let f x =\n i := !i + 1;\n match abs (print_read x + if p.(!i mod n) then 1 else -1) with\n | 0 -> true | 2 -> false | _ -> raise Found\n in int_bisearch_first_satisfying f (0, m) |> ignore\n with Found -> ()\n"}, {"source_code": "\ntype ('a, 'b) result =\n | Left of 'a\n | Right of 'b\n\nlet int_bisearch_first_satisfying\n (callback: int -> bool) ((l, r): int * int): int option =\n let rec f l r =\n if l = r then if callback l then Some l else None\n else let m = (l + r) / 2 in if callback m then f l m else f (m + 1) r\n in f l r\n \nlet print_read (n: int): int =\n n |> string_of_int |> print_endline; flush stdout;\n Scanf.scanf \" %d\" (fun x -> x)\n \nlet determine_p (n: int): (int, bool array) result =\n let ret = Array.make n false in\n let rec f i =\n if i = n then false\n else (\n let t = print_read 0 in\n if t = 0 then true else (ret.(i) <- t = 1; f (i + 1))\n )\n in if f 0 then Left 0 else Right ret\n\nexception Found\n\nlet _ =\n (* m - max. distance *) (* n - #p *)\n let m, n = Scanf.scanf \" %d %d\" (fun x y -> x, y) in\n match determine_p n with\n | Left i -> ()\n | Right p ->\n try\n let f i =\n match abs (print_read i + if p.(i mod n) then 1 else -1) with\n | 0 -> true | 2 -> false | _ -> raise Found\n in int_bisearch_first_satisfying f (0, m) |> ignore\n with Found -> ()\n"}, {"source_code": "\ntype ('a, 'b) result =\n | Left of 'a\n | Right of 'b\n\nlet int_bisearch_first_satisfying\n (callback: int -> bool) ((l, r): int * int): int option =\n let rec f l r =\n if l = r then if callback l then Some l else None\n else let m = (l + r) / 2 in if callback m then f l m else f (m + 1) r\n in f l r\n \nlet print_read (n: int): int =\n n |> string_of_int |> print_endline; flush stdout;\n Scanf.scanf \" %d\" (fun x -> x)\n \nlet determine_p (n: int): (int, bool array) result =\n let ret = Array.make n false in\n let rec f i =\n if i = n then false\n else (\n let t = print_read 1 in\n if t = 0 then true else (ret.(i) <- t = 1; f (i + 1))\n )\n in if f 0 then Left 1 else Right ret\n\nexception Found\n\nlet _ =\n (* m - max. distance *) (* n - #p *)\n let m, n = Scanf.scanf \" %d %d\" (fun x y -> x, y) in\n match determine_p n with\n | Left i -> ()\n | Right p ->\n try\n let f i =\n match abs (print_read i + if p.(i mod n) then 1 else -1) with\n | 0 -> true | 2 -> false | _ -> raise Found\n in int_bisearch_first_satisfying f (0, m) |> ignore\n with Found -> ()\n"}], "src_uid": "f06dff83491772f8879e45b90b61dc88"} {"nl": {"description": "You are given a following process. There is a platform with $$$n$$$ columns. $$$1 \\times 1$$$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $$$n$$$ columns have at least one square in them, the bottom row is being removed. You will receive $$$1$$$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.", "input_spec": "The first line of input contain 2 integer numbers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 1000$$$) \u2014 the length of the platform and the number of the squares. The next line contain $$$m$$$ integer numbers $$$c_1, c_2, \\dots, c_m$$$ ($$$1 \\le c_i \\le n$$$) \u2014 column in which $$$i$$$-th square will appear.", "output_spec": "Print one integer \u2014 the amount of points you will receive.", "sample_inputs": ["3 9\n1 1 2 2 2 3 1 2 3"], "sample_outputs": ["2"], "notes": "NoteIn the sample case the answer will be equal to $$$2$$$ because after the appearing of $$$6$$$-th square will be removed one row (counts of the squares on the platform will look like $$$[2~ 3~ 1]$$$, and after removing one row will be $$$[1~ 2~ 0]$$$).After the appearing of $$$9$$$-th square counts will be $$$[2~ 3~ 1]$$$, and after removing one row it will look like $$$[1~ 2~ 0]$$$.So the answer will be equal to $$$2$$$."}, "positive_code": [{"source_code": "(* Codeforces 962 A Equator - done *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet rec count_vals cnts l = match l with\n| [] -> ()\n| h :: t -> \n\tlet _ = cnts.(h - 1) <- (cnts.(h - 1) + 1) in\n\tcount_vals cnts t;;\n\nlet rec minimum mn l = match l with\n| [] -> mn\n| h :: t ->\n\tlet mn1 = if mn < h then mn else h in\n\tminimum mn1 t;;\t\n\nlet main() =\n\tlet n = gr () in\n\tlet m = gr () in\n\tlet c = readlist m [] in\n\tlet cnta = Array.make n 0 in\n\tlet _ = count_vals cnta c in\n\tlet cntl= Array.to_list cnta in\n\tlet minv = minimum 1002 cntl in\n\tbegin\n\t\tprint_int minv;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}], "negative_code": [], "src_uid": "c249103153c5006e9b37bf15a51fe261"} {"nl": {"description": "In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are \"relaxing\".For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again. Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative. As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.", "input_spec": "The first line contains three integers n, m, k (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u20091000,\u20090\u2009\u2264\u2009k\u2009\u2264\u2009106) \u2014 total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow n lines, each containing two integers: r (1\u2009\u2264\u2009r\u2009\u2264\u2009m) \u2014 index of the row, where belongs the corresponding tooth, and c (0\u2009\u2264\u2009c\u2009\u2264\u2009106) \u2014 its residual viability. It's guaranteed that each tooth row has positive amount of teeth.", "output_spec": "In the first line output the maximum amount of crucians that Valerie can consume for dinner.", "sample_inputs": ["4 3 18\n2 3\n1 2\n3 6\n2 3", "2 2 13\n1 13\n2 12"], "sample_outputs": ["11", "13"], "notes": null}, "positive_code": [{"source_code": "print_int (Scanf.scanf \"%d %d %d\\n\" (fun n m k ->\n\tlet ryads = Array.make m max_int in\n\tlet _ = for i = 1 to n do \n\t\tScanf.scanf \"%d %d\\n\" (fun r z ->\n\t\t\tif z < ryads.(r-1) then (ryads.(r-1) <- z) \n\t\t)\n\tdone in\n\tmin k (Array.fold_left (+) 0 ryads)\n));;\n"}], "negative_code": [], "src_uid": "65eb0f3ab35c4d95c1cbd39fc7a4227b"} {"nl": {"description": "There is a river of width $$$n$$$. The left bank of the river is cell $$$0$$$ and the right bank is cell $$$n + 1$$$ (more formally, the river can be represented as a sequence of $$$n + 2$$$ cells numbered from $$$0$$$ to $$$n + 1$$$). There are also $$$m$$$ wooden platforms on a river, the $$$i$$$-th platform has length $$$c_i$$$ (so the $$$i$$$-th platform takes $$$c_i$$$ consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed $$$n$$$.You are standing at $$$0$$$ and want to reach $$$n+1$$$ somehow. If you are standing at the position $$$x$$$, you can jump to any position in the range $$$[x + 1; x + d]$$$. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if $$$d=1$$$, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells $$$0$$$ and $$$n+1$$$ belong to wooden platforms.You want to know if it is possible to reach $$$n+1$$$ from $$$0$$$ if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).For example, if $$$n=7$$$, $$$m=3$$$, $$$d=2$$$ and $$$c = [1, 2, 1]$$$, then one of the ways to reach $$$8$$$ from $$$0$$$ is follow: The first example: $$$n=7$$$. ", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$d$$$ ($$$1 \\le n, m, d \\le 1000, m \\le n$$$) \u2014 the width of the river, the number of platforms and the maximum distance of your jump, correspondingly. The second line of the input contains $$$m$$$ integers $$$c_1, c_2, \\dots, c_m$$$ ($$$1 \\le c_i \\le n, \\sum\\limits_{i=1}^{m} c_i \\le n$$$), where $$$c_i$$$ is the length of the $$$i$$$-th platform.", "output_spec": "If it is impossible to reach $$$n+1$$$ from $$$0$$$, print NO in the first line. Otherwise, print YES in the first line and the array $$$a$$$ of length $$$n$$$ in the second line \u2014 the sequence of river cells (excluding cell $$$0$$$ and cell $$$n + 1$$$). If the cell $$$i$$$ does not belong to any platform, $$$a_i$$$ should be $$$0$$$. Otherwise, it should be equal to the index of the platform ($$$1$$$-indexed, platforms are numbered from $$$1$$$ to $$$m$$$ in order of input) to which the cell $$$i$$$ belongs. Note that all $$$a_i$$$ equal to $$$1$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_1$$$, all $$$a_i$$$ equal to $$$2$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_2$$$, ..., all $$$a_i$$$ equal to $$$m$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_m$$$. The leftmost position of $$$2$$$ in $$$a$$$ should be greater than the rightmost position of $$$1$$$, the leftmost position of $$$3$$$ in $$$a$$$ should be greater than the rightmost position of $$$2$$$, ..., the leftmost position of $$$m$$$ in $$$a$$$ should be greater than the rightmost position of $$$m-1$$$. See example outputs for better understanding.", "sample_inputs": ["7 3 2\n1 2 1", "10 1 11\n1", "10 1 5\n2"], "sample_outputs": ["YES\n0 1 0 2 2 0 3", "YES\n0 0 0 0 0 0 0 0 0 1", "YES\n0 0 0 0 1 1 0 0 0 0"], "notes": "NoteConsider the first example: the answer is $$$[0, 1, 0, 2, 2, 0, 3]$$$. The sequence of jumps you perform is $$$0 \\rightarrow 2 \\rightarrow 4 \\rightarrow 5 \\rightarrow 7 \\rightarrow 8$$$.Consider the second example: it does not matter how to place the platform because you always can jump from $$$0$$$ to $$$11$$$.Consider the third example: the answer is $$$[0, 0, 0, 0, 1, 1, 0, 0, 0, 0]$$$. The sequence of jumps you perform is $$$0 \\rightarrow 5 \\rightarrow 6 \\rightarrow 11$$$."}, "positive_code": [{"source_code": "open Printf\n\nlet print_list l ~f =\n let rec print_list' l to_string acc =\n match l with\n | [] -> acc ^ \"\"\n | hd::[] -> acc ^ sprintf \"%s\" (to_string hd)\n | hd::tl -> print_list' tl to_string (acc ^ sprintf \"%s \" (to_string hd));\n in\n print_list' l f \"\"\n\ntype river = {\n width: int;\n platforms: int list;\n tot_len: int\n }\n\nlet rec seq f t =\n if t < f then [1] else \n if f = t then t::[] else t::(seq f (t-1))\n\nexception One of int list\n\nlet t river j = seq 1 (min j (river.width - river.tot_len))\n\nlet rec solve_one' river jump_dist sol trys=\n match river.platforms, trys with\n | [], _ -> if river.width >= 0 && river.width < jump_dist then Some sol else None\n | hd::tl, [] -> None\n | phd::ptl, thd::ttl -> let new_river ={width=river.width-((thd-1)+phd); platforms=ptl; tot_len=river.tot_len-phd} in\n solve_one' new_river jump_dist (thd::sol) (t new_river jump_dist)\n\nlet solve_one river jump_dist =\n solve_one' river jump_dist [] (t river jump_dist)\n\nlet rec solve_all' river jump_dist sol acc =\n match river.platforms with\n | [] -> if river.width >= 0 && river.width < jump_dist then sol::acc else acc\n | hd::tl -> List.concat (List.map (fun x -> solve_all' {width=river.width-((x-1)+hd); platforms=tl; tot_len=river.tot_len-x} jump_dist (x::sol) acc) (seq 1 (min river.width jump_dist)))\n\nlet solve_all river jump_dist = solve_all' river jump_dist [] []\n\nlet print_sol river sol =\n let rec repeat i n = if n = 0 then [] else i :: repeat i (n-1) in\n let rec sol_list river sol cur_platform acc =\n match river.platforms, sol with\n | [], [] -> List.concat (acc @ [repeat 0 river.width])\n | plat::plats, cur::next -> sol_list {width=river.width - (cur-1) - plat; platforms=plats; tot_len=0} next (cur_platform+1) (acc @[repeat 0 (cur-1); repeat cur_platform plat])\n | _, _ -> failwith \"CANNOT HAPPEN\"\n in\n print_endline (print_list ~f:string_of_int (sol_list river sol 1 []))\n\nlet solve_input () =\n let open Str in\n let fst = split (regexp \" \") (input_line stdin) in\n let snd = split (regexp \" \") (input_line stdin) in\n let (width,jump) = List.((int_of_string (hd fst), int_of_string (hd (tl (tl fst))))) in\n let platforms = List.map int_of_string snd in\n let river = {width=width;platforms=platforms;tot_len=List.fold_left (+) 0 platforms} in\n let sols = solve_one river jump in\n match sols with\n | Some v -> print_endline \"YES\"; print_sol river v\n | None -> print_endline \"NO\"\n\nlet sum l = List.fold_left (+) 0 l\nlet () =\n solve_input ()\n (* let platforms = [3;6;3;4;3;5;3;5;5;5;3;1;3;8;2;4;4;5;3;2] in\n * let river = {width=1000; platforms=platforms; tot_len=(sum platforms)} \n * and jump = 8 in\n * try\n * let sol = solve_one river jump in\n * match sol with\n * | Some v -> print_endline \"YES\"; print_sol river v\n * | None -> print_endline \"NO\"\n * with _ -> () *)\n"}], "negative_code": [{"source_code": "open Printf\n\nlet print_list l ~f =\n let rec print_list' l to_string acc =\n match l with\n | [] -> acc ^ \"\"\n | hd::[] -> acc ^ sprintf \"%s\" (to_string hd)\n | hd::tl -> print_list' tl to_string (acc ^ sprintf \"%s \" (to_string hd));\n in\n print_list' l f \"\"\n\ntype river = {\n width: int;\n platforms: int list;\n tot_len: int\n }\n\nlet rec seq f t =\n if f = t then f::[] else f::(seq (f+1) t)\n\nexception One of int list\n\nlet t river j = seq 1 (min j (river.width - river.tot_len))\n\nlet rec solve_one' river jump_dist sol trys=\n match river.platforms, trys with\n | [], _ -> if river.width >= 0 && river.width < jump_dist then Some sol else None\n | hd::tl, [] -> None\n | phd::ptl, thd::ttl -> let new_river ={width=river.width-((thd-1)+phd); platforms=ptl; tot_len=river.tot_len-phd} in\n match solve_one' new_river jump_dist (thd::sol) (t new_river jump_dist) with\n | Some v -> Some v\n | None -> solve_one' river jump_dist sol ttl\n\nlet solve_one river jump_dist = solve_one' river jump_dist [] (t river jump_dist)\n\nlet rec solve_all' river jump_dist sol acc =\n match river.platforms with\n | [] -> if river.width >= 0 && river.width < jump_dist then sol::acc else acc\n | hd::tl -> List.concat (List.map (fun x -> solve_all' {width=river.width-((x-1)+hd); platforms=tl; tot_len=river.tot_len-x} jump_dist (x::sol) acc) (seq 1 (min river.width jump_dist)))\n\nlet solve_all river jump_dist = solve_all' river jump_dist [] []\n\nlet print_sol river sol =\n let rec repeat i n = if n = 0 then [] else i :: repeat i (n-1) in\n let rec sol_list river sol cur_platform acc =\n match river.platforms, sol with\n | [], [] -> List.concat (acc @ [repeat 0 river.width])\n | plat::plats, cur::next -> sol_list {width=river.width - (cur-1) - plat; platforms=plats; tot_len=0} next (cur_platform+1) (acc @[repeat 0 (cur-1); repeat cur_platform plat])\n | _, _ -> failwith \"CANNOT HAPPEN\"\n in\n print_endline (print_list ~f:string_of_int (sol_list river sol 1 []))\n\nlet solve_input () =\n let open Str in\n let fst = split (regexp \" \") (input_line stdin) in\n let snd = split (regexp \" \") (input_line stdin) in\n let (width,jump) = List.((int_of_string (hd fst), int_of_string (hd (tl (tl fst))))) in\n let platforms = List.map int_of_string snd in\n let river = {width=width;platforms=platforms;tot_len=List.fold_left (+) 0 platforms} in\n let sols = solve_one river jump in\n match sols with\n | Some v -> print_sol river v\n | None -> print_endline \"NO\"\n\n\nlet () =\n solve_input ()\n (* let river = {width=40; platforms=[1;2;1;10;5;15;1]}\n * and jump = 3 in\n * try\n * let l = solve_all river jump in\n * List.iter (fun x -> print_sol river x) l\n * with _ -> () *)\n"}, {"source_code": "open Printf\n\nlet print_list l ~f =\n let rec print_list' l to_string acc =\n match l with\n | [] -> acc ^ \"]\"\n | hd::[] -> acc ^ sprintf \"%s]\" (to_string hd)\n | hd::tl -> print_list' tl to_string (acc ^ sprintf \"%s \" (to_string hd));\n in\n print_list' l f \"[\"\n\ntype river = {\n width: int;\n platforms: int list\n }\n\nlet rec seq f t =\n if f = t then f::[] else f::(seq (f+1) t)\n\nlet rec solve' river jump_dist sol acc =\n match river.platforms with\n | [] -> if river.width >= 0 && river.width < jump_dist then sol::acc else acc\n | hd::tl -> List.concat (List.map (fun x -> solve' {width=river.width-((x-1)+hd); platforms=tl} jump_dist (x::sol) acc) (seq 1 (min river.width jump_dist)))\n\nlet print_sol river sol =\n let rec repeat i n = if n = 0 then [] else i :: repeat i (n-1) in\n let rec sol_list river sol cur_platform acc =\n match river.platforms, sol with\n | [], [] -> List.concat (acc @ [repeat 0 river.width])\n | plat::plats, cur::next -> sol_list {width=river.width - (cur-1) - plat; platforms=plats} next (cur_platform+1) (acc @[repeat 0 (cur-1); repeat cur_platform plat])\n | _, _ -> failwith \"CANNOT HAPPEN\"\n in\n print_endline (print_list ~f:string_of_int (sol_list river sol 1 []))\n\n\nlet solve river jump_dist =\n solve' river jump_dist [] []\n\nlet solve_all () =\n let open Str in\n let fst = split (regexp \" \") (input_line stdin) in\n let snd = split (regexp \" \") (input_line stdin) in\n let (width,jump) = List.((int_of_string (hd fst), int_of_string (hd (tl (tl fst))))) in\n let platforms = List.map int_of_string snd in\n let river = {width=width;platforms=platforms} in\n let sol = solve river jump in\n match sol with\n | [] -> print_endline \"NO\"\n | hd::tl -> print_sol river hd\n\n\nlet () =\n solve_all ()\n (* let river = {width=100; platforms=[1;2;1;10;5;15;1]}\n * and jump = 10 in\n * try\n * let l = solve river jump in\n * List.iter (fun x -> print_sol river x) l\n * with _ -> () *)\n"}, {"source_code": "open Printf\n\nlet print_list l ~f =\n let rec print_list' l to_string acc =\n match l with\n | [] -> acc ^ \"\"\n | hd::[] -> acc ^ sprintf \"%s\" (to_string hd)\n | hd::tl -> print_list' tl to_string (acc ^ sprintf \"%s \" (to_string hd));\n in\n print_list' l f \"\"\n\ntype river = {\n width: int;\n platforms: int list\n }\n\nlet rec seq f t =\n if f = t then f::[] else f::(seq (f+1) t)\n\nlet rec solve' river jump_dist sol acc =\n match river.platforms with\n | [] -> if river.width >= 0 && river.width < jump_dist then sol::acc else acc\n | hd::tl -> List.concat (List.map (fun x -> solve' {width=river.width-((x-1)+hd); platforms=tl} jump_dist (x::sol) acc) (seq 1 (min river.width jump_dist)))\n\nlet print_sol river sol =\n let rec repeat i n = if n = 0 then [] else i :: repeat i (n-1) in\n let rec sol_list river sol cur_platform acc =\n match river.platforms, sol with\n | [], [] -> List.concat (acc @ [repeat 0 river.width])\n | plat::plats, cur::next -> sol_list {width=river.width - (cur-1) - plat; platforms=plats} next (cur_platform+1) (acc @[repeat 0 (cur-1); repeat cur_platform plat])\n | _, _ -> failwith \"CANNOT HAPPEN\"\n in\n print_endline (print_list ~f:string_of_int (sol_list river sol 1 []))\n\n\nlet solve river jump_dist =\n solve' river jump_dist [] []\n\nlet solve_all () =\n let open Str in\n let fst = split (regexp \" \") (input_line stdin) in\n let snd = split (regexp \" \") (input_line stdin) in\n let (width,jump) = List.((int_of_string (hd fst), int_of_string (hd (tl (tl fst))))) in\n let platforms = List.map int_of_string snd in\n let river = {width=width;platforms=platforms} in\n let sol = solve river jump in\n match sol with\n | [] -> print_endline \"NO\"\n | hd::tl -> print_sol river hd\n\n\nlet () =\n solve_all ()\n (* let river = {width=100; platforms=[1;2;1;10;5;15;1]}\n * and jump = 10 in\n * try\n * let l = solve river jump in\n * List.iter (fun x -> print_sol river x) l\n * with _ -> () *)\n"}], "src_uid": "7f4293c5602429819e05beca45b22c05"} {"nl": {"description": "There are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.In other words, let's say that bi,\u2009c is the number of pebbles of color c in the i-th pile. Then for any 1\u2009\u2264\u2009c\u2009\u2264\u2009k, 1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n the following condition must be satisfied |bi,\u2009c\u2009-\u2009bj,\u2009c|\u2009\u2264\u20091. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then bi,\u2009c is considered to be zero.", "input_spec": "The first line of the input contains positive integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100), separated by a space \u2014 the number of piles and the number of colors respectively. The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) denoting number of pebbles in each of the piles.", "output_spec": "If there is no way to paint the pebbles satisfying the given condition, output \"NO\" (without quotes) . Otherwise in the first line output \"YES\" (without quotes). Then n lines should follow, the i-th of them should contain ai space-separated integers. j-th (1\u2009\u2264\u2009j\u2009\u2264\u2009ai) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.", "sample_inputs": ["4 4\n1 2 3 4", "5 2\n3 2 4 1 3", "5 4\n3 2 4 3 5"], "sample_outputs": ["YES\n1\n1 4\n1 2 4\n1 2 3 4", "NO", "YES\n1 2 3\n1 3\n1 2 3 4\n1 3 4\n1 1 2 3 4"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let k = read_int () in\n\n let a = Array.init n (fun _ -> read_int()) in\n\n let mina = minf 0 (n-1) (fun i -> a.(i)) in\n let maxa = maxf 0 (n-1) (fun i -> a.(i)) in\n\n if maxa - mina > k then (\n printf \"NO\\n\"\n ) else (\n printf \"YES\\n\";\n for i=0 to n-1 do\n let ct = Array.make k 0 in\n ct.(k-1) <- mina;\n\n let rec loop j ac =\n\tif ac=a.(i) then () else (\n\t ct.(j) <- ct.(j) + 1;\n\t loop (j+1) (ac+1)\n\t)\n in\n\n loop 0 mina;\n for c=0 to k-1 do\n\tfor l=1 to ct.(c) do\n\t printf \"%d \" (c+1)\n\tdone\n done;\n print_newline()\n done\n )\n"}, {"source_code": "let () =\n Scanf.scanf \"%d %d\\n\" (fun n k ->\n let piles = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n (* smallest/largest pile size *)\n let min = Array.fold_left min piles.(0) piles\n and max = Array.fold_left max piles.(0) piles in\n\n (* check whether it's possible *)\n if max - min > k then\n print_endline \"NO\"\n else begin\n print_endline \"YES\";\n\n (* fill out each pile with colour 1 *)\n for i = 0 to n - 1 do\n for j = 1 to piles.(i) do\n if j > 1 then print_char ' ';\n if j > min\n then print_int (j - min)\n else print_int 1\n done;\n print_endline \"\"\n done\n end\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let k = read_int () in\n\n let a = Array.init n (fun _ -> read_int()) in\n\n let mina = minf 0 (n-1) (fun i -> a.(i)) in\n let maxa = maxf 0 (n-1) (fun i -> a.(i)) in\n\n if maxa - mina > k then (\n printf \"NO\\n\"\n ) else (\n for i=0 to n-1 do\n let ct = Array.make k 0 in\n ct.(k-1) <- mina;\n\n let rec loop j ac =\n\tif ac=a.(i) then () else (\n\t ct.(j) <- ct.(j) + 1;\n\t loop (j+1) (ac+1)\n\t)\n in\n\n loop 0 mina;\n for c=0 to k-1 do\n\tfor l=1 to ct.(c) do\n\t printf \"%d \" (c+1)\n\tdone\n done;\n print_newline()\n done\n )\n"}], "src_uid": "e512285d15340343e34f596de2be82eb"} {"nl": {"description": "You are given a string $$$s=s_1s_2\\dots s_n$$$ of length $$$n$$$, which only contains digits $$$1$$$, $$$2$$$, ..., $$$9$$$.A substring $$$s[l \\dots r]$$$ of $$$s$$$ is a string $$$s_l s_{l + 1} s_{l + 2} \\ldots s_r$$$. A substring $$$s[l \\dots r]$$$ of $$$s$$$ is called even if the number represented by it is even. Find the number of even substrings of $$$s$$$. Note, that even if some substrings are equal as strings, but have different $$$l$$$ and $$$r$$$, they are counted as different substrings.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 65000$$$)\u00a0\u2014 the length of the string $$$s$$$. The second line contains a string $$$s$$$ of length $$$n$$$. The string $$$s$$$ consists only of digits $$$1$$$, $$$2$$$, ..., $$$9$$$.", "output_spec": "Print the number of even substrings of $$$s$$$.", "sample_inputs": ["4\n1234", "4\n2244"], "sample_outputs": ["6", "10"], "notes": "NoteIn the first example, the $$$[l, r]$$$ pairs corresponding to even substrings are: $$$s[1 \\dots 2]$$$ $$$s[2 \\dots 2]$$$ $$$s[1 \\dots 4]$$$ $$$s[2 \\dots 4]$$$ $$$s[3 \\dots 4]$$$ $$$s[4 \\dots 4]$$$ In the second example, all $$$10$$$ substrings of $$$s$$$ are even substrings. Note, that while substrings $$$s[1 \\dots 1]$$$ and $$$s[2 \\dots 2]$$$ both define the substring \"2\", they are still counted as different substrings."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet (++) = Int64.add\nlet long = Int64.of_int\n\nlet read_int _ = scanf \" %d \" (fun x -> x)\nlet read_str _ = scanf \" %s \" (fun x -> x)\nlet read_num _ = scanf \" %c \" (fun c -> int_of_char c - int_of_char '0')\n\nlet rec loop s n i cnt =\n if i >= n\n then cnt\n else\n let cnt' = if s.(i) land 1 = 0\n then cnt ++ long (i+1)\n else cnt in\n loop s n (i+1) cnt'\n\nlet () =\n let n = read_int () in\n let s = Array.init n read_num in\n printf \"%Ld\\n\" @@ loop s n 0 0L\n"}], "negative_code": [], "src_uid": "43a65d1cfe59931991b6aefae1ecd10e"} {"nl": {"description": "Pay attention to the non-standard memory limit in this problem.In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.The array $$$a=[a_1, a_2, \\ldots, a_n]$$$ ($$$1 \\le a_i \\le n$$$) is given. Its element $$$a_i$$$ is called special if there exists a pair of indices $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le n$$$) such that $$$a_i = a_l + a_{l+1} + \\ldots + a_r$$$. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).Print the number of special elements of the given array $$$a$$$.For example, if $$$n=9$$$ and $$$a=[3,1,4,1,5,9,2,6,5]$$$, then the answer is $$$5$$$: $$$a_3=4$$$ is a special element, since $$$a_3=4=a_1+a_2=3+1$$$; $$$a_5=5$$$ is a special element, since $$$a_5=5=a_2+a_3=1+4$$$; $$$a_6=9$$$ is a special element, since $$$a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$$$; $$$a_8=6$$$ is a special element, since $$$a_8=6=a_2+a_3+a_4=1+4+1$$$; $$$a_9=5$$$ is a special element, since $$$a_9=5=a_2+a_3=1+4$$$. Please note that some of the elements of the array $$$a$$$ may be equal \u2014 if several elements are equal and special, then all of them should be counted in the answer.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given in two lines. The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 8000$$$) \u2014 the length of the array $$$a$$$. The second line contains integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$). It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$8000$$$.", "output_spec": "Print $$$t$$$ numbers \u2014 the number of special elements for each of the given arrays.", "sample_inputs": ["5\n9\n3 1 4 1 5 9 2 6 5\n3\n1 1 2\n5\n1 1 1 1 1\n8\n8 7 6 5 4 3 2 1\n1\n1"], "sample_outputs": ["5\n1\n0\n4\n0"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 1352 E Special Elements train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\nlet tstprintlist head li = \n\tbegin\n\t\tprint_string head;\n\t\tprintlisti li;\n\t\tprint_string \"\\n\"\n\tend;;\n\nlet rec repeat a n = match n with\n | 0 -> []\n | _ -> a :: repeat a (n-1);;\n\nlet sums a = \n let rec r_sums sma sm a = match a with\n | [] -> sma\n \t| h :: t -> \n \t\tlet nsm = h + sm in \n \t\tr_sums (nsm :: sma) nsm t in\n\tr_sums [0] 0 a;;\n\nlet rec setdiffs el spec n sa = match sa with\n | [] -> ()\n\t| h :: t ->\n\t\tlet s = el - h in\n\t\tlet _ = if ((s <= n) && (s > 0)) then spec.(s) <- 1 in\n\t\tsetdiffs el spec n t;;\n\nlet rec set_spec speca n sa = match sa with\n | [] -> ()\n\t| h :: [] -> ()\n\t| h0 :: h1 :: t -> \n\t\tlet _ = setdiffs h0 speca n t in\n\t\tset_spec speca n (h1 :: t);;\t\n\nlet rec set_a cnta a = match a with\n| [] -> ()\n| h :: t -> \n\tbegin\n\t\tcnta.(h) <- (cnta.(h) + 1);\n\t\tset_a cnta t\n\tend;;\n\nlet rec sum_spec cnta speca sm i n = \n\tif i > n then sm\n\telse\n\t\tlet e = cnta.(i) * speca.(i) in\n\t\tsum_spec cnta speca (sm + e) (i+1) n;;\n\nlet num_special n a = \n\tlet sma = sums a in\n\t(* let _ = tstprintlist \"sma \" sma in *)\n\tlet cnta = Array.make (n+1) 0 in\n\tlet speca = Array.make (n+1) 0 in\n\tlet _ = set_spec speca n sma in\n\tlet _ = set_a cnta a in\n (* let _ = tstprintlist \"speca \" (Array.to_list speca) in\n let _ = tstprintlist \"cnta \" (Array.to_list cnta) in*)\n\tlet sumspec = sum_spec cnta speca 0 0 n in\n\tPrintf.printf \"%d \\n\" sumspec;;\t\n \nlet do_one () = \n let n = gr () in\n let a = readlist n [] in\n\t\tlet a = List.rev a in\n\t\tnum_special n a;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [], "src_uid": "2326470337301e0f4b0d1b1a6195e398"} {"nl": {"description": "The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!", "input_spec": "The first line contains two integers, n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.", "output_spec": "In t lines, print the actions the programmers need to make. In the i-th line print: \"LEFT\" (without the quotes), if the i-th action was \"move the ladder to the left\"; \"RIGHT\" (without the quotes), if the i-th action was \"move the ladder to the right\"; \"PRINT x\" (without the quotes), if the i-th action was to \"go up the ladder, paint character x, go down the ladder\". The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them.", "sample_inputs": ["2 2\nR1", "2 1\nR1", "6 4\nGO?GO!"], "sample_outputs": ["PRINT 1\nLEFT\nPRINT R", "PRINT R\nRIGHT\nPRINT 1", "RIGHT\nRIGHT\nPRINT !\nLEFT\nPRINT O\nLEFT\nPRINT G\nLEFT\nPRINT ?\nLEFT\nPRINT O\nLEFT\nPRINT G"], "notes": "NoteNote that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character."}, "positive_code": [{"source_code": "let sr=read_line();;\nlet rec ind i=if sr.[i]=' ' then i else ind (i+1);;\nlet id=ind 0;;\nlet n=int_of_string(String.sub sr 0 id) and k=int_of_string(String.sub sr (id+1) (String.length(sr)-1-id));;\n\nlet s=read_line();;\nif k<=n/2 then\n begin\n for i=1 to k-1 do\n Printf.printf \"LEFT\\n\"\n done;\n for i=0 to n-1 do\n print_string(\"PRINT \"^(String.sub s i 1)^\"\\n\");\n if i<>n-1 then Printf.printf \"RIGHT\\n\"\n done\n end\nelse\n begin\n for i=k to n-1 do\n Printf.printf \"RIGHT\\n\"\n done;\n for i=n-1 downto 0 do\n print_string(\"PRINT \"^(String.sub s i 1)^\"\\n\");\n if i<>0 then Printf.printf \"LEFT\\n\"\n done\n end;;"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = scanf \" %d\" (fun x -> x)\nlet read_string() = scanf \" %s \" (fun x -> x)\n\nlet reverse str =\n let n = String.length str in\n let res = String.create n in\n for i = 0 to n - 1 do\n res.[i] <- str.[n - 1 - i]\n done;\n res in\n\nlet n = read_int () in\nlet k = read_int () in\nlet s = read_string () in\n\nlet res_f sep i c =\n if i > 0 then printf \"%s\\n\" sep;\n printf \"PRINT %c\\n\" c in\n\nif k - 1 <= n - k then begin\n for i = 1 to k - 1 do\n printf \"LEFT\\n\"\n done;\n String.iteri (res_f \"RIGHT\") s\nend else begin\n for i = 1 to n - k do\n printf \"RIGHT\\n\"\n done;\n String.iteri (res_f \"LEFT\") (reverse s)\nend ;;\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let l = k - 1\n and r = n - k in\n if l < r then (\n for i = 1 to l do\n\tPrintf.printf \"LEFT\\n\"\n done;\n for i = 0 to n - 1 do\n\tPrintf.printf \"PRINT %c\\n\" s.[i];\n\tif i < n - 1\n\tthen Printf.printf \"RIGHT\\n\"\n done;\n ) else (\n for i = 1 to r do\n\tPrintf.printf \"RIGHT\\n\"\n done;\n for i = n - 1 downto 0 do\n\tPrintf.printf \"PRINT %c\\n\" s.[i];\n\tif i > 0\n\tthen Printf.printf \"LEFT\\n\"\n done;\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = scanf \" %d\" (fun x -> x)\nlet read_string() = scanf \" %s \" (fun x -> x)\n\nlet reverse str =\n let n = String.length str in\n let res = String.create n in\n for i = 0 to n - 1 do\n res.[i] <- str.[n - 1 - i]\n done;\n res in\n\nlet n = read_int () in\nlet k = read_int () in\nlet s = read_string () in\n\nlet res_f sep i c =\n if i > 0 then printf \"%s\\n\" sep;\n printf \"PRINT %c\\n\" c in\n\nprintf \"%d %d %s\\n\" n k s;\n\nif k - 1 <= n - k then begin\n for i = 1 to k - 1 do\n printf \"LEFT\\n\"\n done;\n String.iteri (res_f \"RIGHT\") s\nend else begin\n for i = 1 to n - k do\n printf \"RIGHT\\n\"\n done;\n String.iteri (res_f \"LEFT\") (reverse s)\nend ;;\n\n"}], "src_uid": "e3a03f3f01a77a1983121bab4218c39c"} {"nl": {"description": "Businessman Divan loves chocolate! Today he came to a store to buy some chocolate. Like all businessmen, Divan knows the value of money, so he will not buy too expensive chocolate. At the same time, too cheap chocolate tastes bad, so he will not buy it as well.The store he came to has $$$n$$$ different chocolate bars, and the price of the $$$i$$$-th chocolate bar is $$$a_i$$$ dollars. Divan considers a chocolate bar too expensive if it costs strictly more than $$$r$$$ dollars. Similarly, he considers a bar of chocolate to be too cheap if it costs strictly less than $$$l$$$ dollars. Divan will not buy too cheap or too expensive bars.Divan is not going to spend all his money on chocolate bars, so he will spend at most $$$k$$$ dollars on chocolates.Please determine the maximum number of chocolate bars Divan can buy.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The description of each test case consists of two lines. The first line contains integers $$$n$$$, $$$l$$$, $$$r$$$, $$$k$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le l \\le r \\le 10^9$$$, $$$1 \\le k \\le 10^9$$$)\u00a0\u2014 the lowest acceptable price of a chocolate, the highest acceptable price of a chocolate and Divan's total budget, respectively. The second line contains a sequence $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) integers\u00a0\u2014 the prices of chocolate bars in the store.", "output_spec": "For each test case print a single integer \u2014 the maximum number of chocolate bars Divan can buy.", "sample_inputs": ["8\n3 1 100 100\n50 100 50\n6 3 5 10\n1 2 3 4 5 6\n6 3 5 21\n1 2 3 4 5 6\n10 50 69 100\n20 30 40 77 1 1 12 4 70 10000\n3 50 80 30\n20 60 70\n10 2 7 100\n2 2 2 2 2 7 7 7 7 7\n4 1000000000 1000000000 1000000000\n1000000000 1000000000 1000000000 1000000000\n1 1 1 1\n1"], "sample_outputs": ["2\n2\n3\n0\n0\n10\n1\n1"], "notes": "NoteIn the first example Divan can buy chocolate bars $$$1$$$ and $$$3$$$ and spend $$$100$$$ dollars on them.In the second example Divan can buy chocolate bars $$$3$$$ and $$$4$$$ and spend $$$7$$$ dollars on them.In the third example Divan can buy chocolate bars $$$3$$$, $$$4$$$, and $$$5$$$ for $$$12$$$ dollars.In the fourth example Divan cannot buy any chocolate bar because each of them is either too cheap or too expensive.In the fifth example Divan cannot buy any chocolate bar because he considers the first bar too cheap, and has no budget for the second or third.In the sixth example Divan can buy all the chocolate bars in the shop."}, "positive_code": [{"source_code": "(* Codeforces 1614 A Divan and a Store train *)\r\n \r\n(* you can use either gr or rdln but not both *)\r\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\r\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\r\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet rdln() = input_line stdin;;\r\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\r\nlet debug = false;;\r\n \r\n(* reading reversed list *)\r\nlet rec readlist n acc = match n with\r\n\t| 0 -> acc\r\n\t| _ -> readlist (n -1) (gr() :: acc);;\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\r\n\r\nlet between l r x =\r\n\t(l <= x) && (x <= r);;\r\n\r\nlet rec max_choc cnt money lc = match lc with\r\n\t| [] -> cnt\r\n\t| h :: t ->\r\n\t\tif h > money then cnt\r\n\t\telse\r\n\t\t\tlet ncnt = cnt + 1 in\r\n\t\t\tlet nMoney = money - h in\r\n\t\t\tlet nlc = t in\r\n\t\t\tmax_choc ncnt nMoney nlc;;\r\n\r\nlet do_one () = \r\n let n = gr() in\r\n let l = gr() in\r\n let r = gr() in\r\n let k = gr() in\r\n\t\tlet a = List.rev (readlist n []) in\r\n\t\tlet sa = List.sort compare a in\r\n\t\tlet fa = List.filter (between l r) sa in\r\n\t\tlet cnt = max_choc 0 k fa in\r\n\t\t(print_int cnt; print_string \"\\n\");;\r\n \r\nlet do_all () = \r\n let t = gr () in\r\n for i = 1 to t do\r\n do_one ()\r\n done;;\r\n \r\nlet main() =\r\n\tdo_all ();;\r\n \r\nmain();;"}], "negative_code": [], "src_uid": "f577695d39a11e8507681f307677c883"} {"nl": {"description": "High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20090\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.", "output_spec": "Print the only integer\u00a0\u2014 the maximum beauty of the string Vasya can achieve by changing no more than k characters.", "sample_inputs": ["4 2\nabba", "8 1\naabaabaa"], "sample_outputs": ["4", "5"], "notes": "NoteIn the first sample, Vasya can obtain both strings \"aaaa\" and \"bbbb\".In the second sample, the optimal answer is obtained with the string \"aaaaabaa\" or with the string \"aabaaaaa\"."}, "positive_code": [{"source_code": "let [n; k] = read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string\nlet s = read_line ()\n\nexception Break of int;;\n\nlet max_charm_at_start ch =\n let mana = ref k in\n try\n for i = 0 to n-1 do\n if s.[i] != ch then\n decr mana;\n if !mana < 0 then\n raise (Break i)\n done;\n n\n with\n | Break i -> i\n\nlet max_charm ch =\n let left = ref 0\n and right = ref (max_charm_at_start ch) in\n let best = ref !right in\n while !right < n do\n if s.[!right] != ch then\n begin\n while s.[!left] == ch do\n incr left\n done;\n incr left\n end;\n incr right;\n if !right - !left > !best then\n best := !right - !left\n done;\n !best\n\nlet () =\n max (max_charm 'a') (max_charm 'b')\n |> Printf.printf \"%d\\n\"\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let k = read_int () in \n let s = read_string () in\n\n let solve a =\n (* a is an array of n+2 bits (0s or 1s). We added an extra 0 at start and end\n what's the maximum block of 1s we can make by toggling at most k 0s to 1s. *)\n let nzeros = sum 1 n (fun i -> if a.(i) = 0 then 1 else 0) in\n if nzeros <= k then n else (\n\n let next = Array.make (n+2) 0 in\n let prev = Array.make (n+2) 0 in\n\n let rec scan i p = if i next.(i) - i - 1)\n ) else (\n\tlet rec step i steps = if steps=0 then i else step next.(i) (steps-1) in\n\tlet rec scan i j ac = if j=n+1 then ac else (\n\t (* evaluate this (i,j) option. *)\n\t let pi = prev.(i) in\n\t let nj = next.(j) in\n\t let ac = max ac (nj-pi-1) in\n\t scan next.(i) next.(j) ac\n\t) in\n\n\tlet i = next.(0) in\n\tlet j = step i (k-1) in\n\tscan i j 0\n )\n )\n in\n\n let ma c = Array.init (n+2) (fun i -> if i-1 < 0 || i-1 > n-1 then 0 else if s.[i-1] = c then 1 else 0) in\n let answer = max (solve (ma 'a')) (solve (ma 'b')) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "0151a87d0f82a9044a0ac8731d369bb9"} {"nl": {"description": "Dasha logged into the system and began to solve problems. One of them is as follows:Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci\u2009=\u2009bi\u2009-\u2009ai.About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l\u2009\u2264\u2009ai\u2009\u2264\u2009r and l\u2009\u2264\u2009bi\u2009\u2264\u2009r. About sequence c we know that all its elements are distinct. Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c\u2009=\u2009[250,\u2009200,\u2009300,\u2009100,\u200950] the compressed sequence will be p\u2009=\u2009[4,\u20093,\u20095,\u20092,\u20091]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.", "input_spec": "The first line contains three integers n, l, r (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009109) \u2014 the length of the sequence and boundaries of the segment where the elements of sequences a and b are. The next line contains n integers a1,\u2009\u2009a2,\u2009\u2009...,\u2009\u2009an (l\u2009\u2264\u2009ai\u2009\u2264\u2009r) \u2014 the elements of the sequence a. The next line contains n distinct integers p1,\u2009\u2009p2,\u2009\u2009...,\u2009\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) \u2014 the compressed sequence of the sequence c.", "output_spec": "If there is no the suitable sequence b, then in the only line print \"-1\". Otherwise, in the only line print n integers \u2014 the elements of any suitable sequence b.", "sample_inputs": ["5 1 5\n1 1 1 1 1\n3 1 5 4 2", "4 2 9\n3 4 8 9\n3 2 1 4", "6 1 5\n1 1 1 1 1 1\n2 3 5 4 1 6"], "sample_outputs": ["3 1 5 4 2", "2 2 2 9", "-1"], "notes": "NoteSequence b which was found in the second sample is suitable, because calculated sequence c\u2009=\u2009[2\u2009-\u20093,\u20092\u2009-\u20094,\u20092\u2009-\u20098,\u20099\u2009-\u20099]\u2009=\u2009[\u2009-\u20091,\u2009\u2009-\u20092,\u2009\u2009-\u20096,\u20090] (note that ci\u2009=\u2009bi\u2009-\u2009ai) has compressed sequence equals to p\u2009=\u2009[3,\u20092,\u20091,\u20094]."}, "positive_code": [{"source_code": "let print_array a =\n\tfor k = 0 to (Array.length a) - 1 do\n\t\tprint_int a.(k);\n\t\tprint_char ' ';\n\tdone;\n\n\tprint_newline ();\n;;\n\n\nlet read_array ?(delta=0) n =\n\tlet arr = Array.make n 0 in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %i\" (fun v -> arr.(k) <- v + delta;);\n\t\tdone;\n\t\tarr\n\tend\n;;\n\n\nlet permute_array a p =\n\tlet n = Array.length a in\n\tlet a' = Array.make n 0 in\n\tbegin\n\t\tfor k = 0 to (n - 1) do\n\t\t\ta'.( p.(k) ) <- a.(k);\n\t\tdone;\n\t\ta'\n\tend\n;;\n\n\nlet permute a p =\n\tlet n = Array.length a in\n\tlet a' = Array.make n 0 in\n\tlet p' = Array.make n 0 in\n\tbegin\n\t\tfor k = 0 to (n - 1) do\n\t\t\ta'.( p.(k) ) <- a.(k);\n\t\t\tp'.( p.(k) ) <- k;\n\t\tdone;\n\t\t(a', p')\n\tend\n;;\n\n\n(* a_permuted - sequence \"a\" permuted so that \\forall k: A_permuted[ P[k] ] = A[ k ] *)\nlet calc_b a_permuted l r = \n\tlet n = Array.length a_permuted in\n\tlet b = Array.make n 0 in\n\tlet b_last = ref l in (* B[ k - 1 ] *)\n\tbegin\n\n\t\tb.(0) <- !b_last;\n\n\t\tlet c = ref (!b_last - a_permuted.(0)) in (* minimum possible c - corresponds to the smallest P[k] *)\n\t\tlet k = ref 1 in\n\t\twhile (!k < n) && (!b_last <= r) do\n\t\t\tc := (!c + 1);\n\t\t\tb_last := max l (!c + a_permuted.(!k)); \n\t\t\tb.(!k) <- !b_last;\n\t\t\tc := !b_last - a_permuted.(!k);\n\t\t\tk := !k + 1;\n\t\tdone;\n\n\t\tif !b_last <= r then Some b else None\n\n\tend\n;;\n\n\nlet load_and_process_data n l r =\n\tlet a = read_array n in\n\tlet p = read_array n ~delta:(-1) in\n\tlet (a', p') = permute a p in\n\tlet b = calc_b a' l r in\n\tmatch b with\n\t| Some l -> print_array (permute_array l p')\n\t| None -> print_endline \"-1\"\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i %i %i \" load_and_process_data\n;;\n\n\nread_input ()\n"}, {"source_code": "let print_array a =\n\tfor k = 0 to (Array.length a) - 1 do\n\t\tprint_int a.(k);\n\t\tprint_char ' ';\n\tdone;\n\n\tprint_newline ();\n;;\n\n\nlet read_array ?(delta=0) n =\n\tlet arr = Array.make n 0 in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %i\" (fun v -> arr.(k) <- v + delta;);\n\t\tdone;\n\t\tarr\n\tend\n;;\n\n\nlet permute_array a p =\n\tlet n = Array.length a in\n\tlet a' = Array.make n 0 in\n\tbegin\n\t\tfor k = 0 to (n - 1) do\n\t\t\ta'.( p.(k) ) <- a.(k);\n\t\tdone;\n\t\ta'\n\tend\n;;\n\n\nlet invert_permutation p =\n\tlet n = Array.length p in\n\tlet p' = Array.make n 0 in\n\tbegin\n\t\tfor k = 0 to (n - 1) do\n\t\t\tp'.( p.(k) ) <- k;\n\t\tdone;\n\t\tp'\n\tend\n;;\n\n\n(* a_permuted - sequence \"a\" permuted so that \\forall k: A_permuted[ P[k] ] = A[ k ] *)\nlet calc_b a_permuted l r = \n\tlet n = Array.length a_permuted in\n\tlet b = Array.make n 0 in\n\tlet b_last = ref l in (* B[ k - 1 ] *)\n\tbegin\n\n\t\tb.(0) <- !b_last;\n\n\t\tlet c = ref (!b_last - a_permuted.(0)) in (* minimum possible c - corresponds to the smallest P[k] *)\n\t\tlet k = ref 1 in\n\t\twhile (!k < n) && (!b_last <= r) do\n\t\t\tc := (!c + 1);\n\t\t\tb_last := max l (!c + a_permuted.(!k)); \n\t\t\tb.(!k) <- !b_last;\n\t\t\tc := !b_last - a_permuted.(!k);\n\t\t\tk := !k + 1;\n\t\tdone;\n\n\t\tif !b_last <= r then Some b else None\n\n\tend\n;;\n\n\nlet load_and_process_data n l r =\n\tlet a = read_array n in\n\tlet p = read_array n ~delta:(-1) in\n\tlet b = calc_b (permute_array a p) l r in\n\tmatch b with\n\t| Some l -> print_array (permute_array l (invert_permutation p))\n\t| None -> print_endline \"-1\"\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i %i %i \" load_and_process_data\n;;\n\n\nread_input ()\n"}, {"source_code": "let print_array a =\n\tfor k = 0 to (Array.length a) - 1 do\n\t\tprint_int a.(k);\n\t\tprint_char ' ';\n\tdone;\n\n\tprint_newline ();\n;;\n\n\nlet read_array ?(delta=0) n =\n\tlet arr = Array.make n 0 in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %i\" (fun v -> arr.(k) <- v + delta;);\n\t\tdone;\n\t\tarr\n\tend\n;;\n\n\nlet invert_permutation p =\n\tlet n = Array.length p in\n\tlet p' = Array.make n 0 in\n\tbegin\n\t\tfor k = 0 to (n - 1) do\n\t\t\tp'.( p.(k) ) <- k;\n\t\tdone;\n\t\tp'\n\tend\n;;\n\n\n(* p' - invert function to p, i.e. the function restoring back the permutation created by p *)\nlet calc_b a p' l r = \n\tlet n = Array.length a in\n\tlet b = Array.make n 0 in\n\tlet b_last = ref l in (* B[ k - 1 ] *)\n\tlet k' = ref p'.( 0 ) in\n\tbegin\n\n\t\tb.( !k' ) <- !b_last;\n\n\t\tlet a_cur = ref a.( !k' ) in\n\t\tlet c = ref (!b_last - !a_cur) in (* minimum possible c - corresponds to the smallest P[k] *)\n\t\tlet k = ref 1 in\n\t\twhile (!k < n) && (!b_last <= r) do\n\t\t\tk' := p'.( !k );\n\t\t\ta_cur := a.( !k' );\n\t\t\tc := (!c + 1);\n\t\t\tb_last := max l (!c + !a_cur); \n\t\t\tb.(!k') <- !b_last;\n\t\t\tc := !b_last - !a_cur;\n\t\t\tk := !k + 1;\n\t\tdone;\n\n\t\tif !b_last <= r then Some b else None\n\n\tend\n;;\n\n\nlet load_and_process_data n l r =\n\tlet a = read_array n in\n\tlet p = read_array n ~delta:(-1) in\n\tlet b = calc_b a (invert_permutation p) l r in\n\tmatch b with\n\t| Some l -> print_array l \n\t| None -> print_endline \"-1\"\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i %i %i \" load_and_process_data\n;;\n\n\nread_input ()\n"}, {"source_code": "let () =\n Scanf.scanf \"%d %d %d \" @@ fun n l r ->\n let a = Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n let p = Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n let b = Array.make n 0 in\n let revp = Array.make n 0 in\n Array.iteri (fun i j -> revp.(j - 1) <- i) p;\n let rec loop prevc i =\n if i < n then\n let j = revp.(i) in\n b.(j) <- max l (a.(j) + prevc + 1);\n if b.(j) > r then\n false\n else\n loop (b.(j) - a.(j)) (i + 1)\n else true in\n if loop (l - r - 1) 0 then\n Array.to_list b |> List.map string_of_int |> String.concat \" \" |> print_endline\n else\n print_endline \"-1\"\n"}], "negative_code": [], "src_uid": "46096413faf7d9f845131d9e48bd8401"} {"nl": {"description": "Vova's house is an array consisting of $$$n$$$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $$$i$$$-th element of the array is $$$1$$$ if there is a heater in the position $$$i$$$, otherwise the $$$i$$$-th element of the array is $$$0$$$.Each heater has a value $$$r$$$ ($$$r$$$ is the same for all heaters). This value means that the heater at the position $$$pos$$$ can warm up all the elements in range $$$[pos - r + 1; pos + r - 1]$$$.Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater. Vova's target is to warm up the whole house (all the elements of the array), i.e. if $$$n = 6$$$, $$$r = 2$$$ and heaters are at positions $$$2$$$ and $$$5$$$, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first $$$3$$$ elements will be warmed up by the first heater and the last $$$3$$$ elements will be warmed up by the second heater).Initially, all the heaters are off.But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.Your task is to find this number of heaters or say that it is impossible to warm up the whole house.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$r$$$ ($$$1 \\le n, r \\le 1000$$$) \u2014 the number of elements in the array and the value of heaters. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 1$$$) \u2014 the Vova's house description.", "output_spec": "Print one integer \u2014 the minimum number of heaters needed to warm up the whole house or -1 if it is impossible to do it.", "sample_inputs": ["6 2\n0 1 1 0 0 1", "5 3\n1 0 0 0 1", "5 10\n0 0 0 0 0", "10 3\n0 0 1 1 0 1 0 0 0 1"], "sample_outputs": ["3", "2", "-1", "3"], "notes": "NoteIn the first example the heater at the position $$$2$$$ warms up elements $$$[1; 3]$$$, the heater at the position $$$3$$$ warms up elements $$$[2, 4]$$$ and the heater at the position $$$6$$$ warms up elements $$$[5; 6]$$$ so the answer is $$$3$$$.In the second example the heater at the position $$$1$$$ warms up elements $$$[1; 3]$$$ and the heater at the position $$$5$$$ warms up elements $$$[3; 5]$$$ so the answer is $$$2$$$.In the third example there are no heaters so the answer is -1.In the fourth example the heater at the position $$$3$$$ warms up elements $$$[1; 5]$$$, the heater at the position $$$6$$$ warms up elements $$$[4; 8]$$$ and the heater at the position $$$10$$$ warms up elements $$$[8; 10]$$$ so the answer is $$$3$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nmodule Imos = struct\n\tlet make n = Array.make (i32 n +$ 2) 0L\n\tlet add_destructive_closed l r a =\n\t\ta.(l+$1) <- a.(l+$1) + 1L;\n\t\ta.(r+$2) <- a.(r+$2) - 1L\n\tlet add_destructive_1orig_closed l r a =\n\t\tlet l = max l 0 in a.(l) <- a.(l) + 1L;\n\t\tlet r = min (r+$1) (Array.length a-$1) in a.(r) <- a.(r) - 1L\n\tlet cumulate_destructive a = for i=1 to Array.length a -$ 2 do\n\t\ta.(i) <- a.(i) + a.(i-$1)\n\tdone\nend\n\nlet () =\n\tlet n,r = get_2_i64\t0 in\n\tlet imos = Imos.make n in\n\tlet ls = ref [] in\n\trep 1L n (fun i ->\n\t\tlet p = get_i64 0 in\n\t\tif p = 1L then (\n\t\t\tls := i :: !ls;\n\t\t\tImos.add_destructive_1orig_closed (i32 @@ i-r+1L) (i32 @@ i+r-1L) imos;\n\t\t\t(* printf \"%Ld: %Ld %Ld\\n\" i (i-r+1L) (i+r-1L); *)\n\t\t\t(* dump_array imos; *)\n\t\t);\n\t\t`Ok\n\t);\n\tImos.cumulate_destructive imos;\n\t(* dump_array imos; *)\n\t(* let f = Array.fold_left (fun u v ->\n\t\tif u then u else if v=0L then true else false) false imos\n\tin\n\tif f then (\n\t\tprintf \"-1\\n\"; exit 0\n\t); *)\n\tif repm 1L n false (fun u i ->\n\t\t`Ok (if u then u else if imos.(i32 i)=0L then true else false)\n\t) then (\n\t\tprintf \"-1\\n\"; exit 0\n\t);\n\tList.fold_left (fun u p ->\n\t\tlet f = ref true in\n\t\tfor i=(max (i32 @@ p-r+1L) 1) to min (i32 @@ p+r-1L) (i32 n) do\n\t\t\tif imos.(i) = 1L then f := false\n\t\tdone;\n\t\t(* printf \"%Ld: %b\\n\" p !f; *)\n\t\tif not !f then u+1L else (\n\t\t\tfor i=max (i32 @@ p-r+1L) 1 to min (i32 @@ p+r-1L) (i32 n) do\n\t\t\t\timos.(i) <- imos.(i) - 1L;\n\t\t\tdone;\n\t\t\t(* dump_array imos; *)\n\t\t\tu\n\t\t)\n\t) 0L !ls\n\t|> printf \"%Ld\\n\"\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nmodule Imos = struct\n\tlet make n = Array.make (i32 n +$ 2) 0L\n\tlet add_destructive_closed l r a =\n\t\ta.(l+$1) <- a.(l+$1) + 1L;\n\t\ta.(r+$2) <- a.(r+$2) - 1L\n\tlet add_destructive_1orig_closed l r a =\n\t\tlet l = max l 0 in a.(l) <- a.(l) + 1L;\n\t\tlet r = min (r+$1) (Array.length a-$1) in a.(r) <- a.(r) - 1L\n\tlet cumulate_destructive a = for i=1 to Array.length a -$ 2 do\n\t\ta.(i) <- a.(i) + a.(i-$1)\n\tdone\nend\n\nlet () =\n\tlet n,r = get_2_i64\t0 in\n\tlet imos = Imos.make n in\n\tlet ls = ref [] in\n\trep 1L n (fun i ->\n\t\tlet p = get_i64 0 in\n\t\tif p = 1L then (\n\t\t\tls := i :: !ls;\n\t\t\tImos.add_destructive_1orig_closed (i32 @@ i-r+1L) (i32 @@ i+r-1L) imos;\n\t\t\t(* printf \"%Ld: %Ld %Ld\\n\" i (i-r+1L) (i+r-1L); *)\n\t\t\t(* dump_array imos; *)\n\t\t);\n\t\t`Ok\n\t);\n\tImos.cumulate_destructive imos;\n\t(* dump_array imos; *)\n\t(* let f = Array.fold_left (fun u v ->\n\t\tif u then u else if v=0L then true else false) false imos\n\tin\n\tif f then (\n\t\tprintf \"-1\\n\"; exit 0\n\t); *)\n\tif repm 1L n false (fun u i ->\n\t\t`Ok (if u then u else if imos.(i32 i)=0L then true else false)\n\t) then (\n\t\tprintf \"-1\\n\"; exit 0\n\t);\n\tList.fold_left (fun u p ->\n\t\tlet f = ref true in\n\t\tfor i=(max (i32 @@ p-r+1L) 1) to min (i32 @@ p+r-1L) (i32 n) do\n\t\t\tif imos.(i) = 1L then f := false\n\t\tdone;\n\t\t(* printf \"%Ld: %b\\n\" p !f; *)\n\t\tif !f then u else u+1L\n\t) 0L !ls\n\t|> printf \"%Ld\\n\"\n\n\n\n\n\n\n"}], "src_uid": "001d8aca7c8421c3e54863f3fb706f0d"} {"nl": {"description": "A tree is a connected graph that doesn't contain any cycles.The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u200950000, 1\u2009\u2264\u2009k\u2009\u2264\u2009500) \u2014 the number of vertices and the required distance between the vertices. Next n\u2009-\u20091 lines describe the edges as \"ai bi\" (without the quotes) (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.", "output_spec": "Print a single integer \u2014 the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["5 2\n1 2\n2 3\n3 4\n2 5", "5 3\n1 2\n2 3\n3 4\n4 5"], "sample_outputs": ["4", "2"], "notes": "NoteIn the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4)."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n for i = 1 to n - 1 do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tes.(v) <- u :: es.(v);\n done;\n let es = Array.map Array.of_list es in\n let res = ref 0L in\n let used = Array.make n false in\n let rec bfs u ds =\n let ds2 = Array.make k 0 in\n let ds4 = Array.make k 0 in\n\tds2.(0) <- 1;\n\tds4.(0) <- 1;\n\tfor i = 1 to k - 1 do\n\t ds2.(i) <- ds.(i - 1);\n\tdone;\n\t(*for i = 0 to k - 1 do\n\t Printf.printf \"asd %d %d +%d\\n\" u i ds.(i);\n\tdone;*)\n\tres := Int64.add !res (Int64.of_int ds.(k - 1));\n\tused.(u) <- true;\n\tfor i = 0 to Array.length es.(u) - 1 do\n\t let v = es.(u).(i) in\n\t if not used.(v) then (\n\t let ds3 = bfs v ds2 in\n\t\tfor i = 1 to k - 1 do\n\t\t ds2.(i) <- ds2.(i) + ds3.(i - 1);\n\t\t ds4.(i) <- ds4.(i) + ds3.(i - 1);\n\t\tdone\n\t )\n\tdone;\n\tds4\n in\n ignore (bfs 0 (Array.make k 0));\n Printf.printf \"%Ld\\n\" !res;\n"}], "negative_code": [], "src_uid": "2fc19c3c9604e746a17a63758060c5d7"} {"nl": {"description": "You are given a book with $$$n$$$ chapters.Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list.Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter.Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 2\\cdot10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$) \u2014 number of chapters. Then $$$n$$$ lines follow. The $$$i$$$-th line begins with an integer $$$k_i$$$ ($$$0 \\le k_i \\le n-1$$$) \u2014 number of chapters required to understand the $$$i$$$-th chapter. Then $$$k_i$$$ integers $$$a_{i,1}, a_{i,2}, \\dots, a_{i, k_i}$$$ ($$$1 \\le a_{i, j} \\le n, a_{i, j} \\ne i, a_{i, j} \\ne a_{i, l}$$$ for $$$j \\ne l$$$) follow \u2014 the chapters required to understand the $$$i$$$-th chapter. It is guaranteed that the sum of $$$n$$$ and sum of $$$k_i$$$ over all testcases do not exceed $$$2\\cdot10^5$$$.", "output_spec": "For each test case, if the entire book can be understood, print how many times you will read it, otherwise print $$$-1$$$.", "sample_inputs": ["5\n4\n1 2\n0\n2 1 4\n1 2\n5\n1 5\n1 1\n1 2\n1 3\n1 4\n5\n0\n0\n2 1 2\n1 2\n2 2 1\n4\n2 2 3\n0\n0\n2 3 2\n5\n1 2\n1 3\n1 4\n1 5\n0"], "sample_outputs": ["2\n-1\n1\n2\n5"], "notes": "NoteIn the first example, we will understand chapters $$$\\{2, 4\\}$$$ in the first reading and chapters $$$\\{1, 3\\}$$$ in the second reading of the book.In the second example, every chapter requires the understanding of some other chapter, so it is impossible to understand the book.In the third example, every chapter requires only chapters that appear earlier in the book, so we can understand everything in one go.In the fourth example, we will understand chapters $$$\\{2, 3, 4\\}$$$ in the first reading and chapter $$$1$$$ in the second reading of the book.In the fifth example, we will understand one chapter in every reading from $$$5$$$ to $$$1$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n\n let graph = Array.make n [] in\n\n for i=0 to n-1 do\n let k = read_int () in\n for z=0 to k-1 do\n\tlet j = -1+read_int () in\n\t(* chapter j depends on i *)\n\tgraph.(i) <- j::graph.(i)\n done\n done;\n (* graph is the reverse of the dependency graph *)\n\n (* first see if the graph is acyclic *)\n let visited = Array.make n false in\n let sorted = Array.make n 0 in\n let k = ref 0 in\n let rec topsort v =\n if not visited.(v) then (\n\tvisited.(v) <- true;\n\tList.iter topsort graph.(v);\n\tsorted.(v) <- !k;\n\tk := !k+1\n )\n in\n for v=0 to n-1 do topsort v done;\n\n let acyclic = forall 0 (n-1) (fun v ->\n List.fold_left (fun ac w ->\n\tac && sorted.(v) > sorted.(w)\n ) true graph.(v))\n in\n if not acyclic then printf \"-1\\n\" else (\n\n let lirp = Array.make n (-1) in (* longest increasing reverse path *)\n\n let rec dfs v =\n\tif lirp.(v) >= 0 then lirp.(v) else (\n\t let my_val = List.fold_left (fun ac w ->\n\t let x = (if w>v then 1 else 0) + (dfs w) in\n\t max ac x\n\t ) 0 graph.(v)\n\t in\n\t lirp.(v) <- my_val;\n\t my_val\n\t)\n in\n\n printf \"%d\\n\" (1 + maxf 0 (n-1) dfs)\n )\n done\n"}], "negative_code": [], "src_uid": "af40a0de6d3c0ff7bcd2c1b077b05d6e"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ integers and an integer $$$s$$$. It is guaranteed that $$$n$$$ is odd.In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $$$s$$$.The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $$$6, 5, 8$$$ is equal to $$$6$$$, since if we sort this array we will get $$$5, 6, 8$$$, and $$$6$$$ is located on the middle position.", "input_spec": "The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1\\le n\\le 2\\cdot 10^5-1$$$, $$$1\\le s\\le 10^9$$$)\u00a0\u2014 the length of the array and the required value of median. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1\\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array $$$a$$$. It is guaranteed that $$$n$$$ is odd.", "output_spec": "In a single line output the minimum number of operations to make the median being equal to $$$s$$$.", "sample_inputs": ["3 8\n6 5 8", "7 20\n21 15 12 11 20 19 12"], "sample_outputs": ["2", "6"], "notes": "NoteIn the first sample, $$$6$$$ can be increased twice. The array will transform to $$$8, 5, 8$$$, which becomes $$$5, 8, 8$$$ after sorting, hence the median is equal to $$$8$$$.In the second sample, $$$19$$$ can be increased once and $$$15$$$ can be increased five times. The array will become equal to $$$21, 20, 12, 11, 20, 20, 12$$$. If we sort this array we get $$$11, 12, 12, 20, 20, 20, 21$$$, this way the median is $$$20$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\t\n\tlet repm from_ to_ m_init fbod =\n\t\tlet i,f,m = ref ~|from_,ref true,ref m_init in\n\t\twhile !i <= ~|to_ && !f do\n\t\t\tmatch fbod (~~| !i) !m with\n\t\t\t| `Break -> f := false\n\t\t\t| `Break_m m' -> (f := false; m := m')\n\t\t\t| `Ok m' -> (i := !i +$ 1; m := m')\n\t\tdone; !m\nend open MyInt64\nmodule Array = struct\n\tinclude Array\n\tlet destruct f a =\n\t\tfor i=0 to (Array.length a -$ 1) do\n\t\t\tlet c = ref a.(i) in f c; a.(i) <- !c;\n\t\tdone\n\tlet destructi f a =\n\t\tfor i=0 to (Array.length a -$ 1) do\n\t\t\tlet c = ref a.(i) in f i c; a.(i) <- !c;\n\t\tdone\n\tlet foldi_left f v a = \n\t\tlet m = ref v in for i=0 to (Array.length a -$ 1) do\n\t\t\tm := f !m (~~|i) a.(i)\n\t\tdone; !m\n\tlet foldii_left f v a =\n\t\tlet m = ref v in for i=0 to (Array.length a -$ 1) do\n\t\t\tm := f !m (~~|i)\n\t\tdone; !m\n\tlet foldmap f v a =\n\t\tlet m = ref v in Array.map (fun w -> let mm,vv = f !m w in m := mm; vv) a\n\tlet foldmapi f v a = \n\t\tlet m = ref v in Array.mapi (fun i w -> let mm,vv = f i !m v in m := mm; vv) a\n\t(* let exists f a = BatArray.exists *)\n\tlet exists f a = let flg,i = ref true,ref 0 in while !flg && !i\n\t\tlet d = labs (s - v) in\n\t\tif i < i_mid && v > s\n\t\t|| i > i_mid && v < s\n\t\t|| i = i_mid && v <> s then u + d\n\t\telse u\n\t) 0L a\n\t|> printf \"%Ld\\n\""}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v\n\tlet labs p = if p < 0L then -1L*p else p\n\tlet (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p\n\n\tlet input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n = n |> Int64.to_string |> print_endline\n\t\n\tlet (mod) m n = m - (m/n) * n let (%) = (mod)\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n\n\tlet repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\n\tlet rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\nend\n\nopen MyInt64\nlet () =\n\tlet n,s = get_2_i64 0\n\tin\n\tif n=1L then (\n\t\tlet v = get_i64 0 in printf \"%Ld\" (labs (v-s))\n\t) else (\n\tlet a = Array.make (~|n) 0L in\n\trep 0L (n) (fun i -> \n\t\ta.(~|i) <- get_i64 0;\n\t\t(* printf \";;%Ld %Ld\\n\" i a.(~|i); *)\n\t\t`Ok\n\t);\n\tArray.sort compare a;\n\tlet i_med = n / 2L\n\tin let i_nearest = (\n\t\tlet fv = ref 0L in\n\t\tlet res = ref (n) in\n\t\trepint 0L (n) (fun i -> \n\t\t\t(* printf \"::%d, %Ld\\n\" i a.(i); *)\n\t\t\tif a.(i) = s then (\n\t\t\t\tres := ~~| i; `Ng\n\t\t\t)\n\t\t\telse if a.(i) < s then (\n\t\t\t\tfv := a.(i); `Ok\n\t\t\t) else (\n\t\t\t\tif s - !fv < a.(i) - s then (\n\t\t\t\t\tres := ~~| i\n\t\t\t\t) else (\n\t\t\t\t\tres := ~~| i - 1L\n\t\t\t\t);\n\t\t\t\t`Ng\n\t\t\t)\n\t\t); !res\n\t) in\n\tlet res = ref 0L in\n\trep i_med i_nearest (fun i -> \n\t\tres += (s - a.(~|i)); `Ok\n\t);\n\t!res |> printf \"%Ld\\n\";\n\t(* printf \"%Ld %Ld\" i_med i_nearest; *)\n\t)\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v\n\tlet labs p = if p < 0L then -1L*p else p\n\tlet (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p\n\n\tlet input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n = n |> Int64.to_string |> print_endline\n\t\n\tlet (mod) m n = m - (m/n) * n let (%) = (mod)\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n\n\tlet repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\n\tlet rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\nend\n\nopen MyInt64\nlet () =\n\tlet n,s = get_2_i64 0\n\tin\n\tif n=1L then (\n\t\tlet v = get_i64 0 in printf \"%Ld\" (labs (v-s))\n\t) else (\n\tlet a = Array.make (~|n) 0L in\n\trep 0L (n) (fun i -> \n\t\ta.(~|i) <- get_i64 0;\n\t\t(* printf \";;%Ld %Ld\\n\" i a.(~|i); *)\n\t\t`Ok\n\t);\n\tArray.sort compare a;\n\tlet i_med = n / 2L\n\tin let i_nearest = (\n\t\tlet fv = ref 0L in\n\t\tlet res = ref (n) in\n\t\trepint 0L (n) (fun i -> \n\t\t\t(* printf \"::%d, %Ld\\n\" i a.(i); *)\n\t\t\tif a.(i) = s then (\n\t\t\t\tres := ~~| i; `Ng\n\t\t\t)\n\t\t\telse if a.(i) < s then (\n\t\t\t\tfv := a.(i); `Ok\n\t\t\t) else (\n\t\t\t\tif !fv = 0L then (\n\t\t\t\t\tres := ~~| i\n\t\t\t\t) else if s - !fv < a.(i) - s then (\n\t\t\t\t\tres := ~~| i\n\t\t\t\t) else (\n\t\t\t\t\tres := ~~| i - 1L\n\t\t\t\t);\n\t\t\t\t`Ng\n\t\t\t)\n\t\t); !res\n\t) in\n\tlet res = ref 0L in\n\tif i_nearest > i_med\n\tthen rep i_med i_nearest (fun i -> \n\t\tres += labs (s - a.(~|i)); `Ok\n\t) else rep i_nearest (i_med + 1L) (fun i -> \n\t\tres += labs (s - a.(~|i)); `Ok\n\t);\n\t!res |> printf \"%Ld\\n\";\n\t(* printf \"%Ld %Ld\" i_med i_nearest; *)\n\t)\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\t\n\tlet repm from_ to_ m_init fbod =\n\t\tlet i,f,m = ref ~|from_,ref true,ref m_init in\n\t\twhile !i <= ~|to_ && !f do\n\t\t\tmatch fbod (~~| !i) !m with\n\t\t\t| `Break -> f := false\n\t\t\t| `Break_m m' -> (f := false; m := m')\n\t\t\t| `Ok m' -> (i := !i +$ 1; m := m')\n\t\tdone; !m\nend\n\nopen MyInt64\nlet rec binary_search_value_nearest v l r a = \n\tif a.(~|l) > v then `Nearest l\n\telse if a.(~|r) < v then `Nearest r\n\telse if l=r then (\n\t\tif a.(~|l)=v then `At l else `Nearest l\n\t) else (\n\t\tlet mid = l+(r-l)/2L in\n\t\tif a.(~|mid)>v then binary_search_value_nearest v l (mid-1L) a else\n\t\tif a.(~|mid) i\n\t) in\n\tlet ans =\n\t\tif i_mid = i_nearest then (\n\t\t\tlabs (s - a.(~|i_nearest))\n\t\t) else if i_mid < i_nearest then (\n\t\t\trepm i_mid i_nearest 0L (fun i m -> `Ok (m + labs (s - a.(~|i))))\n\t\t) else (\n\t\t\trepm i_nearest i_mid 0L (fun i m -> `Ok (m + labs (s - a.(~|i))))\n\t\t)\n\tin\n\tprintf \"%Ld\\n\" ans\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v\n\tlet labs p = if p < 0L then -1L*p else p\n\tlet (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p\n\n\tlet input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n = n |> Int64.to_string |> print_endline\n\t\n\tlet (mod) m n = m - (m/n) * n let (%) = (mod)\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n\n\tlet repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\n\tlet rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\nend\n\nopen MyInt64\nlet () =\n\tlet n,s = get_2_i64 0\n\tin\n\tif n=1L then (\n\t\tlet v = get_i64 0 in printf \"%Ld\" (labs (v-s))\n\t) else (\n\tlet a = Array.make (~|n) 0L in\n\trep 0L (n) (fun i -> \n\t\ta.(~|i) <- get_i64 0;\n\t\t(* printf \";;%Ld %Ld\\n\" i a.(~|i); *)\n\t\t`Ok\n\t);\n\tArray.sort compare a;\n\tlet i_med = n / 2L\n\tin let i_nearest = (\n\t\tlet fv = ref 0L in\n\t\tlet res = ref (n) in\n\t\trepint 0L (n) (fun i -> \n\t\t\t(* printf \"::%d, %Ld\\n\" i a.(i); *)\n\t\t\tif a.(i) = s then (\n\t\t\t\tres := ~~| i; `Ng\n\t\t\t)\n\t\t\telse if a.(i) < s then (\n\t\t\t\tfv := a.(i); `Ok\n\t\t\t) else (\n\t\t\t\tif !fv = 0L then (\n\t\t\t\t\tres := ~~| i\n\t\t\t\t) else if labs (s - !fv) < labs (a.(i) - s) then (\n\t\t\t\t\tres := ~~| i - 1L\n\t\t\t\t) else if labs (s - !fv) > labs (a.(i) - s) then (\n\t\t\t\t\tres := ~~| i \n\t\t\t\t) else (\n\t\t\t\t\tres := (\n\t\t\t\t\t\tif labs (~~|i - i_med) < labs (~~|i - 1L - i_med) then (\n\t\t\t\t\t\t\t~~| i\n\t\t\t\t\t\t) else (\n\t\t\t\t\t\t\t~~| i - 1L\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t\t`Ng\n\t\t\t)\n\t\t); !res\n\t) in\n\tlet res = ref 0L in\n\tif i_nearest > i_med\n\tthen rep i_med (min (i_nearest + 1L) n) (fun i -> \n\t\tres += labs (s - a.(~|i)); `Ok\n\t) else rep i_nearest (i_med + 1L) (fun i -> \n\t\tres += labs (s - a.(~|i)); `Ok\n\t);\n\t!res |> printf \"%Ld\\n\";\n\t(* printf \"%Ld %Ld\" i_med i_nearest; *)\n\t)\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v\n\tlet labs p = if p < 0L then -1L*p else p\n\tlet (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p\n\n\tlet input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n = n |> Int64.to_string |> print_endline\n\t\n\tlet (mod) m n = m - (m/n) * n let (%) = (mod)\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n\n\tlet repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\n\tlet rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\nend\n\nopen MyInt64\nlet () =\n\tlet n,s = get_2_i64 0\n\tin\n\tif n=1L then (\n\t\tlet v = get_i64 0 in printf \"%Ld\" (labs (v-s))\n\t) else (\n\tlet a = Array.make (~|n) 0L in\n\trep 0L (n) (fun i -> \n\t\ta.(~|i) <- get_i64 0;\n\t\t(* printf \";;%Ld %Ld\\n\" i a.(~|i); *)\n\t\t`Ok\n\t);\n\tArray.sort compare a;\n\tlet i_med = n / 2L\n\tin let i_nearest = (\n\t\tlet fv = ref 0L in\n\t\tlet res = ref (n) in\n\t\trepint 0L (n) (fun i -> \n\t\t\t(* printf \"::%d, %Ld\\n\" i a.(i); *)\n\t\t\tif a.(i) = s then (\n\t\t\t\tres := ~~| i; `Ng\n\t\t\t)\n\t\t\telse if a.(i) < s then (\n\t\t\t\tfv := a.(i); `Ok\n\t\t\t) else (\n\t\t\t\tif !fv = 0L then (\n\t\t\t\t\tres := ~~| i\n\t\t\t\t) else if s - !fv < a.(i) - s then (\n\t\t\t\t\tres := ~~| i\n\t\t\t\t) else if s - !fv > a.(i) - s then (\n\t\t\t\t\tres := ~~| i - 1L\n\t\t\t\t) else (\n\t\t\t\t\tres := (\n\t\t\t\t\t\tif labs (~~|i - i_med) < labs (~~|i - 1L - i_med) then (\n\t\t\t\t\t\t\t~~| i\n\t\t\t\t\t\t) else (\n\t\t\t\t\t\t\t~~| i - 1L\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t\t`Ng\n\t\t\t)\n\t\t); !res\n\t) in\n\tlet res = ref 0L in\n\tif i_nearest > i_med\n\tthen rep i_med i_nearest (fun i -> \n\t\tres += labs (s - a.(~|i)); `Ok\n\t) else rep i_nearest (i_med + 1L) (fun i -> \n\t\tres += labs (s - a.(~|i)); `Ok\n\t);\n\t!res |> printf \"%Ld\\n\";\n\t(* printf \"%Ld %Ld\" i_med i_nearest; *)\n\t)"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v\n\tlet labs p = if p < 0L then -1L*p else p\n\tlet (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p\n\n\tlet input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n = n |> Int64.to_string |> print_endline\n\t\n\tlet (mod) m n = m - (m/n) * n let (%) = (mod)\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n\n\tlet repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\n\tlet rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done\nend\n\nopen MyInt64\nlet () =\n\tlet n,s = get_2_i64 0\n\tin\n\tif n=1L then (\n\t\tlet v = get_i64 0 in printf \"%Ld\" (labs (v-s))\n\t) else (\n\tlet a = Array.make (~|n) 0L in\n\trep 0L (n) (fun i -> \n\t\ta.(~|i) <- get_i64 0;\n\t\t(* printf \";;%Ld %Ld\\n\" i a.(~|i); *)\n\t\t`Ok\n\t);\n\tArray.sort compare a;\n\tlet i_med = n / 2L\n\tin let i_nearest = (\n\t\tlet fv = ref 0L in\n\t\tlet res = ref (n) in\n\t\trepint 0L (n) (fun i -> \n\t\t\t(* printf \"::%d, %Ld\\n\" i a.(i); *)\n\t\t\tif a.(i) = s then (\n\t\t\t\tres := ~~| i; `Ng\n\t\t\t)\n\t\t\telse if a.(i) < s then (\n\t\t\t\tfv := a.(i); `Ok\n\t\t\t) else (\n\t\t\t\tif !fv = 0L then (\n\t\t\t\t\tres := ~~| i\n\t\t\t\t) else if s - !fv < a.(i) - s then (\n\t\t\t\t\tres := ~~| i\n\t\t\t\t) else if s - !fv > a.(i) - s then (\n\t\t\t\t\tres := ~~| i - 1L\n\t\t\t\t) else (\n\t\t\t\t\tres := (\n\t\t\t\t\t\tif labs (~~|i - i_med) < labs (~~|i - 1L - i_med) then (\n\t\t\t\t\t\t\t~~| i\n\t\t\t\t\t\t) else (\n\t\t\t\t\t\t\t~~| i - 1L\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t\t`Ng\n\t\t\t)\n\t\t); !res\n\t) in\n\tlet res = ref 0L in\n\tif i_nearest > i_med\n\tthen rep i_med (min (i_nearest + 1L) n) (fun i -> \n\t\tres += labs (s - a.(~|i)); `Ok\n\t) else rep i_nearest (i_med + 1L) (fun i -> \n\t\tres += labs (s - a.(~|i)); `Ok\n\t);\n\t!res |> printf \"%Ld\\n\";\n\t(* printf \"%Ld %Ld\" i_med i_nearest; *)\n\t)"}], "src_uid": "0df33cd53575471b1cc20702bf777059"} {"nl": {"description": "You're given an array $$$a$$$ of length $$$2n$$$. Is it possible to reorder it in such way so that the sum of the first $$$n$$$ elements isn't equal to the sum of the last $$$n$$$ elements?", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 1000$$$), where $$$2n$$$ is the number of elements in the array $$$a$$$. The second line contains $$$2n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_{2n}$$$ ($$$1 \\le a_i \\le 10^6$$$)\u00a0\u2014 the elements of the array $$$a$$$.", "output_spec": "If there's no solution, print \"-1\" (without quotes). Otherwise, print a single line containing $$$2n$$$ space-separated integers. They must form a reordering of $$$a$$$. You are allowed to not change the order.", "sample_inputs": ["3\n1 2 2 1 3 1", "1\n1 1"], "sample_outputs": ["2 1 3 1 1 2", "-1"], "notes": "NoteIn the first example, the first $$$n$$$ elements have sum $$$2+1+3=6$$$ while the last $$$n$$$ elements have sum $$$1+1+2=4$$$. The sums aren't equal.In the second example, there's no solution."}, "positive_code": [{"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x*2) in\n let a = Array.init n\n (fun _ ->\n Scanf.scanf \"%d \" (fun x -> x)\n )\n in\n let xx = a.(0) in\n let a = Array.to_list a in\n let all_eq =\n List.fold_left\n (fun acc x -> x = xx && acc) true a\n in\n if all_eq then Printf.printf \"-1\" else\n let a = List.sort compare a in\n List.iter (fun x -> Printf.printf \"%d \" x) a\n;;\n"}], "negative_code": [], "src_uid": "1f4c057dff45f229b4dca49cd4e0438d"} {"nl": {"description": "Marmot found a row with n pillars. The i-th pillar has the height of hi meters. Starting from one pillar i1, Marmot wants to jump on the pillars i2, ..., ik. (1\u2009\u2264\u2009i1\u2009<\u2009i2\u2009<\u2009...\u2009<\u2009ik\u2009\u2264\u2009n). From a pillar i Marmot can jump on a pillar j only if i\u2009<\u2009j and |hi\u2009-\u2009hj|\u2009\u2265\u2009d, where |x| is the absolute value of the number x.Now Marmot is asking you find out a jump sequence with maximal length and print it.", "input_spec": "The first line contains two integers n and d (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009d\u2009\u2264\u2009109). The second line contains n numbers h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u20091015).", "output_spec": "The first line should contain one integer k, the maximal length of a jump sequence. The second line should contain k integers i1,\u2009i2,\u2009...,\u2009ik (1\u2009\u2264\u2009i1\u2009<\u2009i2\u2009<\u2009...\u2009<\u2009ik\u2009\u2264\u2009n), representing the pillars' indices from the maximal length jump sequence. If there is more than one maximal length jump sequence, print any.", "sample_inputs": ["5 2\n1 3 6 7 4", "10 3\n2 1 3 6 9 11 7 3 20 18"], "sample_outputs": ["4\n1 2 3 5", "6\n1 4 6 7 8 9"], "notes": "NoteIn the first example Marmot chooses the pillars 1, 2, 3, 5 with the heights 1, 3, 6, 4. Another jump sequence of length 4 is 1, 2, 4, 5."}, "positive_code": [{"source_code": "module Lib_option = struct\n module Option = struct\n let value ~default = function\n | None -> default\n | Some value -> value\n end\nend\n\nmodule Lib_algorithm = struct\n open Lib_option\n \n let lower_bound ?(compare=compare) ?len arr ~x =\n let len = Option.value ~default:(Array.length arr) len in\n let bound = ref (-1) in\n let step = ref 1 in\n while !step lsl 1 < len do\n step := !step lsl 1\n done;\n while !step > 0 do\n let pos = !bound + !step in\n if pos < len && compare x arr.(pos) > 0 then\n bound := pos;\n step := !step lsr 1\n done;\n !bound + 1\n ;;\nend\n\nmodule Lib_iterators = struct\n module Make_iterators(C : sig\n type 'a t;;\n val iter : ('a -> unit) -> 'a t -> unit\n val map : ('a -> 'b) -> 'a t -> 'b t\n val iteri : (int -> 'a -> unit) -> 'a t -> unit\n val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t\n end) = struct\n let map ~f arr = C.map f arr;;\n let mapi ~f arr = C.mapi f arr;;\n let iter ~f arr = C.iter f arr;;\n let iteri ~f arr = C.iteri f arr;;\n end\nend\n\nmodule Lib_array = struct\n open Lib_iterators\n \n module T = struct\n include Array\n type 'a t = 'a array;;\n end\n \n module Array = struct\n include T\n include Make_iterators(T)\n \n let sort ?(cmp=compare) arr = sort cmp arr;;\n end\nend\n\nmodule Lib_int64 = struct\n module Int64 = struct\n include Int64\n \n let (+),(-),( * ),(/),(%),(~-) = add,sub,mul,div,rem,neg;;\n end\nend\n\nmodule Lib_core = struct\n let id x = x;;\n let const x _ = x;;\n \n let fail () = failwith \"\";;\nend\n\nmodule Lib_io = struct\n open Lib_core\n \n let printf = Printf.printf;;\n let scanf = Scanf.scanf;;\n \n let read_int () = scanf \" %d \" id;;\n let read_long () = scanf \" %Ld \" id;;\n let read_char () = scanf \" %c \" id;;\n let read_array n ~f = Array.init n (fun _ -> f ());;\nend\n\nmodule Lib_list = struct\n open Lib_iterators\n \n module T = struct\n include List\n type 'a t = 'a list;;\n end\n \n module List = struct\n include T\n include Make_iterators(T)\n \n let rev_map ~f l = rev_map f l;;\n end\nend\n\nmodule Lib_fenwick = struct\n module Make_fenwick(V : sig\n type t;;\n val neutral : t;;\n val reduce : t -> t -> t;;\n end) : sig\n type t;;\n type value;;\n val create : int -> t;;\n val update : t -> int -> value -> unit;;\n val query : t -> int -> value;;\n end with type value := V.t \n = struct\n type t = V.t array;;\n \n let create n = Array.make n V.neutral;;\n \n let lowbit x = x land -x;;\n \n let update t i x =\n let len = Array.length t in\n let i = ref (i + 1) in\n while !i <= len do\n t.(!i - 1) <- V.reduce t.(!i - 1) x;\n i := !i + lowbit !i\n done\n ;;\n \n let query t i =\n let i = ref (i + 1) in\n let acc = ref V.neutral in\n while !i > 0 do\n acc := V.reduce !acc t.(!i - 1);\n i := !i - lowbit !i\n done;\n !acc\n ;;\n end\nend\n\nmodule Lib_maxpos_fenwick = struct\n open Lib_fenwick\n \n module Make_fenwick(T : sig \n type t;; \n val zero : t;; \n end) = Make_fenwick (struct\n type t = T.t;;\n let neutral = T.zero;;\n let reduce = max;;\n end)\n \n module Int_fenwick = Make_fenwick(struct\n type t = int;;\n let zero = 0;;\n end)\nend\n\nopen Lib_io\nopen Lib_array\nopen Lib_list\nopen Lib_algorithm\nopen Lib_int64\n\nmodule Fenwick = Lib_maxpos_fenwick.Int_fenwick\n\nlet () =\n let n = read_int () in\n let d = read_long () in\n let hgs = read_array n ~f:read_long in\n let shgs = Array.copy hgs in\n Array.sort shgs;\n let lfen = Fenwick.create n in\n let rfen = Fenwick.create n in\n let vals = ref [] in\n let best = ref 0 in\n Array.iter hgs ~f:(fun h ->\n let lpos = lower_bound shgs ~x:Int64.(h - d + 1L) - 1 in\n let rpos = lower_bound shgs ~x:Int64.(h + d) in\n let curr = \n max (Fenwick.query lfen lpos) (Fenwick.query rfen (n - rpos - 1)) + 1\n in\n vals := curr :: !vals;\n best := max !best curr;\n let pos = lower_bound shgs ~x:h in\n Fenwick.update lfen pos curr;\n Fenwick.update rfen (n - pos - 1) curr\n );\n let curr = ref !best in\n let lasth = ref 0L in\n let path = ref [] in\n List.iteri !vals ~f:(fun i v ->\n let i = n - i - 1 in\n let h = hgs.(i) in\n if v = !curr && (!lasth = 0L || Int64.(abs (!lasth - h)) >= d) then begin\n path := (i + 1) :: !path;\n decr curr;\n lasth := h\n end\n );\n printf \"%d\\n\" !best;\n List.iter !path ~f:(printf \"%d \");\n print_newline ()\n;;\n"}], "negative_code": [], "src_uid": "81eedb71b77c6e7fda78049c23e7b6b7"} {"nl": {"description": "One day, Twilight Sparkle is interested in how to sort a sequence of integers a1,\u2009a2,\u2009...,\u2009an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1,\u2009a2,\u2009...,\u2009an\u2009\u2192\u2009an,\u2009a1,\u2009a2,\u2009...,\u2009an\u2009-\u20091. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?", "input_spec": "The first line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integer numbers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105).", "output_spec": "If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.", "sample_inputs": ["2\n2 1", "3\n1 3 2", "2\n1 2"], "sample_outputs": ["1", "-1", "0"], "notes": null}, "positive_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\n\nmodule Array = ArrayLabels ;;\nmodule List = ListLabels ;;\n\nlet solve n arr =\n let prev = ref arr.(0) in\n let rec iter i =\n if i = n then n\n else if !prev > arr.(i) then i\n else begin prev := arr.(i); iter (i + 1) end in\n let last = iter 1 in\n if last = n then pf \"0\"\n else\n let prev = ref arr.(last) in\n let rec iter i =\n if i = n then n\n else if !prev > arr.(i) then i\n else begin prev := arr.(i); iter (i + 1) end in\n let l = iter (last + 1) in\n if l = n && arr.(n - 1) <= arr.(0) then pf \"%d\\n\" (n - last)\n else pf \"-1\\n\"\n;;\n\n\nlet () =\n sf \"%d \" (fun n ->\n let arr = Array.init n ~f:(fun _ -> sf \"%d \" (fun i -> i)) in\n solve n arr)\n;;\n \n \n"}, {"source_code": "let input () =\n let n = Scanf.scanf \" %d \" (fun x -> x) in\n let a = ref 0 in\n let l = ref [] in\n for i = 1 to n do\n if i = n then\n a := Scanf.scanf \"%d\\n\" (fun x -> x)\n else\n a := Scanf.scanf \" %d \" (fun x -> x);\n\n l := !a :: !l;\n done;\n List.rev !l\n\nlet () = \n let rec scan l n head turn_down index =\n match l with\n | [] -> Printf.printf \"-1\\n\"\n | t :: [] ->\n begin\n\t match n with\n\t | 2 ->\n\t if (t <= head) then\n\t Printf.printf \"%d\\n\" (index - turn_down)\n\t else\n\t Printf.printf \"-1\\n\"\n\t | 1 ->\n\t Printf.printf \"0\\n\"\n\t | _ ->\n\t Printf.printf \"-1\\n\"\n end\n | last :: ((h :: t) as tl) ->\n if n <= 2 then\n\t if h >= last then\n\t scan tl n head turn_down (index+1)\n\t else\n\t scan tl (n+1) head index (index+1)\n else\n\t Printf.printf \"%d\\n\" (-1)\n in\n let l = input () in\n scan l 1 (List.hd l) (-1) 1\n"}], "negative_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\n\nmodule Array = ArrayLabels ;;\nmodule List = ListLabels ;;\n\nlet solve n arr =\n let prev = ref arr.(0) in\n let rec iter i =\n if i = n then n\n else if !prev > arr.(i) then i\n else begin prev := arr.(i); iter (i + 1) end in\n let last = iter 1 in\n if last = n then pf \"0\"\n else\n let prev = ref arr.(last) in\n let rec iter i =\n if i = n then n\n else if !prev > arr.(i) then i\n else begin prev := arr.(i); iter (i + 1) end in\n let l = iter (last + 1) in\n if l = n && arr.(n - 1) < arr.(0) then pf \"%d\\n\" (n - last)\n else pf \"-1\\n\"\n;;\n\n\nlet () =\n sf \"%d \" (fun n ->\n let arr = Array.init n ~f:(fun _ -> sf \"%d \" (fun i -> i)) in\n solve n arr)\n;;\n \n \n"}, {"source_code": "let input () =\n let n = Scanf.scanf \" %d \" (fun x -> x) in\n let a = ref 0 in\n let l = ref [] in\n for i = 1 to n do\n if i = n then\n a := Scanf.scanf \"%d\\n\" (fun x -> x)\n else\n a := Scanf.scanf \" %d \" (fun x -> x);\n\n l := !a :: !l;\n done;\n List.rev !l\n\nlet () = \n let rec scan l n head turn_down index =\n match l with\n | [] -> Printf.printf \"-1\\n\"\n | t :: [] ->\n if n = 2 then\n\t if t <= head then\n\t Printf.printf \"%d\\n\" (index - turn_down)\n\t else\n\t Printf.printf \"-1\\n\"\n else\n\t Printf.printf \"0\\n\"\n | last :: ((h :: t) as tl) ->\n if n <= 2 then\n\t if h >= last then\n\t scan tl n head turn_down (index+1)\n\t else\n\t scan tl (n+1) head index (index+1)\n else\n\t Printf.printf \"%d\\n\" (-1)\n in\n let l = input () in\n scan l 1 (List.hd l) (-1) 1\n"}, {"source_code": "let input () =\n let n = Scanf.scanf \" %d \" (fun x -> x) in\n let a = ref 0 in\n let l = ref [] in\n for i = 1 to n do\n if i = n then\n a := Scanf.scanf \"%d\\n\" (fun x -> x)\n else\n a := Scanf.scanf \" %d \" (fun x -> x);\n\n l := !a :: !l;\n done;\n List.rev !l\n\nlet () = \n let rec scan l n head turn_down index =\n match l with\n | [] -> Printf.printf \"-1\\n\"\n | t :: [] ->\n begin\n\t match n with\n\t | 2 ->\n\t if (t <= head) then\n\t Printf.printf \"%d\\n\" (index - turn_down)\n\t else\n\t Printf.printf \"-1\\n\"\n\t | 1 ->\n\t Printf.printf \"0\\n\"\n\t | _ ->\n\t Printf.printf \"-1\\n\"\n end\n | last :: ((h :: t) as tl) ->\n if n <= 2 then\n\t if h >= last then\n\t scan tl n head (index+1) (index+1)\n\t else\n\t scan tl (n+1) head index (index+1)\n else\n\t Printf.printf \"%d\\n\" (-1)\n in\n let l = input () in\n scan l 1 (List.hd l) (-1) 1\n"}], "src_uid": "c647e36495fb931ac72702a12c6bfe58"} {"nl": {"description": "There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) \u2014 the number of pearls in a row. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2013 the type of the i-th pearl.", "output_spec": "On the first line print integer k \u2014 the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj,\u2009rj (1\u2009\u2264\u2009lj\u2009\u2264\u2009rj\u2009\u2264\u2009n) \u2014 the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number \"-1\".", "sample_inputs": ["5\n1 2 3 4 1", "5\n1 2 3 4 5", "7\n1 2 1 3 1 2 1"], "sample_outputs": ["1\n1 5", "-1", "2\n1 3\n4 7"], "notes": null}, "positive_code": [{"source_code": "module IntSet = Set.Make(struct type t = int let compare = compare end)\n\nlet find_segs xs =\n let rec find_segs_aux i xs seen acc =\n match xs with\n | [] -> acc\n | [x] -> begin\n match acc with\n | [] ->\n if IntSet.mem x seen\n then [ 1, i ]\n else []\n | (lo, hi)::rest ->\n if IntSet.mem x seen\n then (hi + 1, i) :: (lo, hi) :: rest\n else (lo, i) :: rest\n end\n | x :: xs -> begin\n match acc with\n | [] ->\n if IntSet.mem x seen\n then find_segs_aux (i + 1) xs (IntSet.empty) [ 1, i ]\n else find_segs_aux (i + 1) xs (IntSet.add x seen) []\n | (lo, hi)::rest ->\n if IntSet.mem x seen\n then find_segs_aux (i + 1) xs (IntSet.empty) ((hi + 1, i)::acc)\n else find_segs_aux (i + 1) xs (IntSet.add x seen) acc\n end\n in\n find_segs_aux 1 xs IntSet.empty []\n\nlet print_output = function\n | [] -> print_int (-1); print_newline ()\n | xs ->\n print_int (List.length xs);\n print_newline ();\n List.iter (fun (lo, hi) ->\n print_int lo;\n print_string \" \";\n print_int hi;\n print_newline ()) xs\n\nlet () =\n ignore (read_line ()); read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string\n |> find_segs\n |> print_output\n"}, {"source_code": "let xint() = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let rec find a l r x =\n let m = (l + r) / 2 in\n if a.(m) = x then m\n else (\n if a.(m) < x then (find a (m + 1) r x)\n else (find a l (m - 1) x)\n )\n in\n\n let min x y =\n if x < y then x\n else y\n in\n\n let n = xint() in\n let a = Array.make n 0 in\n let xs = Array.make n 0 and m = ref 0 in\n\n for i = 0 to n - 1 do\n a.(i) <- xint();\n xs.(i) <- a.(i);\n done;\n Array.sort (fun x y -> x - y) xs;\n m := 1;\n for i = 1 to n - 1 do\n if xs.(i) != xs.(i - 1) then (\n xs.(!m) <- xs.(i);\n m := !m + 1;\n )\n done;\n\n let nx = Array.make n n and pos = Array.make !m n in\n\n for i = n - 1 downto 0 do\n a.(i) <- find xs 0 (!m - 1) a.(i);\n nx.(i) <- pos.(a.(i));\n pos.(a.(i)) <- i;\n done;\n\n let l = Array.make n 0 and r = Array.make n 0 in\n let ret = ref 0 and i = ref 0 in\n while !i < n do\n let x = !i and y = ref nx.(!i) in\n while !i < !y do\n y := min !y nx.(!i);\n i := !i + 1;\n done;\n if !y != n then (\n l.(!ret) <- x + 1;\n r.(!ret) <- !y + 1;\n ret := !ret + 1;\n );\n if !y = n && x != 0 then (\n r.(!ret - 1) <- n;\n );\n i := !i + 1;\n done;\n\n if !ret = 0 then (\n Printf.printf \"-1\\n\";\n ) else (\n Printf.printf \"%d\\n\" !ret;\n for i = 0 to !ret - 1 do\n Printf.printf \"%d %d\\n\" l.(i) r.(i);\n done;\n )\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let ks = ref [] in\n let ht = Hashtbl.create 10 in\n let prev = ref (-1) in\n for i = 0 to n - 1 do\n if Hashtbl.mem ht a.(i) then (\n\tks := (!prev + 1, i) :: !ks;\n\tprev := i;\n\tHashtbl.clear ht;\n ) else (\n\tHashtbl.replace ht a.(i) ()\n )\n done;\n let ks =\n if !prev = n - 1\n then !ks\n else (\n\tmatch !ks with\n\t | [] ->\n\t Printf.printf \"-1\\n\";\n\t exit 0\n\t | (l, r) :: ks ->\n\t (l, n - 1) :: ks\n )\n in\n let ks = List.rev ks in\n Printf.printf \"%d\\n\" (List.length ks);\n List.iter\n\t(fun (l, r) ->\n\t Printf.printf \"%d %d\\n\" (l + 1) (r + 1)\n\t) ks\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n \n let find_segment i =\n (* find segment starting from i. either Some (i,j) or None *)\n let h = Hashtbl.create 5 in\n let rec loop j = if j>=n then None else\n\tif Hashtbl.mem h a.(j) then Some (i,j) else (\n\t Hashtbl.add h a.(j) true;\n\t loop (j+1)\n\t)\n in\n if i >= n then None else (\n Hashtbl.add h a.(i) true; \n loop (i+1)\n )\n in\n\n let rec outer_loop i ac = \n match find_segment i with\n | Some (_,j) -> outer_loop (j+1) ((i,j)::ac)\n | None ->\n\tmatch ac with\n\t | [] -> []\n\t | (i,j)::tail -> (i,n-1)::tail\n in\n\n match outer_loop 0 [] with\n | [] -> printf \"-1\\n\"\n | li ->\n printf \"%d\\n\" (List.length li);\n List.iter (fun (i,j) -> printf \"%d %d\\n\" (i+1) (j+1)) li\n"}], "negative_code": [{"source_code": "let xint() = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () = \n let rec find a l r x = \n let m = (l + r) / 2 in\n if a.(m) = x then m\n else (\n if a.(m) < x then (find a (m + 1) r x)\n else (find a l (m - 1) x)\n )\n in\n\n let min x y = \n if x < y then x\n else y\n in\n\n let n = xint() in\n let a = Array.make n 0 in\n let xs = Array.make n 0 and m = ref 0 in\n\n for i = 0 to n - 1 do\n a.(i) <- xint();\n xs.(i) <- a.(i);\n done;\n Array.sort (fun x y -> x - y) xs;\n m := 1;\n for i = 1 to n - 1 do\n if xs.(i) != xs.(i - 1) then (\n xs.(!m) <- xs.(i);\n m := !m + 1;\n )\n done;\n\n let nx = Array.make n n and pos = Array.make !m n in\n\n for i = n - 1 downto 0 do\n a.(i) <- find xs 0 (!m - 1) a.(i);\n nx.(i) <- pos.(a.(i));\n pos.(a.(i)) <- i;\n done;\n\n let l = Array.make n 0 and r = Array.make n 0 in\n let ret = ref 0 and i = ref 0 in\n while !i < n do\n let x = !i and y = ref nx.(!i) in\n while !i < !y do\n y := min !y nx.(!i);\n i := !i + 1;\n done;\n if !y != n then (\n l.(!ret) <- x + 1;\n r.(!ret) <- !y + 1;\n ret := !ret + 1;\n );\n i := !i + 1;\n done;\n \n if !ret = 0 then (\n Printf.printf \"-1\\n\";\n ) else (\n Printf.printf \"%d\\n\" !ret;\n for i = 0 to !ret - 1 do\n Printf.printf \"%d %d\\n\" l.(i) r.(i);\n done;\n )\n"}], "src_uid": "4cacec219e4577b255ddf6d39d308e10"} {"nl": {"description": "Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.You are given a tree with $$$n$$$ nodes. In the beginning, $$$0$$$ is written on all edges. In one operation, you can choose any $$$2$$$ distinct leaves $$$u$$$, $$$v$$$ and any real number $$$x$$$ and add $$$x$$$ to values written on all edges on the simple path between $$$u$$$ and $$$v$$$.For example, on the picture below you can see the result of applying two operations to the graph: adding $$$2$$$ on the path from $$$7$$$ to $$$6$$$, and then adding $$$-0.5$$$ on the path from $$$4$$$ to $$$5$$$. Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?Leaf is a node of a tree of degree $$$1$$$. Simple path is a path that doesn't contain any node twice.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$)\u00a0\u2014 the number of nodes. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\le u, v \\le n$$$, $$$u \\neq v$$$), meaning that there is an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that these edges form a tree.", "output_spec": "If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output \"NO\". Otherwise, output \"YES\". You can print each letter in any case (upper or lower).", "sample_inputs": ["2\n1 2", "3\n1 2\n2 3", "5\n1 2\n1 3\n1 4\n2 5", "6\n1 2\n1 3\n1 4\n2 5\n2 6"], "sample_outputs": ["YES", "NO", "NO", "YES"], "notes": "NoteIn the first example, we can add any real $$$x$$$ to the value written on the only edge $$$(1, 2)$$$. In the second example, one of configurations that we can't reach is $$$0$$$ written on $$$(1, 2)$$$ and $$$1$$$ written on $$$(2, 3)$$$. Below you can see graphs from examples $$$3$$$, $$$4$$$: "}, "positive_code": [{"source_code": "let () =\n let main () =\n let n = int_of_string (read_line ()) in\n let nodes = Array.make n 0 in\n for i = 1 to n - 1 do\n Scanf.sscanf (read_line ()) \"%d %d\" (fun a b ->\n nodes.(a - 1) <- nodes.(a - 1) + 1;\n nodes.(b - 1) <- nodes.(b - 1) + 1)\n done;\n let rec loop i =\n if i < 0 then \"YES\" else\n if nodes.(i) = 2 then \"NO\" else loop (i - 1)\n in\n print_endline (loop (n - 1))\n in\n main ()\n"}], "negative_code": [], "src_uid": "ba47e6eea45d32cba660eb6d66a9adbb"} {"nl": {"description": "Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $$$k$$$ such that Mr. Black can exit the house after opening the first $$$k$$$ doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.", "input_spec": "The first line contains integer $$$n$$$ ($$$2 \\le n \\le 200\\,000$$$)\u00a0\u2014 the number of doors. The next line contains $$$n$$$ integers: the sequence in which Mr. Black opened the doors. The $$$i$$$-th of these integers is equal to $$$0$$$ in case the $$$i$$$-th opened door is located in the left exit, and it is equal to $$$1$$$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.", "output_spec": "Print the smallest integer $$$k$$$ such that after Mr. Black opened the first $$$k$$$ doors, he was able to exit the house.", "sample_inputs": ["5\n0 0 1 0 0", "4\n1 0 0 1"], "sample_outputs": ["3", "3"], "notes": "NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit."}, "positive_code": [{"source_code": "\nlet scanf = Scanf.scanf\n\nlet printf = Printf.printf\n\nlet flip = function 0 -> 1\n | 1 -> 0\n\nlet find_last_index (e: 'a) (src: 'a array): int option =\n let rec f (i: int): int option =\n if i < 0\n then None\n else if src.(i) = e then Some i\n else f (i - 1)\n in f (Array.length src - 1)\n\nlet extract_option (Some x) = x\n\nlet _ =\n let n = Scanf.scanf \"%d \" (fun i -> i) in\n let arr = Array.init n (fun _ -> Scanf.scanf \" %d\" (fun i -> i)) in\n let ele_to_find = flip (arr.(Array.length arr - 1)) in\n printf \"%d\\n\" ((find_last_index ele_to_find arr |> extract_option) + 1)\n"}], "negative_code": [], "src_uid": "653455bb6762effbf7358d75660a7689"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $$$[2, 1, 4]$$$ you can obtain the following arrays: $$$[3, 4]$$$, $$$[1, 6]$$$ and $$$[2, 5]$$$.Your task is to find the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). ", "output_spec": "For each query print one integer in a single line \u2014 the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing described operation an arbitrary (possibly, zero) number of times.", "sample_inputs": ["2\n5\n3 1 2 3 1\n7\n1 1 1 1 1 2 2"], "sample_outputs": ["3\n3"], "notes": "NoteIn the first query of the example you can apply the following sequence of operations to obtain $$$3$$$ elements divisible by $$$3$$$: $$$[3, 1, 2, 3, 1] \\rightarrow [3, 3, 3, 1]$$$.In the second query you can obtain $$$3$$$ elements divisible by $$$3$$$ with the following sequence of operations: $$$[1, 1, 1, 1, 1, 2, 2] \\rightarrow [1, 1, 1, 1, 2, 3] \\rightarrow [1, 1, 1, 3, 3] \\rightarrow [2, 1, 3, 3] \\rightarrow [3, 3, 3]$$$."}, "positive_code": [{"source_code": "let read_x x_of_string () = read_line () |> Str.(split (regexp \" \")) |> List.map x_of_string;;\nlet read_ints = read_x int_of_string;;\nlet read_int64s = read_x Int64.of_string;;\nlet print_x string_of_x xs = List.map string_of_x xs |> String.concat \" \" |> print_endline;;\nlet print_ints = print_x string_of_int;;\nlet print_int64s = print_x Int64.to_string;;\n\nlet [t] = read_ints ();;\nfor _ = 1 to t do\n let [n] = read_ints () and a = read_ints () in\n let [c0; c1; c2] = List.(\n map\n (fun r -> fold_left (fun acc x -> if x mod 3 = r then acc + 1 else acc) 0 a)\n [0; 1; 2]) in\n let r =\n if c1 > c2 then\n c0 + c2 + (c1 - c2) / 3\n else\n c0 + c1 + (c2 - c1) / 3\n in\n print_ints [r]\ndone;;\n"}], "negative_code": [{"source_code": "let read_x x_of_string () = read_line () |> Str.(split (regexp \" \")) |> List.map x_of_string;;\nlet read_ints = read_x int_of_string;;\nlet read_int64s = read_x Int64.of_string;;\nlet print_x string_of_x xs = List.map string_of_x xs |> String.concat \" \" |> print_endline;;\nlet print_ints = print_x string_of_int;;\nlet print_int64s = print_x Int64.to_string;;\n\nlet [t] = read_ints ();;\nfor _ = 1 to t do\n let [n] = read_ints () and a = read_ints () in\n let [c0; c1; c2] = List.(\n map\n (fun r -> fold_left (fun acc x -> if x mod 3 = r then acc + 1 else acc) 0 a)\n [0; 1; 2]) in\n let r = c0 + (c1 + 2*c2) / 3 - (if c2 mod 3 == 2 && c1 < 2 then 1 else 0) in\n print_ints [r]\ndone;;\n"}, {"source_code": "let read_x x_of_string () = read_line () |> Str.(split (regexp \" \")) |> List.map x_of_string;;\nlet read_ints = read_x int_of_string;;\nlet read_int64s = read_x Int64.of_string;;\nlet print_x string_of_x xs = List.map string_of_x xs |> String.concat \" \" |> print_endline;;\nlet print_ints = print_x string_of_int;;\nlet print_int64s = print_x Int64.to_string;;\n\nlet rec solve n =\n 1 +\n let open Int64 in\n if rem n 2L = 0L then\n solve (div n 2L)\n else if rem n 3L = 0L then\n solve (mul 2L (div n 3L))\n else if rem n 5L = 0L then\n solve (mul 4L (div n 5L))\n else if n = 1L then\n -1\n else\n raise Not_found;;\n\nlet [t] = read_ints ();;\nfor _ = 1 to t do\n let [n] = read_ints () and a = read_int64s () in\n let open Int64 in\n let [c0; c1; c2] = List.(\n map\n (fun r -> fold_left (fun acc x -> if rem x 3L = r then acc + 1 else acc) 0 a)\n [0L; 1L; 2L]) in\n let r = c0 + (c1 + 2*c2) / 3 - (if c2 > c1 && (c1 + 2*c2) mod 3 == 1 then 1 else 0) in\n print_ints [r]\ndone;;\n"}, {"source_code": "let read_x x_of_string () = read_line () |> Str.(split (regexp \" \")) |> List.map x_of_string;;\nlet read_ints = read_x int_of_string;;\nlet read_int64s = read_x Int64.of_string;;\nlet print_x string_of_x xs = List.map string_of_x xs |> String.concat \" \" |> print_endline;;\nlet print_ints = print_x string_of_int;;\nlet print_int64s = print_x Int64.to_string;;\n\nlet [t] = read_ints ();;\nfor _ = 1 to t do\n let [n] = read_ints () and a = read_ints () in\n let [c0; c1; c2] = List.(\n map\n (fun r -> fold_left (fun acc x -> if x mod 3 = r then acc + 1 else acc) 0 a)\n [0; 1; 2]) in\n let r = c0 + (c1 + 2*c2) / 3 - (if c2 mod 3 == 2 && c1 == 0 then 1 else 0) in\n print_ints [r]\ndone;;\n"}, {"source_code": "let read_x x_of_string () = read_line () |> Str.(split (regexp \" \")) |> List.map x_of_string;;\nlet read_ints = read_x int_of_string;;\nlet read_int64s = read_x Int64.of_string;;\nlet print_x string_of_x xs = List.map string_of_x xs |> String.concat \" \" |> print_endline;;\nlet print_ints = print_x string_of_int;;\nlet print_int64s = print_x Int64.to_string;;\n\nlet rec solve n =\n 1 +\n let open Int64 in\n if rem n 2L = 0L then\n solve (div n 2L)\n else if rem n 3L = 0L then\n solve (mul 2L (div n 3L))\n else if rem n 5L = 0L then\n solve (mul 4L (div n 5L))\n else if n = 1L then\n -1\n else\n raise Not_found;;\n\nlet [t] = read_ints ();;\nfor _ = 1 to t do\n let [n] = read_ints () and a = read_int64s () in\n let open Int64 in\n let [c0; c1; c2] = List.(\n map\n (fun r -> fold_left (fun acc x -> if rem x 3L = r then acc + 1 else acc) 0 a)\n [0L; 1L; 2L]) in\n let r = c0 + (c1 + 2*c2) / 3 - (if c1 >= c2 then 0 else 1)\n in\n print_ints [r]\ndone;;\n"}, {"source_code": "let read_x x_of_string () = read_line () |> Str.(split (regexp \" \")) |> List.map x_of_string;;\nlet read_ints = read_x int_of_string;;\nlet read_int64s = read_x Int64.of_string;;\nlet print_x string_of_x xs = List.map string_of_x xs |> String.concat \" \" |> print_endline;;\nlet print_ints = print_x string_of_int;;\nlet print_int64s = print_x Int64.to_string;;\n\nlet rec solve n =\n 1 +\n let open Int64 in\n if rem n 2L = 0L then\n solve (div n 2L)\n else if rem n 3L = 0L then\n solve (mul 2L (div n 3L))\n else if rem n 5L = 0L then\n solve (mul 4L (div n 5L))\n else if n = 1L then\n -1\n else\n raise Not_found;;\n\nlet [t] = read_ints ();;\nfor _ = 1 to t do\n let [n] = read_ints () in\n let open Int64 in\n print_int64s [\n div\n (read_int64s ()\n |> List.map (fun x -> succ (rem (pred x) 3L))\n |> List.fold_left add 0L)\n 3L\n ]\ndone;;\n"}, {"source_code": "let read_x x_of_string () = read_line () |> Str.(split (regexp \" \")) |> List.map x_of_string;;\nlet read_ints = read_x int_of_string;;\nlet read_int64s = read_x Int64.of_string;;\nlet print_x string_of_x xs = List.map string_of_x xs |> String.concat \" \" |> print_endline;;\nlet print_ints = print_x string_of_int;;\nlet print_int64s = print_x Int64.to_string;;\n\nlet [t] = read_ints ();;\nfor _ = 1 to t do\n let [n] = read_ints () and a = read_ints () in\n let [c0; c1; c2] = List.(\n map\n (fun r -> fold_left (fun acc x -> if x mod 3 = r then acc + 1 else acc) 0 a)\n [0; 1; 2]) in\n let r =\n if c1 > c2 then\n c0 + c2 + c1 / 3\n else\n c0 + c1 + c2 / 3\n in\n print_ints [r]\ndone;;\n"}], "src_uid": "e59cddb6c941b1d7556ee9c020701007"} {"nl": {"description": "You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right. Obviously, there is not enough sand on the beach, so you brought n packs of sand with you. Let height hi of the sand pillar on some spot i be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with H sand packs to the left of the first spot and you should prevent sand from going over it. Finally you ended up with the following conditions to building the castle: h1\u2009\u2264\u2009H: no sand from the leftmost spot should go over the fence; For any |hi\u2009-\u2009hi\u2009+\u20091|\u2009\u2264\u20091: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen; : you want to spend all the sand you brought with you. As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible. Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.", "input_spec": "The only line contains two integer numbers n and H (1\u2009\u2264\u2009n,\u2009H\u2009\u2264\u20091018) \u2014 the number of sand packs you have and the height of the fence, respectively.", "output_spec": "Print the minimum number of spots you can occupy so the all the castle building conditions hold.", "sample_inputs": ["5 2", "6 8"], "sample_outputs": ["3", "3"], "notes": "NoteHere are the heights of some valid castles: n\u2009=\u20095,\u2009H\u2009=\u20092,\u2009[2,\u20092,\u20091,\u20090,\u2009...],\u2009[2,\u20091,\u20091,\u20091,\u20090,\u2009...],\u2009[1,\u20090,\u20091,\u20092,\u20091,\u20090,\u2009...] n\u2009=\u20096,\u2009H\u2009=\u20098,\u2009[3,\u20092,\u20091,\u20090,\u2009...],\u2009[2,\u20092,\u20091,\u20091,\u20090,\u2009...],\u2009[0,\u20091,\u20090,\u20091,\u20092,\u20091,\u20091,\u20090...] (this one has 5 spots occupied) The first list for both cases is the optimal answer, 3 spots are occupied in them.And here are some invalid ones: n\u2009=\u20095,\u2009H\u2009=\u20092,\u2009[3,\u20092,\u20090,\u2009...],\u2009[2,\u20093,\u20090,\u2009...],\u2009[1,\u20090,\u20092,\u20092,\u2009...] n\u2009=\u20096,\u2009H\u2009=\u20098,\u2009[2,\u20092,\u20092,\u20090,\u2009...],\u2009[6,\u20090,\u2009...],\u2009[1,\u20094,\u20091,\u20090...],\u2009[2,\u20092,\u20091,\u20090,\u2009...] "}, "positive_code": [{"source_code": "\nmodule type Idx = sig\n type t\n val to_string: t -> string\n val of_int: int -> t\n val (+): t -> t -> t\n val (-): t -> t -> t\n val (/): t -> t -> t\nend\n\nmodule IdxI64 = struct\n type t = int64\n let to_string = Int64.to_string\n let of_int = Int64.of_int\n let compare = Int64.compare\n let (+) = Int64.add\n let (/) = Int64.div\n let (-) = Int64.sub\n let ( * ) = Int64.mul\n let rem = Int64.rem\nend\n\n(* find the first one that makes callback returns true *)\nmodule Bisearch_first (Idx: Idx) = struct\n let perform\n (callback: 'a -> bool)\n ((l, r): Idx.t * Idx.t) (* range is closed *)\n (get: Idx.t -> 'a): Idx.t option =\n let open Idx in\n let rec f (l, r) =\n if l = r\n then if l |> get |> callback then Some l else None\n else\n let m = (l + r) / (Idx.of_int 2) in\n if m |> get |> callback\n then f (l, m)\n else f (m + (Idx.of_int 1), r)\n in\n f (l, r)\nend\n\nlet option_get (src: 'a option): 'a =\n match src with\n | Some a -> a\n | None -> raise Not_found\n\nlet log2 (v: float): float = log v /. log 2.\n \nmodule Bisearch_first_i64 = Bisearch_first(IdxI64)\n\nlet max_capacity (h: int64) (i: int64): int64 =\n let open IdxI64 in\n if h >= i\n then\n if i |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else (i * (i + 1L)) / 2L\n else\n let sum = h + i in\n let m = sum / 2L in\n if m |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else\n (((m + h - 1L) * (m - h)) / 2L) +\n (((m + 1L) * m) / 2L) +\n (if rem sum 2L = 1L then m else 0L)\n\n(* module Bigint = struct\n * type t = Big_int.big_int\n * let of_int = Big_int.big_int_of_int\n * let to_int = Big_int.int_of_big_int\n * let of_int64 = Big_int.big_int_of_int64\n * let to_int64 = Big_int.int64_of_big_int\n * let (+) = Big_int.add_big_int\n * let (/) = Big_int.div_big_int\n * let (-) = Big_int.sub_big_int\n * let ( * ) = Big_int.mult_big_int\n * let rem = Big_int.mod_big_int\n * let compare = Big_int.compare_big_int\n * let equal = Big_int.eq_big_int\n * let min = Big_int.min_big_int\n * end\n * \n * let max_capacity_big (h: int64) (i: int64): int64 =\n * let open Bigint in\n * let h = of_int64 h in\n * let i = of_int64 i in\n * let one = of_int 1 in\n * let two = of_int 2 in\n * let ret =\n * if compare h i >= 0\n * then (i * (i + one)) / two\n * else\n * let sum = h + i in\n * let m = sum / two in\n * (((m + h - one) * (m - h)) / two) +\n * (((m + one) * m) / two) +\n * (if equal (rem sum two) one then m else (of_int 0)) in\n * min ret (of_int64 Int64.max_int) |> to_int64 *)\n\n(* 1000000000000000000 1000000000000000000 -> 1414213562 *)\n(* 1000000000000000000 1 -> 1999999999 *)\n(* 1036191544337895 1 -> 64379858 *)\n \nlet compute (n: int64) (h: int64): int64 =\n let f i = (max_capacity h i) >= n in\n Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get\n \nlet _ =\n let (n, h) = Scanf.scanf \" %Ld %Ld\" (fun a b -> (a, b)) in\n compute n h |> IdxI64.to_string |> print_endline\n"}, {"source_code": "\nmodule type Idx = sig\n type t\n val to_string: t -> string\n val of_int: int -> t\n val (+): t -> t -> t\n val (-): t -> t -> t\n val (/): t -> t -> t\nend\n\nmodule IdxI64 = struct\n type t = int64\n let to_string = Int64.to_string\n let of_int = Int64.of_int\n let compare = Int64.compare\n let (+) = Int64.add\n let (/) = Int64.div\n let (-) = Int64.sub\n let ( * ) = Int64.mul\n let rem = Int64.rem\nend\n\n(* find the first one that makes callback returns true *)\nmodule Bisearch_first (Idx: Idx) = struct\n let perform\n (callback: 'a -> bool)\n ((l, r): Idx.t * Idx.t) (* range is closed *)\n (get: Idx.t -> 'a): Idx.t option =\n let open Idx in\n let rec f (l, r) =\n if l = r\n then if l |> get |> callback then Some l else None\n else\n let m = (l + r) / (Idx.of_int 2) in\n if m |> get |> callback\n then f (l, m)\n else f (m + (Idx.of_int 1), r)\n in\n f (l, r)\nend\n\nlet option_get (src: 'a option): 'a =\n match src with\n | Some a -> a\n | None -> raise Not_found\n\nlet log2 (v: float): float = log v /. log 2.\n \nmodule Bisearch_first_i64 = Bisearch_first(IdxI64)\n\n\nlet max_capacity (h: int64) (i: int64): int64 =\n let open IdxI64 in\n if h >= i\n then\n if i |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else (i * (i + 1L)) / 2L\n else\n let sum = h + i in\n let m = sum / 2L in\n if m |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else\n (((m + h - 1L) * (m - h)) / 2L) +\n (((m + 1L) * m) / 2L) +\n (if rem sum 2L = 1L then m else 0L)\n\nmodule Bigint = struct\n type t = Big_int.big_int\n let of_int = Big_int.big_int_of_int\n let to_int = Big_int.int_of_big_int\n let of_int64 = Big_int.big_int_of_int64\n let to_int64 = Big_int.int64_of_big_int\n let (+) = Big_int.add_big_int\n let (/) = Big_int.div_big_int\n let (-) = Big_int.sub_big_int\n let ( * ) = Big_int.mult_big_int\n let rem = Big_int.mod_big_int\n let compare = Big_int.compare_big_int\n let equal = Big_int.eq_big_int\n let min = Big_int.min_big_int\nend\n\nlet max_capacity_big (h: int64) (i: int64): int64 =\n let open Bigint in\n let h = of_int64 h in\n let i = of_int64 i in\n let one = of_int 1 in\n let two = of_int 2 in\n let ret =\n if compare h i >= 0\n then (i * (i + one)) / two\n else\n let sum = h + i in\n let m = sum / two in\n (((m + h - one) * (m - h)) / two) +\n (((m + one) * m) / two) +\n (if equal (rem sum two) one then m else (of_int 0)) in\n min ret (of_int64 Int64.max_int) |> to_int64\n\nlet max_capacity_big h i =\n let ret = max_capacity_big h i in\n (* Printf.printf \"mc %Ld %Ld -> %Ld\\n\" h i ret; *)\n ret\n\nlet compute (n: int64) (h: int64): int64 =\n let f i = (max_capacity_big h i) >= n in\n (* let f i = let ret = f i in Printf.printf \"f %Ld %Ld %b\\n\" h i ret; ret in *)\n Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get\n \n(* 1000000000000000000 1000000000000000000 -> 1414213562 *)\n(* 1000000000000000000 1 -> 1999999999 *)\n(* 1036191544337895 1 -> 64379858 *)\n \nlet _ =\n (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;\n * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)\n Printexc.record_backtrace true;\n let (n, h) = Scanf.scanf \" %Ld %Ld\" (fun a b -> (a, b)) in\n compute n h |> IdxI64.to_string |> print_endline\n"}], "negative_code": [{"source_code": "\nmodule type Idx = sig\n type t\n val to_string: t -> string\n val of_int: int -> t\n val (+): t -> t -> t\n val (-): t -> t -> t\n val (/): t -> t -> t\nend\n\nmodule IdxI64 = struct\n type t = int64\n let to_string = Int64.to_string\n let of_int = Int64.of_int\n let compare = Int64.compare\n let (+) = Int64.add\n let (/) = Int64.div\n let (-) = Int64.sub\n let ( * ) = Int64.mul\n let rem = Int64.rem\nend\n\n(* find the first one that makes callback returns true *)\nmodule Bisearch_first (Idx: Idx) = struct\n let perform\n (callback: 'a -> bool)\n ((l, r): Idx.t * Idx.t) (* range is closed *)\n (get: Idx.t -> 'a): Idx.t option =\n let open Idx in\n let rec f (l, r) =\n if l = r\n then if l |> get |> callback then Some l else None\n else\n let m = (l + r) / (Idx.of_int 2) in\n if m |> get |> callback\n then f (l, m)\n else f (m + (Idx.of_int 1), r)\n in\n f (l, r)\nend\n\nlet option_get (src: 'a option): 'a =\n match src with\n | Some a -> a\n | None -> raise Not_found\n \nmodule Bisearch_first_i64 = Bisearch_first(IdxI64)\n \nlet max_capacity (h: int64) (i: int64): int64 =\n let open IdxI64 in\n if h >= i\n then (i * (i + 1L)) / 2L\n else\n let sum = h + i in\n let m = sum / 2L in\n (((m + h) * (m - h)) / 2L) +\n (((m + 1L) * m) / 2L) +\n (if rem sum 2L = 1L then m else 0L)\n\nlet compute (n: int64) (h: int64): int64 =\n let f i = (max_capacity h i) >= n in\n Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get\n \nlet _ =\n let (n, h) = Scanf.scanf \" %Ld %Ld\" (fun a b -> (a, b)) in\n compute n h |> IdxI64.to_string |> print_endline\n"}, {"source_code": "\nmodule type Idx = sig\n type t\n val to_string: t -> string\n val of_int: int -> t\n val (+): t -> t -> t\n val (-): t -> t -> t\n val (/): t -> t -> t\nend\n\nmodule IdxI64 = struct\n type t = int64\n let to_string = Int64.to_string\n let of_int = Int64.of_int\n let compare = Int64.compare\n let (+) = Int64.add\n let (/) = Int64.div\n let (-) = Int64.sub\n let ( * ) = Int64.mul\n let rem = Int64.rem\nend\n\n(* find the first one that makes callback returns true *)\nmodule Bisearch_first (Idx: Idx) = struct\n let perform\n (callback: 'a -> bool)\n ((l, r): Idx.t * Idx.t) (* range is closed *)\n (get: Idx.t -> 'a): Idx.t option =\n let open Idx in\n let rec f (l, r) =\n if l = r\n then if l |> get |> callback then Some l else None\n else\n let m = (l + r) / (Idx.of_int 2) in\n if m |> get |> callback\n then f (l, m)\n else f (m + (Idx.of_int 1), r)\n in\n f (l, r)\nend\n\nlet option_get (src: 'a option): 'a =\n match src with\n | Some a -> a\n | None -> raise Not_found\n\nlet log2 (v: float): float = log v /. log 2.\n \nmodule Bisearch_first_i64 = Bisearch_first(IdxI64)\n \nlet max_capacity (h: int64) (i: int64): int64 =\n let open IdxI64 in\n if h >= i\n then\n if i |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else (i * (i + 1L)) / 2L\n else\n let sum = h + i in\n let m = sum / 2L in\n (((m + h) * (m - h)) / 2L) +\n (((m + 1L) * m) / 2L) +\n (if rem sum 2L = 1L then m else 0L)\n\nlet compute (n: int64) (h: int64): int64 =\n let f i = (max_capacity h i) >= n in\n (* let f i = let ret = f i in Printf.printf \"f %Ld %b\\n\" i ret; ret in *)\n Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get\n \n(* 1000000000000000000 1000000000000000000 -> 1414213562 *)\n \nlet _ =\n max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;\n max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline;\n let (n, h) = Scanf.scanf \" %Ld %Ld\" (fun a b -> (a, b)) in\n compute n h |> IdxI64.to_string |> print_endline\n"}, {"source_code": "\nmodule type Idx = sig\n type t\n val to_string: t -> string\n val of_int: int -> t\n val (+): t -> t -> t\n val (-): t -> t -> t\n val (/): t -> t -> t\nend\n\nmodule IdxI64 = struct\n type t = int64\n let to_string = Int64.to_string\n let of_int = Int64.of_int\n let compare = Int64.compare\n let (+) = Int64.add\n let (/) = Int64.div\n let (-) = Int64.sub\n let ( * ) = Int64.mul\n let rem = Int64.rem\nend\n\n(* find the first one that makes callback returns true *)\nmodule Bisearch_first (Idx: Idx) = struct\n let perform\n (callback: 'a -> bool)\n ((l, r): Idx.t * Idx.t) (* range is closed *)\n (get: Idx.t -> 'a): Idx.t option =\n let open Idx in\n let rec f (l, r) =\n if l = r\n then if l |> get |> callback then Some l else None\n else\n let m = (l + r) / (Idx.of_int 2) in\n if m |> get |> callback\n then f (l, m)\n else f (m + (Idx.of_int 1), r)\n in\n f (l, r)\nend\n\nlet option_get (src: 'a option): 'a =\n match src with\n | Some a -> a\n | None -> raise Not_found\n\nlet log2 (v: float): float = log v /. log 2.\n \nmodule Bisearch_first_i64 = Bisearch_first(IdxI64)\n \nlet max_capacity (h: int64) (i: int64): int64 =\n let open IdxI64 in\n if h >= i\n then\n if i |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else (i * (i + 1L)) / 2L\n else\n let sum = h + i in\n let m = sum / 2L in\n if m |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else\n (((m + h) * (m - h)) / 2L) +\n (((m + 1L) * m) / 2L) +\n (if rem sum 2L = 1L then m else 0L)\n\nlet compute (n: int64) (h: int64): int64 =\n let f i = (max_capacity h i) >= n in\n (* let f i = let ret = f i in Printf.printf \"f %Ld %b\\n\" i ret; ret in *)\n Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get\n \n(* 1000000000000000000 1000000000000000000 -> 1414213562 *)\n(* 1000000000000000000 1 -> 1999999999 *)\n \nlet _ =\n (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;\n * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)\n let (n, h) = Scanf.scanf \" %Ld %Ld\" (fun a b -> (a, b)) in\n compute n h |> IdxI64.to_string |> print_endline\n"}, {"source_code": "\nmodule type Idx = sig\n type t\n val to_string: t -> string\n val of_int: int -> t\n val (+): t -> t -> t\n val (-): t -> t -> t\n val (/): t -> t -> t\nend\n\nmodule IdxI64 = struct\n type t = int64\n let to_string = Int64.to_string\n let of_int = Int64.of_int\n let compare = Int64.compare\n let (+) = Int64.add\n let (/) = Int64.div\n let (-) = Int64.sub\n let ( * ) = Int64.mul\n let rem = Int64.rem\nend\n\n(* find the first one that makes callback returns true *)\nmodule Bisearch_first (Idx: Idx) = struct\n let perform\n (callback: 'a -> bool)\n ((l, r): Idx.t * Idx.t) (* range is closed *)\n (get: Idx.t -> 'a): Idx.t option =\n let open Idx in\n let rec f (l, r) =\n if l = r\n then if l |> get |> callback then Some l else None\n else\n let m = (l + r) / (Idx.of_int 2) in\n if m |> get |> callback\n then f (l, m)\n else f (m + (Idx.of_int 1), r)\n in\n f (l, r)\nend\n\nlet option_get (src: 'a option): 'a =\n match src with\n | Some a -> a\n | None -> raise Not_found\n\nlet log2 (v: float): float = log v /. log 2.\n \nmodule Bisearch_first_i64 = Bisearch_first(IdxI64)\n \nlet max_capacity (h: int64) (i: int64): int64 =\n let open IdxI64 in\n if h >= i\n then\n if i |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else (i * (i + 1L)) / 2L\n else\n let sum = h + i in\n let m = sum / 2L in\n (((m + h) * (m - h)) / 2L) +\n (((m + 1L) * m) / 2L) +\n (if rem sum 2L = 1L then m else 0L)\n\nlet compute (n: int64) (h: int64): int64 =\n let f i = (max_capacity h i) >= n in\n (* let f i = let ret = f i in Printf.printf \"f %Ld %b\\n\" i ret; ret in *)\n Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get\n \n(* 1000000000000000000 1000000000000000000 -> 1414213562 *)\n \nlet _ =\n (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;\n * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)\n let (n, h) = Scanf.scanf \" %Ld %Ld\" (fun a b -> (a, b)) in\n compute n h |> IdxI64.to_string |> print_endline\n"}, {"source_code": "\nmodule type Idx = sig\n type t\n val to_string: t -> string\n val of_int: int -> t\n val (+): t -> t -> t\n val (-): t -> t -> t\n val (/): t -> t -> t\nend\n\nmodule IdxI64 = struct\n type t = int64\n let to_string = Int64.to_string\n let of_int = Int64.of_int\n let compare = Int64.compare\n let (+) = Int64.add\n let (/) = Int64.div\n let (-) = Int64.sub\n let ( * ) = Int64.mul\n let rem = Int64.rem\nend\n\n(* find the first one that makes callback returns true *)\nmodule Bisearch_first (Idx: Idx) = struct\n let perform\n (callback: 'a -> bool)\n ((l, r): Idx.t * Idx.t) (* range is closed *)\n (get: Idx.t -> 'a): Idx.t option =\n let open Idx in\n let rec f (l, r) =\n if l = r\n then if l |> get |> callback then Some l else None\n else\n let m = (l + r) / (Idx.of_int 2) in\n if m |> get |> callback\n then f (l, m)\n else f (m + (Idx.of_int 1), r)\n in\n f (l, r)\nend\n\nlet option_get (src: 'a option): 'a =\n match src with\n | Some a -> a\n | None -> raise Not_found\n\nlet log2 (v: float): float = log v /. log 2.\n \nmodule Bisearch_first_i64 = Bisearch_first(IdxI64)\n\n\nlet max_capacity (h: int64) (i: int64): int64 =\n let open IdxI64 in\n if h >= i\n then\n if i |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else (i * (i + 1L)) / 2L\n else\n let sum = h + i in\n let m = sum / 2L in\n if m |> Int64.to_float |> log2 >= 31.\n then Int64.max_int\n else\n (((m + h - 1L) * (m - h)) / 2L) +\n (((m + 1L) * m) / 2L) +\n (if rem sum 2L = 1L then m else 0L)\n\nmodule Bigint = struct\n type t = Big_int.big_int\n let of_int = Big_int.big_int_of_int\n let to_int = Big_int.int_of_big_int\n let of_int64 = Big_int.big_int_of_int64\n let to_int64 = Big_int.int64_of_big_int\n let (+) = Big_int.add_big_int\n let (/) = Big_int.div_big_int\n let (-) = Big_int.sub_big_int\n let ( * ) = Big_int.mult_big_int\n let rem = Big_int.mod_big_int\n let compare = Big_int.compare_big_int\n let equal = Big_int.eq_big_int\n let min = Big_int.min_big_int\nend\n\nlet max_capacity_big (h: int64) (i: int64): int64 =\n let open Bigint in\n let h = of_int64 h in\n let i = of_int64 i in\n let one = of_int 1 in\n let two = of_int 2 in\n let ret =\n if compare h i >= 0\n then (i * (i + one)) / two\n else\n let sum = h + i in\n let m = sum / two in\n (((m + h - one) * (m - h)) / two) +\n (((m + one) * m) / two) +\n (if equal (rem sum two) one then m else (of_int 0)) in\n min ret (of_int64 Int64.max_int) |> to_int64\n\nlet max_capacity_big h i =\n let ret = max_capacity_big h i in\n Printf.printf \"mc %Ld %Ld -> %Ld\\n\" h i ret;\n ret\n\nlet compute (n: int64) (h: int64): int64 =\n let f i = (max_capacity_big h i) >= n in\n let f i = let ret = f i in Printf.printf \"f %Ld %Ld %b\\n\" h i ret; ret in\n Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get\n \n(* 1000000000000000000 1000000000000000000 -> 1414213562 *)\n(* 1000000000000000000 1 -> 1999999999 *)\n(* 1036191544337895 1 -> 64379858 *)\n \nlet _ =\n (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;\n * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)\n Printexc.record_backtrace true;\n let (n, h) = Scanf.scanf \" %Ld %Ld\" (fun a b -> (a, b)) in\n compute n h |> IdxI64.to_string |> print_endline\n"}], "src_uid": "c35102fa418cbfdcb150b52d216040d9"} {"nl": {"description": "The Olympic Games have just started and Federico is eager to watch the marathon race.There will be $$$n$$$ athletes, numbered from $$$1$$$ to $$$n$$$, competing in the marathon, and all of them have taken part in $$$5$$$ important marathons, numbered from $$$1$$$ to $$$5$$$, in the past. For each $$$1\\le i\\le n$$$ and $$$1\\le j\\le 5$$$, Federico remembers that athlete $$$i$$$ ranked $$$r_{i,j}$$$-th in marathon $$$j$$$ (e.g., $$$r_{2,4}=3$$$ means that athlete $$$2$$$ was third in marathon $$$4$$$).Federico considers athlete $$$x$$$ superior to athlete $$$y$$$ if athlete $$$x$$$ ranked better than athlete $$$y$$$ in at least $$$3$$$ past marathons, i.e., $$$r_{x,j}<r_{y,j}$$$ for at least $$$3$$$ distinct values of $$$j$$$.Federico believes that an athlete is likely to get the gold medal at the Olympics if he is superior to all other athletes.Find any athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes), or determine that there is no such athlete.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1\\le n\\le 50\\,000$$$) \u2014 the number of athletes. Then $$$n$$$ lines follow, each describing the ranking positions of one athlete. The $$$i$$$-th of these lines contains the $$$5$$$ integers $$$r_{i,1},\\,r_{i,2},\\,r_{i,3},\\,r_{i,4},\\, r_{i,5}$$$ ($$$1\\le r_{i,j}\\le 50\\,000$$$) \u2014 the ranking positions of athlete $$$i$$$ in the past $$$5$$$ marathons. It is guaranteed that, in each of the $$$5$$$ past marathons, the $$$n$$$ athletes have distinct ranking positions, i.e., for each $$$1\\le j\\le 5$$$, the $$$n$$$ values $$$r_{1,j},\\, r_{2, j},\\, \\dots,\\, r_{n, j}$$$ are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$50\\,000$$$.", "output_spec": "For each test case, print a single integer \u2014 the number of an athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes). If there are no such athletes, print $$$-1$$$. If there is more than such one athlete, print any of them.", "sample_inputs": ["4\n1\n50000 1 50000 50000 50000\n3\n10 10 20 30 30\n20 20 30 10 10\n30 30 10 20 20\n3\n1 1 1 1 1\n2 2 2 2 2\n3 3 3 3 3\n6\n9 5 3 7 1\n7 4 1 6 8\n5 6 7 3 2\n6 7 8 8 6\n4 2 2 4 5\n8 3 6 9 4"], "sample_outputs": ["1\n-1\n1\n5"], "notes": "NoteExplanation of the first test case: There is only one athlete, therefore he is superior to everyone else (since there is no one else), and thus he is likely to get the gold medal.Explanation of the second test case: There are $$$n=3$$$ athletes. Athlete $$$1$$$ is superior to athlete $$$2$$$. Indeed athlete $$$1$$$ ranks better than athlete $$$2$$$ in the marathons $$$1$$$, $$$2$$$ and $$$3$$$. Athlete $$$2$$$ is superior to athlete $$$3$$$. Indeed athlete $$$2$$$ ranks better than athlete $$$3$$$ in the marathons $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$. Athlete $$$3$$$ is superior to athlete $$$1$$$. Indeed athlete $$$3$$$ ranks better than athlete $$$1$$$ in the marathons $$$3$$$, $$$4$$$ and $$$5$$$. Explanation of the third test case: There are $$$n=3$$$ athletes. Athlete $$$1$$$ is superior to athletes $$$2$$$ and $$$3$$$. Since he is superior to all other athletes, he is likely to get the gold medal. Athlete $$$2$$$ is superior to athlete $$$3$$$. Athlete $$$3$$$ is not superior to any other athlete. Explanation of the fourth test case: There are $$$n=6$$$ athletes. Athlete $$$1$$$ is superior to athletes $$$3$$$, $$$4$$$, $$$6$$$. Athlete $$$2$$$ is superior to athletes $$$1$$$, $$$4$$$, $$$6$$$. Athlete $$$3$$$ is superior to athletes $$$2$$$, $$$4$$$, $$$6$$$. Athlete $$$4$$$ is not superior to any other athlete. Athlete $$$5$$$ is superior to athletes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$6$$$. Since he is superior to all other athletes, he is likely to get the gold medal. Athlete $$$6$$$ is only superior to athlete $$$4$$$. "}, "positive_code": [{"source_code": "(* Codeforces 1552 B Running for Gold, train *)\r\n \r\n(* you can use either gr or rdln but not both *)\r\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\r\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\r\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet rdln() = input_line stdin;;\r\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\r\nlet debug = false;;\r\n \r\n(* reading reversed list *)\r\nlet rec readlist n acc = match n with\r\n\t| 0 -> acc\r\n\t| _ -> readlist (n -1) (gr() :: acc);;\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\r\n\r\n(* end my library. below concrete program *) \r\n\r\ntype player = { ord: int; res: int list };;\r\n\r\nlet rec count_more cnt al bl = match al with\r\n\t| [] -> cnt\r\n\t| h :: t ->\r\n\t\tlet ncnt = if h <(List.hd bl) then (cnt + 1) else cnt in\r\n\t\tcount_more ncnt t (List.tl bl);;\r\n\r\nlet win ap bp = \r\n\tlet cnta = count_more 0 ap.res bp.res in\r\n\tlet cntb = count_more 0 bp.res ap.res in\r\n\t(cnta > cntb);;\r\n\r\nlet winner ap bp = \r\n\tlet cnta = count_more 0 ap.res bp.res in\r\n\tlet cntb = count_more 0 bp.res ap.res in\r\n\tif cnta > cntb then ap\r\n\t\telse bp;;\r\n\r\nlet rec select_winner w = function\r\n\t| [] -> w\r\n\t| a :: t ->\r\n\t\t\tlet nw = winner w a in\r\n\t\t\tselect_winner nw t;; \r\n\r\nlet rec check_winner w pl = match pl with\r\n\t| [] -> true\r\n\t| a :: t ->\r\n\t\t\tif (win a w) && (a.ord != w.ord) then false\r\n\t\t\telse\r\n\t\t\t check_winner w t;; \r\n\r\nlet read_player o = \r\n\tlet a = readlist 5 [] in\r\n\t{ ord=o; res = a};;\r\n\r\nlet rec read_players lp idx n = match n with\r\n\t| 0 -> lp\r\n\t| _ -> let p = read_player idx in\r\n\t\t\t\t\tread_players (p :: lp) (idx + 1) (n - 1);; \r\n\r\nlet do_one () = \r\n let n = gr() in\r\n let lp = read_players [] 1 n in\r\n\t\tlet w = select_winner (List.hd lp) (List.tl lp) in\r\n\t\tlet ans = if check_winner w lp then w.ord else -1 in \r\n Printf.printf \"%d\\n\" ans;;\r\n \r\nlet do_all t = \r\n for i = 1 to t do\r\n do_one ()\r\n done;;\r\n \r\nlet main() =\r\n\tlet st = rdln () in\r\n\tlet t = int_of_string st in\r\n\tdo_all t;;\r\n \r\nmain();;"}], "negative_code": [], "src_uid": "8d9fc054fb1541b70991661592ae70b1"} {"nl": {"description": "Leha decided to move to a quiet town Vi\u010dkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vi\u010dkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109\u2009+\u20097.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) denoting the number of hacked computers. The second line contains n integers x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009xi\u2009\u2264\u2009109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.", "output_spec": "Print a single integer\u00a0\u2014 the required sum modulo 109\u2009+\u20097.", "sample_inputs": ["2\n4 7", "3\n4 3 1"], "sample_outputs": ["3", "9"], "notes": "NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7\u2009-\u20094\u2009=\u20093. In total the answer is 0\u2009+\u20090\u2009+\u20093\u2009=\u20093.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4\u2009-\u20093)\u2009+\u2009(4\u2009-\u20091)\u2009+\u2009(3\u2009-\u20091)\u2009+\u2009(4\u2009-\u20091)\u2009=\u20099."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet p = 1_000_000_007L\n\nlet ( %% ) a b = Int64.rem a b\nlet ( ** ) a b = (Int64.mul a b) %% p\nlet ( ++ ) a b = (Int64.add a b) %% p\nlet ( -- ) a b = (Int64.sub a b) ++ p\n\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let x = Array.init (n+1) (fun i -> if i=0 then 0L else long (read_int())) in\n Array.sort compare x;\n\n let pow2 = Array.make (n+1) 1L in\n\n for i=1 to n do\n pow2.(i) <- 2L ** pow2.(i-1)\n done;\n\n let part1 = sum 2 n (fun j -> (x.(j) ** pow2.(j-1)) -- x.(j)) in\n let part2 = sum 1 (n-1) (fun i -> (x.(i) ** pow2.(n-i)) -- x.(i)) in\n\n printf \"%Ld\\n\" (part1 -- part2)\n"}], "negative_code": [], "src_uid": "acff03fe274e819a74b5e9350a859471"} {"nl": {"description": "The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.", "input_spec": "The first line of the input contains two integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1\u2009\u2264\u2009j\u2009\u2264\u2009n, 1\u2009\u2264\u2009i\u2009\u2264\u2009m, 0\u2009\u2264\u2009aij\u2009\u2264\u2009109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.", "output_spec": "Print a single number \u2014 the index of the candidate who won the elections. The candidates are indexed starting from one.", "sample_inputs": ["3 3\n1 2 3\n2 3 1\n1 2 1", "3 4\n10 10 3\n5 1 6\n2 2 2\n1 5 7"], "sample_outputs": ["2", "1"], "notes": "NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index."}, "positive_code": [{"source_code": "let get a'= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ()));;\nlet [n; m] = get ();;\nlet kk = Array.make n 0 and mm = ref 0 and mj = ref 0;;\nfor i = 1 to m do\n\tlet ins = get () in begin\n\t\tmm := (-1);\n\t\tfor j = 0 to n - 1 do if !mm < List.nth ins j then begin\n\t\t\tmm := List.nth ins j;\n\t\t\tmj := j;\n\t\tend\tdone;\n\t\tArray.set kk !mj (kk.(!mj) + 1);\nend done;;\nmm := 0;;\nfor j = 0 to n - 1 do if !mm < kk.(j) then begin\n\tmm := kk.(j);\n\tmj := j;\nend done;;\nprint_int (!mj + 1);;\n"}, {"source_code": "let winner a =\n fst (Array.fold_left (fun (i, pos) b -> if b > a.(i) then (pos, pos + 1) else (i, pos + 1)) (0, 0) a)\n\nlet () = Scanf.scanf \"%d %d\\n\" (fun n m ->\n\t\t\t\t(* candidates *)\n\t\t\t\tlet c = Array.make n 0 in\n\t\t\t\tfor i = 1 to m do\n\t\t\t\t let e = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n\t\t\t\t let w = winner e in\n\t\t\t\t c.(w) <- c.(w) + 1\n\t\t\t\tdone;\n\t\t\t\tPrintf.printf \"%d\\n\" (winner c + 1))\n"}], "negative_code": [{"source_code": "let get a'= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ()));;\nlet [n; m] = get ();;\nlet kk = Array.make n 0 and mm = ref 0 and mj = ref 0;;\nfor i = 1 to m do\n\tlet ins = get () in begin\n\t\tmm := 0;\n\t\tfor j = 0 to n - 1 do if !mm < List.nth ins j then begin\n\t\t\tmm := List.nth ins j;\n\t\t\tmj := j;\n\t\tend\tdone;\n\t\tArray.set kk !mj (kk.(!mj) + 1);\nend done;;\nmm := 0;;\nfor j = 0 to n - 1 do if !mm < kk.(j) then begin\n\tmm := kk.(j);\n\tmj := j;\nend done;;\nprint_int (!mj + 1);;\n"}, {"source_code": "let get a'= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ()));;\nlet [n; m] = get ();;\nlet kk = Array.make n 0 and mm = ref 0 and mj = ref 0;;\nfor i = 1 to m do\n\tlet ins = get () in begin\n\t\tmm := (-1);\n\t\tfor j = 0 to n - 1 do if !mm < List.nth ins j then begin\n\t\t\tmm := List.nth ins j;\n\t\t\tmj := j;\n\t\tend\tdone;\nend done;;\nmm := 0;;\nfor j = 0 to n - 1 do if !mm < kk.(j) then begin\n\tmm := kk.(j);\n\tmj := j;\nend done;;\nprint_int (!mj + 1);;\n"}], "src_uid": "b20e98f2ea0eb48f790dcc5dd39344d3"} {"nl": {"description": "One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.", "input_spec": "The only line of the input contains one integer n (7\u2009\u2264\u2009n\u2009\u2264\u2009777) \u2014 the number of potential employees that sent resumes.", "output_spec": "Output one integer \u2014 the number of different variants of group composition.", "sample_inputs": ["7"], "sample_outputs": ["29"], "notes": null}, "positive_code": [{"source_code": "open Big_int\n\nlet (+|) = add_big_int\nlet (-|) = sub_big_int\nlet ( *| ) = mult_big_int\nlet (/|) = div_big_int\nlet bmod = mod_big_int\nlet (=|) = eq_big_int\nlet (/=|) a b = not (a =| b)\nlet (>|) = gt_big_int\nlet (<|) = lt_big_int\nlet (>=|) = ge_big_int\nlet (<=|) = le_big_int\n\nlet n0 = zero_big_int\nlet n1 = unit_big_int\nlet n2 = big_int_of_int 2\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = big_int_of_int n in\n let res =\n (n -| big_int_of_int 4) *|\n\t(n -| big_int_of_int 3) *|\n\t (n -| big_int_of_int 2) *|\n\t\t(n -| big_int_of_int 1) *| n *|\n\t\t (n *| n -| big_int_of_int 4 *| n +| big_int_of_int 37) /|\n\t\t\tbig_int_of_int 5040\n in\n Printf.printf \"%s\\n\" (string_of_big_int res)\n"}], "negative_code": [], "src_uid": "09276406e16b46fbefd6f8c9650472f0"} {"nl": {"description": "Stanley defines the beauty of an array $$$a$$$ of length $$$n$$$, which contains non-negative integers, as follows: $$$$$$\\sum\\limits_{i = 1}^{n} \\left \\lfloor \\frac{a_{i}}{k} \\right \\rfloor,$$$$$$ which means that we divide each element by $$$k$$$, round it down, and sum up the resulting values.Stanley told Sam the integer $$$k$$$ and asked him to find an array $$$a$$$ of $$$n$$$ non-negative integers, such that the beauty is equal to $$$b$$$ and the sum of elements is equal to $$$s$$$. Help Sam\u00a0\u2014 find any of the arrays satisfying the conditions above.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first line of each test case contains integers $$$n$$$, $$$k$$$, $$$b$$$, $$$s$$$ ($$$1 \\leq n \\leq 10^{5}$$$, $$$1 \\leq k \\leq 10^{9}$$$, $$$0 \\leq b \\leq 10^{9}$$$, $$$0 \\leq s \\leq 10^{18}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print $$$-1$$$ if such array $$$a$$$ does not exist. Otherwise print $$$n$$$ non-negative integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_{i} \\leq 10^{18}$$$)\u00a0\u2014 the answer.", "sample_inputs": ["8\n\n1 6 3 100\n\n3 6 3 12\n\n3 6 3 19\n\n5 4 7 38\n\n5 4 7 80\n\n99978 1000000000 100000000 1000000000000000000\n\n1 1 0 0\n\n4 1000000000 1000000000 1000000000000000000"], "sample_outputs": ["-1\n-1\n0 0 19\n0 3 3 3 29\n-1\n-1\n0\n0 0 0 1000000000000000000"], "notes": "NoteIn the first, the second, the fifth and the sixth test cases of the example it is possible to show that such array does not exist.In the third testcase of the example $$$a = [0, 0, 19]$$$. The sum of elements in it is equal to 19, the beauty of it is equal to $$$\\left ( \\left \\lfloor \\frac{0}{6} \\right \\rfloor + \\left \\lfloor \\frac{0}{6} \\right \\rfloor + \\left \\lfloor \\frac{19}{6} \\right \\rfloor \\right ) = (0 + 0 + 3) = 3$$$.In the fourth testcase of the example $$$a = [0, 3, 3, 3, 29]$$$. The sum of elements in it is equal to $$$38$$$, the beauty of it is equal to $$$(0 + 0 + 0 + 0 + 7) = 7$$$."}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nmodule Opt = struct\n let get = function\n | None -> assert false\n | Some v -> v\nend\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\n\nlet read_long () = sf \" %Ld\" (fun x -> x)\n\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet i_bit x i = (x lsr i) land 1\n\nlet () =\n let t = read_int () in\n\n for _ = 1 to t do\n let n0 = read_int () in\n let k = read_long () in\n let b = read_long () in\n let s = read_long () in\n let one = I.of_int 1 in\n let n = I.of_int n0 in\n let k1 = I.sub k one in\n if (I.mul b k <= s && s <= I.add (I.mul k1 n) (I.mul b k)) then begin\n let a = Array.make n0 I.zero in\n a.(0) <- I.mul b k;\n let sm = ref (I.sub s (I.mul b k)) in\n for i = 0 to n0 - 1 do\n if (!sm >= k1) then begin\n a.(i) <- I.add a.(i) k1;\n sm := I.sub (!sm) k1;\n end else begin\n a.(i) <- I.add a.(i) !sm;\n sm := I.zero;\n end;\n done;\n\n A.iter (pf \"%Ld \") a;\n pf \"\\n\";\n\n end else pf \"-1\\n\"\n done;"}], "negative_code": [], "src_uid": "b7ed6f296536d7cd464768b6f315fb99"} {"nl": {"description": "Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms \u2014 the left one and the right one. The robot can consecutively perform the following actions: Take the leftmost item with the left hand and spend wi\u2009\u00b7\u2009l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; Take the rightmost item with the right hand and spend wj\u2009\u00b7\u2009r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.", "input_spec": "The first line contains five integers n,\u2009l,\u2009r,\u2009Ql,\u2009Qr (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u20091\u2009\u2264\u2009l,\u2009r\u2009\u2264\u2009100;\u20091\u2009\u2264\u2009Ql,\u2009Qr\u2009\u2264\u2009104). The second line contains n integers w1,\u2009w2,\u2009...,\u2009wn (1\u2009\u2264\u2009wi\u2009\u2264\u2009100).", "output_spec": "In the single line print a single number \u2014 the answer to the problem.", "sample_inputs": ["3 4 4 19 1\n42 3 99", "4 7 2 3 9\n1 2 3 4"], "sample_outputs": ["576", "34"], "notes": "NoteConsider the first sample. As l\u2009=\u2009r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4\u00b742\u2009+\u20094\u00b799\u2009+\u20094\u00b73\u2009=\u2009576 energy units.The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2\u00b74)\u2009+\u2009(7\u00b71)\u2009+\u2009(2\u00b73)\u2009+\u2009(2\u00b72\u2009+\u20099)\u2009=\u200934 energy units."}, "positive_code": [{"source_code": "let (@@) f x = f x ;;\nlet (|>) x f = f x ;;\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet input () =\n let n, l, r, ql, qr = Scanf.scanf \"%d %Ld %Ld %Ld %Ld \" (fun n l r ql qr -> n, l, r, ql, qr) in\n let arr = Array.create n 0L in\n iter_for 0 n ~f:(fun i ->\n let w = Scanf.scanf \"%Ld \" ident in\n arr.(i) <- w);\n (n, l, r, ql, qr, arr)\n;;\n\nlet solve n l r ql qr ws =\n let sum_l = Array.create (n + 1) 0L in\n let sum_r = Array.create (n + 1)\n (Array.fold_left ws ~init:0L ~f:(fun acc i -> Int64.(acc + i * r))) in\n Array.iter sum_l ~f:(Printf.eprintf \"%Ld \");\n prerr_endline \"\";\n Array.iter sum_r ~f:(Printf.eprintf \"%Ld \");\n prerr_endline \"\";\n let (+/) = Int64.(+) in\n let ( */ ) = Int64.( * ) in\n iter_for 1 (n + 1) ~f:(fun i ->\n let (+/) = Int64.(+) in\n let (-/) = Int64.(-) in\n let ( */ ) = Int64.( * ) in\n sum_l.(i) <- sum_l.(i - 1) +/ ws.(i - 1) */ l;\n sum_r.(i) <- sum_r.(i - 1) -/ ws.(i - 1) */ r);\n Array.iter sum_l ~f:(Printf.eprintf \"%Ld \");\n prerr_endline \"\";\n Array.iter sum_r ~f:(Printf.eprintf \"%Ld \");\n prerr_endline \"\";\n fold_for 0 n ~init:(Int64.of_int max_int) ~f:(fun acc i ->\n let nl = i and nr = n - i - 1 in\n let r =\n if nl = nr then\n sum_l.(i) +/ sum_r.(i + 1) +/ min (ws.(i) */ l) (ws.(i) */ r)\n else if nl > nr then\n sum_l.(i) +/ sum_r.(i + 1) +/ ql */ Int64.of_int (nl - nr - 1) +/ min (ws.(i) */ l +/ ql) (ws.(i) */ r)\n else\n sum_l.(i) +/ sum_r.(i + 1) +/ qr */ Int64.of_int (nr - nl - 1) +/ min (ws.(i) */ l) (ws.(i) */ r +/ qr) in\n Printf.eprintf \"i = %d, sum = %Ld\\n\" i r;\n min acc r)\n;;\n\nlet () =\n let n, l, r, ql, qr, arr = input () in\n Printf.printf \"%Ld\\n\" @@ solve n l r ql qr arr\n;;\n"}], "negative_code": [{"source_code": "let (@@) f x = f x ;;\nlet (|>) x f = f x ;;\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet input () =\n let n, l, r, ql, qr = Scanf.scanf \"%d %d %d %d %d \" (fun n l r ql qr -> n, l, r, ql, qr) in\n let arr = Array.create n 0 in\n iter_for 0 n ~f:(fun i ->\n let w = Scanf.scanf \"%d \" ident in\n arr.(i) <- w);\n (n, l, r, ql, qr, arr)\n;;\n\nlet solve n l r ql qr ws =\n let sum_l = Array.create (n + 1) 0 in\n let sum_r = Array.create (n + 1) (Array.fold_left ws ~init:0 ~f:(fun acc i -> acc + i * r)) in\n Array.iter sum_l ~f:(Printf.eprintf \"%d \");\n prerr_endline \"\";\n Array.iter sum_r ~f:(Printf.eprintf \"%d \");\n prerr_endline \"\";\n iter_for 1 (n + 1) ~f:(fun i ->\n sum_l.(i) <- sum_l.(i - 1) + ws.(i - 1) * l;\n sum_r.(i) <- sum_r.(i - 1) - ws.(i - 1) * r);\n Array.iter sum_l ~f:(Printf.eprintf \"%d \");\n prerr_endline \"\";\n Array.iter sum_r ~f:(Printf.eprintf \"%d \");\n prerr_endline \"\";\n fold_for 0 n ~init:max_int ~f:(fun acc i ->\n let nl = i and nr = n - i - 1 in\n let r =\n if nl = nr then\n sum_l.(i) + sum_r.(i + 1) + min (ws.(i) * l) (ws.(i) * r)\n else if nl > nr then\n sum_l.(i) + sum_r.(i + 1) + ql * (nl - nr - 1) + min (ws.(i) * l + ql) (ws.(i) * r)\n else\n sum_l.(i) + sum_r.(i + 1) + qr * (nr - nl - 1) + min (ws.(i) * l) (ws.(i) * r + qr) in\n Printf.eprintf \"i = %d, sum = %d\\n\" i r;\n min acc r)\n;;\n\nlet () =\n let n, l, r, ql, qr, arr = input () in\n Printf.printf \"%d\\n\" @@ solve n l r ql qr arr\n;;\n"}, {"source_code": "let (@@) f x = f x ;;\nlet (|>) x f = f x ;;\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet input () =\n let n, l, r, ql, qr = Scanf.scanf \"%d %d %d %d %d \" (fun n l r ql qr -> n, l, r, ql, qr) in\n let arr = Array.create n 0 in\n iter_for 0 n ~f:(fun i ->\n let w = Scanf.scanf \"%d \" ident in\n arr.(i) <- w);\n (n, l, r, ql, qr, arr)\n;;\n\nlet solve n l r ql qr ws =\n let sum_l = Array.create (n + 1) 0 in\n let sum_r = Array.create (n + 1) (Array.fold_left ws ~init:0 ~f:(fun acc i -> acc + i * r)) in\n Array.iter sum_l ~f:(Printf.eprintf \"%d \");\n prerr_endline \"\";\n Array.iter sum_r ~f:(Printf.eprintf \"%d \");\n prerr_endline \"\";\n iter_for 1 (n + 1) ~f:(fun i ->\n sum_l.(i) <- sum_l.(i - 1) + ws.(i - 1) * l;\n sum_r.(i) <- sum_r.(i - 1) - ws.(i - 1) * r);\n Array.iter sum_l ~f:(Printf.eprintf \"%d \");\n prerr_endline \"\";\n Array.iter sum_r ~f:(Printf.eprintf \"%d \");\n prerr_endline \"\";\n fold_for 0 n ~init:max_int ~f:(fun acc i ->\n let nl = i and nr = n - i - 1 in\n let r =\n if nl = nr then\n sum_l.(i) + sum_r.(i + 1) + min (ws.(i) * l) (ws.(i) * r)\n else if nl > nr then\n sum_l.(i) + sum_r.(i + 1) + ql * (nl - nr - 1) + min (ws.(i) * l + ql) (ws.(i) * r)\n else\n sum_l.(i) + sum_r.(i + 1) + qr * (nr - nl - 1) + min (ws.(i) * l) (ws.(i) * r + qr) in\n Printf.eprintf \"i = %d, sum = %d\\n\" i r;\n min acc r)\n;;\n\nlet () =\n let n, l, r, ql, qr, arr = input () in\n Printf.printf \"%d\\n\" @@ solve n l r ql qr arr\n;;\n"}, {"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet () =\n let n = Scanf.scanf \"%d \" ident in\n let arr = Array.make_matrix (n + 2) (n + 2) ' ' in\n iter_for 1 (n + 1) ~f:(fun i ->\n iter_for 1 (n + 1) ~f:(fun j ->\n arr.(i).(j) <- Scanf.scanf \"%c \" ident));\n let memo = Array.make_matrix (n + 2) (n + 2) 0 in\n iter_for 1 (n + 1) ~f:(fun i ->\n iter_for 1 (n + 1) ~f:(fun j ->\n let i = (n + 1) - i in\n let j = (n + 1) - j in\n Printf.eprintf \"i, j, c = %d, %d, %c\\n\" i j arr.(i).(j);\n let d = if arr.(i).(j) = 'a' then 1 else if arr.(i).(j) = 'b' then -1 else 0 in\n if i = n then\n memo.(i).(j) <- memo.(i).(j + 1) + d\n else if j = n then\n memo.(i).(j) <- memo.(i + 1).(j) + d\n else if (i + j) mod 2 = 1 then\n memo.(i).(j) <- max memo.(i + 1).(j) memo.(i).(j + 1) + d\n else\n memo.(i).(j) <- min memo.(i + 1).(j) memo.(i).(j + 1) + d));\n Array.iter memo ~f:(fun x ->\n Array.iter x ~f:(fun k -> Printf.eprintf \"%d \" k);\n prerr_endline \"\");\n if memo.(1).(1) = 0 then print_endline \"DRAW\"\n else if memo.(1).(1) > 0 then print_endline \"FIRST\"\n else print_endline \"SECOND\"\n;;\n"}], "src_uid": "e6fcbe3f102b694a686c0295edbc35e9"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$m$$$. You have to construct the array $$$a$$$ of length $$$n$$$ consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly $$$m$$$ and the value $$$\\sum\\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ is the maximum possible. Recall that $$$|x|$$$ is the absolute value of $$$x$$$.In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array $$$a=[1, 3, 2, 5, 5, 0]$$$ then the value above for this array is $$$|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$$$. Note that this example doesn't show the optimal answer but it shows how the required value for some array is calculated.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^9$$$) \u2014 the length of the array and its sum correspondingly.", "output_spec": "For each test case, print the answer \u2014 the maximum possible value of $$$\\sum\\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ for the array $$$a$$$ consisting of $$$n$$$ non-negative integers with the sum $$$m$$$.", "sample_inputs": ["5\n1 100\n2 2\n5 5\n2 1000000000\n1000000000 1000000000"], "sample_outputs": ["0\n2\n10\n1000000000\n2000000000"], "notes": "NoteIn the first test case of the example, the only possible array is $$$[100]$$$ and the answer is obviously $$$0$$$.In the second test case of the example, one of the possible arrays is $$$[2, 0]$$$ and the answer is $$$|2-0| = 2$$$.In the third test case of the example, one of the possible arrays is $$$[0, 2, 0, 3, 0]$$$ and the answer is $$$|0-2| + |2-0| + |0-3| + |3-0| = 10$$$."}, "positive_code": [{"source_code": "open Scanf;;\n\nlet read () = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet nbTests = read () in\nfor iTest = 1 to nbTests do\n let nbEntiers = read() in\n let somme = read() in\n \n if nbEntiers = 1 then\n print_int 0\n else if nbEntiers = 2 then\n print_int somme\n else\n print_string (Int64.to_string (Int64.mul 2L (Int64.of_int somme)))\n ;\n print_newline ()\ndone;"}], "negative_code": [{"source_code": "open Scanf;;\n\nlet read () = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet nbTests = read () in\nfor iTest = 1 to nbTests do\n let nbEntiers = read() in\n let somme = read() in\n \n if nbEntiers = 1 then\n print_int 0\n else if nbEntiers = 2 then\n print_int somme\n else\n print_int (2 * somme)\n ;\n print_newline ()\ndone;"}], "src_uid": "905cc16ecbbb3305416f9aa6e4412642"} {"nl": {"description": "Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were $$$n$$$ classes of that subject during the semester and on $$$i$$$-th class professor mentioned some non-negative integer $$$a_i$$$ to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of $$$a$$$ to help out students like Mishka: $$$a$$$ was sorted in non-decreasing order ($$$a_1 \\le a_2 \\le \\dots \\le a_n$$$); $$$n$$$ was even; the following sequence $$$b$$$, consisting of $$$\\frac n 2$$$ elements, was formed and given out to students: $$$b_i = a_i + a_{n - i + 1}$$$. Professor also mentioned that any sequence $$$a$$$, which produces sequence $$$b$$$ with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence $$$a$$$ of non-negative integers, which produces sequence $$$b$$$ with the presented technique. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of sequence $$$a$$$. $$$n$$$ is always even. The second line contains $$$\\frac n 2$$$ integers $$$b_1, b_2, \\dots, b_{\\frac n 2}$$$ ($$$0 \\le b_i \\le 10^{18}$$$) \u2014 sequence $$$b$$$, where $$$b_i = a_i + a_{n - i + 1}$$$. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.", "output_spec": "Print $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 10^{18}$$$) in a single line. $$$a_1 \\le a_2 \\le \\dots \\le a_n$$$ should be satisfied. $$$b_i = a_i + a_{n - i + 1}$$$ should be satisfied for all valid $$$i$$$.", "sample_inputs": ["4\n5 6", "6\n2 1 2"], "sample_outputs": ["2 3 3 3", "0 0 1 1 1 2"], "notes": null}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in let a = iia (n/2L) in\n let res = make (i32 n) 0L in\n let l,r = ref 0L,ref a.(0) in\n iteri (fun i sum ->\n let ll = binary_search !l !r (fun v -> sum-v <= !r) in\n let rr = sum - ll in\n res.(i) <- ll;\n res.(i32 n-$i-$1) <- rr;\n l := ll; r := rr;\n ) a;\n print_array ist res\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "4585419ab2b7200770cfe1e607161e9f"} {"nl": {"description": "After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on \u2014 you can go from the (n\u2009-\u20091)-th room to the n-th room. Thus, you can go to room x only from room x\u2009-\u20091.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x\u2009-\u20091, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n\u2009-\u20091 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.", "input_spec": "The first line of the input contains a positive integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014\u00a0the number of rooms in the house. The second line of the input contains string s of length 2\u00b7n\u2009-\u20092. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters\u00a0\u2014\u00a0the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter \u2014 the type of the key that lies in room number (i\u2009+\u20091)\u2009/\u20092. The even positions in the given string contain uppercase Latin letters \u2014 the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter \u2014 the type of the door that leads from room i\u2009/\u20092 to room i\u2009/\u20092\u2009+\u20091.", "output_spec": "Print the only integer \u2014 the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.", "sample_inputs": ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"], "sample_outputs": ["0", "3", "2"], "notes": null}, "positive_code": [{"source_code": "open Scanf;;\nopen Printf;;\n\nlet rec change list target cur value = (* list\u306etarget\u756a\u76ee\u3092value\u306b\u5909\u3048\u305flist\u3092\u8fd4\u3059 *)\n if cur = target then value::( List.tl list )\n else ( List.hd list )::( change (List.tl list ) target ( cur + 1 ) value );;\n\n\nlet rec init size =\n if size <= 0 then [] \n else 0::( init ( size - 1 ) ) ;;\n\nlet n = scanf \"%d\\n\" ( fun n -> n );;\n\nlet rec solve s i list =\n if i >= ( String.length s ) then 0\n else begin\n if ( 'a' <= s.[i] && s.[i] <= 'z' ) then begin\n solve s ( i + 1 ) ( change list ( ( Char.code s.[i] ) - ( Char.code 'a' ) ) 0 ( 1 + ( List.nth list ( ( Char.code s.[i] ) - ( Char.code 'a' ) ) ) ) )\n end else begin\n if ( List.nth list ( ( Char.code s.[i] ) - ( Char.code 'A' ) ) ) = 0 then begin\n 1 + solve s ( i + 1 ) list\n end else begin\n solve s ( i + 1 ) ( change list ( ( Char.code s.[i] ) - ( Char.code 'A' ) ) 0 ( ( List.nth list ( ( Char.code s.[i] ) - ( Char.code 'A' ) ) ) - 1 ) )\n end\n end\n end\n;;\n\nlet s = scanf \"%s\\n\" ( fun s -> s ) in\n printf \"%d\\n\" ( solve s 0 ( init 26 ) );;"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let a = Array.make 26 0 in\n let res = ref 0 in\n for i = 0 to n - 2 do\n let k = Char.code s.[2 * i] - Char.code 'a' in\n\ta.(k) <- a.(k) + 1;\n\tlet k = Char.code s.[2 * i + 1] - Char.code 'A' in\n\t if a.(k) > 0\n\t then a.(k) <- a.(k) - 1\n\t else incr res\n done;\n Printf.printf \"%d\\n\" !res;\n"}], "negative_code": [], "src_uid": "80fdb95372c1e8d558b8c8f31c9d0479"} {"nl": {"description": "You are given a 0-1 rectangular matrix. What is the number of squares in it? A square is a solid square frame (border) with linewidth equal to 1. A square should be at least 2\u2009\u00d7\u20092. We are only interested in two types of squares: squares with each side parallel to a side of the matrix; squares with each side parallel to a diagonal of the matrix. For example the following matrix contains only one square of the first type: 0000000 0111100 0100100 0100100 0111100The following matrix contains only one square of the second type:00000000010000010100000100000000000Regardless of type, a square must contain at least one 1 and can't touch (by side or corner) any foreign 1. Of course, the lengths of the sides of each square should be equal.How many squares are in the given matrix?", "input_spec": "The first line contains integer t (1\u2009\u2264\u2009t\u2009\u2264\u200910000), where t is the number of test cases in the input. Then test cases follow. Each case starts with a line containing integers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009250), where n is the number of rows and m is the number of columns. The following n lines contain m characters each (0 or 1). The total number of characters in all test cases doesn't exceed 106 for any input file.", "output_spec": "You should output exactly t lines, with the answer to the i-th test case on the i-th line.", "sample_inputs": ["2\n8 8\n00010001\n00101000\n01000100\n10000010\n01000100\n00101000\n11010011\n11000011\n10 10\n1111111000\n1000001000\n1011001000\n1011001010\n1000001101\n1001001010\n1010101000\n1001001000\n1000001000\n1111111000", "1\n12 11\n11111111111\n10000000001\n10111111101\n10100000101\n10101100101\n10101100101\n10100000101\n10100000101\n10111111101\n10000000001\n11111111111\n00000000000"], "sample_outputs": ["1\n2", "3"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\n\nlet ds = [|0,1; 1,0; 0,-1; -1,0; 1,-1; 1,1; -1,1; -1,-1|]\n\nexception No\n\nlet () =\n for cc = 1 to read_int 0 do\n let n = read_int 0 in\n let m = read_int 0 in\n let a = Array.init n read_str in\n\n let rec dfs i j =\n let s = ref 0 in\n let rec go i j =\n if 0 <= i && i < n && 0 <= j && j < m && a.(i).[j] = '1' then (\n a.(i).[j] <- '2';\n incr s;\n Array.iter (fun (dx,dy) -> go (i+dx) (j+dy)) ds\n )\n in\n go i j;\n !s\n in\n\n let span i j l u v =\n try\n for d = u to v-1 do\n let x = ref i and y = ref j in\n for k = 0 to l do\n if not (0 <= !x && !x < n && 0 <= !y && !y < m && a.(!x).[!y] = '2') then\n raise No;\n x := !x + fst ds.(d);\n y := !y + snd ds.(d)\n done\n done;\n true\n with No ->\n false\n in\n\n let ans = ref 0 in\n for i = 0 to n-1 do\n for j = 0 to m-1 do\n if a.(i).[j] = '1' then (\n let s = dfs i j in\n if s mod 4 = 0 && s <= (n-1)*4 then (\n if span i j (s/4) 0 2 && span (i+s/4) (j+s/4) (s/4) 2 4 then\n incr ans;\n if span i j (s/4) 4 6 && span (i+s/2) j (s/4) 6 8 then\n incr ans;\n )\n )\n done\n done;\n Printf.printf \"%d\\n\" !ans\n done\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\n\nlet ds = [|0,1; 1,0; 0,-1; -1,0; 1,-1; 1,1; -1,1; -1,-1|]\n\nexception No\n\nlet () =\n for cc = 1 to read_int 0 do\n let n = read_int 0 in\n let m = read_int 0 in\n let a = Array.init n read_str in\n\n let rec dfs i j =\n let s = ref 0 in\n let rec go i j =\n if 0 <= i && i < n && 0 <= j && j < m && a.(i).[j] = '1' then (\n a.(i).[j] <- '2';\n incr s;\n Array.iter (fun (dx,dy) -> go (i+dx) (j+dy)) ds\n )\n in\n go i j;\n !s\n in\n\n let span i j l u v =\n try\n for d = u to v-1 do\n let x = ref i and y = ref j in\n for k = 0 to l do\n if not (0 <= !x && !x < n && 0 <= !y && !y < m && a.(!x).[!y] = '2') then\n raise No;\n x := !x + fst ds.(u);\n y := !y + snd ds.(u)\n done\n done;\n true\n with No ->\n false\n in\n\n let ans = ref 0 in\n for i = 0 to n-1 do\n for j = 0 to m-1 do\n if a.(i).[j] = '1' then (\n let s = dfs i j in\n if s mod 4 = 0 && s <= (n-1)*4 then (\n if span i j (s/4) 0 2 && span (i+s/4) (j+s/4) (s/4) 2 4 then\n incr ans;\n if span i j (s/4) 4 6 && span (i+s/2) j (s/4) 6 8 then\n incr ans;\n )\n )\n done\n done;\n Printf.printf \"%d\\n\" !ans\n done\n"}], "src_uid": "54b2a420296695edfb016b39d565e593"} {"nl": {"description": "Suppose you have two polynomials and . Then polynomial can be uniquely represented in the following way:This can be done using long division. Here, denotes the degree of polynomial P(x). is called the remainder of division of polynomial by polynomial , it is also denoted as . Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials . If the polynomial is zero, the result is , otherwise the result is the value the algorithm returns for pair . On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question. You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair to pair . ", "input_spec": "You are given a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009150)\u00a0\u2014 the number of steps of the algorithm you need to reach.", "output_spec": "Print two polynomials in the following format. In the first line print a single integer m (0\u2009\u2264\u2009m\u2009\u2264\u2009n)\u00a0\u2014 the degree of the polynomial. In the second line print m\u2009+\u20091 integers between \u2009-\u20091 and 1\u00a0\u2014 the coefficients of the polynomial, from constant to leading. The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials. If there is no answer for the given n, print -1. If there are multiple answer, print any of them.", "sample_inputs": ["1", "2"], "sample_outputs": ["1\n0 1\n0\n1", "2\n-1 0 1\n1\n0 1"], "notes": "NoteIn the second example you can print polynomials x2\u2009-\u20091 and x. The sequence of transitions is(x2\u2009-\u20091,\u2009x)\u2009\u2192\u2009(x,\u2009\u2009-\u20091)\u2009\u2192\u2009(\u2009-\u20091,\u20090).There are two steps in it."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n\n let zero() = Array.make (n+1) 0 in\n \n let shift p =\n if p.(n) <> 0 then failwith \"overflow\";\n Array.init (n+1) (fun i -> if i>0 then p.(i-1) else 0)\n in\n\n let sum p q =\n Array.init (n+1) (fun i -> (p.(i) + q.(i)) mod 3)\n in\n\n let scalar_mult d p =\n Array.init (n+1) (fun i -> (d * p.(i)) mod 3)\n in\n\n let mult (d0,d1) p =\n let p1 = scalar_mult d1 (shift p) in\n let p2 = scalar_mult d0 p in\n sum p1 p2\n in\n\n let rec build i (curr,prev) = if i=n then (curr,prev)\n else build (i+1) (sum (mult (0,1) curr) prev, curr)\n in\n\n let a0 = zero() in\n let a1 = zero() in\n a1.(0) <- 1;\n\n let (curr,prev) = build 0 (a1,a0) in\n\n let printpoly p =\n let rec find i = if i<0 then failwith \"not found\"\n else if p.(i) = 0 then find (i-1)\n else i\n in\n let degree = find n in\n printf \"%d\\n\" degree;\n for i=0 to degree do\n printf \"%d \" (if p.(i) = 2 then -1 else p.(i))\n done;\n print_newline()\n in\n\n printpoly curr;\n printpoly prev\n"}], "negative_code": [], "src_uid": "c2362d3254aefe30da99c4aeb4e1a894"} {"nl": {"description": "Anton came to a chocolate factory. There he found a working conveyor and decided to run on it from the beginning to the end.The conveyor is a looped belt with a total length of 2l meters, of which l meters are located on the surface and are arranged in a straight line. The part of the belt which turns at any moment (the part which emerges from under the floor to the surface and returns from the surface under the floor) is assumed to be negligibly short.The belt is moving uniformly at speed v1 meters per second. Anton will be moving on it in the same direction at the constant speed of v2 meters per second, so his speed relatively to the floor will be v1\u2009+\u2009v2 meters per second. Anton will neither stop nor change the speed or the direction of movement.Here and there there are chocolates stuck to the belt (n chocolates). They move together with the belt, and do not come off it. Anton is keen on the chocolates, but he is more keen to move forward. So he will pick up all the chocolates he will pass by, but nothing more. If a chocolate is at the beginning of the belt at the moment when Anton starts running, he will take it, and if a chocolate is at the end of the belt at the moment when Anton comes off the belt, he will leave it. The figure shows an example with two chocolates. One is located in the position a1\u2009=\u2009l\u2009-\u2009d, and is now on the top half of the belt, the second one is in the position a2\u2009=\u20092l\u2009-\u2009d, and is now on the bottom half of the belt. You are given the positions of the chocolates relative to the initial start position of the belt 0\u2009\u2264\u2009a1\u2009<\u2009a2\u2009<\u2009...\u2009<\u2009an\u2009<\u20092l. The positions on the belt from 0 to l correspond to the top, and from l to 2l \u2014 to the the bottom half of the belt (see example). All coordinates are given in meters.Anton begins to run along the belt at a random moment of time. This means that all possible positions of the belt at the moment he starts running are equiprobable. For each i from 0 to n calculate the probability that Anton will pick up exactly i chocolates.", "input_spec": "The first line contains space-separated integers n, l, v1 and v2 (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009l,\u2009v1,\u2009v2\u2009\u2264\u2009109) \u2014 the number of the chocolates, the length of the conveyor's visible part, the conveyor's speed and Anton's speed. The second line contains a sequence of space-separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009a1\u2009<\u2009a2\u2009<\u2009...\u2009<\u2009an\u2009<\u20092l) \u2014 the coordinates of the chocolates.", "output_spec": "Print n\u2009+\u20091 numbers (one per line): the probabilities that Anton picks up exactly i chocolates, for each i from 0 (the first line) to n (the last line). The answer will be considered correct if each number will have absolute or relative error of at most than 10\u2009-\u20099.", "sample_inputs": ["1 1 1 1\n0", "2 3 1 2\n2 5"], "sample_outputs": ["0.75000000000000000000\n0.25000000000000000000", "0.33333333333333331000\n0.66666666666666663000\n0.00000000000000000000"], "notes": "NoteIn the first sample test Anton can pick up a chocolate if by the moment he starts running its coordinate is less than 0.5; but if by the moment the boy starts running the chocolate's coordinate is greater than or equal to 0.5, then Anton won't be able to pick it up. As all positions of the belt are equiprobable, the probability of picking up the chocolate equals , and the probability of not picking it up equals ."}, "positive_code": [{"source_code": "open Num\nopen Big_int\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let v1 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let v2 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0.0 in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n\ta.(i) <- Int32.to_float k\n done;\n in\n let d =\n num_of_int l // (num_of_int v1 +/ num_of_int v2)\n */ num_of_int v2\n in\n let d = float_of_num d in\n let l2 = 2.0 *. float_of_int l in\n let eps = 10e-7 in\n let e = ref [] in\n let () =\n e := (d, 0) :: !e;\n e := (d +. l2, 0) :: !e;\n for i = 0 to n - 1 do\n e := (a.(i), 1) :: !e;\n e := (a.(i) +. l2, 1) :: !e;\n e := (a.(i) +. d, -1) :: !e;\n e := (a.(i) +. d +. l2, -1) :: !e;\n done;\n in\n let e = Array.of_list !e in\n let () = Array.sort compare e in\n let j = ref 0 in\n let c = ref 0 in\n let prev = ref 0.0 in\n let res = Array.make (n + 1) 0.0 in\n while !j < Array.length e && fst e.(!j) <= d +. eps do\n c := !c + snd e.(!j);\n incr j\n done;\n prev := d;\n while !j < Array.length e && fst e.(!j) <= d +. l2 +. eps do\n res.(!c) <- res.(!c) +. fst e.(!j) -. !prev;\n prev := fst e.(!j);\n c := !c + snd e.(!j);\n incr j\n done;\n for i = 0 to n do\n Printf.printf \"%.9f\\n\" (res.(i) /. l2);\n done;\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let v1 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let v2 = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0.0 in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n\ta.(i) <- Int32.to_float k\n done;\n in\n let d =\n float_of_int l /. (float_of_int v1 +. float_of_int v2)\n *. float_of_int v2\n in\n let l2 = 2.0 *. float_of_int l in\n let e = ref [] in\n let () =\n e := (d, 0) :: !e;\n e := (d +. l2, 0) :: !e;\n for i = 0 to n - 1 do\n e := (a.(i), 1) :: !e;\n e := (a.(i) +. l2, 1) :: !e;\n e := (a.(i) +. d, -1) :: !e;\n e := (a.(i) +. d +. l2, -1) :: !e;\n done;\n in\n let e = Array.of_list !e in\n let () = Array.sort compare e in\n let j = ref 0 in\n let c = ref 0 in\n let prev = ref 0.0 in\n let res = Array.make (n + 1) 0.0 in\n while !j < Array.length e && fst e.(!j) < d do\n c := !c + snd e.(!j);\n incr j\n done;\n prev := d;\n while !j < Array.length e && fst e.(!j) <= d +. l2 do\n res.(!c) <- res.(!c) +. fst e.(!j) -. !prev;\n prev := fst e.(!j);\n c := !c + snd e.(!j);\n incr j\n done;\n for i = 0 to n do\n Printf.printf \"%.9f\\n\" (res.(i) /. l2);\n done;\n"}], "src_uid": "9320fb6d8d989a4ad71cfe09c3ce3e7f"} {"nl": {"description": "Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so that all brothers got the same number of candies.", "input_spec": "The single line contains a single integer n (n is even, 2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of Gerald's brothers.", "output_spec": "Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers \u2014 the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order. It is guaranteed that the solution exists at the given limits.", "sample_inputs": ["2"], "sample_outputs": ["1 4\n2 3"], "notes": "NoteThe sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother."}, "positive_code": [{"source_code": "let n = read_int () in\nfor i = 1 to n do\n for j = 0 to n/2 - 1 do\n Printf.printf \"%d %d \" (i + j*n) (n*(n-j) - i + 1)\n done ;\n print_newline ()\ndone ;;\n"}], "negative_code": [], "src_uid": "0ac2a0954fe43d66eac32072c8ea5070"} {"nl": {"description": "Let's call beauty of an array $$$b_1, b_2, \\ldots, b_n$$$ ($$$n > 1$$$) \u00a0\u2014 $$$\\min\\limits_{1 \\leq i < j \\leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \\ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.", "input_spec": "The first line contains integers $$$n, k$$$ ($$$2 \\le k \\le n \\le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^5$$$).", "output_spec": "Output one integer\u00a0\u2014 the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.", "sample_inputs": ["4 3\n1 7 3 5", "5 5\n1 10 100 1000 10000"], "sample_outputs": ["8", "9"], "notes": "NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$\u00a0\u2014 $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$\u00a0\u2014 the whole array, which has the beauty equal to $$$|10-1| = 9$$$."}, "positive_code": [{"source_code": "let modulo = 998244353l;;\nlet (+%) a b = let sum = Int32.add a b in if sum >= modulo then Int32.sub sum modulo else sum;;\n\nlet read_int_list() = read_line() |> Str.(split (regexp \" \")) |> List.map (fun x -> Int32.of_string x);;\nlet n_sub = List.nth (read_int_list()) 1;;\nlet nums = List.sort compare (read_int_list());;\n\nlet rec generate_list len value =\n if len == 0\n then []\n else value :: (generate_list (len - 1) value)\n;;\n\nlet compute_num_subseq_least_diff nums k x =\n let rec compute_dp_one x cur_nums suffix_nums suffix_dp sum_prefix =\n (* Printf.printf \"%ld %d %d %d %ld\\n\" x (List.length cur_nums) (List.length suffix_nums) (List.length suffix_dp) sum_prefix; *)\n if cur_nums == []\n then []\n else if suffix_dp == [] || (Int32.add (List.hd suffix_nums) x) > (List.hd cur_nums)\n then sum_prefix :: compute_dp_one x (List.tl cur_nums) suffix_nums suffix_dp sum_prefix\n else compute_dp_one x cur_nums (List.tl suffix_nums) (List.tl suffix_dp) (sum_prefix +% (List.hd suffix_dp))\n in\n let rec compute_dp_all nums k x =\n (* Printf.printf \"%ld\\n\" k; *)\n if k = 1l\n then generate_list (List.length nums) 1l\n else compute_dp_one x nums nums (compute_dp_all nums (Int32.sub k 1l) x) 0l\n in\n List.fold_left (fun a b -> a +% b) 0l (compute_dp_all nums k x)\n;;\n\nlet rec compute_result nums k i =\n let count = compute_num_subseq_least_diff nums k i\n in\n if count = 0l\n then 0l\n else count +% (compute_result nums k (Int32.add i 1l))\nin\n Printf.printf \"%ld\\n\" (compute_result nums n_sub 1l)\n;;\n"}], "negative_code": [{"source_code": "let modulo = 998244353;;\nlet (+%) a b = if a + b >= modulo then a + b - modulo else a + b;;\n\nlet read_int_list() = read_line() |> Str.(split (regexp \" \")) |> List.map (fun x -> int_of_string x);;\nlet n_sub = List.nth (read_int_list()) 1;;\nlet nums = List.sort compare (read_int_list());;\n\nlet rec generate_list len value =\n if len == 0\n then []\n else value :: (generate_list (len - 1) value)\n;;\n\nlet compute_num_subseq_least_diff nums k x =\n let rec compute_dp_one x cur_nums suffix_nums suffix_dp sum_prefix =\n (* Printf.printf \"%d %d %d %d %d\\n\" x (List.length cur_nums) (List.length suffix_nums) (List.length suffix_dp) sum_prefix; *)\n if cur_nums == []\n then []\n else if suffix_dp == [] || (List.hd suffix_nums) + x > (List.hd cur_nums)\n then sum_prefix :: compute_dp_one x (List.tl cur_nums) suffix_nums suffix_dp sum_prefix\n else compute_dp_one x cur_nums (List.tl suffix_nums) (List.tl suffix_dp) (sum_prefix +% (List.hd suffix_dp))\n in\n let rec compute_dp_all nums k x =\n match k with\n | 1 -> generate_list (List.length nums) 1\n | _ -> compute_dp_one x nums nums (compute_dp_all nums (k - 1) x) 0\n in\n List.fold_left (fun a b -> a +% b) 0 (compute_dp_all nums k x)\n;;\n\nlet rec compute_result nums k i =\n (* Printf.printf \"\\n\"; *)\n let count = compute_num_subseq_least_diff nums k i\n in\n if count == 0\n then 0\n else count +% (compute_result nums k (i + 1))\nin\n Printf.printf \"%d\\n\" (compute_result nums n_sub 1)\n;;\n"}], "src_uid": "624bf3063400fd0c2c466295ff63469b"} {"nl": {"description": "Drazil created a following problem about putting 1\u2009\u00d7\u20092 tiles into an n\u2009\u00d7\u2009m grid:\"There is a grid with some cells that are empty and some cells that are occupied. You should use 1\u2009\u00d7\u20092 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it.\"But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: \"how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' \".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied.", "output_spec": "If there is no solution or the solution is not unique, you should print the string \"Not unique\". Otherwise you should print how to cover all empty cells with 1\u2009\u00d7\u20092 tiles. Use characters \"<>\" to denote horizontal tiles and characters \"^v\" to denote vertical tiles. Refer to the sample test for the output format example.", "sample_inputs": ["3 3\n...\n.*.\n...", "4 4\n..**\n*...\n*.**\n....", "2 4\n*..*\n....", "1 1\n.", "1 1\n*"], "sample_outputs": ["Not unique", "<>**\n*^<>\n*v**\n<><>", "*<>*\n<><>", "Not unique", "*"], "notes": "NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is \"Not unique\"."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let board = Array.init n (fun _ -> read_string()) in\n\n let is_empty i j = board.(i).[j] = '.' in (* return true if empty *)\n\n let empty = ref 0 in\n for i=0 to n-1 do\n for j=0 to m-1 do\n if is_empty i j then empty := !empty + 1\n done\n done;\n\n (* algorithm:\n\n (1) make a list of all force points\n (2) pick one and put a piece in\n look at all empty neighbors, if any of\n them has become a force point add it to\n the list of force points\n\n *)\n \n let count_empty_neighbors (i,j) = \n List.fold_left (fun ac (i,j) -> \n if i<0 || i>=n || j<0 || j>=m then ac \n else if is_empty i j then ac+1 else ac\n ) 0 [(i,j+1);(i,j-1);(i+1,j);(i-1,j)]\n in\n\n let empty_neighbor_direction (i,j) = \n List.fold_left (fun ac ((i,j),d) -> \n if i<0 || i>=n || j<0 || j>=m then ac \n else if is_empty i j then ((i,j),d) else ac\n ) ((0,0),0) [((i,j+1),0);((i,j-1),1);((i+1,j),2);((i-1,j),3)]\n in \n\n let next (i,j) = if i printf \"force point (%d,%d)\\n\" i j) fpl;\n*)\n let rec fill_in fpl nempty = \n if nempty=0 then true else if fpl = [] then false else (\n let (i,j) = List.hd fpl in\n let fpl = List.tl fpl in\n if not (is_empty i j) then fill_in fpl nempty else (\n\tif count_empty_neighbors (i,j) <> 1 then fill_in fpl nempty else (\n\t let ((i',j'),d) = empty_neighbor_direction (i,j) in\n(*\t printf \"empty neighbor direction = ((%d,%d),%d)\\n\" i' j' d; *)\n\t let (c1,c2) = match d with\n\t | 0 -> ('<','>')\n\t | 1 -> ('>','<')\n\t | 2 -> ('^','v')\n\t | 3 -> ('v','^')\n\t | _ -> failwith \"bad dir\"\n\t in\n\t board.(i).[j] <- c1;\n\t board.(i').[j'] <- c2;\n\n\t let nempty = nempty - 2 in\n\n\t let (i,j) = (i',j') in\n\t let fpl = List.fold_left (fun ac (i,j) ->\n\t if i<0 || i>=n || j<0 || j>=m then ac \n\t else if count_empty_neighbors (i,j) = 1 then (i,j)::ac else ac\n\t ) fpl [(i,j+1);(i,j-1);(i+1,j);(i-1,j)]\n\t in\n\t fill_in fpl nempty\n\t)\n )\n )\n in\n\n if fill_in fpl !empty then (\n for i=0 to n-1 do\n printf \"%s\\n\" board.(i)\n done;\n ) else (\n printf \"Not unique\\n\"\n )\n"}], "negative_code": [], "src_uid": "9465c37b6f948da14e71cc96ac24bb2e"} {"nl": {"description": "\"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come.\" \u2014 The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?", "input_spec": "First line consists of a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of stewards with Jon Snow. Second line consists of n space separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) representing the values assigned to the stewards.", "output_spec": "Output a single integer representing the number of stewards which Jon will feed.", "sample_inputs": ["2\n1 5", "3\n1 2 5"], "sample_outputs": ["0", "1"], "notes": "NoteIn the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2."}, "positive_code": [{"source_code": "let () =\n let n = read_int () in\n let a = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n (* sort ascending *)\n Array.sort compare a;\n let a = List.filter (fun x -> x <> a.(0) && x <> a.(n - 1)) (Array.to_list a) in\n print_int (List.length a);\n print_newline ()\n"}, {"source_code": "let _ =\n\tScanf.scanf \"%d\" @@ fun n ->\n\t\tlet l = (Array.init n (fun _ -> Scanf.scanf \" %d\" (fun i -> i)))\n\t\t\t|> Array.to_list\n\t\tin\n\t\tlet mini = List.fold_left min max_int l in\n\t\tlet maxi = List.fold_left max min_int l in\n\t\tlet l' = List.filter ((<>) mini) l in\n\t\tlet l'' = List.filter ((<>) maxi) l' in\n\t\t\tprint_int (List.length l'')"}], "negative_code": [], "src_uid": "acaa8935e6139ad1609d62bb5d35128a"} {"nl": {"description": "We are sum for we are manySome NumberThis version of the problem differs from the next one only in the constraint on $$$t$$$. You can make hacks only if both versions of the problem are solved.You are given two positive integers $$$l$$$ and $$$r$$$.Count the number of distinct triplets of integers $$$(i, j, k)$$$ such that $$$l \\le i < j < k \\le r$$$ and $$$\\operatorname{lcm}(i,j,k) \\ge i + j + k$$$.Here $$$\\operatorname{lcm}(i, j, k)$$$ denotes the least common multiple (LCM) of integers $$$i$$$, $$$j$$$, and $$$k$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$\\bf{1 \\le t \\le 5}$$$). Description of the test cases follows. The only line for each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le 2 \\cdot 10^5$$$, $$$l + 2 \\le r$$$).", "output_spec": "For each test case print one integer\u00a0\u2014 the number of suitable triplets.", "sample_inputs": ["5\n\n1 4\n\n3 5\n\n8 86\n\n68 86\n\n6 86868"], "sample_outputs": ["3\n1\n78975\n969\n109229059713337"], "notes": "NoteIn the first test case, there are $$$3$$$ suitable triplets: $$$(1,2,3)$$$, $$$(1,3,4)$$$, $$$(2,3,4)$$$. In the second test case, there is $$$1$$$ suitable triplet: $$$(3,4,5)$$$. "}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet max_n = 200000\n\nmodule SegTree = struct\n type t = int64 array\n\n let init n = A.make (2 * n) I.zero\n\n let add t i x =\n let v = ref i in\n let n = A.length t in\n while !v < n do\n t.(!v) <- I.add t.(!v) x;\n v := !v lor (!v + 1);\n done\n\n let pref_sum t i =\n let r = ref i in\n let res = ref I.zero in\n while !r >= 0 do\n res := I.add !res t.(!r);\n r := (!r land (!r + 1)) - 1;\n done;\n !res\n\n let sum t l r = I.sub (pref_sum t r) (pref_sum t (l - 1))\nend\n\nmodule L_ = struct\n let filter_map f =\n let rec aux accu = function\n | [] -> L.rev accu\n | x :: l ->\n match f x with\n | None -> aux accu l\n | Some v -> aux (v :: accu) l\n in\n aux []\nend\n\ntype query = {\n l: int;\n q_index: int;\n}\n\nlet find_first_div n =\n let i = ref 2 in\n let found = ref (-1) in\n while !i * !i <= n && !found = -1 do\n if (n mod !i = 0) then found := !i;\n i := !i + 1;\n done;\n if (!found = -1) then n\n else !found\n\nlet () =\n let q = read_int () in\n let original_queries: (int * int) array = Array.make q (0, 0) in\n let ans = Array.make q I.zero in\n let (events: query list array) = Array.init (max_n + 1) (fun _ -> []) in\n for i = 0 to q - 1 do\n let l = read_int () in\n let r = read_int () in\n original_queries.(i) <- (l, r);\n events.(r) <- {l; q_index = i;} :: events.(r);\n done;\n\n let (divisors: int list array) = Array.make (max_n + 1) [] in\n let pw2 = Array.make (max_n + 1) 0 in\n divisors.(1) <- [1];\n\n let inc_tree = SegTree.init max_n in\n for k = 2 to max_n do\n let fd = find_first_div k in\n let divs_prev = divisors.(k / fd) in\n divisors.(k) <- L.sort_uniq compare (divs_prev @ List.map (fun x -> x * fd) divs_prev);\n if (k mod 2 = 0) then pw2.(k) <- pw2.(k / 2) + 1;\n\n let divs = divisors.(k) in\n let divs_num = L.length divs in\n L.iteri (fun idx i ->\n if (i <> k) then\n SegTree.add inc_tree i @@ I.of_int @@ divs_num - idx - 2;\n ) divs;\n let p = pw2.(k) in\n\n let new_divs =\n A.of_list @@\n L.tl @@\n L.fast_sort (fun x y -> -compare x y) @@\n divs @ L_.filter_map (fun d ->\n if (d * 2 < k && pw2.(d) == p) then Some (d * 2)\n else None\n ) divs in\n let sj_p = ref 0 and ptr_j = ref (-1) in\n A.iteri (fun idx i ->\n while (!ptr_j <> -1 && new_divs.(!ptr_j) + i <= k) do\n let cd = new_divs.(!ptr_j) in\n if (pw2.(cd) = p + 1) then sj_p := !sj_p - 1;\n ptr_j := !ptr_j - 1\n done;\n\n if (pw2.(i) = p + 1) then\n SegTree.add inc_tree i @@ I.of_int @@ !ptr_j + 1\n else\n SegTree.add inc_tree i @@ I.of_int !sj_p;\n\n while (!ptr_j + 1 <= idx && new_divs.(!ptr_j + 1) + i > k) do\n let cd = new_divs.(!ptr_j + 1) in\n if (pw2.(cd) = p + 1) then sj_p := !sj_p + 1;\n ptr_j := !ptr_j + 1\n done;\n ) new_divs;\n\n L.iter (fun q ->\n ans.(q.q_index) <- SegTree.sum inc_tree q.l k;\n ) events.(k)\n done;\n\n for i = 0 to q - 1 do\n let n = snd original_queries.(i) - fst original_queries.(i) + 1 in\n let real_ans =\n I.(sub\n (div\n (mul (mul (of_int n) (of_int @@ n - 1)) (of_int @@ n - 2))\n (of_int 6))\n ans.(i)) in\n pf \"%Ld\\n\" real_ans;\n done;"}], "negative_code": [], "src_uid": "2cc753baa293ee832054de494dee0f15"} {"nl": {"description": "You are given an integer $$$n$$$ ($$$n \\ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \\cdot b^{k-1} + a_2 \\cdot b^{k-2} + \\ldots a_{k-1} \\cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\\cdot17^2+15\\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.", "input_spec": "The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\\le b\\le 100$$$, $$$1\\le k\\le 10^5$$$)\u00a0\u2014 the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \\ldots, a_k$$$ ($$$0\\le a_i < b$$$)\u00a0\u2014 the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.", "output_spec": "Print \"even\" if $$$n$$$ is even, otherwise print \"odd\". You can print each letter in any case (upper or lower).", "sample_inputs": ["13 3\n3 2 7", "10 9\n1 2 3 4 5 6 7 8 9", "99 5\n32 92 85 74 4", "2 2\n1 0"], "sample_outputs": ["even", "odd", "odd", "even"], "notes": "NoteIn the first example, $$$n = 3 \\cdot 13^2 + 2 \\cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \\cdot 99^4 + 92 \\cdot 99^3 + 85 \\cdot 99^2 + 74 \\cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$."}, "positive_code": [{"source_code": "let rec sum acc base digits = match digits with \n| [] -> acc\n| first :: digits -> sum (acc + first * base) base digits in\n\nlet is_even base digits = match digits with\n| [] -> false\n| first :: digits -> ((sum first base digits) mod 2 == 0) in\n\nlet main b a = if is_even b a then \"even\" else \"odd\" in\n\nlet rec read (acc: int list) k = if k == 0\n then acc \n else read ((Scanf.scanf \" %s\" (fun a -> (int_of_string (String.trim a)))) :: acc) (k - 1) in\n\nScanf.scanf \"%s %s\\n\" (fun b k -> \n print_string(main (int_of_string (String.trim b)) (read [] (int_of_string (String.trim k))))\n)\n"}], "negative_code": [], "src_uid": "ee105b664099808143a94a374d6d5daa"} {"nl": {"description": "There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \\le l < r \\le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \\ldots r] = [a_{l+1}, a_{l+2}, \\ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10 ^ 5$$$) \u00a0\u2014 the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$) \u00a0\u2014 elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le n$$$) \u00a0\u2014 elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10 ^ 5$$$", "output_spec": "For each test case, print \"YES\" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and \"NO\" (without quotes) otherwise. You can output \"YES\" and \"NO\" in any case (for example, strings \"yEs\", \"yes\" and \"Yes\" will be recognized as a positive response).", "sample_inputs": ["5\n\n5\n\n1 2 3 3 2\n\n1 3 3 2 2\n\n5\n\n1 2 4 2 1\n\n4 2 2 1 1\n\n5\n\n2 4 5 5 2\n\n2 2 4 5 5\n\n3\n\n1 2 3\n\n1 2 3\n\n3\n\n1 1 2\n\n2 1 1"], "sample_outputs": ["YES\nYES\nNO\nYES\nNO"], "notes": "NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation."}, "positive_code": [{"source_code": "let parse len str = let rep = Array.make len (-1) in\r\n let temp = ref \"\" in\r\n let j = ref 0 in\r\n for i = 0 to String.length str -1 do\r\n if str.[i] = ' ' then \r\n (rep.(!j) <- (int_of_string !temp) ; incr j ; temp:=\"\" ) \r\n else \r\n (temp:= !temp ^ (String.make 1 str.[i]))\r\n done; rep.(!j) <- (int_of_string !temp) ;rep\r\n;; \r\n\r\nlet rec update ind2 tab2 loserb len =\r\n \r\n if tab2.(!ind2 -1) = tab2.(!ind2) && Hashtbl.mem loserb (tab2.(!ind2)) then begin\r\n let num = Hashtbl.find loserb (tab2.(!ind2)) in \r\n if num = 1 then Hashtbl.remove loserb (tab2.(!ind2))\r\n else Hashtbl.replace loserb (tab2.(!ind2)) (num-1) ;\r\n incr ind2 ;\r\n if !ind2 < len then\r\n update ind2 tab2 loserb len\r\n ;\r\n end\r\n;;\r\n\r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor j = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str1 = (input_line stdin) in\r\n let str2 = (input_line stdin) in\r\n let tab1 = parse len str1 in\r\n let tab2 = parse len str2 in\r\n let ind2 = ref 0 in\r\n let loserb = Hashtbl.create(len) in\r\n for i = 0 to len -1 do\r\n if tab1.(i) = tab2.(!ind2) then begin \r\n incr ind2;\r\n if !ind2 < len then\r\n update ind2 tab2 loserb len\r\n ;\r\n end \r\n else begin\r\n if Hashtbl.mem loserb (tab1.(i)) then \r\n (let num = Hashtbl.find loserb (tab1.(i)) in Hashtbl.replace loserb (tab1.(i)) (num+1))\r\n else Hashtbl.add loserb (tab1.(i)) 1\r\n end;\r\n \r\n done;\r\nif !ind2 = len then print_endline \"YES\" else print_endline \"NO\"\r\ndone;;"}], "negative_code": [], "src_uid": "158bd0ab8f4319f5fd1e6062caddad4e"} {"nl": {"description": "The Little Elephant has got a problem \u2014 somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, \u2014 array a. Note that the elements of the array are not necessarily distinct numbers.", "output_spec": "In a single line print \"YES\" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and \"NO\" (without the quotes) otherwise.", "sample_inputs": ["2\n1 2", "3\n3 2 1", "4\n4 3 2 1"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is \"YES\".In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is \"YES\".In the third sample we can't sort the array in more than one swap operation, so the answer is \"NO\"."}, "positive_code": [{"source_code": "let swap ary i j =\n let temp = ary.(i) in\n ary.(i) <- ary.(j);\n ary.(j) <- temp\n\nlet input_array size ary =\n let rec input_array n =\n if n == size then ary\n else begin\n ary.(n) <- Scanf.scanf \" %d\" (fun x -> x);\n input_array (n + 1);\n end\n in\n input_array 0\n \nlet solve n =\n let a = input_array n (Array.make n 0) in\n let a_ = Array.copy a in\n let sorted_a =\n begin\n Array.stable_sort (fun a b -> if a <= b then -1 else 1) a;\n a;\n end\n in\n let rec solve x cnt =\n if cnt >= 3 then \"NO\"\n else if n == x then \"YES\"\n else if a_.(x) != sorted_a.(x) then solve (x + 1) (cnt + 1)\n else solve (x + 1) cnt\n in\n solve 0 0\n\nlet _ =\n Printf.printf \"%s\\n\" (Scanf.scanf \" %d\" solve)\n\t \n \n"}, {"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int();;\nlet tab=Array.make n 0;;\nfor i=0 to n-1 do\n tab.(i)<-read_int()\ndone;;\nlet creas()=let b=ref true in\nfor i=0 to n-2 do\n if tab.(i)>tab.(i+1) then b:=false\ndone;\n!b;;\nlet r=creas();;\nlet rec mins i v=if i=0 then 0 else if tab.(i-1)=v then mins (i-1) v else i;;\nlet rec maxs i v=if i=n-1 then n-1 else if tab.(i+1)=v then maxs (i+1) v else i;;\nlet rec prem i=\nif i=n-1 then 0 else if tab.(i)>tab.(i+1) then mins i tab.(i) else prem (i+1);;\nlet rec last i=\nif i=0 then 0 else if tab.(i) s) in\n let a = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n done;\n in\n let b = Array.copy a in\n let cmp (x : int) y =\n if x < y\n then -1\n else if x = y\n then 0\n else 1\n in\n Array.sort cmp b;\n let c = ref 0 in\n for i = 0 to n - 1 do\n\tif a.(i) <> b.(i)\n\tthen incr c;\n done;\n if !c >= 3\n then Printf.printf \"NO\\n\"\n else Printf.printf \"YES\\n\"\n"}], "negative_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int();;\nlet tab=Array.make n 0;;\nfor i=0 to n-1 do\n tab.(i)<-read_int()\ndone;;\nlet creas()=let b=ref true in\nfor i=0 to n-2 do\n if tab.(i)>tab.(i+1) then b:=false\ndone;\n!b;;\nlet r=creas();;\nlet rec mins i v=if i=0 then 0 else if tab.(i-1)=v then mins (i-1) v else i;;\nlet rec maxs i v=if i=n-1 then n-1 else if tab.(i+1)=v then mins (i+1) v else i;;\nlet rec prem i=\nif i=n-1 then 0 else if tab.(i)>tab.(i+1) then mins i tab.(i) else prem (i+1);;\nlet rec last i=\nif i=0 then 0 else if tab.(i)x);;\nlet n=read_int();;\nlet tab=Array.make n 0;;\nfor i=0 to n-1 do\n tab.(i)<-read_int()\ndone;;\nlet creas()=let b=ref true in\nfor i=0 to n-2 do\n if tab.(i)>tab.(i+1) then b:=false\ndone;\n!b;;\nlet r=creas();;\nlet rec prem i=\nif i=n-1 then 0 else if tab.(i)>tab.(i+1) then i else prem (i+1);;\nlet rec last i=\nif i=0 then 0 else if tab.(i)x);;\nlet n=read_int();;\nlet tab=Array.make n 0;;\nfor i=0 to n-1 do\n tab.(i)<-read_int()\ndone;;\nlet creas()=let b=ref true in\nfor i=0 to n-2 do\n if tab.(i)>tab.(i+1) then b:=false\ndone;\n!b;;\nlet r=creas();;\nlet rec prem i=\nif i=n-1 then 0 else if tab.(i)>tab.(i+1) then i else prem (i+1);;\nlet rec last i=\nif i=0 then 0 else if tab.(i)x);;\nlet n=read_int();;\nlet tab=Array.make n 0;;\nfor i=0 to n-1 do\n tab.(i)<-read_int()\ndone;;\nlet creas()=let b=ref true in\nfor i=0 to n-2 do\n if tab.(i)>tab.(i+1) then b:=false\ndone;\n!b;;\nlet r=creas();;\nlet rec prem i=\nif i=n-1 then 0 else if tab.(i)>tab.(i+1) then i else prem (i+1);;\nlet rec last i=\nif i=0 then 0 else if tab.(i) x)\n\nlet n = read_int ();;\nlet m = read_int ();;\nlet i = (ref 0);;\nlet tab = (ref [(0,0)]);;\nwhile ((!i) < (n)) do \n let a = read_int ()\n in\n let b = read_int ()\n in\n tab := [(a, b)]@(!tab);\n i := (!i + 1)\ndone\nlet tab = (rev (!tab));;\nif ((fst (List.hd tab)) <> 0) then \n begin\n print_string \"NO\";\n print_endline\n end\nelse\n begin\n let f a (x, y) = \n if (a>=x) then (max a y)\n else a\n in\n let zas = \n List.fold_left f 0 tab\n in \n if zas>=m then\n begin\n print_string \"YES\";\n print_endline\n end\n else\n begin\n print_string \"NO\";\n print_endline\n end\n end\n;;"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n let tele = Array.init n read_pair in\n\n let rec loop i reach =\n if reach >= m then true\n else if i = n then false \n else\n let (a,b) = tele.(i) in\n if a > reach then false\n else loop (i+1) (max reach b)\n in\n\n if loop 0 0 then printf \"YES\\n\" else printf \"NO\\n\"\n"}], "negative_code": [{"source_code": "open Pervasives\nopen List\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet n = read_int ();;\nlet m = read_int ();;\nlet i = (ref 0);;\nlet tab = (ref [(0,0)]);;\nwhile ((!i) < (n)) do \n let a = read_int ()\n in\n let b = read_int ()\n in\n tab := [(a, b)]@(!tab);\n i := (!i + 1)\ndone\nlet tab = (rev (!tab));;\nif ((fst (List.hd tab)) <> 0) then \n begin\n print_string \"NO\";\n print_endline\n end\nelse\n begin\n let f a (x, y) = \n if (a>=x) then (max a (x+y))\n else a\n in\n let zas = \n List.fold_left f 0 tab\n in \n if zas>=m then\n begin\n print_string \"YES\";\n print_endline\n end\n else\n begin\n print_string \"NO\";\n print_endline\n end\n end\n;;"}], "src_uid": "d646834d58c519d5e9c0545df2ca4be2"} {"nl": {"description": "Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!", "input_spec": "The first line contains an odd positive integer n\u00a0\u2014 the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.", "output_spec": "If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print \u2009-\u20091. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.", "sample_inputs": ["527", "4573", "1357997531"], "sample_outputs": ["572", "3574", "-1"], "notes": null}, "positive_code": [{"source_code": "let f mot =\n\tlet flag = ref true and last = mot.[String.length mot - 1] in\n\tfor i=0 to String.length mot - 1 do\n\t\tif !flag && (int_of_char (mot.[i]) mod 2 = 0) && (mot.[i] < last)\n\t\t\tthen (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);\n\tdone;\n\tif !flag\n\t\tthen for i=String.length mot - 1 downto 0 do\n\t\tif !flag && (int_of_char (mot.[i]) mod 2 = 0)\n\t\t\tthen (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);\n\t\tdone;\n\t!flag;;\n\nlet test n =\n\tlet mot = string_of_int n in\n\t\tif f mot\n\t\t\tthen -1\n\t\t\telse int_of_string mot;;\n\nlet final () =\n\tlet m = Scanf.scanf \"%s \" (fun i -> i) in\n\t\tif f m\n\t\t\tthen Printf.printf \"-1\"\n\t\t\telse Printf.printf \"%s \" m;;\n\nfinal ();;\n"}, {"source_code": "let int_of_char c = int_of_char c - int_of_char '0'\nand char_of_int i = char_of_int (i + int_of_char '0')\n\nlet () =\n let n = read_line () in\n let last = int_of_char (n.[String.length n - 1]) in\n let best = ref (-1) in\n let even = ref (-1) in\n\n for i = 0 to String.length n - 1 do\n let c = int_of_char n.[i] in\n if c mod 2 = 0 then begin\n even := i;\n if !best = (-1) && c < last then\n best := i\n end\n done;\n\n if !best <> (-1) then even := !best;\n if !even <> (-1)\n then begin\n n.[String.length n - 1] <- n.[!even];\n n.[!even] <- char_of_int last;\n print_endline n\n end\n else\n print_endline \"-1\"\n"}], "negative_code": [{"source_code": "let f mot =\n\tlet flag = ref true and last = mot.[String.length mot - 1] in\n\tfor i=0 to String.length mot - 1 do\n\t\tif !flag && (int_of_char (mot.[i]) mod 2 = 0) && (mot.[i] > last)\n\t\t\tthen (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);\n\tdone;\n\tif !flag\n\t\tthen for i=String.length mot - 1 downto 0 do\n\t\tif !flag && (int_of_char (mot.[i]) mod 2 = 0)\n\t\t\tthen (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);\n\t\tdone;\n\t!flag;;\n\nlet final () =\n\tlet m = Scanf.scanf \"%s \" (fun i -> i) in\n\t\tif f m\n\t\t\tthen Printf.printf \"-1\"\n\t\t\telse Printf.printf \"%s \" m;;\n\nfinal ();;\n"}], "src_uid": "bc375e27bd52f413216aaecc674366f8"} {"nl": {"description": "The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was ai kilobits per second.There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of n integers: a1,\u2009a2,\u2009...,\u2009an (16\u2009\u2264\u2009ai\u2009\u2264\u200932768); number ai denotes the maximum data transfer speed on the i-th computer.", "output_spec": "Print a single integer \u2014 the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer.", "sample_inputs": ["3 2\n40 20 30", "6 4\n100 20 40 20 50 50"], "sample_outputs": ["30", "40"], "notes": "NoteIn the first test case the organizers can cut the first computer's speed to 30 kilobits. Then two computers (the first and the third one) will have the same speed of 30 kilobits. They should be used as the participants' computers. This answer is optimal."}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\n\nlet n=read_int() and k=read_int();;\n\nlet l=ref [];;\nfor i=1 to n do\n l:=(read_int())::(!l)\ndone;;\n\nlet rec inserer v=function\n|[]->[v]\n|h::t->if v>=h then v::h::t else h::(inserer v t);;\n\nlet rec tri=function\n|[]->[]\n|h::t->inserer h (tri t);;\n \nlet sol=tri(!l);;\n\nlet rec neme i=function\n|[]->0\n|h::t->if i=1 then h else neme (i-1) t;;\n\nprint_int(neme k sol);;"}, {"source_code": "open Scanf\nopen Printf\n\nlet flip f a b = f b a in\n\nlet read_int () = scanf \" %d \" (fun x -> x) in\n\nlet rec range a b = if a > b then [] else a :: (range (a + 1) b) in\n\nlet read_list n =\n let f l _ = ((read_int ()) :: l) in\n List.fold_left f [] (range 1 n) in\n\nlet n = read_int () in\nlet k = read_int () in\nlet l = read_list n in\n\nlet (|>) a f = f a in\n\nl |> (List.sort compare) |> List.rev |> (flip List.nth (k - 1)) |> (printf \"%d\\n\");;\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a\n in\n Printf.printf \"%d\\n\" a.(n - k);\n"}], "negative_code": [], "src_uid": "6eca08d7cc2dec6f4f84d3faa9a8a915"} {"nl": {"description": "You are a coach of a group consisting of $$$n$$$ students. The $$$i$$$-th student has programming skill $$$a_i$$$. All students have distinct programming skills. You want to divide them into teams in such a way that: No two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $$$1$$$); the number of teams is the minimum possible. You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$) \u2014 the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of students in the query. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$, all $$$a_i$$$ are distinct), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student.", "output_spec": "For each query, print the answer on it \u2014 the minimum number of teams you can form if no two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than $$$1$$$)", "sample_inputs": ["4\n4\n2 10 1 20\n2\n3 6\n5\n2 3 4 99 100\n1\n42"], "sample_outputs": ["2\n1\n2\n1"], "notes": "NoteIn the first query of the example, there are $$$n=4$$$ students with the skills $$$a=[2, 10, 1, 20]$$$. There is only one restriction here: the $$$1$$$-st and the $$$3$$$-th students can't be in the same team (because of $$$|a_1 - a_3|=|2-1|=1$$$). It is possible to divide them into $$$2$$$ teams: for example, students $$$1$$$, $$$2$$$ and $$$4$$$ are in the first team and the student $$$3$$$ in the second team.In the second query of the example, there are $$$n=2$$$ students with the skills $$$a=[3, 6]$$$. It is possible to compose just a single team containing both students."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet solve n = \n\tlet t = Array.make n 0 in\n\tfor i = 0 to (n - 1) do\n\t\tlet a = read_int () in\n\t\tt.(i) <- a\n\tdone; \n\tArray.sort compare t;\n\tlet result = ref 1 in\n\t\tfor i = 1 to (n - 1) do\n\t\t\tif t.(i) - t.(i - 1) = 1\n\t\t\t\tthen result := 2\n\t\tdone;\n\t!result\n\t\nlet () = \n\tlet q = read_int () in\n\tfor tests = 1 to q do\n\t\tlet n = read_int () in\n\t\tprintf \"%d\\n\" (solve n)\n\tdone;"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet solve n = \n\tlet t = Array.make (n + 1) 0 in\n\tfor i = 0 to (n - 1) do\n\t\tlet a = read_int () in\n\t\tt.(i) <- a\n\tdone; \n\tArray.sort compare t;\n\tlet result = ref 1 in\n\t\tfor i = 1 to n - 1 do\n\t\t\tif t.(i) - t.(i - 1) = 1\n\t\t\t\tthen result := 2\n\t\tdone;\n\t!result\nlet () = \n\tlet q = read_int () in\n\tfor tests = 1 to q do\n\t\tlet n = read_int () in\n\t\tprintf \"%d\\n\" (solve n)\n\tdone;"}], "src_uid": "dd2cd365d7afad9c2b5bdbbd45d87c8a"} {"nl": {"description": "The only difference between the two versions is that this version asks the maximal possible answer.Homer likes arrays a lot. Today he is painting an array $$$a_1, a_2, \\dots, a_n$$$ with two kinds of colors, white and black. A painting assignment for $$$a_1, a_2, \\dots, a_n$$$ is described by an array $$$b_1, b_2, \\dots, b_n$$$ that $$$b_i$$$ indicates the color of $$$a_i$$$ ($$$0$$$ for white and $$$1$$$ for black).According to a painting assignment $$$b_1, b_2, \\dots, b_n$$$, the array $$$a$$$ is split into two new arrays $$$a^{(0)}$$$ and $$$a^{(1)}$$$, where $$$a^{(0)}$$$ is the sub-sequence of all white elements in $$$a$$$ and $$$a^{(1)}$$$ is the sub-sequence of all black elements in $$$a$$$. For example, if $$$a = [1,2,3,4,5,6]$$$ and $$$b = [0,1,0,1,0,0]$$$, then $$$a^{(0)} = [1,3,5,6]$$$ and $$$a^{(1)} = [2,4]$$$.The number of segments in an array $$$c_1, c_2, \\dots, c_k$$$, denoted $$$\\mathit{seg}(c)$$$, is the number of elements if we merge all adjacent elements with the same value in $$$c$$$. For example, the number of segments in $$$[1,1,2,2,3,3,3,2]$$$ is $$$4$$$, because the array will become $$$[1,2,3,2]$$$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $$$0$$$.Homer wants to find a painting assignment $$$b$$$, according to which the number of segments in both $$$a^{(0)}$$$ and $$$a^{(1)}$$$, i.e. $$$\\mathit{seg}(a^{(0)})+\\mathit{seg}(a^{(1)})$$$, is as large as possible. Find this number.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq n$$$).", "output_spec": "Output a single integer, indicating the maximal possible total number of segments.", "sample_inputs": ["7\n1 1 2 2 3 3 3", "7\n1 2 3 4 5 6 7"], "sample_outputs": ["6", "7"], "notes": "NoteIn the first example, we can choose $$$a^{(0)} = [1,2,3,3]$$$, $$$a^{(1)} = [1,2,3]$$$ and $$$\\mathit{seg}(a^{(0)}) = \\mathit{seg}(a^{(1)}) = 3$$$. So the answer is $$$3+3 = 6$$$.In the second example, we can choose $$$a^{(0)} = [1,2,3,4,5,6,7]$$$ and $$$a^{(1)}$$$ is empty. We can see that $$$\\mathit{seg}(a^{(0)}) = 7$$$ and $$$\\mathit{seg}(a^{(1)}) = 0$$$. So the answer is $$$7+0 = 7$$$."}, "positive_code": [{"source_code": "(* When there's more than one in the block, WLOG they go to opposite streams.\n So all we have to do is decide what happens between big blocks.\n\n Case1: The two big blocks differ. In this case we just\n leave the stuff between the blocks in one of the streams.\n\n Case2: The two big blocks are the same, say x.\n The only question becomes if it's possible to move one from the\n stream that is not x that is not between two identical ones.\n*)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int() in\n let a = Array.init n read_int in\n\n let compressed = fold 0 (n-1) (\n fun i ac ->\n if i=0 || a.(i-1) <> a.(i) then ( (* first of a block *)\n\tlet more_than_1 = i=n then (-2,true) else c.(i) in\n\n let p = ref (-1) in\n let count = ref 0 in\n\n for j=0 to n do\n let i = !p in\n let (xi,_) = get i in\n let (xj,doub) = get j in\n let delta = if j=n then 0 else 1 in\n if doub then (\n(* printf \"count = %d doub %d\\n\" !count xj; *)\n p := j;\n count := !count + 2*delta + j-i-1;\n if xi = xj then (\n\tif i+1 = j then failwith \"should not happen i+1=j\";\n\tif exists (i+1) (j-1) (fun k ->\n\t let (a,_) = get (k-1) in\n\t let (b,_) = get k in\n\t let (c,_) = get (k+1) in\n\t a <> c && b <> xi\n\t) then () else (\n\t count := !count - 1\n\t)\n )\n )\n done;\n\n printf \"%d\\n\" !count\n"}], "negative_code": [{"source_code": "(* When there's more than one in the block, WLOG they go to opposite streams.\n So all we have to do is decide what happens between big blocks.\n\n Case1: The two big blocks differ. In this case we just\n leave the stuff between the blocks in one of the streams.\n\n Case2: The two big blocks are the same, say x.\n The only question becomes if it's possible to move one from the\n stream that is not x that is not between two identical ones.\n*)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int() in\n let a = Array.init n read_int in\n\n let compressed = fold 0 (n-1) (\n fun i ac ->\n if i=0 || a.(i-1) <> a.(i) then ( (* first of a block *)\n\tlet more_than_1 = i=n then (-2,true) else c.(i) in\n\n let p = ref (-1) in\n let count = ref 0 in\n\n for j=0 to n do\n let i = !p in\n let (xi,_) = get i in\n let (xj,doub) = get j in\n let delta = if j=n then 0 else 1 in\n if doub then (\n printf \"count = %d doub %d\\n\" !count xj;\n p := j;\n count := !count + 2*delta + j-i-1;\n if xi = xj then (\n\tif i+1 = j then failwith \"should not happen i+1=j\";\n\tif exists (i+1) (j-1) (fun k ->\n\t let (a,_) = get (k-1) in\n\t let (b,_) = get k in\n\t let (c,_) = get (k+1) in\n\t a <> c && b <> xi\n\t) then () else (\n\t count := !count - 1\n\t)\n )\n )\n done;\n\n printf \"%d\\n\" !count\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int() in\n let a = Array.init n read_int in\n\n let compressed = fold 0 (n-1) (\n fun i ac ->\n if i=0 || a.(i-1) <> a.(i) then ( (* first of a block *)\n\tlet more_than_1 = i ac\n | (x,true)::t ->\n\tscan t x x true true (ac + (delta l1 x) + (delta l2 x))\n | (x,false)::t ->\n\tif x = l1 then scan t l1 x split1 false (ac + (delta l2 x))\n\telse if x = l2 then scan t x l2 false split2 (ac + (delta l1 x))\n\telse if split1 then scan t x l2 false split2 (ac + (delta l1 x))\n\telse scan t l1 x split1 false (ac + (delta l2 x))\n in\n\n let answer = scan compressed (-1) (-1) false false 0 in\n\n printf \"%d\\n\" answer\n"}, {"source_code": "open Printf\r\nopen Scanf\r\n\r\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\r\n\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\n \r\nlet () = \r\n let n = read_int() in\r\n let a = Array.init n read_int in\r\n\r\n(* if n=1 then printf \"1\\n\" *)\r\n\r\n let (comp_a,b) = fold 0 (n-1) (\r\n fun i (ac1,ac2) ->\r\n let ac1 = if i=0 || a.(i-1) <> a.(i) then a.(i)::ac1 else ac1 in\r\n let ac2 = if not (i=0 || a.(i-1) <> a.(i)) then a.(i)::ac2 else ac2 in\r\n (ac1,ac2)\r\n ) ([],[]) in\r\n\r\n let b = Array.of_list b in\r\n let nb = Array.length b in\r\n\r\n let comp_b = fold 0 (nb-1) (\r\n fun i ac ->\r\n if i=0 || b.(i-1) <> b.(i) then b.(i)::ac else ac\r\n ) [] in\r\n\r\n printf \"%d\\n\" ((List.length comp_a) + (List.length comp_b))\r\n"}], "src_uid": "55f0ecc597e6e40256a14debcad1b878"} {"nl": {"description": "Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n\u2009\u00d7\u2009n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A: The unusual square of A is equal to (1\u00b71\u2009+\u20091\u00b70\u2009+\u20091\u00b71)\u2009+\u2009(0\u00b71\u2009+\u20091\u00b71\u2009+\u20091\u00b70)\u2009+\u2009(1\u00b71\u2009+\u20090\u00b71\u2009+\u20090\u00b70)\u2009=\u20090\u2009+\u20091\u2009+\u20091\u2009=\u20090.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following: given a row index i, flip all the values in the i-th row in A; given a column index i, flip all the values in the i-th column in A; find the unusual square of A. To flip a bit value w means to change it to 1\u2009-\u2009w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?", "input_spec": "The first line of input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0\u2009\u2264\u2009aij\u2009\u2264\u20091) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009106), the number of queries. Each of the next q lines describes a single query, which can be one of the following: 1 i \u2014 flip the values of the i-th row; 2 i \u2014 flip the values of the i-th column; 3 \u2014 output the unusual square of A. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.", "output_spec": "Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.", "sample_inputs": ["3\n1 1 1\n0 1 1\n1 0 0\n12\n3\n2 3\n3\n2 2\n2 2\n1 3\n3\n3\n1 2\n2 1\n1 1\n3"], "sample_outputs": ["01001"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\n\nlet n=read_int();;\n\nlet l=ref 0;;\n\nfor i=0 to n-1 do\n for j=0 to n-1 do\n let a=read_int() in if i=j then l:= !l+a\n done\ndone;;\n\nlet m=read_int();;\n\nl:= ( !l mod 2);;\n\nlet p=ref [];;\n\nfor i=1 to m do\n let q=read_int() in if q<>3 then let a=read_int() in l:=1- !l else p:=(!l):: !p\ndone;;\n\nlet rec print_list=function\n|[]->()\n|h::t->print_list t;print_int h;;\n\nprint_list !p;;"}, {"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\n\nlet n=read_int();;\n\nlet l=ref 0;;\n\nlet a=ref 0;;\n\nfor i=0 to n-1 do\n for j=0 to i do\n a:=read_int()\n done;\n for j=i+1 to n-1 do\n let b=read_int() in ()\n done;\n l:= !l+ !a;\ndone;;\n\nlet m=read_int();;\n\nl:= (!l mod 2);;\n\nfor i=1 to m do\n let q=read_int() in if q<>3 then let a=read_int() in l:=1- !l else print_int !l\ndone;;\n"}, {"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\n\nlet n=read_int();;\n\nlet l=ref 0;;\n\nlet s=ref \" \";;\n\nlet a=ref 0;;\n\nfor i=0 to n-1 do\n for j=0 to i do\n a:=read_int()\n done;\n for j=i+1 to n-1 do\n let b=read_int() in ()\n done;\n l:= !l+ !a;\ndone;;\n\nlet m=read_int();;\n\nl:= (!l mod 2);;\n\nlet p=ref [];;\n\nfor i=1 to m do\n let q=read_int() in if q<>3 then let a=read_int() in l:=1- !l else p:=(!l):: !p\ndone;;\n\nlet rec print_list=function\n|[]->()\n|h::t->print_list t;print_int h;;\n\nprint_list !p;;"}], "negative_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet split_spaces chaine =\n let res = ref [] in\n let temp = ref \"\" in\n for i = 0 to String.length chaine - 1 do\n if chaine.[i]=' '\n then\n begin\n res := !res @ [!temp];\n temp := \"\";\n end\n else\n temp := !temp ^ (String.sub chaine i 1);\n done;\n res := !res @ [!temp];\n !res;;\nlet n = int_of_string (input_line stdin);;\nlet mat = Array.init n (fun _ -> Array.map int_of_string (Array.of_list (split_spaces (input_line stdin))));;\nlet m=read_int();;\n\nlet aj tab=\nlet l=ref 0 in\n for i=0 to n-1 do\n l:= !l+tab.(i).(i)\n done;\n!l mod 2;;\n\nlet chg a=mat.(a-1).(a-1)<-1-mat.(a-1).(a-1);;\n\nlet p=ref [];;\n\nfor i=1 to m do\n let q=read_int() in if q<>3 then let a=read_int() in mat.(a-1).(a-1)<-1-mat.(a-1).(a-1) else p:=(aj mat):: !p\ndone;;\n\nlet rec print_list=function\n|[]->()\n|h::t->print_list t;print_int h;;"}, {"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet split_spaces chaine =\n let res = ref [] in\n let temp = ref \"\" in\n for i = 0 to String.length chaine - 1 do\n if chaine.[i]=' '\n then\n begin\n res := !res @ [!temp];\n temp := \"\";\n end\n else\n temp := !temp ^ (String.sub chaine i 1);\n done;\n res := !res @ [!temp];\n !res;;\nlet n = int_of_string (input_line stdin);;\nlet mat = Array.init n (fun _ -> Array.map int_of_string (Array.of_list (split_spaces (input_line stdin))));;\nlet m=read_int();;\n\nlet l=ref 0;;\nfor i=0 to n-1 do\n l:= !l+mat.(i).(i)\ndone;;\n\nlet p=ref [];;\n\nfor i=1 to m do\n let q=read_int() in if q<>3 then let a=read_int() in l:=1- !l else p:=(!l):: !p\ndone;;\n\nlet rec print_list=function\n|[]->()\n|h::t->print_list t;print_int h;;\n\nprint_list !p;;"}], "src_uid": "332902284154faeaf06d5d05455b7eb6"} {"nl": {"description": "Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex $$$1$$$ is the root of this tree. Also, each edge has its own cost.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $$$0$$$.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $$$2$$$ rounding down. More formally, during one move, you choose some edge $$$i$$$ and divide its weight by $$$2$$$ rounding down ($$$w_i := \\left\\lfloor\\frac{w_i}{2}\\right\\rfloor$$$).Each edge $$$i$$$ has an associated cost $$$c_i$$$ which is either $$$1$$$ or $$$2$$$ coins. Each move with edge $$$i$$$ costs $$$c_i$$$ coins.Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most $$$S$$$. In other words, if $$$w(i, j)$$$ is the weight of the path from the vertex $$$i$$$ to the vertex $$$j$$$, then you have to make $$$\\sum\\limits_{v \\in leaves} w(root, v) \\le S$$$, where $$$leaves$$$ is the list of all leaves.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$S$$$ ($$$2 \\le n \\le 10^5; 1 \\le S \\le 10^{16}$$$) \u2014 the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next $$$n-1$$$ lines describe edges of the tree. The edge $$$i$$$ is described as four integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ and $$$c_i$$$ ($$$1 \\le v_i, u_i \\le n; 1 \\le w_i \\le 10^6; 1 \\le c_i \\le 2$$$), where $$$v_i$$$ and $$$u_i$$$ are vertices the edge $$$i$$$ connects, $$$w_i$$$ is the weight of this edge and $$$c_i$$$ is the cost of this edge. It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$ ($$$\\sum n \\le 10^5$$$).", "output_spec": "For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most $$$S$$$.", "sample_inputs": ["4\n4 18\n2 1 9 2\n3 2 4 1\n4 1 1 2\n3 20\n2 1 8 1\n3 1 7 2\n5 50\n1 3 100 1\n1 5 10 2\n2 3 123 2\n5 4 55 1\n2 100\n1 2 409 2"], "sample_outputs": ["0\n0\n11\n6"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n \nmodule Pair = struct \n type t = int64 * int \n let compare = compare\nend\n \nmodule SS = Set.Make(Pair)\n \nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n \nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n \nlet solve() =\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n \n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n let c = read_int() in\n g.(u) <- ((v, w, c) :: g.(u));\n g.(v) <- ((u, w, c) :: g.(v))\n done;\n \n let list_1 = ref [] in\n let list_2 = ref [] in\n let sum = ref 0L in\n \n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n \n let upd_cnt new_vert cost t =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n \n let mult = Int64.mul cost (Int64.of_int add) in\n sum := Int64.add !sum mult;\n let c = ref cost in\n while !c > 0L do\n let mult = Int64.mul (div2 !c) (Int64.of_int add) in\n if t = 1 then (\n list_1 := mult :: !list_1\n ) \n else (\n list_2 := mult :: !list_2\n );\n c := Int64.div !c 2L\n done \n )\n in\n \n List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n \n let answer = ref 0 in\n \n let arr_1 = Array.of_list !list_1 in\n let arr_2 = Array.of_list !list_2 in\n Array.fast_sort compare arr_1;\n Array.fast_sort compare arr_2;\n let id_1 = ref (Array.length arr_1 - 1) in\n let id_2 = ref (Array.length arr_2 - 1) in\n \n while !sum > s do\n if -1 = !id_1 then (\n sum := Int64.sub !sum arr_2.(!id_2);\n id_2 := !id_2 - 1;\n answer := !answer + 1\n ) else if -1= !id_2 then (\n sum := Int64.sub !sum arr_1.(!id_1);\n id_1 := !id_1 - 1\n ) else (\n if arr_1.(!id_1) >= arr_2.(!id_2) || !sum <= (Int64.add s arr_1.(!id_1)) then (\n sum := Int64.sub !sum arr_1.(!id_1);\n id_1 := !id_1 - 1\n ) else (\n if 0 != !id_1 then (\n if (Int64.add arr_1.(!id_1) arr_1.(!id_1 - 1)) >= arr_2.(!id_2) then (\n sum := Int64.sub !sum arr_1.(!id_1);\n id_1 := !id_1 - 1\n ) else (\n sum := Int64.sub !sum arr_2.(!id_2);\n id_2 := !id_2 - 1;\n answer := !answer + 1\n )\n )\n else (\n sum := Int64.sub !sum arr_2.(!id_2);\n id_2 := !id_2 - 1;\n answer := !answer + 1\n )\n )\n );\n \n answer := !answer + 1\n done;\n \n printf \"%d\\n\" !answer\n \nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}, {"source_code": "open Printf\nopen Scanf\n\nmodule Pair = struct \n type t = int64 * int \n let compare = compare\nend\n\nmodule SS = Set.Make(Pair)\n \nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n\nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n\nlet solve() =\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n\n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n let c = read_int() in\n g.(u) <- ((v, w, c) :: g.(u));\n g.(v) <- ((u, w, c) :: g.(v))\n done;\n\n let edges = Array.make n (0L, 0) in\n let set_1 = ref (SS.empty) in\n let set_2 = ref (SS.empty) in\n let sum = ref 0L in\n\n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n\n let upd_cnt new_vert cost t =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n edges.(new_vert) <- (cost, add);\n\n let mult = Int64.mul cost (Int64.of_int add) in\n sum := Int64.add !sum mult;\n let mult = Int64.mul (div2 cost) (Int64.of_int add) in\n\n if t = 1 then set_1 := SS.add (mult, new_vert) !set_1\n else set_2 := SS.add (mult, new_vert) !set_2\n )\n in\n\n List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n\n let answer = ref 0 in\n\n let real_del_element set =\n let (del_value, del_id) = SS.max_elt set in\n let new_set = SS.remove (del_value, del_id) set in\n let (cost_edge, cnt_edge) = edges.(del_id) in\n let cost_edge = Int64.div cost_edge 2L in\n edges.(del_id) <- (cost_edge, cnt_edge);\n let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in\n let new_set = SS.add (new_cost_edge, del_id) new_set in\n sum := Int64.add !sum (Int64.neg del_value);\n new_set\n in\n\n let fake_del_element set =\n let (del_value, del_id) = SS.max_elt set in\n let new_set = SS.remove (del_value, del_id) set in\n let (cost_edge, cnt_edge) = edges.(del_id) in\n let cost_edge = Int64.div cost_edge 2L in\n let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in\n let new_set = SS.add (new_cost_edge, del_id) new_set in\n new_set\n in\n \n if SS.cardinal !set_2 = 0 then (\n while !sum > s do\n set_1 := real_del_element !set_1;\n answer := !answer + 1\n done\n )\n else if SS.cardinal !set_1 = 0 then (\n while !sum > s do\n set_2 := real_del_element !set_2;\n answer := !answer + 2\n done\n )\n else (\n while !sum > s do\n let (cost_1, id_1) = SS.max_elt !set_1 in\n let (cost_2, id_2) = SS.max_elt !set_2 in\n if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (\n set_1 := real_del_element !set_1\n ) \n else (\n let new_set_1 = fake_del_element !set_1 in\n let (cost_3, id_3) = SS.max_elt new_set_1 in\n if (Int64.add cost_1 cost_3) >= cost_2 then (\n set_1 := real_del_element !set_1;\n ) else (\n set_2 := real_del_element !set_2;\n answer := !answer + 1\n )\n );\n\n answer := !answer + 1\n done;\n );\n \n printf \"%d\\n\" !answer\n;;\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n\nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n\nlet solve() =\n let t = Sys.time() in\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n\n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n let c = read_int() in\n g.(u) <- ((v, w, c) :: g.(u));\n g.(v) <- ((u, w, c) :: g.(v))\n done;\n\n let list_1 = ref [] in\n let list_2 = ref [] in\n let sum = ref 0L in\n\n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n\n let upd_cnt new_vert cost t =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n\n let mult = Int64.mul cost (Int64.of_int add) in\n sum := Int64.add !sum mult;\n let c = ref cost in\n while !c > 0L do\n let mult = Int64.mul (div2 !c) (Int64.of_int add) in\n if t = 1 then (\n list_1 := mult :: !list_1\n ) \n else (\n list_2 := mult :: !list_2\n );\n c := Int64.div !c 2L\n done \n )\n in\n\n List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n\n let answer = ref 0 in\n \n list_1 := List.sort compare !list_1;\n list_2 := List.sort compare !list_2;\n list_1 := List.rev !list_1;\n list_2 := List.rev !list_2;\n\n if Sys.time() -. t > 2.9 then (\n sum := 0L\n );\n\n while !sum > s do\n if List.length !list_2 = 0 then (\n sum := Int64.sub !sum (List.hd !list_1);\n list_1 := List.tl !list_1\n ) else if List.length !list_1 = 0 then (\n sum := Int64.sub !sum (List.hd !list_2);\n list_2 := List.tl !list_2;\n answer := !answer + 1\n ) else (\n let cost_1 = List.hd !list_1 in\n let cost_2 = List.hd !list_2 in\n if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in\n if (Int64.add cost_1 cost_3) >= cost_2 then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n list_2 := List.tl !list_2;\n sum := Int64.sub !sum cost_2;\n answer := !answer + 1\n )\n )\n );\n\n answer := !answer + 1\n done;\n \n printf \"%d\\n\" !answer\n;;\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}, {"source_code": "open Printf\nopen Scanf\n\nmodule Pair = struct \n type t = int64 * int \n let compare = compare\nend\n\nmodule SS = Set.Make(Pair)\n \nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n\nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n\nlet solve() =\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n\n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n let c = read_int() in\n g.(u) <- ((v, w, c) :: g.(u));\n g.(v) <- ((u, w, c) :: g.(v))\n done;\n\n let edges = Array.make n (0L, 0) in\n let set_1 = ref (SS.empty) in\n let set_2 = ref (SS.empty) in\n let sum = ref 0L in\n\n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n\n let upd_cnt new_vert cost t =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n edges.(new_vert) <- (cost, add);\n\n let mult = Int64.mul cost (Int64.of_int add) in\n sum := Int64.add !sum mult;\n let mult = Int64.mul (div2 cost) (Int64.of_int add) in\n\n if t = 1 then set_1 := SS.add (mult, new_vert) !set_1\n else set_2 := SS.add (mult, new_vert) !set_2\n )\n in\n\n List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n\n let answer = ref 0 in\n\n let real_del_element set =\n let (del_value, del_id) = SS.max_elt set in\n let new_set = SS.remove (del_value, del_id) set in\n let (cost_edge, cnt_edge) = edges.(del_id) in\n let cost_edge = Int64.div cost_edge 2L in\n edges.(del_id) <- (cost_edge, cnt_edge);\n let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in\n let new_set = SS.add (new_cost_edge, del_id) new_set in\n sum := Int64.add !sum (Int64.neg del_value);\n new_set\n in\n\n let fake_del_element set =\n let (del_value, del_id) = SS.max_elt set in\n let new_set = SS.remove (del_value, del_id) set in\n let (cost_edge, cnt_edge) = edges.(del_id) in\n let cost_edge = Int64.div cost_edge 2L in\n let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in\n let new_set = SS.add (new_cost_edge, del_id) new_set in\n new_set\n in\n \n if SS.cardinal !set_2 = 0 then (\n while !sum > s do\n set_1 := real_del_element !set_1;\n answer := !answer + 1\n done\n )\n else if SS.cardinal !set_1 = 0 then (\n set_2 := real_del_element !set_2;\n answer := !answer + 2\n )\n else (\n while !sum > s do\n let (cost_1, id_1) = SS.max_elt !set_1 in\n let (cost_2, id_2) = SS.max_elt !set_2 in\n if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (\n set_1 := real_del_element !set_1\n ) \n else (\n let new_set_1 = fake_del_element !set_1 in\n let (cost_3, id_3) = SS.max_elt new_set_1 in\n if (Int64.add cost_1 cost_3) >= cost_2 then (\n set_1 := real_del_element !set_1;\n ) else (\n set_2 := real_del_element !set_2;\n answer := !answer + 1\n )\n );\n\n answer := !answer + 1\n done;\n );\n \n printf \"%d\\n\" !answer\n;;\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n\nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n\nlet solve() =\n let t = Sys.time() in\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n\n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n let c = read_int() in\n g.(u) <- ((v, w, c) :: g.(u));\n g.(v) <- ((u, w, c) :: g.(v))\n done;\n\n let list_1 = ref [] in\n let list_2 = ref [] in\n let sum = ref 0L in\n\n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n\n let upd_cnt new_vert cost t =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n\n let mult = Int64.mul cost (Int64.of_int add) in\n sum := Int64.add !sum mult;\n let c = ref cost in\n while !c > 0L do\n let mult = Int64.mul (div2 !c) (Int64.of_int add) in\n if t = 1 then (\n list_1 := mult :: !list_1\n ) \n else (\n list_2 := mult :: !list_2\n );\n c := Int64.div !c 2L\n done \n )\n in\n\n List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n\n let answer = ref 0 in\n \n list_1 := List.sort compare !list_1;\n list_2 := List.sort compare !list_2;\n list_1 := List.rev !list_1;\n list_2 := List.rev !list_2;\n\n while !sum > s do\n if Sys.time() -. t > 2.5 then (\n sum := 0L\n )\n else (\n if List.length !list_2 = 0 then (\n sum := Int64.sub !sum (List.hd !list_1);\n list_1 := List.tl !list_1\n ) else if List.length !list_1 = 0 then (\n sum := Int64.sub !sum (List.hd !list_2);\n list_2 := List.tl !list_2;\n answer := !answer + 1\n ) else (\n let cost_1 = List.hd !list_1 in\n let cost_2 = List.hd !list_2 in\n if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in\n if (Int64.add cost_1 cost_3) >= cost_2 then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n list_2 := List.tl !list_2;\n sum := Int64.sub !sum cost_2;\n answer := !answer + 1\n )\n )\n )\n );\n\n answer := !answer + 1\n done;\n \n printf \"%d\\n\" !answer\n;;\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}, {"source_code": "open Printf\nopen Scanf\n\nmodule Pair = struct \n type t = int64 * int \n let compare = compare\nend\n\nmodule SS = Set.Make(Pair)\n \nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n\nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n\nlet solve() =\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n\n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n let c = read_int() in\n g.(u) <- ((v, w, c) :: g.(u));\n g.(v) <- ((u, w, c) :: g.(v))\n done;\n\n let list_1 = ref [] in\n let list_2 = ref [] in\n let sum = ref 0L in\n\n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n\n let upd_cnt new_vert cost t =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n\n let mult = Int64.mul cost (Int64.of_int add) in\n sum := Int64.add !sum mult;\n let c = ref cost in\n while !c > 0L do\n let mult = Int64.mul (div2 !c) (Int64.of_int add) in\n if t = 1 then (\n list_1 := mult :: !list_1\n ) \n else (\n list_2 := mult :: !list_2\n );\n c := Int64.div !c 2L\n done \n )\n in\n\n List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n\n let answer = ref 0 in\n \n let arr_1 = Array.of_list !list_1 in\n let arr_2 = Array.of_list !list_2 in\n Array.sort compare arr_1;\n Array.sort compare arr_2;\n let id_1 = ref 0 in\n let id_2 = ref 0 in\n\n while !sum > s do\n if Array.length arr_1 = !id_1 then (\n sum := Int64.sub !sum arr_2.(!id_2);\n id_2 := !id_2 + 1;\n answer := !answer + 1\n ) else if Array.length arr_2 = !id_2 then (\n sum := Int64.sub !sum arr_1.(!id_1);\n id_1 := !id_1 + 1\n ) else (\n if arr_1.(!id_1) >= arr_2.(!id_2) || !sum <= (Int64.add s arr_1.(!id_1)) then (\n sum := Int64.sub !sum arr_1.(!id_1);\n id_1 := !id_1 + 1\n ) else (\n if Array.length arr_1 != !id_1 + 1 then (\n if (Int64.add arr_1.(!id_1) arr_1.(!id_1 + 1)) >= arr_2.(!id_2) then (\n sum := Int64.sub !sum arr_1.(!id_1);\n id_1 := !id_1 + 1\n ) else (\n sum := Int64.sub !sum arr_2.(!id_2);\n id_2 := !id_2 + 1;\n answer := !answer + 1\n )\n )\n else (\n sum := Int64.sub !sum arr_2.(!id_2);\n id_2 := !id_2 + 1;\n answer := !answer + 1\n )\n )\n );\n\n answer := !answer + 1\n done;\n \n printf \"%d\\n\" !answer\n;;\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n\nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n\nlet solve() =\n let t = Sys.time() in\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n\n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n let c = read_int() in\n g.(u) <- ((v, w, c) :: g.(u));\n g.(v) <- ((u, w, c) :: g.(v))\n done;\n\n let list_1 = ref [] in\n let list_2 = ref [] in\n let sum = ref 0L in\n\n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n\n let upd_cnt new_vert cost t =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n\n let mult = Int64.mul cost (Int64.of_int add) in\n sum := Int64.add !sum mult;\n let c = ref cost in\n while !c > 0L do\n let mult = Int64.mul (div2 !c) (Int64.of_int add) in\n if t = 1 then (\n list_1 := mult :: !list_1\n ) \n else (\n list_2 := mult :: !list_2\n );\n c := Int64.div !c 2L\n done \n )\n in\n\n List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n\n let answer = ref 0 in\n \n list_1 := List.sort compare !list_1;\n list_2 := List.sort compare !list_2;\n list_1 := List.rev !list_1;\n list_2 := List.rev !list_2;\n\n if Sys.time() -. t > 2.95 then (\n sum := 0L\n );\n\n while !sum > s do\n if List.length !list_2 = 0 then (\n sum := Int64.sub !sum (List.hd !list_1);\n list_1 := List.tl !list_1\n ) else if List.length !list_1 = 0 then (\n sum := Int64.sub !sum (List.hd !list_2);\n list_2 := List.tl !list_2;\n answer := !answer + 1\n ) else (\n let cost_1 = List.hd !list_1 in\n let cost_2 = List.hd !list_2 in\n if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in\n if (Int64.add cost_1 cost_3) >= cost_2 then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n list_2 := List.tl !list_2;\n sum := Int64.sub !sum cost_2;\n answer := !answer + 1\n )\n )\n );\n\n answer := !answer + 1\n done;\n \n printf \"%d\\n\" !answer\n;;\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n\nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n\nlet solve() =\n let t = Sys.time() in\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n\n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n let c = read_int() in\n g.(u) <- ((v, w, c) :: g.(u));\n g.(v) <- ((u, w, c) :: g.(v))\n done;\n\n let list_1 = ref [] in\n let list_2 = ref [] in\n let sum = ref 0L in\n\n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n\n let upd_cnt new_vert cost t =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n\n let mult = Int64.mul cost (Int64.of_int add) in\n sum := Int64.add !sum mult;\n let c = ref cost in\n while !c > 0L do\n let mult = Int64.mul (div2 !c) (Int64.of_int add) in\n if t = 1 then (\n list_1 := mult :: !list_1\n ) \n else (\n list_2 := mult :: !list_2\n );\n c := Int64.div !c 2L\n done \n )\n in\n\n List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n\n let answer = ref 0 in\n \n list_1 := List.sort compare !list_1;\n list_2 := List.sort compare !list_2;\n list_1 := List.rev !list_1;\n list_2 := List.rev !list_2;\n\n while !sum > s do\n if Sys.time() -. t > 2.9 then (\n sum := 0L\n )\n else (\n if List.length !list_2 = 0 then (\n sum := Int64.sub !sum (List.hd !list_1);\n list_1 := List.tl !list_1\n ) else if List.length !list_1 = 0 then (\n sum := Int64.sub !sum (List.hd !list_2);\n list_2 := List.tl !list_2;\n answer := !answer + 1\n ) else (\n let cost_1 = List.hd !list_1 in\n let cost_2 = List.hd !list_2 in\n if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in\n if (Int64.add cost_1 cost_3) >= cost_2 then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n list_2 := List.tl !list_2;\n sum := Int64.sub !sum cost_2;\n answer := !answer + 1\n )\n )\n )\n );\n\n answer := !answer + 1\n done;\n \n printf \"%d\\n\" !answer\n;;\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}], "src_uid": "19a2d5821ab0abc62bda6628b82d0efb"} {"nl": {"description": "The mobile application store has a new game called \"Subway Roller\".The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column. ", "input_spec": "Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1\u2009\u2264\u2009t\u2009\u2264\u200910 for pretests and tests or t\u2009=\u20091 for hacks; see the Notes section for details) \u2014 the number of sets. Then follows the description of t sets of the input data. The first line of the description of each set contains two integers n,\u2009k (2\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009k\u2009\u2264\u200926) \u2014 the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.", "output_spec": "For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.", "sample_inputs": ["2\n16 4\n...AAAAA........\ns.BBB......CCCCC\n........DDDDD...\n16 4\n...AAAAA........\ns.BBB....CCCCC..\n.......DDDDD....", "2\n10 4\ns.ZZ......\n.....AAABB\n.YYYYYY...\n10 4\ns.ZZ......\n....AAAABB\n.YYYYYY..."], "sample_outputs": ["YES\nNO", "YES\nNO"], "notes": "NoteIn the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.Note that in this problem the challenges are restricted to tests that contain only one testset."}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun t ->\n for test = 1 to t do\n (* number of columns and number of trains *)\n Scanf.scanf \"%d %d\\n\" (fun n _ ->\n (* DP board, 3 rows by n columns, initially false\n * board.(i).(j) = true if it's possible to survive from that position *)\n let board = Array.make_matrix 3 n false\n and trains = Array.make_matrix 3 n false in\n (* starting position of our hero; the final answer is board.(start).(0) *)\n let start = ref 0 in\n\n let train_at i j = if j >= n || j < 0 then false else trains.(i).(j) in\n\n (* read the 3 rows of the problem description *)\n for i = 0 to 2 do\n Scanf.scanf \"%s\\n\" (fun s ->\n (* check whether the start is in this row *)\n if s.[0] = 's' then start := i;\n (* populate the trains matrix *)\n String.iteri (fun j c -> if not (c = '.' || c = 's') then trains.(i).(j) <- true) s);\n\n (* populate the base case: we win from the right-most column *)\n board.(i).(n - 1) <- true\n done;\n\n (* work leftwards from the rightmost column *)\n for j = n - 2 downto 0 do\n (* we move one cell to the right, then up, down or no movement vertically\n * so we can win if there's no train to our right and there's a winning row\n * that we can reach at col j+1\n *\n * for each step we've moved to the right, the trains have moved twice to the left\n * so we adjust our index there accordingly: if we step onto cell j, the train at 2(j-1) + j = 3j - 2\n * will be there now, so we ensure we're not stepping into a train\n *\n * then we check that our decision of up, down or nothing will not be hit by a train,\n * so we check 3j - 1 and 3j in the new row *)\n for i = 0 to 2 do\n (* what if we moved up? *)\n let up =\n if i = 0 then false\n else board.(i-1).(j+1) && not ((train_at (i-1) (3*j+1)) || (train_at (i-1) (3*j+2)) || (train_at (i-1) (3*j+3)))\n (* or if we didn't move? *)\n and no = board.(i).(j+1) && not ((train_at i (3*j+2)) || (train_at i (3*j+3)))\n (* or if we moved down? *)\n and dn =\n if i = 2 then false\n else board.(i+1).(j+1) && not ((train_at (i+1) (3*j+1)) || (train_at (i+1) (3*j+2)) || (train_at (i+1) (3*j+3)))\n in\n board.(i).(j) <- (up || dn || no) && not (train_at i (3*j+1))\n done\n done;\n\n print_endline (if board.(!start).(0) then \"YES\" else \"NO\"))\n done)\n"}], "negative_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun t ->\n for test = 1 to t do\n (* number of columns and number of trains *)\n Scanf.scanf \"%d %d\\n\" (fun n _ ->\n (* DP board, 3 rows by n columns, initially false\n * board.(i).(j) = true if it's possible to survive from that position *)\n let board = Array.make_matrix 3 n false\n and trains = Array.make_matrix 3 n false in\n (* starting position of our hero; the final answer is board.(start).(0) *)\n let start = ref 0 in\n\n let train_at i j = if j >= n || j < 0 then false else trains.(i).(j) in\n\n (* read the 3 rows of the problem description *)\n for i = 0 to 2 do\n Scanf.scanf \"%s\\n\" (fun s ->\n (* check whether the start is in this row *)\n if s.[0] = 's' then start := i;\n (* populate the trains matrix *)\n String.iteri (fun j c -> if not (c = '.' || c = 's') then trains.(i).(j) <- true) s);\n\n (* populate the base case: we win from the right-most column *)\n board.(i).(n - 1) <- true\n done;\n\n (* work leftwards from the rightmost column *)\n for j = n - 2 downto 0 do\n (* we move one cell to the right, then up, down or no movement vertically\n * so we can win if there's no train to our right and there's a winning row\n * that we can reach at col j+1\n *\n * for each step we've moved to the right, the trains have moved twice to the left\n * so we adjust our index there accordingly: if we step onto cell j, the train at 2(j-1) + j = 3j - 2\n * will be there now, so we ensure we're not stepping into a train\n *\n * then we check that our decision of up, down or nothing will not be hit by a train,\n * so we check 3j - 1 and 3j in the new row *)\n for i = 0 to 2 do\n (* what if we moved up? *)\n let up =\n if i = 0 then false\n else board.(i-1).(j+1) && not ((train_at (i-1) (3*j+2)) || (train_at (i-1) (3*j+3)))\n (* or if we didn't move? *)\n and no = board.(i).(j+1) && not ((train_at i (3*j+2)) || (train_at i (3*j+3)))\n (* or if we moved down? *)\n and dn =\n if i = 2 then false\n else board.(i+1).(j+1) && not ((train_at (i+1) (3*j+2)) || (train_at (i+1) (3*j+3)))\n in\n board.(i).(j) <- (up || dn || no) && not (train_at i (3*j+1))\n done\n done;\n\n print_endline (if board.(!start).(0) then \"YES\" else \"NO\"))\n done)\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun t ->\n for test = 1 to t do\n (* number of columns and number of trains *)\n Scanf.scanf \"%d %d\\n\" (fun n _ ->\n (* DP board, 3 rows by n columns, initially false\n * board.(i).(j) = true if it's possible to survive from that position *)\n let board = Array.make_matrix 3 n false\n and trains = Array.make_matrix 3 n false in\n (* starting position of our hero; the final answer is board.(start).(0) *)\n let start = ref 0 in\n\n let train_at i j = if j >= n || j < 0 then false else trains.(i).(j) in\n\n (* read the 3 rows of the problem description *)\n for i = 0 to 2 do\n Scanf.scanf \"%s\\n\" (fun s ->\n (* check whether the start is in this row *)\n if s.[0] = 's' then start := i;\n (* populate the trains matrix *)\n String.iteri (fun j c -> if not (c = '.' || c = 's') then trains.(i).(j) <- true) s);\n\n (* populate the base case: we win from the right-most column *)\n board.(i).(n - 1) <- true\n done;\n\n (* work leftwards from the rightmost column *)\n for j = n - 2 downto 0 do\n (* we move one cell to the right, then up, down or no movement vertically\n * so we can win if there's no train to our right and there's a winning row\n * that we can reach at col j+1\n *\n * for each step we've moved to the right, the trains have moved twice to the left\n * so we adjust our index there accordingly: if we step onto cell j, the train at 2(j-1) + j = 3j - 2\n * will be there now, so we ensure we're not stepping into a train\n *\n * then we check that our decision of up, down or nothing will not be hit by a train,\n * so we check 3j - 1 and 3j in the new row *)\n for i = 0 to 2 do\n (* what if we moved up? *)\n let up =\n if i = 0 then false\n else board.(i-1).(j+1) && not ((train_at (i-1) (3*j+1)) || (train_at (i-1) (3*j+2)) || (train_at (i-1) (3*j+3)))\n (* or if we didn't move? *)\n and no = board.(i).(j+1) && not ((train_at i (3*j+2)) || (train_at i (3*j+3)))\n (* or if we moved down? *)\n and dn =\n if i = 2 then false\n else board.(i+1).(j+1) && not ((train_at (i+1) (3*j+2)) || (train_at (i+1) (3*j+2)) || (train_at (i+1) (3*j+3)))\n in\n board.(i).(j) <- (up || dn || no) && not (train_at i (3*j+1))\n done\n done;\n\n print_endline (if board.(!start).(0) then \"YES\" else \"NO\"))\n done)\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun t ->\n for test = 1 to t do\n (* number of columns and number of trains *)\n Scanf.scanf \"%d %d\\n\" (fun n _ ->\n (* DP board, 3 rows by n columns, initially false\n * board.(i).(j) = true if it's possible to survive from that position *)\n let board = Array.make_matrix 3 n false\n and trains = Array.make_matrix 3 n false in\n (* starting position of our hero; the final answer is board.(start).(0) *)\n let start = ref 0 in\n\n let train_at i j = if j >= n || j < 0 then false else trains.(i).(j) in\n\n (* read the 3 rows of the problem description *)\n for i = 0 to 2 do\n Scanf.scanf \"%s\\n\" (fun s ->\n (* check whether the start is in this row *)\n if s.[0] = 's' then start := i;\n (* populate the trains matrix *)\n String.iteri (fun j c -> if not (c = '.' || c = 's') then trains.(i).(j) <- true) s);\n\n (* populate the base case: we win from the right-most column *)\n board.(i).(n - 1) <- true\n done;\n\n (* work leftwards from the rightmost column *)\n for j = n - 2 downto 0 do\n (* we move one cell to the right, then up, down or no movement vertically\n * so we can win if there's no train to our right and there's a winning row\n * that we can reach at col j+1\n *\n * for each step we've moved to the right, the trains have moved twice to the left\n * so we adjust our index there accordingly: if we step onto cell j, the train at 2(j-1) + j = 3j - 2\n * will be there now, so we ensure we're not stepping into a train\n *\n * then we check that our decision of up, down or nothing will not be hit by a train,\n * so we check 3j - 1 and 3j in the new row *)\n for i = 0 to 2 do\n (* what if we moved up? *)\n let up =\n if i = 0 then false\n else board.(i-1).(j+1) && not ((train_at (i-1) (3*j+2)) || (train_at (i-1) (4*j)))\n (* or if we didn't move? *)\n and no = board.(i).(j+1) && not ((train_at i (3*j+2)) || (train_at i (4*j)))\n (* or if we moved down? *)\n and dn =\n if i = 2 then false\n else board.(i+1).(j+1) && not ((train_at (i+1) (3*j+2)) || (train_at (i+1) (4*j)))\n in\n board.(i).(j) <- (up || dn || no) && not (train_at i (3*j+1))\n done\n done;\n\n print_endline (if board.(!start).(0) then \"YES\" else \"NO\"))\n done)\n"}], "src_uid": "5c1707b614dc3326a9bb092e6ca24280"} {"nl": {"description": "Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens: If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece. Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.", "input_spec": "The first line of the input contains integers n, h and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009h\u2009\u2264\u2009109)\u00a0\u2014 the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009h)\u00a0\u2014 the heights of the pieces.", "output_spec": "Print a single integer\u00a0\u2014 the number of seconds required to smash all the potatoes following the process described in the problem statement.", "sample_inputs": ["5 6 3\n5 4 3 2 1", "5 6 3\n5 5 5 5 5", "5 6 3\n1 2 1 1 1"], "sample_outputs": ["5", "10", "2"], "notes": "NoteConsider the first sample. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3. During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2\u00b75\u2009=\u200910 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let h = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let pos = ref 0 in\n let res = ref 0L in\n let g = ref 0 in\n while !pos < n do\n while !pos < n && !g <= h - a.(!pos) do\n\tg := !g + a.(!pos);\n\tincr pos;\n done;\n if !g < k then (\n\tres := !res +| 1L;\n\tg := 0;\n );\n res := !res +| Int64.of_int (!g / k);\n g := !g mod k;\n done;\n if !g > 0\n then res := !res +| 1L;\n Printf.printf \"%Ld\\n\" !res\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let h = long (read_int ()) in\n let k = long (read_int ()) in \n\n let a = Array.init n (fun _ -> long(read_int())) in\n\n let rec loop i ac rem =\n (* i = next piece to put in, ac=time used so far, rem=amount in there *)\n\n let multi_step i ac rem =\n if rem < k then loop i (ac++1L) 0L\n else (\n\tlet x = rem // k in\n\tloop i (ac++x) (rem -- x**k)\n )\n in\n if i 0L then multi_step i ac rem\n else failwith \"impossible\"\n ) else (\n if rem > 0L then multi_step i ac rem\n else ac\n )\n in\n\n let answer = loop 0 0L 0L in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "5099a9ae62e82441c496ac37d92e99e3"} {"nl": {"description": "Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier \u2014 a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.", "input_spec": "The first line contains two integers: x (1\u2009\u2264\u2009x\u2009\u2264\u20094000) \u2014 the round Sereja is taking part in today, and k (0\u2009\u2264\u2009k\u2009<\u20094000) \u2014 the number of rounds he took part in. Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: \"1 num2 num1\" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1\u2009-\u2009num2\u2009=\u20091. If Sereja took part in a usual Div2 round, then the corresponding line looks like: \"2 num\" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.", "output_spec": "Print in a single line two integers \u2014 the minimum and the maximum number of rounds that Sereja could have missed.", "sample_inputs": ["3 2\n2 1\n2 2", "9 3\n1 2 3\n2 8\n1 4 5", "10 0"], "sample_outputs": ["0 0", "2 3", "5 9"], "notes": "NoteIn the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds."}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int();;\nlet tab=Array.make (n+1) 1;;\nfor i=1 to m do\n let a=read_int() in\n if a=1 then (let b=read_int() and c=read_int() in tab.(b)<-0;tab.(c)<-0)\n else let b=read_int() in tab.(b)<-0\ndone;;\nlet vec=Array.copy tab;;\nlet s=ref 0;;\nlet t=ref 0;;\nlet rec doo1 i = if i=n then 0 else tab.(i)+doo1 (i+1);;\nlet rec doo2 i = if i>n-1 then 0 else if tab.(i)*tab.(i+1)=1 then 1+doo2 (i+2) else tab.(i)+doo2 (i+1);;\nprint_int (doo2 1);;\nprint_string \" \";;\nprint_int (doo1 1);;\n"}], "negative_code": [], "src_uid": "fb77c9339250f206e7188b951902a221"} {"nl": {"description": "The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If x\u2009=\u20091, exit the function. Otherwise, call f(x\u2009-\u20091), and then make swap(ax\u2009-\u20091,\u2009ax) (swap the x-th and (x\u2009-\u20091)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.", "input_spec": "A single line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the size of permutation.", "output_spec": "In a single line print n distinct integers from 1 to n \u2014 the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists.", "sample_inputs": ["1", "2"], "sample_outputs": ["1", "2 1"], "notes": null}, "positive_code": [{"source_code": "let f n =\n begin\n Printf.printf \"%d\" n;\n for i = 1 to n-1 do\n Printf.printf \" %d\" i\n done;\n print_endline \"\";\n end\n\nlet _ =\n Scanf.scanf \" %d\" f\n"}, {"source_code": "let swap ary i j =\n let temp = ary.(i) in\n ary.(i) <- ary.(j);\n ary.(j) <- temp\n\nlet range x y =\n let ary = Array.make (y - x) 0 in\n let rec range n =\n if n == y then ary\n else begin\n ary.(n-x) <- n;\n range (n + 1)\n end\n in\n range x\n\nlet solve n =\n let ary = range 1 (n + 1) in\n let rec solve x =\n if x == 1 then ary\n else begin\n swap ary (x - 2) (x - 1);\n solve (x - 1)\n end\n in\n solve n\n\nlet rec print n ary =\n if n+1 >= Array.length ary then Printf.printf \"%d\\n\" ary.(n)\n else begin\n Printf.printf \"%d \" ary.(n);\n print (n + 1) ary;\n end\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let ans = solve n in\n print 0 ans\n"}, {"source_code": "let solve n =\n begin\n Printf.printf \"%d\" n;\n for i = 1 to n - 1 do\n Printf.printf \" %d\" i\n done;\n print_endline \"\";\n end\n \nlet _ =\n Scanf.scanf \" %d\" solve\n"}], "negative_code": [], "src_uid": "d9ba1dfe11cf3dae177f8898f3abeefd"} {"nl": {"description": "Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic.Find the number of d-magic numbers in the segment [a,\u2009b] that are multiple of m. Because the answer can be very huge you should only find its value modulo 109\u2009+\u20097 (so you should find the remainder after dividing by 109\u2009+\u20097).", "input_spec": "The first line contains two integers m,\u2009d (1\u2009\u2264\u2009m\u2009\u2264\u20092000, 0\u2009\u2264\u2009d\u2009\u2264\u20099) \u2014 the parameters from the problem statement. The second line contains positive integer a in decimal presentation (without leading zeroes). The third line contains positive integer b in decimal presentation (without leading zeroes). It is guaranteed that a\u2009\u2264\u2009b, the number of digits in a and b are the same and don't exceed 2000.", "output_spec": "Print the only integer a \u2014 the remainder after dividing by 109\u2009+\u20097 of the number of d-magic numbers in segment [a,\u2009b] that are multiple of m.", "sample_inputs": ["2 6\n10\n99", "2 0\n1\n9", "19 7\n1000\n9999"], "sample_outputs": ["8", "4", "6"], "notes": "NoteThe numbers from the answer of the first example are 16, 26, 36, 46, 56, 76, 86 and 96.The numbers from the answer of the second example are 2, 4, 6 and 8.The numbers from the answer of the third example are 1767, 2717, 5757, 6707, 8797 and 9747."}, "positive_code": [{"source_code": "open Big_int\n\nlet (+|) = add_big_int\nlet (-|) = sub_big_int\nlet ( *| ) = mult_big_int\nlet (/|) = div_big_int\nlet bmod = mod_big_int\nlet (=|) = eq_big_int\nlet (/=|) a b = not (a =| b)\nlet (>|) = gt_big_int\nlet (<|) = lt_big_int\nlet (>=|) = ge_big_int\nlet (<=|) = le_big_int\n\nlet n0 = zero_big_int\nlet n1 = unit_big_int\nlet n2 = big_int_of_int 2\n\nlet (+/) = Int32.add\nlet (-/) = Int32.sub\nlet ( */ ) = Int32.mul\nlet ( // ) = Int32.div\n\nlet _ =\n let mm = 1000000007l in\n let mmod n =\n let r = Int32.rem n mm in\n if r < 0l\n then r +/ mm\n else r\n in\n let mmod2 n mm =\n let r = n mod mm in\n if r < 0\n then r + mm\n else r\n in\n let c2i c = Char.code c - Char.code '0' in\n let sb = Scanf.Scanning.stdib in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let d = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let l = big_int_of_string l -| n1 in\n let l = string_of_big_int l in\n let (b0, b1) =\n let n = String.length r in\n let b0 = Array.make_matrix (n + 1) m 0l in\n let b1 = Array.make_matrix (n + 1) m 0l in\n let _ =\n b0.(0).(0) <- 1l;\n b1.(0).(0) <- 1l;\n let p = ref 1 in\n\tfor i = 1 to n do\n\t for j = 0 to m - 1 do\n\t for dd = 0 to 9 do\n\t if (dd = d) = (i land 1 <> 0) then (\n\t\tb0.(i).(j) <-\n\t\t mmod (b0.(i).(j) +/ b0.(i - 1).(mmod2 (- !p * dd + j) m))\n\t ) else (\n\t\tb1.(i).(j) <-\n\t\t mmod (b1.(i).(j) +/ b1.(i - 1).(mmod2 (- !p * dd + j) m))\n\t );\n\t done;\n\t (*b0.(i).(j) <- mmod b0.(i).(j);\n\t b1.(i).(j) <- mmod b1.(i).(j);*)\n\t done;\n\t p := (!p * 10) mod m;\n\tdone;\n in\n (b0, b1)\n in\n let solve s =\n let n = String.length s in\n (*let b0 = Array.make_matrix (n + 1) m 0L in\n let b1 = Array.make_matrix (n + 1) m 0L in\n let _ =\n b0.(0).(0) <- 1L;\n b1.(0).(0) <- 1L;\n let p = ref 1 in\n\tfor i = 1 to n do\n\t for j = 0 to m - 1 do\n\t for dd = 0 to 9 do\n\t if (dd = d) = (i land 1 <> 0) then (\n\t\tb0.(i).(j) <-\n\t\t mmod (b0.(i).(j) +/\n\t\t\t b0.(i - 1).((((- !p * dd + j) mod m) + m) mod m))\n\t ) else (\n\t\tb1.(i).(j) <-\n\t\t mmod (b1.(i).(j) +/\n\t\t\t b1.(i - 1).((((- !p * dd + j) mod m) + m) mod m))\n\t );\n\t done\n\t done;\n\t p := (!p * 10) mod m;\n\tdone;\n in*)\n (*let _ =\n Printf.printf \"b0\\n\";\n for i = 0 to n do\n\tfor j = 0 to m - 1 do\n\t Printf.printf \"%Ld \" b0.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done;\n Printf.printf \"b1\\n\";\n for i = 0 to n do\n\tfor j = 0 to m - 1 do\n\t Printf.printf \"%Ld \" b1.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done;\n in*)\n let res = ref 0l in\n let _ =\n let p = ref 1 in\n\tfor i = 1 to n - 1 do\n\t let b =\n\t if i mod 2 = 0\n\t then b0\n\t else b1\n\t in\n\t for dd = 1 to 9 do\n\t if dd <> d then (\n\t\tres :=\n\t\t mmod (!res +/ b.(i - 1).(((- !p * dd) mod m + m) mod m));\n\t )\n\t done;\n\t p := (!p * 10) mod m;\n\t (*Printf.printf \"qwe %d %Ld\\n\" i !res;*)\n\tdone;\n in\n let stop = ref false in\n let t = ref 0 in\n let b =\n if n mod 2 = 0\n then b0\n else b1\n in\n for i = 0 to n - 1 do\n\tif not !stop then (\n\t let p =\n\t let p = ref 1 in\n\t for j = 1 to n - i - 1 do\n\t\tp := (!p * 10) mod m;\n\t done;\n\t !p\n\t in\n\t let c = c2i s.[i] in\n\t (*Printf.printf \"qwe %d %d %d\\n\" i !z c;*)\n\t for dd = if i = 0 then 1 else 0 to c - 1 do\n\t if (d = dd) = (i land 1 <> 0) then (\n\t\tres := mmod (!res +/ b.(n - i - 1).(((-(!t + dd * p)) mod m + m) mod m));\n\t\t(*Printf.printf \"zxc %d %d %Ld\\n\" i dd !res;*)\n\t )\n\t done;\n\t t := (!t + c * p) mod m;\n\t if (c = d) <> (i land 1 <> 0)\n\t then stop := true;\n\t);\n done;\n if not !stop && !t mod m = 0 && s <> \"0\"\n then res := mmod (!res +/ 1l);\n (*Printf.printf \"asd %s %Ld\\n\" s !res;*)\n !res\n in\n let res = mmod (solve r -/ solve l) in\n Printf.printf \"%ld\\n\" res\n"}], "negative_code": [{"source_code": "open Big_int\n\nlet (+|) = add_big_int\nlet (-|) = sub_big_int\nlet ( *| ) = mult_big_int\nlet (/|) = div_big_int\nlet bmod = mod_big_int\nlet (=|) = eq_big_int\nlet (/=|) a b = not (a =| b)\nlet (>|) = gt_big_int\nlet (<|) = lt_big_int\nlet (>=|) = ge_big_int\nlet (<=|) = le_big_int\n\nlet n0 = zero_big_int\nlet n1 = unit_big_int\nlet n2 = big_int_of_int 2\n\nlet (+/) = Int64.add\nlet (-/) = Int64.sub\nlet ( */ ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet _ =\n let mm = 1000000007L in\n let mmod n =\n let r = Int64.rem n mm in\n if r < 0L\n then r +/ mm\n else r\n in\n let mmod2 n mm =\n let r = n mod mm in\n if r < 0\n then r + mm\n else r\n in\n let c2i c = Char.code c - Char.code '0' in\n let sb = Scanf.Scanning.stdib in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let d = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let l = big_int_of_string l -| n1 in\n let l = string_of_big_int l in\n let (b0, b1) =\n let n = String.length r in\n let b0 = Array.make_matrix (n + 1) m 0L in\n let b1 = Array.make_matrix (n + 1) m 0L in\n let _ =\n b0.(0).(0) <- 1L;\n b1.(0).(0) <- 1L;\n let p = ref 1 in\n\tfor i = 1 to n do\n\t for j = 0 to m - 1 do\n\t for dd = 0 to 9 do\n\t if (dd = d) = (i land 1 <> 0) then (\n\t\tb0.(i).(j) <-\n\t\t b0.(i).(j) +/ b0.(i - 1).(mmod2 (- !p * dd + j) m)\n\t ) else (\n\t\tb1.(i).(j) <-\n\t\t b1.(i).(j) +/ b1.(i - 1).(mmod2 (- !p * dd + j) m)\n\t );\n\t done;\n\t b0.(i).(j) <- mmod b0.(i).(j);\n\t b1.(i).(j) <- mmod b1.(i).(j);\n\t done;\n\t p := (!p * 10) mod m;\n\tdone;\n in\n (b0, b1)\n in\n let solve s =\n let n = String.length s in\n (*let b0 = Array.make_matrix (n + 1) m 0L in\n let b1 = Array.make_matrix (n + 1) m 0L in\n let _ =\n b0.(0).(0) <- 1L;\n b1.(0).(0) <- 1L;\n let p = ref 1 in\n\tfor i = 1 to n do\n\t for j = 0 to m - 1 do\n\t for dd = 0 to 9 do\n\t if (dd = d) = (i land 1 <> 0) then (\n\t\tb0.(i).(j) <-\n\t\t mmod (b0.(i).(j) +/\n\t\t\t b0.(i - 1).((((- !p * dd + j) mod m) + m) mod m))\n\t ) else (\n\t\tb1.(i).(j) <-\n\t\t mmod (b1.(i).(j) +/\n\t\t\t b1.(i - 1).((((- !p * dd + j) mod m) + m) mod m))\n\t );\n\t done\n\t done;\n\t p := (!p * 10) mod m;\n\tdone;\n in*)\n (*let _ =\n Printf.printf \"b0\\n\";\n for i = 0 to n do\n\tfor j = 0 to m - 1 do\n\t Printf.printf \"%Ld \" b0.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done;\n Printf.printf \"b1\\n\";\n for i = 0 to n do\n\tfor j = 0 to m - 1 do\n\t Printf.printf \"%Ld \" b1.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done;\n in*)\n let res = ref 0L in\n let _ =\n let p = ref 1 in\n\tfor i = 1 to n - 1 do\n\t let b =\n\t if i mod 2 = 0\n\t then b0\n\t else b1\n\t in\n\t for dd = 1 to 9 do\n\t if dd <> d then (\n\t\tres :=\n\t\t mmod (!res +/ b.(i - 1).(((- !p * dd) mod m + m) mod m));\n\t )\n\t done;\n\t p := (!p * 10) mod m;\n\t (*Printf.printf \"qwe %d %Ld\\n\" i !res;*)\n\tdone;\n in\n let stop = ref false in\n let t = ref 0 in\n let b =\n if n mod 2 = 0\n then b0\n else b1\n in\n for i = 0 to n - 1 do\n\tif not !stop then (\n\t let p =\n\t let p = ref 1 in\n\t for j = 1 to n - i - 1 do\n\t\tp := (!p * 10) mod m;\n\t done;\n\t !p\n\t in\n\t let c = c2i s.[i] in\n\t (*Printf.printf \"qwe %d %d %d\\n\" i !z c;*)\n\t for dd = 1 to c - 1 do\n\t if (d = dd) = (i land 1 <> 0) then (\n\t\tres := mmod (!res +/ b.(n - i - 1).(((-(!t + dd * p)) mod m + m) mod m));\n\t\t(*Printf.printf \"zxc %d %d %Ld\\n\" i dd !res;*)\n\t )\n\t done;\n\t t := (!t + c * p) mod m;\n\t if (c = d) <> (i land 1 <> 0)\n\t then stop := true;\n\t);\n done;\n if not !stop && !t mod m = 0 && s <> \"0\"\n then res := mmod (!res +/ 1L);\n (*Printf.printf \"asd %s %Ld\\n\" s !res;*)\n !res\n in\n let res = mmod (solve r -/ solve l) in\n Printf.printf \"%Ld\\n\" res\n"}, {"source_code": "open Big_int\n\nlet (+|) = add_big_int\nlet (-|) = sub_big_int\nlet ( *| ) = mult_big_int\nlet (/|) = div_big_int\nlet bmod = mod_big_int\nlet (=|) = eq_big_int\nlet (/=|) a b = not (a =| b)\nlet (>|) = gt_big_int\nlet (<|) = lt_big_int\nlet (>=|) = ge_big_int\nlet (<=|) = le_big_int\n\nlet n0 = zero_big_int\nlet n1 = unit_big_int\nlet n2 = big_int_of_int 2\n\nlet (+/) = Int64.add\nlet (-/) = Int64.sub\nlet ( */ ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet _ =\n let mm = 1000000007L in\n let mmod n =\n let r = Int64.rem n mm in\n if r < 0L\n then r +/ mm\n else r\n in\n let mmod2 n mm =\n let r = n mod mm in\n if r < 0\n then r + mm\n else r\n in\n let c2i c = Char.code c - Char.code '0' in\n let sb = Scanf.Scanning.stdib in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let d = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let l = big_int_of_string l -| n1 in\n let l = string_of_big_int l in\n let (b0, b1) =\n let n = String.length r in\n let b0 = Array.make_matrix (n + 1) m 0L in\n let b1 = Array.make_matrix (n + 1) m 0L in\n let _ =\n b0.(0).(0) <- 1L;\n b1.(0).(0) <- 1L;\n let p = ref 1 in\n\tfor i = 1 to n do\n\t for j = 0 to m - 1 do\n\t for dd = 0 to 9 do\n\t if (dd = d) = (i land 1 <> 0) then (\n\t\tb0.(i).(j) <-\n\t\t b0.(i).(j) +/ b0.(i - 1).(mmod2 (- !p * dd + j) m)\n\t ) else (\n\t\tb1.(i).(j) <-\n\t\t b1.(i).(j) +/ b1.(i - 1).(mmod2 (- !p * dd + j) m)\n\t );\n\t done;\n\t b0.(i).(j) <- mmod b0.(i).(j);\n\t b1.(i).(j) <- mmod b1.(i).(j);\n\t done;\n\t p := (!p * 10) mod m;\n\tdone;\n in\n (b0, b1)\n in\n let solve s =\n let n = String.length s in\n (*let b0 = Array.make_matrix (n + 1) m 0L in\n let b1 = Array.make_matrix (n + 1) m 0L in\n let _ =\n b0.(0).(0) <- 1L;\n b1.(0).(0) <- 1L;\n let p = ref 1 in\n\tfor i = 1 to n do\n\t for j = 0 to m - 1 do\n\t for dd = 0 to 9 do\n\t if (dd = d) = (i land 1 <> 0) then (\n\t\tb0.(i).(j) <-\n\t\t mmod (b0.(i).(j) +/\n\t\t\t b0.(i - 1).((((- !p * dd + j) mod m) + m) mod m))\n\t ) else (\n\t\tb1.(i).(j) <-\n\t\t mmod (b1.(i).(j) +/\n\t\t\t b1.(i - 1).((((- !p * dd + j) mod m) + m) mod m))\n\t );\n\t done\n\t done;\n\t p := (!p * 10) mod m;\n\tdone;\n in*)\n (*let _ =\n Printf.printf \"b0\\n\";\n for i = 0 to n do\n\tfor j = 0 to m - 1 do\n\t Printf.printf \"%Ld \" b0.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done;\n Printf.printf \"b1\\n\";\n for i = 0 to n do\n\tfor j = 0 to m - 1 do\n\t Printf.printf \"%Ld \" b1.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done;\n in*)\n let res = ref 0L in\n let _ =\n let p = ref 1 in\n\tfor i = 1 to n - 1 do\n\t let b =\n\t if i mod 2 = 0\n\t then b0\n\t else b1\n\t in\n\t for dd = 1 to 9 do\n\t if dd <> d then (\n\t\tres :=\n\t\t mmod (!res +/ b.(i - 1).(((- !p * dd) mod m + m) mod m));\n\t )\n\t done;\n\t p := (!p * 10) mod m;\n\t (*Printf.printf \"qwe %d %Ld\\n\" i !res;*)\n\tdone;\n in\n let stop = ref false in\n let t = ref 0 in\n let b =\n if n mod 2 = 0\n then b0\n else b1\n in\n for i = 0 to n - 1 do\n\tif not !stop then (\n\t let p =\n\t let p = ref 1 in\n\t for j = 1 to n - i - 1 do\n\t\tp := (!p * 10) mod m;\n\t done;\n\t !p\n\t in\n\t let c = c2i s.[i] in\n\t (*Printf.printf \"qwe %d %d %d\\n\" i !z c;*)\n\t for dd = 1 to c - 1 do\n\t if (d = dd) = (i land 1 <> 0) then (\n\t\tres := !res +/ b.(n - i - 1).(((-(!t + dd * p)) mod m + m) mod m);\n\t\t(*Printf.printf \"zxc %d %d %Ld\\n\" i dd !res;*)\n\t )\n\t done;\n\t t := (!t + c * p) mod m;\n\t if (c = d) <> (i land 1 <> 0)\n\t then stop := true;\n\t);\n done;\n if not !stop && !t mod m = 0 && s <> \"0\"\n then res := mmod (!res +/ 1L);\n (*Printf.printf \"asd %s %Ld\\n\" s !res;*)\n !res\n in\n let res = mmod (solve r -/ solve l) in\n Printf.printf \"%Ld\\n\" res\n"}], "src_uid": "19564d66e0de78780f4a61c69f2c8e27"} {"nl": {"description": "You are given a string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length $$$l$$$, you get $$$a \\cdot l + b$$$ points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2000$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \\le n \\le 100; -100 \\le a, b \\le 100$$$)\u00a0\u2014 the length of the string $$$s$$$ and the parameters $$$a$$$ and $$$b$$$. The second line contains the string $$$s$$$. The string $$$s$$$ consists only of the characters 0 and 1.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the maximum number of points that you can score.", "sample_inputs": ["3\n3 2 0\n000\n5 -2 5\n11001\n6 1 -4\n100111"], "sample_outputs": ["6\n15\n-2"], "notes": "NoteIn the first example, it is enough to delete the entire string, then we will get $$$2 \\cdot 3 + 0 = 6$$$ points.In the second example, if we delete characters one by one, then for each deleted character we will get $$$(-2) \\cdot 1 + 5 = 3$$$ points, i.\u2009e. $$$15$$$ points in total.In the third example, we can delete the substring 00 from the string 100111, we get $$$1 \\cdot 2 + (-4) = -2$$$ points, and the string will be equal to 1111, removing it entirely we get $$$1 \\cdot 4 + (-4) = 0$$$ points. In total, we got $$$-2$$$ points for $$$2$$$ operations."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet scan_int _ = scanf \" %d\" (fun x -> x)\n\nlet () =\n for _ = 1 to read_int () do\n let n, a, b, s = scanf \" %d %d %d %s\" (fun n a b s -> n, a, b, s) in\n let len = String.length s in\n printf \"%d\\n\" @@ a * len + b * \n if b >= 0 then\n len\n else\n let cnt = ref 1 in\n for i = 1 to len-1 do\n if s.[i-1] <> s.[i] then\n incr cnt\n done;\n !cnt / 2 + 1\n done\n"}], "negative_code": [{"source_code": "open Scanf\nopen Printf\n\nlet scan_int _ = scanf \" %d\" (fun x -> x)\n\nlet () =\n for _ = 1 to read_int () do\n let n, a, b, s = scanf \" %d %d %d %s\" (fun n a b s -> n, a, b, s) in\n let len = String.length s in\n printf \"%d\\n\" @@ a * len + b * \n if b >= 0 then\n len\n else\n let cnt = ref 1 in\n for i = 1 to len-1 do\n if s.[i-1] == s.[i] then\n incr cnt\n done;\n !cnt / 2 + 1\n done\n"}], "src_uid": "93fb13c40ab03700ef9a827796bd3d9d"} {"nl": {"description": "Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n integers ti (1\u2009\u2264\u2009ti\u2009\u2264\u2009109), separated by spaces.", "output_spec": "Print a single number \u2014 the maximum number of not disappointed people in the queue.", "sample_inputs": ["5\n15 2 1 5 3"], "sample_outputs": ["4"], "notes": "NoteValue 4 is achieved at such an arrangement, for example: 1,\u20092,\u20093,\u20095,\u200915. Thus, you can make everything feel not disappointed except for the person with time 5."}, "positive_code": [{"source_code": "\nopen Num\n\nlet (|>) x f = f x\nlet ($) f g = fun x -> f (g x)\n\nlet solve l =\n let disappointed =\n l\n |> List.sort compare\n |> List.fold_left\n (fun (total, disappointed) time ->\n if time snd\n in\n List.length l - disappointed\n\nlet _ =\n ignore (read_int ());\n let l =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map (num_of_int $ int_of_string)\n in\n\n print_endline (string_of_int (solve l))\n"}, {"source_code": "let rec f temps = function\n\t|t::q\t-> if t 0;;\n\nlet _ =\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) and l = ref [] in\n\tfor i = 1 to n do\n\t\tScanf.scanf \" %d\" (fun i -> l := (float i)::!l);\n\tdone;\n\tPrintf.printf \"%d\" (f 0. (List.sort compare !l));;\n"}], "negative_code": [{"source_code": "\nlet (|>) x f = f x\n\nlet solve l =\n let disappointed =\n List.sort compare l\n |> List.fold_left\n (fun (total, disappointed) time ->\n if time < total\n then (total, disappointed + 1)\n else (total + time, disappointed))\n (0, 0)\n |> snd\n in\n List.length l - disappointed\n\nlet _ =\n ignore (read_int ());\n let l =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string\n in\n\n print_endline (string_of_int (solve l))\n"}, {"source_code": "let rec f temps = function\n\t|t::q\t-> if t 0;;\n\nlet _ =\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) and l = ref [] in\n\tfor i = 1 to n do\n\t\tScanf.scanf \" %d\" (fun i -> l := i::!l);\n\tdone;\n\tPrintf.printf \"%d\" (f 0 (List.sort compare !l));;\n"}, {"source_code": "let rec f decu pasdecu temps = function\n\t|t::q\t-> if t (List.rev pasdecu) @ decu;;\n\nlet _ =\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) and l = ref [] in\n\tfor i = 1 to n do\n\t\tScanf.scanf \" %d\" (fun i -> l := i::!l);\n\tdone;\n\tList.iter (fun i -> Printf.printf \"%d \" i) (f [] [] 0 (List.sort compare !l));;\n"}, {"source_code": "let rec f decu pasdecu temps = function\n\t|t::q\t-> if t List.length pasdecu;;\n\nlet _ =\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) and l = ref [] in\n\tfor i = 1 to n do\n\t\tScanf.scanf \" %d\" (fun i -> l := i::!l);\n\tdone;\n\tPrintf.printf \"%d\" (f [] [] 0 (List.sort compare !l));;\n"}], "src_uid": "08c4d8db40a49184ad26c7d8098a8992"} {"nl": {"description": "Recently, you found a bot to play \"Rock paper scissors\" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $$$s = s_1 s_2 \\dots s_{n}$$$ of length $$$n$$$ where each letter is either R, S or P.While initializing, the bot is choosing a starting index $$$pos$$$ ($$$1 \\le pos \\le n$$$), and then it can play any number of rounds. In the first round, he chooses \"Rock\", \"Scissors\" or \"Paper\" based on the value of $$$s_{pos}$$$: if $$$s_{pos}$$$ is equal to R the bot chooses \"Rock\"; if $$$s_{pos}$$$ is equal to S the bot chooses \"Scissors\"; if $$$s_{pos}$$$ is equal to P the bot chooses \"Paper\"; In the second round, the bot's choice is based on the value of $$$s_{pos + 1}$$$. In the third round\u00a0\u2014 on $$$s_{pos + 2}$$$ and so on. After $$$s_n$$$ the bot returns to $$$s_1$$$ and continues his game.You plan to play $$$n$$$ rounds and you've already figured out the string $$$s$$$ but still don't know what is the starting index $$$pos$$$. But since the bot's tactic is so boring, you've decided to find $$$n$$$ choices to each round to maximize the average number of wins.In other words, let's suggest your choices are $$$c_1 c_2 \\dots c_n$$$ and if the bot starts from index $$$pos$$$ then you'll win in $$$win(pos)$$$ rounds. Find $$$c_1 c_2 \\dots c_n$$$ such that $$$\\frac{win(1) + win(2) + \\dots + win(n)}{n}$$$ is maximum possible.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contain test cases\u00a0\u2014 one per line. The first and only line of each test case contains string $$$s = s_1 s_2 \\dots s_{n}$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$; $$$s_i \\in \\{\\text{R}, \\text{S}, \\text{P}\\}$$$)\u00a0\u2014 the string of the bot. It's guaranteed that the total length of all strings in one test doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print $$$n$$$ choices $$$c_1 c_2 \\dots c_n$$$ to maximize the average number of wins. Print them in the same manner as the string $$$s$$$. If there are multiple optimal answers, print any of them.", "sample_inputs": ["3\nRRRR\nRSP\nS"], "sample_outputs": ["PPPP\nRSP\nR"], "notes": "NoteIn the first test case, the bot (wherever it starts) will always choose \"Rock\", so we can always choose \"Paper\". So, in any case, we will win all $$$n = 4$$$ rounds, so the average is also equal to $$$4$$$.In the second test case: if bot will start from $$$pos = 1$$$, then $$$(s_1, c_1)$$$ is draw, $$$(s_2, c_2)$$$ is draw and $$$(s_3, c_3)$$$ is draw, so $$$win(1) = 0$$$; if bot will start from $$$pos = 2$$$, then $$$(s_2, c_1)$$$ is win, $$$(s_3, c_2)$$$ is win and $$$(s_1, c_3)$$$ is win, so $$$win(2) = 3$$$; if bot will start from $$$pos = 3$$$, then $$$(s_3, c_1)$$$ is lose, $$$(s_1, c_2)$$$ is lose and $$$(s_2, c_3)$$$ is lose, so $$$win(3) = 0$$$; The average is equal to $$$\\frac{0 + 3 + 0}{3} = 1$$$ and it can be proven that it's the maximum possible average.A picture from Wikipedia explaining \"Rock paper scissors\" game: "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\n \nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let s = read_string() in\n let n = String.length s in\n let hist = Array.make 3 0 in\n for i=0 to n-1 do\n let x = match s.[i] with 'R' -> 0 | 'S' -> 1 | 'P' -> 2 | _ -> failwith \"bad\" in\n hist.(x) <- hist.(x) + 1\n done;\n\n let answer =\n if hist.(0) >= hist.(1) && hist.(0) >= hist.(2) then 'P'\n else if hist.(1) >= hist.(0) && hist.(1) >= hist.(2) then 'R'\n else 'S'\n in\n for i=1 to n do\n printf \"%c\" answer\n done;\n print_newline()\n done\n"}], "negative_code": [], "src_uid": "38e884cbc5bede371bccbc848096f499"} {"nl": {"description": "When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging\u00a0\u2014 but why not make a similar programming contest problem while we're at it?You're given a sequence of n data points a1,\u2009...,\u2009an. There aren't any big jumps between consecutive data points\u00a0\u2014 for each 1\u2009\u2264\u2009i\u2009<\u2009n, it's guaranteed that |ai\u2009+\u20091\u2009-\u2009ai|\u2009\u2264\u20091.A range [l,\u2009r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l\u2009\u2264\u2009i\u2009\u2264\u2009r; the range [l,\u2009r] is almost constant if M\u2009-\u2009m\u2009\u2264\u20091.Find the length of the longest almost constant range.", "input_spec": "The first line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of data points. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100\u2009000).", "output_spec": "Print a single number\u00a0\u2014 the maximum length of an almost constant range of the given sequence.", "sample_inputs": ["5\n1 2 3 3 2", "11\n5 4 5 5 6 7 8 8 8 7 6"], "sample_outputs": ["4", "5"], "notes": "NoteIn the first sample, the longest almost constant range is [2,\u20095]; its length (the number of data points in it) is 4.In the second sample, there are three almost constant ranges of length 4: [1,\u20094], [6,\u20099] and [7,\u200910]; the only almost constant range of the maximum length 5 is [6,\u200910]."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let equal_block_length n a =\n let rec loop i current_run best_run = if i=n then best_run\n else if a.(i-1) = a.(i) then\n\tlet current_run = current_run+1 in\n\tlet best_run = max best_run current_run in\n\tloop (i+1) current_run best_run\n else\n\tloop (i+1) 1 best_run\n in\n loop 1 1 1\n in\n\n let b = Array.init n (fun i -> a.(i)/2) in\n\n let c = Array.init n (fun i -> (a.(i)+1)/2) in\n\n let answer = max (equal_block_length n b) (equal_block_length n c) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "b784cebc7e50cc831fde480171b9eb84"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \\leq x$$$ holds for each $$$i$$$ ($$$1 \\le i \\le n$$$).", "input_spec": "The first line of input contains one integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\leq n \\leq 50$$$; $$$1 \\leq x \\leq 1000$$$)\u00a0\u2014 the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_1 \\le a_2 \\le \\dots \\le a_n \\leq x$$$)\u00a0\u2014 the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\leq b_1 \\le b_2 \\le \\dots \\le b_n \\leq x$$$)\u00a0\u2014 the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.", "output_spec": "For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \\leq x$$$ holds for each $$$i$$$ ($$$1 \\le i \\le n$$$) or No otherwise. Each character can be printed in any case.", "sample_inputs": ["4\n3 4\n1 2 3\n1 1 2\n\n2 6\n1 4\n2 5\n\n4 4\n1 2 3 4\n1 2 3 4\n\n1 5\n5\n5"], "sample_outputs": ["Yes\nYes\nNo\nNo"], "notes": "NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \\leq 4$$$; $$$2 + 2 \\leq 4$$$; $$$3 + 1 \\leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \\leq 6$$$; $$$4 + 2 \\leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 > 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 > 5$$$."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let t = read_int () in\n let ncompare a b : int =\n if a = b then\n 0\n else if a < b then\n 1\n else\n -1\n in\n let init n f =\n let rec init_aux acc = function\n | 0 -> acc\n | n -> init_aux ([f ()] @ acc) (n - 1)\n in init_aux [] n\n in\n let rec solve x a b =\n match a, b with\n | [], _ -> \"YES\"\n | _, [] -> \"YES\"\n | hd1 :: tl1, hd2 :: tl2 ->\n if hd1 + hd2 > x then \"NO\" else solve x tl1 tl2\n in\n for i = 1 to t do\n let n = read_int () in\n let x = read_int () in\n let a = List.sort compare (init n read_int) in\n let b = List.sort ncompare (init n read_int) in\n Printf.printf \"%s\\n\" (solve x a b)\n done\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () =\n Scanf.scanf \" %d\" (fun x -> x)\n\nlet rec read_ints n =\n match n with\n | 0 -> []\n | x -> read_int () :: (read_ints (n-1))\n\n(* let read_ints () =\n * let line = read_line () in\n * let ints = Str.split (Str.regexp \" *\") line in\n * List.map int_of_string ints *)\n\nlet rec print_list = function \n [] -> ()\n | e::l -> print_int e ; print_string \" \" ; print_list l\n\nlet solve () =\n let n = read_int () in\n let x = read_int () in\n let a = List.sort compare (read_ints n) in\n let b = List.sort compare (read_ints n) in\n let c = List.map2 (+) a (List.rev b) in\n if\n (List.fold_left (fun m x -> if m >= x then m else x) (-1) c <= x)\n then\n print_endline \"Yes\"\n else print_endline \"No\"\n\n\nlet () =\n let x = read_int () in\n let rec loop n =\n match n with\n | 0 -> ()\n | x -> solve (); loop (n-1) in\n loop x\n"}], "negative_code": [], "src_uid": "7e765c1b0e3f3e9c44de825a79bc1da2"} {"nl": {"description": "Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi.Vasya wonders what the numbers ai could be like. Of all the possible options he likes the one sequence with the minimum possible last number an. Help Vasya restore the initial sequence.It is guaranteed that such a sequence always exists.", "input_spec": "The first line contains a single integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009300). Next n lines contain integer numbers b1, ..., bn \u00a0\u2014 the required sums of digits. All bi belong to the range 1\u2009\u2264\u2009bi\u2009\u2264\u2009300.", "output_spec": "Print n integer numbers, one per line\u00a0\u2014 the correct option for numbers ai, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to bi. If there are multiple sequences with least possible number an, print any of them. Print the numbers without leading zeroes.", "sample_inputs": ["3\n1\n2\n3", "3\n3\n2\n1"], "sample_outputs": ["1\n2\n3", "3\n11\n100"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let sums = Array.init n (fun _ -> read_int()) in\n\n (* fill in b.(0)...b.(i-1) so that it achieves the given sum with minimum value *)\n (* returns true it it works, false if it's impossible *)\n let fill_in b i sum =\n if sum<0 then false else\n let rec loop j remain =\n\tif i=j then remain=0 else\n\t let d = min 9 remain in\n\t b.(j) <- d;\n\t loop (j+1) (remain - d)\n in\n \n loop 0 sum\n in\n\n (* return the smallest number > b whose digit sum is gs (goal sum) *)\n (* b is an array, where b.(0) is the 1s digit, etc *)\n (* sb is the sum of the digits in the b array *)\n let f gs b sb = \n let b' = Array.copy b in\n let rec scan i sum = (* work on increasing position i. sum=desired total for digits i,i-1...0 *)\n if sum<0 then scan (i+1) (sum+b.(i+1)) else\n\tlet rec loop d = (* d=digit we're trying in position i. *)\n\t if d>9 then false else (\n\t b'.(i) <- d;\n\t if fill_in b' i (sum-d) then true else loop (d+1)\n\t )\n\tin\n\t\n\tif loop (b.(i)+1) then () else scan (i+1) (sum+b.(i+1))\n in\n\n scan 0 (gs-(sb-b.(0)));\n b'\n in\n\n let max_length = n + (300/9) + 2 in (* maximum number of digits possible *)\n \n let rec loop i b = if i=n then () else\n let sb = if i=0 then 0 else sums.(i-1) in\n let b = f sums.(i) b sb in\n let rec ploop j front = \n\tif j < 0 then ()\n\telse if b.(j)=0 && front then ploop (j-1) true else (\n\t printf \"%d\" b.(j);\n\t ploop (j-1) false\n\t)\n in\n ploop (max_length-1) true;\n print_newline();\n loop (i+1) b\n in\n\n loop 0 (Array.make max_length 0)\n"}], "negative_code": [], "src_uid": "4577a9b2d96110966ad95a960ef7ec20"} {"nl": {"description": "n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji\u2009=\u20091\u2009-\u2009aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200918) \u2014 the amount of fish in the lake. Then there follow n lines with n real numbers each \u2014 matrix a. aij (0\u2009\u2264\u2009aij\u2009\u2264\u20091) \u2014 the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij\u2009=\u20091\u2009-\u2009aji. All real numbers are given with not more than 6 characters after the decimal point.", "output_spec": "Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.", "sample_inputs": ["2\n0 0.5\n0.5 0", "5\n0 1 1 1 1\n0 0 0.5 0.5 0.5\n0 0.5 0 0.5 0.5\n0 0.5 0.5 0 0.5\n0 0.5 0.5 0.5 0"], "sample_outputs": ["0.500000 0.500000", "1.000000 0.000000 0.000000 0.000000 0.000000"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let a = Array.make_matrix n n 0.0 in\n for i = 0 to n-1 do\n for j = 0 to n-1 do\n a.(i).(j) <- read_float 0\n done\n done;\n let s = Array.make (1 lsl n) 0.0 in\n s.(1 lsl n - 1) <- 1.0;\n for i = 1 lsl n - 1 downto 1 do\n let pop = ref 0 in\n for j = 0 to n-1 do\n if i land 1 lsl j <> 0 then\n incr pop;\n done;\n for j = 0 to n-1 do\n if i land 1 lsl j <> 0 then\n for k = j+1 to n-1 do\n if i land 1 lsl k <> 0 then (\n let ij = i lxor 1 lsl k in\n let ik = i lxor 1 lsl j in\n let t = s.(i) /. ((!pop-1) * !pop / 2 |> float_of_int) in\n s.(ij) <- s.(ij) +. t *. a.(j).(k);\n s.(ik) <- s.(ik) +. t *. a.(k).(j)\n )\n done\n done\n done;\n for i = 0 to n-1 do\n Printf.printf \"%f%c\" s.(1 lsl i) (if i = n-1 then '\\n' else ' ')\n done\n"}], "negative_code": [], "src_uid": "da2d76d47c1ed200982495dc4a234014"} {"nl": {"description": "Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which two planks of length at least $$$k+1$$$ \u2014 the base of the ladder; $$$k$$$ planks of length at least $$$1$$$ \u2014 the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps. You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised \"ladder\" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$) \u2014 the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^5$$$) \u2014 the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.", "output_spec": "Print $$$T$$$ integers \u2014 one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.", "sample_inputs": ["4\n4\n1 3 1 3\n3\n3 3 2\n5\n2 3 3 4 2\n3\n1 1 2"], "sample_outputs": ["2\n1\n2\n0"], "notes": "NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders: "}, "positive_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve n a =\n let (Some x, Some y) = Array.fold_left (fun (x, y) z -> if Some z > x then (Some z, x) else if Some z > y then (x, Some z) else (x, y)) (None, None) a in\n min (n - 2) (y - 1)\n\nlet main () =\n let t = readInt () in\n for i=0 to t-1 do\n let n = readInt () in\n let a = Array.init n (fun _ -> readInt ()) in\n Printf.printf \"%d\\n\" (solve n a)\n done\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "130fd7f40d879e25b0bff886046bf699"} {"nl": {"description": "The Little Elephant loves sortings.He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) and increase ai by 1 for all i such that l\u2009\u2264\u2009i\u2009\u2264\u2009r.Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1\u2009\u2264\u2009i\u2009<\u2009n) ai\u2009\u2264\u2009ai\u2009+\u20091 holds.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of array a. The next line contains n integers, separated by single spaces \u2014 array a (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). The array elements are listed in the line in the order of their index's increasing.", "output_spec": "In a single line print a single integer \u2014 the answer to the problem. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["3\n1 2 3", "3\n3 2 1", "4\n7 4 1 47"], "sample_outputs": ["0", "2", "6"], "notes": "NoteIn the first sample the array is already sorted in the non-decreasing order, so the answer is 0.In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]).In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47]."}, "positive_code": [{"source_code": "let _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let b = ref 0 in\n let s = ref Int64.zero in\n for i = 0 to n - 1 do\n let a = Scanf.scanf \" %d\" (fun x -> x) in\n if !b > a then s := Int64.add !s (Int64.of_int (!b - a));\n b := a\n done;\n print_string (Int64.to_string !s)\n;;\n"}, {"source_code": "#load \"str.cma\";;\n\nlet rec iter ls cur height =\n match ls with\n\t [] -> cur\n\t| h::ls' -> \n\t if height <= (Int64.add h cur) then iter ls' cur (Int64.add h cur)\n\t else iter ls' (Int64.sub height h) height ;;\n\nlet solve ls =\n iter (List.tl ls) 0L (List.hd ls);;\n\n\nlet get_input () =\n let n = int_of_string (read_line ()) and\n\t ls = List.map (fun x -> Int64.of_int (int_of_string x))\n\t(Str.split (Str.regexp \"[ \\t]+\") (read_line ())) in\n (n, ls);;\n\nlet (n, ls) = get_input () in\nif n == 1 then Printf.printf \"0\\n\"\nelse Printf.printf \"%Ld\\n\" (solve ls)\n"}], "negative_code": [{"source_code": "let _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let b = ref 0 in\n let s = ref 0 in\n for i = 0 to n - 1 do\n let a = Scanf.scanf \" %d\" (fun x -> x) in\n s := !s + max 0 (!b - a);\n b := a\n done;\n print_int !s\n;;\n"}, {"source_code": "#load \"str.cma\";;\n\nlet rec iter ls cur height =\n match ls with\n\t [] -> cur\n\t| h::ls' -> \n\t if height <= (h + cur) then iter ls' cur (h + cur)\n\t else iter ls' ((height - h - cur) + cur) height ;;\n\nlet solve ls =\n iter (List.tl ls) 0 (List.hd ls);;\n\n\nlet get_input () =\n let n = int_of_string (read_line ()) and\n\t ls = List.map int_of_string (Str.split (Str.regexp \"[ \\t]+\") (read_line ())) in\n (n, ls);;\n\nlet (n, ls) = get_input () in\nif n == 1 then Printf.printf \"0\\n\"\nelse Printf.printf \"%d\\n\" (solve ls)\n"}, {"source_code": "#load \"str.cma\";;\n\nlet rec iter ls cur height =\n match ls with\n\t [] -> cur\n\t| h::ls' -> \n\t if height <= (h + cur) then iter ls' cur (h + cur)\n\t else iter ls' ((height - h - cur) + cur) height ;;\n\nlet solve ls =\n iter (List.tl ls) 0 (List.hd ls);;\n\n\nlet get_input () =\n let n = int_of_string (read_line ()) and\n\t ls = List.map int_of_string (Str.split (Str.regexp \"[ \\t]+\") (read_line ())) in\n (n, ls);;\n\nlet (n, ls) = get_input () in\nif n == 1 then Printf.printf \"1\\n\"\nelse Printf.printf \"%d\\n\" (solve ls)\n"}], "src_uid": "1cd295e204724335c63e685fcc0708b8"} {"nl": {"description": "You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1\u2009\u2264\u2009j\u2009\u2264\u2009m) of sequence s means that you can choose an arbitrary position i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation.Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s.", "input_spec": "The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes. ", "output_spec": "Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes.", "sample_inputs": ["1024\n010", "987\n1234567"], "sample_outputs": ["1124", "987"], "notes": null}, "positive_code": [{"source_code": "open Array;;\nopen Char;;\nlet (|>) x f = f x\nlet identity x = x\n \nlet f _ = Scanf.scanf \"%s\\n\" (fun s -> init (String.length s) (fun i-> s.[i]))\nlet fold_right m f a = \n let rec fold_ i acc =\n if i>=0 && acc < m\n then fold_ (i-1) (f a.(i) acc)\n else acc\n in fold_ (length a - 1)\nlet main () =\n let acc = Scanf.scanf \"%s\\n\" identity in\n let s = f () in\n let y a =\n let rec y' i = \n if i >= String.length acc\n then i\n else if compare a acc.[i] > 0 \n then (acc.[i]<-a; i)\n else y' (i+1)\n in y'\n in\n fast_sort compare s;\n fold_right (String.length acc) y s 0;\n print_string acc\n ;;\nmain()"}], "negative_code": [{"source_code": "\nopen Array;;\nopen Char;;\nlet (|>) x f = f x\nlet identity = fun x -> x\n \nlet flip f y x = f x y\n \nlet readInStr _ = Scanf.scanf \"%d \" identity\nlet readIntLn _ = Scanf.scanf \"%d\\n\" identity\n \nlet f _ = Scanf.scanf \"%s\\n\" (fun s -> init (String.length s) (fun i-> s.[i]))\nlet y s (acc, i) a = \n if i >= 0 && Char.compare s.(i) a > 0 \n then (Printf.printf \"%s \" acc; (acc ^ (escaped s.(i)) , i-1))\n else (acc ^ (escaped a) , i)\n \nlet main () =\n let a = f () in\n let s = f () in\n fast_sort Char.compare s;\n fold_left (y s) (\"\", length s - 1) a |>fst|>print_string\n ;;\nmain()\n "}, {"source_code": "open Array;;\n \nlet (|>) x f = f x\nlet identity = fun x -> x\n \nlet flip f y x = f x y\n \nlet readInStr _ = Scanf.scanf \"%d \" identity\nlet readIntLn _ = Scanf.scanf \"%d\\n\" identity\n \nlet f _ = Scanf.scanf \"%s\\n\" (fun s -> init (String.length s) (fun i-> s.[i]))\nlet y s (acc, i) a = \n if i >= 0 && Char.compare s.(i) a > 0 \n then (acc*10 + (Char.code s.(i)) - 48, i-1)\n else (acc*10 + (Char.code a) - 48, i)\n \nlet main () =\n let a = f () in\n let s = f () in\n fast_sort Char.compare s;\n fold_left (y s) (0, length s - 1) a |>fst|>print_int\n ;;\nmain()"}, {"source_code": "open Array;;\nopen Char;;\nlet (|>) x f = f x\nlet identity x = x\n \nlet f _ = Scanf.scanf \"%s\\n\" (fun s -> init (String.length s) (fun i-> s.[i]))\nlet fold_right m f a = \n let rec fold_ i acc =\n if i>0 && acc < m\n then fold_ (i-1) (f a.(i) acc)\n else acc\n in fold_ (length a - 1)\nlet main () =\n let acc = Scanf.scanf \"%s\\n\" identity in\n let s = f () in\n let y a =\n let rec y' i = \n if i >= String.length acc\n then i\n else if compare a acc.[i] > 0 \n then (acc.[i]<-a; i)\n else y' (i+1)\n in y'\n in\n fast_sort compare s;\n fold_right (String.length acc) y s 0;\n print_string acc\n ;;\nmain()"}], "src_uid": "a2cd56f2d2c3dd9fe152b8e4111df7d4"} {"nl": {"description": "Marin wants you to count number of permutations that are beautiful. A beautiful permutation of length $$$n$$$ is a permutation that has the following property: $$$$$$ \\gcd (1 \\cdot p_1, \\, 2 \\cdot p_2, \\, \\dots, \\, n \\cdot p_n) > 1, $$$$$$ where $$$\\gcd$$$ is the greatest common divisor.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$) \u2014 the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \\le n \\le 10^3$$$).", "output_spec": "For each test case, print one integer \u2014 number of beautiful permutations. Because the answer can be very big, please print the answer modulo $$$998\\,244\\,353$$$.", "sample_inputs": ["7\n1\n2\n3\n4\n5\n6\n1000"], "sample_outputs": ["0\n1\n0\n4\n0\n36\n665702330"], "notes": "NoteIn first test case, we only have one permutation which is $$$[1]$$$ but it is not beautiful because $$$\\gcd(1 \\cdot 1) = 1$$$.In second test case, we only have one beautiful permutation which is $$$[2, 1]$$$ because $$$\\gcd(1 \\cdot 2, 2 \\cdot 1) = 2$$$. "}, "positive_code": [{"source_code": "(* https://codeforces.com/problemset/problem/1658/B *)\nopen Printf\nopen Scanf \nmodule LL = Int64\n\nlet maxn = 1001\nlet q = 998244353L\nlet ( %% ) x y = LL.sub x ( LL.mul y (LL.div x y) )\nlet ( ** ) x y = LL.mul x y\nlet ( // ) x y = LL.div x y\nlet (!) x = LL.of_int x\n\nlet fac = Array.make maxn 1L;;\nfor i = 1 to maxn-1 do\n fac.(i) <- !i ** fac.(i-1) %% q\ndone\n\nlet solve n =\n if n mod 2 = 1 \n then 0L\n else\n let m = n/2 in\n fac.(m) ** fac.(m) %% q\n\nlet () =\n let t = read_int () in\n for i=1 to t do \n let n = read_int () in \n printf \"%Ld\\n\" (solve n)\n done;\n\n\n"}, {"source_code": "let modul x = Int64.sub x (Int64.mul (Int64.div x (Int64.of_int 998244353)) (Int64.of_int 998244353))\r\n\r\nlet rec test x = match x with\r\n |2 -> Int64.of_int 1\r\n |r when r mod 2 = 0 -> let t = r/2 in\r\n modul(Int64.mul (modul (Int64.mul (Int64.of_int(t)) (Int64.of_int(t)))) (test (x-2)))\r\n |_ -> Int64.zero\r\n;;\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let num = int_of_string(input_line stdin) in\r\n print_endline (Int64.to_string (test num))\r\ndone;\r\n;;"}], "negative_code": [{"source_code": "(* https://codeforces.com/problemset/problem/1658/B *)\r\nopen Printf\r\nopen Scanf \r\n\r\nlet maxn = 100\r\nlet q = 998244353 \r\n\r\nlet fac : int array = Array.make 1001 1;;\r\nfor i = 1 to 1000 do\r\n fac.(i) <- i * fac.(i-1) mod q\r\ndone\r\n\r\nlet solve n =\r\n if n mod 2 = 1 \r\n then 0\r\n else\r\n let m = n/2 in\r\n fac.(m) * fac.(m) mod q\r\n\r\nlet () =\r\n let t = read_int () in\r\n for i=1 to t do \r\n let n = read_int () in \r\n printf \"%d\\n\" (solve n)\r\n done;\r\n\r\n"}, {"source_code": "(* https://codeforces.com/problemset/problem/1658/B *)\r\nopen Printf\r\nopen Scanf \r\n\r\nlet maxn = 100\r\nlet q = 998244353 \r\n\r\nlet fac : int array = Array.make 1001 1;;\r\nfor i = 1 to 1000 do\r\n fac.(i) <- i * fac.(i-1) mod q\r\ndone\r\n\r\nlet solve n =\r\n if n mod 2 = 1 \r\n then 0\r\n else\r\n let m = n/2 in\r\n fac.(m) * fac.(m) mod q\r\n\r\nlet () =\r\n let t = read_int () in\r\n printf \"%d\\n\" t;\r\n for i=1 to t do \r\n let n = read_int () in \r\n printf \"%d\\n\" (solve n)\r\n done;\r\n\r\n"}], "src_uid": "0b718a81787c3c5c1aa5b92834ee8bf5"} {"nl": {"description": "Recently Vova found $$$n$$$ candy wrappers. He remembers that he bought $$$x$$$ candies during the first day, $$$2x$$$ candies during the second day, $$$4x$$$ candies during the third day, $$$\\dots$$$, $$$2^{k-1} x$$$ candies during the $$$k$$$-th day. But there is an issue: Vova remembers neither $$$x$$$ nor $$$k$$$ but he is sure that $$$x$$$ and $$$k$$$ are positive integers and $$$k > 1$$$.Vova will be satisfied if you tell him any positive integer $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \\dots + 2^{k-1} x = n$$$. It is guaranteed that at least one solution exists. Note that $$$k > 1$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$3 \\le n \\le 10^9$$$) \u2014 the number of candy wrappers Vova found. It is guaranteed that there is some positive integer $$$x$$$ and integer $$$k>1$$$ that $$$x + 2x + 4x + \\dots + 2^{k-1} x = n$$$.", "output_spec": "Print one integer \u2014 any positive integer value of $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \\dots + 2^{k-1} x = n$$$.", "sample_inputs": ["7\n3\n6\n7\n21\n28\n999999999\n999999984"], "sample_outputs": ["1\n2\n1\n7\n4\n333333333\n333333328"], "notes": "NoteIn the first test case of the example, one of the possible answers is $$$x=1, k=2$$$. Then $$$1 \\cdot 1 + 2 \\cdot 1$$$ equals $$$n=3$$$.In the second test case of the example, one of the possible answers is $$$x=2, k=2$$$. Then $$$1 \\cdot 2 + 2 \\cdot 2$$$ equals $$$n=6$$$.In the third test case of the example, one of the possible answers is $$$x=1, k=3$$$. Then $$$1 \\cdot 1 + 2 \\cdot 1 + 4 \\cdot 1$$$ equals $$$n=7$$$.In the fourth test case of the example, one of the possible answers is $$$x=7, k=2$$$. Then $$$1 \\cdot 7 + 2 \\cdot 7$$$ equals $$$n=21$$$.In the fifth test case of the example, one of the possible answers is $$$x=4, k=3$$$. Then $$$1 \\cdot 4 + 2 \\cdot 4 + 4 \\cdot 4$$$ equals $$$n=28$$$."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n\nlet get n =\n let rec test k =\n let tmp = (1 lsl k) - 1 in\n if n mod tmp = 0 then n / tmp\n else test (k + 1) in\n test 2\n;;\n\nlet _ =\n let t = scan_int () in\n for i = 1 to t do\n Printf.printf \"%d\\n\" (get (scan_int ()))\n done\n;;\n"}, {"source_code": "let nbTests = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet rec pow x = function \n| 0 -> 1\n| n -> x * pow x (n - 1);;\n\nlet rec solve n k =\n if n mod ((pow 2 k) - 1) = 0 then\n n / ((pow 2 k) - 1)\n else\n solve n (k + 1)\n;;\n\nfor iTest = 1 to nbTests\ndo\n let nbBonbons = Scanf.scanf \" %d\" (fun x -> x) in\n \n print_int (solve nbBonbons 2);\n print_newline ()\ndone;;"}], "negative_code": [], "src_uid": "d04cbe78b836e53b51292401c8c969b2"} {"nl": {"description": "DZY has a hash table with p buckets, numbered from 0 to p\u2009-\u20091. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x)\u2009=\u2009x\u00a0mod\u00a0p. Operation a\u00a0mod\u00a0b denotes taking a remainder after division a by b.However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a \"conflict\" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.", "input_spec": "The first line contains two integers, p and n (2\u2009\u2264\u2009p,\u2009n\u2009\u2264\u2009300). Then n lines follow. The i-th of them contains an integer xi (0\u2009\u2264\u2009xi\u2009\u2264\u2009109).", "output_spec": "Output a single integer \u2014 the answer to the problem.", "sample_inputs": ["10 5\n0\n21\n53\n41\n53", "5 5\n0\n1\n2\n3\n4"], "sample_outputs": ["4", "-1"], "notes": null}, "positive_code": [{"source_code": "let (@@) f x = f x ;;\n\nlet solve p n arr =\n let htbl = Array.create p false in\n try\n for i = 0 to n - 1 do\n let h = arr.(i) mod p in\n match htbl.(h) with\n | false -> htbl.(h) <- true\n | true -> Printf.printf \"%d\\n\" @@ i + 1; raise Exit\n done;\n Printf.printf \"-1\\n\";\n with\n | Exit -> ()\n;;\n\nlet () =\n Scanf.scanf \"%d %d \" (fun p n ->\n let arr = Array.create n 0 in\n for i = 0 to n - 1 do\n Scanf.scanf \"%d \" (fun x -> arr.(i) <- x);\n done;\n solve p n arr)\n;;\n"}, {"source_code": "(**D. The Child and Sequence*)\n\nopen Scanf;;\nopen Num;;\nopen Printf;;\n\nlet p,n = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" ( fun x y -> x,y );;\n\nlet hashv = Array.create p 0;;\n\nexception BreakLoop;;\n\nlet j = ref 0;;\nlet rslt = ref (-1);;\ntry\n for i = 1 to n do\n j := !j + 1;\n let x = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n let y = x mod p in\n match hashv.(y) with\n | 0 -> hashv.(y) <- 1\n | 1 -> raise BreakLoop \n done;\nwith BreakLoop -> rslt := !j;;\n\nprintf \"%d\\n\" !rslt;;\n\n"}], "negative_code": [], "src_uid": "5d5dfa4f129bda46055fb636ef33515f"} {"nl": {"description": "Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1,\u2009a2,\u2009...,\u2009ak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n\u2009-\u2009k cities, and, of course, flour delivery should be paid\u00a0\u2014 for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (ai\u2009\u2260\u2009b for every 1\u2009\u2264\u2009i\u2009\u2264\u2009k) and choose a storage in some city s (s\u2009=\u2009aj for some 1\u2009\u2264\u2009j\u2009\u2264\u2009k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.", "input_spec": "The first line of the input contains three integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105, 0\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n, 1\u2009\u2264\u2009l\u2009\u2264\u2009109, u\u2009\u2260\u2009v) meaning that there is a road between cities u and v of length of l kilometers . If k\u2009>\u20090, then the last line of the input contains k distinct integers a1,\u2009a2,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u2009n)\u00a0\u2014 the number of cities having flour storage located in. If k\u2009=\u20090 then this line is not presented in the input.", "output_spec": "Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print \u2009-\u20091 in the only line.", "sample_inputs": ["5 4 2\n1 2 5\n1 2 3\n2 3 4\n1 4 10\n1 5", "3 1 1\n1 2 3\n3"], "sample_outputs": ["3", "-1"], "notes": "NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened. "}, "positive_code": [{"source_code": "open Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_int64 () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\ntype path = {\n start: int;\n stop: int;\n distance: int64;\n}\n\nlet inf = 2000000000L\n\nlet find_nearest path_arr stops_arr =\n Array.fold_left (fun acc ele ->\n if stops_arr.(ele.start) != stops_arr.(ele.stop) && ele.distance < acc\n then ele.distance\n else acc) inf path_arr\n\nlet () =\n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n let data_arr = Array.init m (fun _ ->\n let start = read_int () in\n let stop = read_int () in\n let distance = read_int64 () in\n {start; stop; distance}\n ) in\n let stops_arr = Array.make (n+1) 0 in\n for i = 1 to k do\n let index = read_int () in\n stops_arr.(index) <- 1\n done;\n let v = find_nearest data_arr stops_arr in\n if v = inf then print_int (-1) else Printf.printf \"%Ld\" v\n"}], "negative_code": [], "src_uid": "b0e6a9b500b3b75219309b5e6295e105"} {"nl": {"description": "A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.", "input_spec": "The first input line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105;\u00a02\u2009\u2264\u2009k\u2009\u2264\u200926). The second line contains n uppercase English letters. Letter \"A\" stands for the first color, letter \"B\" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.", "output_spec": "Print a single integer \u2014 the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.", "sample_inputs": ["6 3\nABBACC", "3 2\nBBB"], "sample_outputs": ["2\nABCACA", "1\nBAB"], "notes": null}, "positive_code": [{"source_code": "open Scanf;;\nopen Printf;;\nopen Str;;\n\nlet split_by_space = split (regexp \" +\")\n\nlet rec head n ls =\n if n < 0 then invalid_arg \"head : passed negative integer\"\n else \n match (n, ls) with\n (0, _) -> []\n | (n, []) -> failwith \"head : list is too short\"\n | (n, x::xs) -> x :: (head (n - 1) xs)\n\nlet rec tail n ls =\n if n < 0 then invalid_arg \"tail : passed negative integer\"\n else\n match (n, ls) with\n (0, ls) -> ls\n | (n, []) -> failwith \"tail : list is too short\"\n | (n, x::xs) -> tail (n - 1) xs\n\nmodule UF = struct\n type t = int array\n\n let make n = Array.make n (-1)\n\n let rec root x uf =\n if uf.(x) < 0 then x \n else (uf.(x) <- root uf.(x) uf; uf.(x))\n\n let union_set x y uf =\n let x = root x uf and\n y = root y uf in\n begin\n if x != y then \n let x, y = if uf.(y) < uf.(x) then y, x else x, y in\n begin\n uf.(x) <- uf.(x) + uf.(y);\n uf.(y) <- x\n end\n end;\n x != y\n\n let find_set x y uf = root x uf = root y uf\n\n let size x uf = - uf.(x)\nend\n\nlet input () = \n let (n, k) = scanf \"%d %d \" (fun x y -> (x, y)) in\n let row = scanf \"%s \" (fun x -> x) in\n (n, k, row)\n\nexception Exit of char\nlet get_other a b k =\n let a_code = Char.code 'A' in\n let ac = Char.code a - a_code and\n bc = Char.code b - a_code in\n try \n for i = 0 to k - 1 do\n if i <> ac && i <> bc then begin\n raise (Exit (Char.chr (i + a_code)))\n end \n done;\n '_'\n with\n Exit c -> c\n\ntype t = Left of int | Right of int\n\nlet solve (n, k, row) =\n if String.length row = 1 then\n (0, row)\n else if String.length row = 2 then begin\n let cnt = ref 0 in\n if row.[0] = row.[1] then begin\n row.[0] <- Char.chr ((Char.code (row.[1]) - Char.code 'A' + 1) mod k + \n Char.code 'A');\n cnt := 1;\n end;\n (!cnt, row)\n end\n else if k > 2 then begin\n let cnt = ref 0 in\n for i = 1 to String.length row - 2 do\n if row.[i - 1] = row.[i] then begin\n row.[i] <- get_other row.[i - 1] row.[i + 1] k;\n cnt := !cnt + 1\n end\n done;\n let c1 = row.[String.length row - 2] and\n c2 = row.[String.length row - 1] in\n if c1 = c2 then begin\n row.[String.length row - 1] <- \n Char.chr (((Char.code c1 - Char.code 'A') + 1) mod k + Char.code 'A');\n cnt := !cnt + 1\n end;\n (!cnt, row)\n end\n else \n let count row b = \n let cnt = ref 0 in\n for i = 0 to String.length row - 1 do\n match (if b then i mod 2 else (i + 1) mod 2) with\n 0 -> if row.[i] = 'B' then begin \n row.[i] <- 'A';\n cnt := !cnt + 1\n end\n | 1 -> if row.[i] = 'A' then begin \n row.[i] <- 'B';\n cnt := !cnt + 1\n end\n done;\n (!cnt, row) in\n let crow = String.copy row in\n let (cnt, row) = count row true in\n let (ccnt, crow) = count crow false in\n if cnt < ccnt then\n (cnt, row) \n else \n (ccnt, crow)\nlet () = \n let inp = input () in\n let (n, res) = solve inp in\n printf \"%d\\n%s\\n\" n res\n"}], "negative_code": [], "src_uid": "0ecf60ea733eba71ef1cc1e736296d96"} {"nl": {"description": "Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad\u2014'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0,\u20091,\u20090,\u20091}, {1,\u20090,\u20091}, and {1,\u20090,\u20091,\u20090} are alternating sequences, while {1,\u20090,\u20090} and {0,\u20091,\u20090,\u20091,\u20091} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring\u2014that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.", "input_spec": "The first line contains the number of questions on the olympiad n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000). The following line contains a binary string of length n representing Kevin's results on the USAICO. ", "output_spec": "Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.", "sample_inputs": ["8\n10000011", "2\n01"], "sample_outputs": ["5", "2"], "notes": "NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score."}, "positive_code": [{"source_code": "open Scanf\n\nlet read_int () = scanf \" %d\" (fun x -> x)\nlet read_string () = scanf \" %s\" (fun x -> x)\nlet n = read_int ()\nlet s = read_string ()\n\nlet longest_seq s =\n let last = ref '2'\n and cnt = ref 0 in\n begin\n for i = 0 to n - 1 do\n if s.[i] <> !last then\n begin\n incr cnt;\n last := s.[i]\n end\n done;\n !cnt\n end\n\nlet res = min n (longest_seq s + 2)\nlet _ = print_int res\n"}, {"source_code": "open Printf;;\nopen Scanf;;\n\nlet n = read_int();;\nlet s = input_line stdin;;\nlet dp0 = Array.make (n+1) 0;;\nlet dp1 = Array.make (n+1) 0;;\nlet dp2 = Array.make (n+1) 0;;\nfor i=1 to n-1 do\n let aux1 = if s.[i]<>s.[i-1] then 1 + dp1.(i-1) else dp1.(i-1)\n and aux2 = if s.[i]<>s.[i-1] then dp0.(i-1) else 1 + dp0.(i-1)\n and aux3 = if s.[i]<>s.[i-1] then 1 + dp2.(i-1) else dp2.(i-1)\n and aux4 = if s.[i]<>s.[i-1] then dp1.(i-1) else 1 + dp1.(i-1)\n in let res1 = max aux1 aux2\n and res2 = max aux3 aux4 in\n dp0.(i) <- if s.[i]<>s.[i-1] then 1 + dp0.(i-1) else dp0.(i-1);\n dp1.(i) <- res1;\n dp2.(i) <- res2;\ndone;;\nprintf \"%d\" (1 + max dp0.(n-1) (max dp1.(n-1) dp2.(n-1)));;"}, {"source_code": "let n = read_int()\nand s = input_line stdin;;\n\nlet rec solve i =\nif (i=0) then (0,0,0) else\nbegin\n let (r0,r1,r2) = solve (i-1)\n and ib b = if(b) then 1 else 0 in\n (ib(s.[i]<>s.[i-1]) + r0,\n max (ib(s.[i]<>s.[i-1]) + r1) (ib(not(s.[i]<>s.[i-1])) + r0),\n max (ib(s.[i]<>s.[i-1]) + r2) (ib(not(s.[i]<>s.[i-1])) + r1))\nend;;\n\nlet (a,b,c) = solve(n-1) in\nPrintf.printf \"%d\" (1 + max a (max b c));;"}, {"source_code": "let n = read_int();;\nlet s = input_line stdin;;\nlet dp = Array.make_matrix (n+1) 3 0;;\n\nlet rec solve i =\nif (i=0) then (0,0,0) else\nbegin\n let (r0,r1,r2) = solve (i-1)\n and ib b = if(b) then 1 else 0 in\n (ib(s.[i]<>s.[i-1]) + r0,\n max (ib(s.[i]<>s.[i-1]) + r1) (ib(not(s.[i]<>s.[i-1])) + r0),\n max (ib(s.[i]<>s.[i-1]) + r2) (ib(not(s.[i]<>s.[i-1])) + r1))\nend;;\n\nlet (a,b,c) = solve(n-1);;\nPrintf.printf \"%d\" (1 + max a (max b c));;"}, {"source_code": "let n = read_int();;\nlet s = input_line stdin;;\nlet dp = Array.make_matrix (n+1) 3 0;;\n\nlet rec solve i =\nif (i=0) then (0,0,0) else\nbegin\n let (r0,r1,r2) = solve (i-1)\n and ib b = if(b) then 1 else 0 in\n (ib(s.[i]<>s.[i-1]) + r0, max (ib(s.[i]<>s.[i-1]) + r1) (ib(not(s.[i]<>s.[i-1])) + r0), max (ib(s.[i]<>s.[i-1]) + r2) (ib(not(s.[i]<>s.[i-1])) + r1))\nend;;\n\nlet (a,b,c) = solve(n-1);;\nPrintf.printf \"%d\" (1 + max a (max b c));;"}, {"source_code": "open Printf;;\nopen Scanf;;\n\nlet n = read_int();;\nlet s = input_line stdin;;\nlet dp = Array.make_matrix (n+1) 3 0;;\nfor i=1 to n-1 do\n let aux1 = if s.[i]<>s.[i-1] then 1 + dp.(i-1).(1) else dp.(i-1).(1)\n and aux2 = if s.[i]<>s.[i-1] then dp.(i-1).(0) else 1 + dp.(i-1).(0)\n and aux3 = if s.[i]<>s.[i-1] then 1 + dp.(i-1).(2) else dp.(i-1).(2)\n and aux4 = if s.[i]<>s.[i-1] then dp.(i-1).(1) else 1 + dp.(i-1).(1)\n in let res1 = max aux1 aux2\n and res2 = max aux3 aux4 in\n dp.(i).(0) <- if s.[i]<>s.[i-1] then 1 + dp.(i-1).(0) else dp.(i-1).(0);\n dp.(i).(1) <- res1;\n dp.(i).(2) <- res2;\ndone;;\nprintf \"%d\" (1 + max dp.(n-1).(0) (max dp.(n-1).(1) dp.(n-1).(2)));;"}, {"source_code": "open Printf;;\nopen Scanf;;\n\nlet bi i = if(i=0) then false else true;;\nlet ib b = if(b) then 1 else 0;;\n\nlet n = read_int();;\nlet s = input_line stdin;;\nlet dp = Array.make_matrix (n+1) 3 0;;\n\nfor i=1 to n-1 do\n let aux1 = ib(s.[i]<>s.[i-1]) + dp.(i-1).(1)\n and aux2 = ib(not(s.[i]<>s.[i-1])) + dp.(i-1).(0)\n and aux3 = ib(s.[i]<>s.[i-1]) + dp.(i-1).(2)\n and aux4 = ib(not(s.[i]<>s.[i-1])) + dp.(i-1).(1)\n in let res1 = max aux1 aux2\n and res2 = max aux3 aux4 in\n dp.(i).(0) <- ib(s.[i]<>s.[i-1]) + dp.(i-1).(0);\n dp.(i).(1) <- res1;\n dp.(i).(2) <- res2;\ndone;;\nprintf \"%d\" (1 + max dp.(n-1).(0) (max dp.(n-1).(1) dp.(n-1).(2)));;"}, {"source_code": "let score_without w =\n let a = ref (w.[0]) and res = ref 1 in\n for i = 1 to String.length w - 1 do\n if w.[i] <> !a\n then (incr res; a := w.[i]);\n done;\n !res\n\nlet score w =\n let l = String.length w and s = score_without w in\n s + min 2 (l - s)\n\nlet main () =\n let w = Scanf.scanf \"%d %s\" (fun _ w -> w) in\n Printf.printf \"%d\" (score w);;\n\nmain ();;"}, {"source_code": "let score_without w =\n let a = ref (w.[0]) and res = ref 1 in\n for i = 1 to String.length w - 1 do\n if w.[i] <> !a\n then (incr res; a := w.[i]);\n done;\n !res\n\nlet score w =\n let l = String.length w and s = score_without w in\n s + min 2 (l - s)\n\nlet main () =\n let w = Scanf.scanf \"%d %s\" (fun _ w -> w) in\n Printf.printf \"%d\" (score w);;\n\nmain ();;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n \nlet () =\n let n = read_int() in\n let s = read_string() in\n\n let k = (* alternation length *)\n let rec loop prev i ac = if i=n then ac\n else if s.[i] = prev\n then loop prev (i+1) ac\n else loop s.[i] (i+1) (ac+1)\n in\n loop 'x' 0 0\n in\n\n let answer =\n if n=k then n\n else if n=k+1 then n\n else if n >= k+2 then k+2\n else failwith \"impossible\"\n in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "open Printf;;\nopen Scanf;;\n\nlet n = read_int();;\nlet s = input_line stdin;;\nlet dp0 = Array.make (n+1) 0;;\nlet dp1 = Array.make (n+1) 0;;\nlet dp2 = Array.make (n+1) 0;;\nfor i=1 to n-1 do\n let aux1 = if s.[i]<>s.[i-1] then 1 + dp1.(i-1) else dp1.(i-1)\n and aux2 = if s.[i]<>s.[i-1] then dp0.(i-1) else 1 + dp0.(i-1)\n and aux3 = if s.[i]<>s.[i-1] then 1 + dp2.(i-1) else dp2.(i-1)\n and aux4 = if s.[i]<>s.[i-1] then dp1.(i-1) else 1 + dp1.(i-1)\n in let res1 = max aux1 aux2\n and res2 = max aux3 aux4 in\n dp0.(i) <- if s.[i]<>s.[i-1] then 1 + dp0.(i-1) else dp0.(i-1);\n dp1.(i) <- res1;\n dp2.(i) <- res2;\ndone;;\nprintf \"%d\" (max dp0.(n-1) (max dp1.(n-1) dp2.(n-1)));;"}], "src_uid": "7b56edf7cc71a1b3e39b3057a4387cad"} {"nl": {"description": "Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.But wait, something is still known, because that day a record was achieved \u2014 M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s\u2009+\u20091, s\u2009+\u20092, ..., s\u2009+\u2009T\u2009-\u20091. So, the user's time online can be calculated as the union of time intervals of the form [s,\u2009s\u2009+\u2009T\u2009-\u20091] over all times s of requests from him.Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that: the number of different users online did not exceed M at any moment, at some second the number of distinct users online reached value M, the total number of users (the number of distinct identifiers) was as much as possible. Help Polycarpus cope with the test.", "input_spec": "The first line contains three integers n, M and T (1\u2009\u2264\u2009n,\u2009M\u2009\u2264\u200920\u2009000, 1\u2009\u2264\u2009T\u2009\u2264\u200986400) \u2014 the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format \"hh:mm:ss\", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s,\u2009s\u2009+\u2009T\u2009-\u20091] are within one 24-hour range (from 00:00:00 to 23:59:59). ", "output_spec": "In the first line print number R \u2014 the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print \"No solution\" (without the quotes).", "sample_inputs": ["4 2 10\n17:05:53\n17:05:58\n17:06:01\n22:39:47", "1 2 86400\n00:00:00"], "sample_outputs": ["3\n1\n2\n2\n3", "No solution"], "notes": "NoteConsider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M\u2009=\u20092. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 \u2014 from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 \u2014 from 22:39:47 to 22:39:56.In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.) "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_time () = bscanf Scanning.stdib \" %d:%d:%d \" (fun x y z -> 3600*x + 60*y + z) \n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let t = read_int () in\n let query = Array.init n (fun _ -> read_time()) in\n\n let rec build_events i ac = if i=n then ac else\n let e = query.(i) in\n let ac = (e, true, i)::ac in (* entering *)\n let ac = (e+t, false, i)::ac in (* leaving *)\n build_events (i+1) ac\n in\n\n let events = List.sort compare (build_events 0 []) in\n\n let label = Array.make n 0 in\n\n let reachedm = ref false in\n\n let rec scan events nextlabel ninset set = match events with [] -> nextlabel\n | (e,true,i)::tail ->\n if ninset = m then (\n\tlet (id,j) = Pset.max_elt set in\n\tlet set = Pset.add (id,i) set in\n\tlabel.(i) <- id;\n\tscan tail nextlabel ninset set\n ) else (\n\tlet id = nextlabel in\n\tlet set = Pset.add (id,i) set in\n\tlabel.(i) <- id;\n\tlet ninset = ninset+1 in\n\treachedm := !reachedm || ninset = m;\n\tscan tail (nextlabel+1) ninset set\n )\n | (e,false,i)::tail ->\n let set = Pset.remove (label.(i), i) set in\n let (_,_,r) = Pset.split (label.(i), -1) set in\n let d = if Pset.is_empty r then 1 else\n\t let (id,j) = Pset.min_elt r in\n\t if id <> label.(i) then 1 else 0\n in\n scan tail nextlabel (ninset-d) set\n in\n\n let lab = scan events 1 0 Pset.empty in\n\n if not !reachedm then printf \"No solution\\n\" else (\n printf \"%d\\n\" (lab-1);\n \n for i=0 to n-1 do\n printf \"%d\\n\" label.(i)\n done;\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_time () = bscanf Scanning.stdib \" %d:%d:%d \" (fun x y z -> 3600*x + 60*y + z) \n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let t = read_int () in\n let query = Array.init n (fun _ -> read_time()) in\n\n let rec build_events i ac = if i=n then ac else\n let e = query.(i) in\n let ac = (e, true, i)::ac in (* entering *)\n let ac = (e+t, false, i)::ac in (* leaving *)\n build_events (i+1) ac\n in\n\n let events = List.sort compare (build_events 0 []) in\n\n let label = Array.make n 0 in\n\n let rec scan depth events nextlabel reachedm set = match events with [] -> (nextlabel, reachedm)\n | (e,true,i)::tail ->\n let depth = depth + 1 in\n if depth > m then (\n\tlet (id,j) = Pset.min_elt set in\n\tlet set = Pset.add (id,i) set in\n\tlabel.(i) <- id;\n\tscan depth tail nextlabel reachedm set\n ) else (\n\tlet reachedm = reachedm || depth = m in\n\tlet id = nextlabel in\n\tlet set = Pset.add (id,i) set in\n\tlabel.(i) <- id;\n\tscan depth tail (nextlabel+1) reachedm set\n )\n | (e,false,i)::tail ->\n scan (depth-1) tail nextlabel reachedm set\n in\n\n let (lab,reachedm) = scan 0 events 1 false Pset.empty in\n\n if not reachedm then printf \"No solution\\n\" else (\n printf \"%d\\n\" (lab-1);\n \n for i=0 to n-1 do\n printf \"%d\\n\" label.(i)\n done;\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_time () = bscanf Scanning.stdib \" %d:%d:%d \" (fun x y z -> 3600*x + 60*y + z) \n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let t = read_int () in\n let query = Array.init n (fun _ -> read_time()) in\n\n let rec build_events i ac = if i=n then ac else\n let e = query.(i) in\n let ac = (e, true, i)::ac in (* entering *)\n let ac = (e+t, false, i)::ac in (* leaving *)\n build_events (i+1) ac\n in\n\n let events = List.sort compare (build_events 0 []) in\n\n let label = Array.make n 0 in\n\n let rec scan depth events nextlabel reachedm set = match events with [] -> (nextlabel, reachedm)\n | (e,true,i)::tail ->\n let depth = depth + 1 in\n if depth > m then (\n\tlet (id,j) = Pset.min_elt set in\n\tlet set = Pset.add (id,i) set in\n\tlabel.(i) <- id;\n\tscan depth tail nextlabel reachedm set\n ) else (\n\tlet reachedm = reachedm || depth = m in\n\tlet id = nextlabel in\n\tlet set = Pset.add (id,i) set in\n\tlabel.(i) <- id;\n\tscan depth tail (nextlabel+1) reachedm set\n )\n | (e,false,i)::tail ->\n let set = Pset.remove (label.(i), i) set in\n scan (depth-1) tail nextlabel reachedm set\n in\n\n let (lab,reachedm) = scan 0 events 1 false Pset.empty in\n\n if not reachedm then printf \"No solution\\n\" else (\n printf \"%d\\n\" (lab-1);\n \n for i=0 to n-1 do\n printf \"%d\\n\" label.(i)\n done;\n )\n"}], "src_uid": "a83fe44e7a53294fcfba93bb7b690b88"} {"nl": {"description": "Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi \u2014 the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.", "output_spec": "Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.", "sample_inputs": ["4\n2 3 4 1", "3\n1 3 2", "2\n1 2"], "sample_outputs": ["4 1 2 3", "1 3 2", "1 2"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet () = \n let l = read () in\n let gifter = Array.init l (fun x -> read ()) in\n let giftee = Array.make l 0 in\n let rec loop i = \n if i < l\n then\n (let j = (Array.get gifter i) - 1 in\n Array.set giftee j (i + 1);\n loop (i + 1))\n else\n Array.iter(Printf.printf \"%d \") giftee\n in loop 0"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = Array.init (read ()) (fun n -> read ())\n\nlet solve gifter = \n let l = Array.length gifter in\n let giftee = Array.make l 0 in\n let rec loop i = \n if i < l\n then\n (let j = (Array.get gifter i) - 1 in\n Array.set giftee j (i + 1);\n loop (i + 1))\n else\n giftee\n in loop 0\n\nlet () = Array.iter(Printf.printf \"%d \") (solve (input()))"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = Array.init (read ()) (fun n -> read ())\n\nlet solve gifter = \n let l = Array.length gifter in\n let giftee = Array.make l 0 in\n let rec loop i = \n if i < l\n then\n (let j = Array.get gifter i in\n Array.set giftee (j - 1) (i + 1);\n loop (i + 1))\n else\n giftee\n in loop 0\n\nlet () = Array.iter(Printf.printf \"%d \") (solve (input()))"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\nlet n = read_int()\nlet a = Array.make n 0\n\nlet _ = \n for i=0 to n-1 do\n a.(i) <- read_int() -1 \n done\n \nlet b = Array.make n 0\n\nlet _ =\n for i=0 to n-1 do\n b.(a.(i)) <- i\n done;\n\n for i=0 to n-1 do\n Printf.printf \"%d\" (b.(i)+1);\n if i x)\n\nlet () = \n let n = read_int () in\n let arr = Array.make n 0 in\n for i = 0 to n-1 do\n let e = read_int () in\n (Array.set arr (e-1) i)\n done; \n Array.iter (fun x -> (Printf.printf \"%d \" (x + 1))) arr\n"}, {"source_code": "let string_of_charlist cl =\n let rec iter cl str =\n match cl with\n [] -> str\n | r :: rest ->\n let s = Char.escaped r in\n iter rest (str ^ s)\n in iter cl \"\"\n\nlet charlist_of_string str =\n let n = String.length str in\n let rec iter i cl =\n if i < 0 then\n cl\n else\n let sc = str.[i] in\n iter (i-1) (sc :: cl)\n in iter (n-1) []\n\nlet split c s =\n let n = String.length s in\n let rec spliti i cl sl = \n if i < 0 then\n if cl = [] then\n sl\n else\n let cs = string_of_charlist cl in\n cs :: sl\n else if s.[i] = c then\n if cl = [] then\n spliti (i-1) cl sl\n else\n let cs = string_of_charlist cl in\n spliti (i-1) [] (cs :: sl)\n else\n spliti (i-1) (s.[i] :: cl) sl\n in spliti (n-1) [] []\n\nlet n = read_line ();;\n\nlet input = List.map int_of_string (split ' ' (read_line ()));;\n\nlet rec f i = function\n [] -> []\n | r :: rest -> (i, r) :: (f (i+1) rest);;\n\nlet hoge = f 1 input;;\n\nlet output =\n let fn (_, a) (_, b) = a <= b in\n let fm (a, b) = string_of_int a in\n let out = Sort.list fn hoge in\n let ou2 = List.map fm out in\n String.concat \" \" ou2;;\n\nprint_endline output;;\n\n"}, {"source_code": "let rec split str sep = \n\tif str = \"\" then []\n\telse try\n\t\tlet i = String.index str sep in\n\t\tlet x = String.sub str 0 i in\n\t\tlet xs = String.sub str (i+1) (String.length str - i - 1) in\n\t\tx::(split xs sep)\n\twith _ -> [str]\n;;\n\nlet n = read_int () in\nlet nums = List.map int_of_string (split (read_line()) ' ') in\nlet p = Array.make n 0 in\nlet _ = for i = 0 to n-1 do\n\tArray.set p (List.nth nums i - 1) i\ndone in\nfor i = 0 to n-1 do\n\tprint_string (string_of_int (p.(i) + 1) ^ \" \")\ndone;;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make (n + 1) 0 in\n for i = 1 to n do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(k) <- i\n done;\n for i = 1 to n do\n Printf.printf \"%d \" a.(i);\n done;\n Printf.printf \"\\n\"\n"}, {"source_code": "let iteri f = \n let rec iteri' i = function\n [] -> ()\n | x::xs -> f i x; iteri' (i+1) xs\n in\n iteri' 0\nlet read_int () = Scanf.scanf \"%d%c\" (fun x c -> x)\nlet rec read_ints n = \n if n = 0 then [] \n else let tmp = read_int () in tmp :: read_ints (n-1)\nlet print_array v = Array.iter (Printf.printf \"%d \") v\nlet p x = prerr_int x; prerr_newline ()\n\n;;\n\nlet _ =\n let n = read_int ()\n in\n let ans = Array.make n 0\n in\n iteri (fun i x -> ans.(x-1) <- i+1) (read_ints n);\n print_array ans\n"}], "negative_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = Array.init (read ()) (fun n -> read ())\n\nlet solve gifter = \n let l = Array.length gifter in\n let giftee = Array.make l 0 in\n let rec loop i = \n if i < l\n then\n (let j = Array.get gifter i in\n Array.set giftee (j - 1) j;\n loop (i + 1))\n else\n giftee\n in loop 0\n\nlet () = Array.iter(Printf.printf \"%d \") (solve (input()))"}, {"source_code": "open Str;;\n\nprint_string (read_line ());;\n\n"}], "src_uid": "48bb148e2c4d003cad9d57e7b1ab78fb"} {"nl": {"description": "You are given two segments $$$[l_1; r_1]$$$ and $$$[l_2; r_2]$$$ on the $$$x$$$-axis. It is guaranteed that $$$l_1 < r_1$$$ and $$$l_2 < r_2$$$. Segments may intersect, overlap or even coincide with each other. The example of two segments on the $$$x$$$-axis. Your problem is to find two integers $$$a$$$ and $$$b$$$ such that $$$l_1 \\le a \\le r_1$$$, $$$l_2 \\le b \\le r_2$$$ and $$$a \\ne b$$$. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment $$$[l_1; r_1]$$$ and the second one belongs to the segment $$$[l_2; r_2]$$$.It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 500$$$) \u2014 the number of queries. Each of the next $$$q$$$ lines contains four integers $$$l_{1_i}, r_{1_i}, l_{2_i}$$$ and $$$r_{2_i}$$$ ($$$1 \\le l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} \\le 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}$$$) \u2014 the ends of the segments in the $$$i$$$-th query.", "output_spec": "Print $$$2q$$$ integers. For the $$$i$$$-th query print two integers $$$a_i$$$ and $$$b_i$$$ \u2014 such numbers that $$$l_{1_i} \\le a_i \\le r_{1_i}$$$, $$$l_{2_i} \\le b_i \\le r_{2_i}$$$ and $$$a_i \\ne b_i$$$. Queries are numbered in order of the input. It is guaranteed that the answer exists. If there are multiple answers, you can print any.", "sample_inputs": ["5\n1 2 1 2\n2 6 3 4\n2 4 1 3\n1 2 1 3\n1 4 5 8"], "sample_outputs": ["2 1\n3 4\n3 2\n1 2\n3 7"], "notes": null}, "positive_code": [{"source_code": "\nopen Str\n\nlet twoPoints (l1:int) (r1:int) (l2:int) (r2:int) : int * int=\n if l1 <> l2 then (l1,l2) \n else if r1 > l1 then (r1, l2) \n else (l1,r2)\n\nlet rec repeat (n:int) f =\n if n > 0 then (f () ; repeat (n-1) f)\n\nlet oneiter () =\n let inp = read_line() in\n let [l1;r1;l2;r2] =\n List.map int_of_string (Str.split (Str.regexp \" +\") inp) in\n let (x,y) = twoPoints l1 r1 l2 r2 in\n print_string ((string_of_int x) ^ \" \" ^ (string_of_int y) ^ \"\\n\")\n\nlet main () =\n let q = int_of_string (read_line ()) in\n repeat q oneiter\n\nlet () = main()\n"}, {"source_code": "let q = int_of_string (input_line stdin);;\n\nlet output a b c d =\n let other = if a = c then d else c in\n Printf.printf \"%d %d\\n\" a other ;;\n\nlet solve () = Scanf.scanf \"%d %d %d %d \" output ;;\n\nfor i = 1 to q do\n solve ()\ndone"}], "negative_code": [{"source_code": "let q = int_of_string (input_line stdin);;\n\nlet output a b c d =\n let min = Pervasives.min a c in\n let max = Pervasives.max b d in\n Printf.printf \"%d %d\\n\" min max ;;\n\nlet solve () = Scanf.scanf \"%d %d %d %d \" output ;;\n\nfor i = 1 to q do\n solve ()\ndone"}, {"source_code": "let q = int_of_string (input_line stdin);;\n\nlet output a b c d = Printf.printf \"%d %d\\n\" a d ;;\nlet solve () = Scanf.scanf \"%d %d %d %d \" output ;;\n\nfor i = 1 to q do\n solve ()\ndone"}], "src_uid": "cdafe800094113515e1de1acb60c4bb5"} {"nl": {"description": "The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of $$$n$$$ elements (the elements of the array are indexed starting from 1); also, there are $$$q$$$ queries, each one is defined by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \\le l_i \\le r_i \\le n)$$$. You need to find for each query the sum of elements of the array with indexes from $$$l_i$$$ to $$$r_i$$$, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.", "input_spec": "The first line contains two space-separated integers $$$n$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$) and $$$q$$$ ($$$1 \\le q \\le 2\\cdot10^5$$$) \u2014 the number of elements in the array and the number of queries, correspondingly. The next line contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \\le a_i \\le 2\\cdot10^5$$$) \u2014 the array elements. Each of the following $$$q$$$ lines contains two space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$) \u2014 the $$$i$$$-th query.", "output_spec": "In a single line print, a single integer \u2014 the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["3 3\n5 3 2\n1 2\n2 3\n1 3", "5 3\n5 2 4 1 3\n1 5\n2 3\n2 3"], "sample_outputs": ["25", "33"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 276C - Devochka max sum *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec read_pairs_list n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ ->\n\t\t\tlet x = gr()-1 in\n\t\t\tlet y = gr()-1 in\n\t\t\tread_pairs_list (n -1) ((x, y) :: acc);;\n\nlet n = gr();;\nlet q = gr();;\nlet a = readlist n [];;\nlet lr = read_pairs_list q [];;\nlet ocua = Array.make n 0;;\nlet ocu1000 = Array.make ((n /1000) +1) 0;;\n\nlet rec count_ocu lp = match lp with\n\t| [] -> ()\n\t| (l, r) :: tl ->\n\t\t\tbegin\n\t\t\t\tlet lt = l /1000 in\n\t\t\t\tlet rt = r /1000 in\n\t\t\t\tif lt < rt -1 then begin\n\t\t\t\t\tfor i = lt +1 to rt -1 do\n\t\t\t\t\t\tocu1000.(i) <- ocu1000.(i) + 1\n\t\t\t\t\tdone;\n\t\t\t\t\tfor i = l to (lt +1) *1000 -1 do\n\t\t\t\t\t\tocua.(i) <- ocua.(i) + 1\n\t\t\t\t\tdone;\n\t\t\t\t\tfor i = rt *1000 to r do\n\t\t\t\t\t\tocua.(i) <- ocua.(i) + 1\n\t\t\t\t\tdone\n\t\t\t\tend else\n\t\t\t\t\tfor i = l to r do\n\t\t\t\t\t\tocua.(i) <- ocua.(i) + 1\n\t\t\t\t\tdone;\n\t\t\t\tcount_ocu tl\n\t\t\tend;;\n\nlet rec use_thousands n = match n with\n\t| 0 -> ()\n\t| _ ->\n\t\t\tlet n1 = n -1 in (\n\t\t\t\tocua.(n1) <- ocua.(n1) + ocu1000.(n1 /1000);\n\t\t\t\tuse_thousands n1\n\t\t\t);;\n\nlet rec cntmul sa sb cnt =\n\tmatch sa, sb with\n\t| [], [] -> cnt\n\t| ha :: ta, hb :: tb ->\n\t\t\tlet ncnt = (Int64.add cnt (Int64.mul (Int64.of_int ha) (Int64.of_int hb))) in\n\t\t\tcntmul ta tb ncnt\n\t| _ -> raise (Failure \"Different lengths sa sb\");;\n\nlet main() =\n\tbegin\n\t\tcount_ocu lr;\n\t\tuse_thousands (n -1);\n\t\tlet sb = List.sort compare (Array.to_list ocua) in\n\t\tlet sa = List.sort compare a in\n\t\tlet sum_mul = cntmul sa sb Int64.zero in\n\t\tprint_string ((Int64.to_string sum_mul) ^ \"\\n\")\n\tend;;\n\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = Scanf.bscanf Scanf.Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet () = \n let (n,q) = read_pair() in\n\n let a = Array.init n (fun i -> read_long()) in\n\n let range = Array.init q (fun _ -> read_pair()) in\n\n let count = Array.make (n+1) 0L in\n\n for i=0 to q-1 do\n let (l,r) = range.(i) in\n\tcount.(l-1) <- count.(l-1) ++ 1L;\n\tcount.(r) <- count.(r) -- 1L;\n done;\n\n for i=1 to n do\n count.(i) <- count.(i-1) ++ count.(i)\n done;\n\n let () = count.(n) <- Int64.max_int in\n\n let () = Array.sort compare count in\n \n let () = Array.sort compare a in\n\n let answer = sum 0 (n-1) (fun i-> count.(i) ** a.(i)) in\n Printf.printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "926ec28d1c80e7cbe0bb6d209e664f48"} {"nl": {"description": "You need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an element of the subtree rooted at ai's left child. Similarly in the case of right direction bi is an element of the subtree rooted at ai's right child.", "input_spec": "The first line of input contains two integers n and c. The next c lines contain 2 integers ai, bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n) and either \"LEFT\" or \"RIGHT\" denoting whether b is in the subtree rooted at ai's left child or in the subtree rooted at ai's right child. The problem consists of multiple subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem D1 (9 points), the constraints 1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009c\u2009\u2264\u200950 will hold. In subproblem D2 (8 points), the constraints 1\u2009\u2264\u2009n\u2009\u2264\u20091000000, 1\u2009\u2264\u2009c\u2009\u2264\u2009100000 will hold. ", "output_spec": "Output will be on a single line. Any binary tree that satisfies the constraints will be accepted. The tree's nodes should be printed out as n space separated labels representing an in-order traversal, using the pre-order numbers as labels of vertices. If there are no trees that satisfy the constraints, print \"IMPOSSIBLE\" (without quotes).", "sample_inputs": ["3 2\n1 2 LEFT\n1 3 RIGHT", "3 2\n1 2 RIGHT\n1 3 LEFT"], "sample_outputs": ["2 1 3", "IMPOSSIBLE"], "notes": "NoteConsider the first sample test. We need to find a tree with 3 nodes that satisfies the following two constraints. The node labeled 2 with pre-order traversal should be in the left subtree of the node labeled 1 with pre-order traversal; the node labeled 3 with pre-order traversal should be in the right subtree of the node labeled 1. There is only one tree with three nodes that satisfies these constraints and its in-order traversal is (2,\u20091,\u20093).Pre-order is the \"root \u2013 left subtree \u2013 right subtree\" order. In-order is the \"left subtree \u2013 root \u2013 right subtree\" order.For other information regarding in-order and pre-order, see http://en.wikipedia.org/wiki/Tree_traversal."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let c = read_int () in\n\n (* the following 3 arrays represent the input, and are not computed *) \n let lhi = Array.make (n+1) 0 in (* lhi.(x) is the highest node required to be in the left subtree of x *)\n let rlo = Array.make (n+1) (n+1) in (* everything in [rlo.(x), rhi.(x)] must be in the right subtree of x*)\n let rhi = Array.make (n+1) 0 in\n\n (* the following two arrays are computed *)\n let rtc = Array.init (n+1) (fun i -> i) in \n (* rtc.(x) (required to contain)\n We know that the subtree rooted at x must contain x,x+1 ... y\n for some y. rtc.(x) is the minimum such y required by the \n constraints on the nodes x and greater. *)\n let l = Array.make (n+1) 0 in (* size of the left subtree of x *)\n\n try (\n for i=1 to c do\n let x = read_int() in\n let y = read_int() in\n if y <= x then raise (Failure \"1\");\n match read_string() with \n\t| \"LEFT\" -> \n\t lhi.(x) <- max lhi.(x) y;\n\t| \"RIGHT\" -> \n\t rlo.(x) <- min rlo.(x) y;\n\t rhi.(x) <- max rhi.(x) y;\n\t| _ -> failwith \"bad command\"\n done;\n\n let rec set_rtc x elist = if x>1 then (\n rtc.(x) <- max rtc.(x) (max lhi.(x-1) (max lhi.(x) rhi.(x)));\n let rec loop elist =\n\tmatch elist with\n\t | [] -> [(x,rtc.(x))]\n\t | (a,b)::tail ->\n\t if rtc.(x) < a then (x,rtc.(x))::elist else (\n\t rtc.(x) <- max b rtc.(x);\n\t loop tail\n\t )\n in\n if rtc.(x) > x then set_rtc (x-1) (loop elist) else set_rtc (x-1) elist\n )\n in\n\n set_rtc (n-1) [];\n\n for x = 1 to n-1 do\n l.(x) <- if lhi.(x) = 0 then 0 else rtc.(x+1) - (x+1) + 1;\n done;\n\n for x = 1 to n-1 do\n if x + l.(x) >= rlo.(x) then raise (Failure \"2\");\n done;\n\n let rec inorder x s = \n if l.(x) > 0 then inorder (x+1) l.(x);\n printf \"%d \" x;\n let rsize = s - l.(x) - 1 in\n if rsize > 0 then inorder (x+l.(x)+1) rsize\n in\n inorder 1 n;\n print_newline();\n\n ) with Failure s -> printf \"IMPOSSIBLE\\n\";\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let c = read_int () in\n\n (* the following 3 arrays represent the input, and are not computed *) \n let lhi = Array.make (n+1) 0 in (* lhi.(x) is the highest node required to be in the left subtree of x *)\n let rlo = Array.make (n+1) (n+1) in (* everything in [rlo.(x), rhi.(x)] must be in the right subtree of x*)\n let rhi = Array.make (n+1) 0 in\n\n (* the following two arrays are computed *)\n let rtc = Array.init (n+1) (fun i -> i) in \n (* rtc.(x) (required to contain)\n We know that the subtree rooted at x must contain x,x+1 ... y\n for some y. rtc.(x) is the minimum such y required by the \n constraints on the nodes x and greater. *)\n let l = Array.make (n+1) 0 in (* size of the left subtree of x *)\n\n try (\n for i=1 to c do\n let x = read_int() in\n let y = read_int() in\n if y <= x then raise (Failure \"1\");\n match read_string() with \n\t| \"LEFT\" -> \n\t lhi.(x) <- max lhi.(x) y;\n\t| \"RIGHT\" -> \n\t rlo.(x) <- min rlo.(x) y;\n\t rhi.(x) <- max rhi.(x) y;\n\t| _ -> failwith \"bad command\"\n done;\n \n for x = n-1 downto 2 do\n rtc.(x) <- max rtc.(x) (max lhi.(x-1) (max lhi.(x) rhi.(x)));\n rtc.(x) <- maxf x rtc.(x) (Array.get rtc);\n done;\n \n for x = 1 to n-1 do\n l.(x) <- if lhi.(x) = 0 then 0 else rtc.(x+1) - (x+1) + 1;\n done;\n\n for x = 1 to n-1 do\n if x + l.(x) >= rlo.(x) then raise (Failure \"2\");\n done;\n\n let rec inorder x s = \n if l.(x) > 0 then inorder (x+1) l.(x);\n printf \"%d \" x;\n let rsize = s - l.(x) - 1 in\n if rsize > 0 then inorder (x+l.(x)+1) rsize\n in\n inorder 1 n;\n print_newline();\n\n ) with Failure s -> printf \"IMPOSSIBLE\\n\";\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let c = read_int () in\n \n let l = Array.make (n+1) 0 in (* size of the left subtree of x *)\n let lhi = Array.make (n+1) 0 in (* lhi.(x) is the highest node required to be in the left subtree of x *)\n let rlo = Array.make (n+1) (n+1) in (* everything in [rlo.(x), rhi.(x)] must be in the right subtree of x*)\n let rhi = Array.make (n+1) 0 in\n let rtc = Array.init (n+1) (fun i -> i) in \n (* rtc.(x) (required to contain)\n We know that the subtree rooted at x must contain x,x+1 ... y\n for some y. rc.(x) is the minimum such y required by the \n constraints on the nodes x and greater. *)\n\n try (\n for i=1 to c do\n let x = read_int() in\n let y = read_int() in\n if y <= x then raise (Failure \"1\");\n match read_string() with \n\t| \"LEFT\" -> \n\t lhi.(x) <- max lhi.(x) y;\n\t| \"RIGHT\" -> \n\t rlo.(x) <- min rlo.(x) y;\n\t rhi.(x) <- max rhi.(x) y;\n\t| _ -> failwith \"bad command\"\n done;\n \n for x = n-1 downto 2 do\n rtc.(x) <- max rtc.(x) (max lhi.(x-1) (max lhi.(x) rhi.(x)));\n let rec loop rtcx = \n\trtc.(x) <- maxf x rtcx (Array.get rtc);\n\tif rtc.(x) > rtcx then loop rtc.(x)\n in\n loop rtc.(x);\n done;\n \n for x = 1 to n-1 do\n l.(x) <- if lhi.(x) = 0 then 0 else rtc.(x+1) - (x+1) + 1;\n done;\n\n for x = 1 to n-1 do\n if x + l.(x) >= rlo.(x) then raise (Failure \"2\");\n done;\n\n let rec inorder x s = \n if l.(x) > 0 then inorder (x+1) l.(x);\n printf \"%d \" x;\n let rsize = s - l.(x) - 1 in\n if rsize > 0 then inorder (x+l.(x)+1) rsize\n in\n inorder 1 n;\n print_newline();\n\n ) with Failure s -> printf \"IMPOSSIBLE\\n\";\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let c = read_int () in\n\n (* the following 3 arrays represent the input, and are not computed *) \n let lhi = Array.make (n+1) 0 in (* lhi.(x) is the highest node required to be in the left subtree of x *)\n let rlo = Array.make (n+1) (n+1) in (* everything in [rlo.(x), rhi.(x)] must be in the right subtree of x*)\n let rhi = Array.make (n+1) 0 in\n\n (* the following two arrays are computed *)\n let rtc = Array.init (n+1) (fun i -> i) in \n (* rtc.(x) (required to contain)\n We know that the subtree rooted at x must contain x,x+1 ... y\n for some y. rtc.(x) is the minimum such y required by the \n constraints on the nodes x and greater. *)\n let l = Array.make (n+1) 0 in (* size of the left subtree of x *)\n\n try (\n for i=1 to c do\n let x = read_int() in\n let y = read_int() in\n if y <= x then raise (Failure \"1\");\n match read_string() with \n\t| \"LEFT\" -> \n\t lhi.(x) <- max lhi.(x) y;\n\t| \"RIGHT\" -> \n\t rlo.(x) <- min rlo.(x) y;\n\t rhi.(x) <- max rhi.(x) y;\n\t| _ -> failwith \"bad command\"\n done;\n\n let rec set_rtc x elist = if x>2 then (\n rtc.(x) <- max rtc.(x) (max lhi.(x-1) (max lhi.(x) rhi.(x)));\n let rec loop elist =\n\tmatch elist with\n\t | [] -> [(x,rtc.(x))]\n\t | (a,b)::tail ->\n\t if rtc.(x) < a then (x,rtc.(x))::elist else (\n\t rtc.(x) <- max b rtc.(x);\n\t loop tail\n\t )\n in\n if rtc.(x) > x then set_rtc (x-1) (loop elist) else set_rtc (x-1) elist\n )\n in\n\n set_rtc (n-1) [];\n\n for x = 1 to n-1 do\n l.(x) <- if lhi.(x) = 0 then 0 else rtc.(x+1) - (x+1) + 1;\n done;\n\n for x = 1 to n-1 do\n if x + l.(x) >= rlo.(x) then raise (Failure \"2\");\n done;\n\n let rec inorder x s = \n if l.(x) > 0 then inorder (x+1) l.(x);\n printf \"%d \" x;\n let rsize = s - l.(x) - 1 in\n if rsize > 0 then inorder (x+l.(x)+1) rsize\n in\n inorder 1 n;\n print_newline();\n\n ) with Failure s -> printf \"IMPOSSIBLE\\n\";\n"}], "src_uid": "e683d660af1e8a98f20296f289aa8960"} {"nl": {"description": "While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings \"ac\", \"bc\", \"abc\" and \"a\" are subsequences of string \"abc\" while strings \"abbc\" and \"acb\" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.", "input_spec": "The first line contains string a, and the second line\u00a0\u2014 string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.", "output_spec": "If there's no uncommon subsequence, print \"-1\". Otherwise print the length of the longest uncommon subsequence of a and b.", "sample_inputs": ["abcd\ndefgh", "a\na"], "sample_outputs": ["5", "-1"], "notes": "NoteIn the first example: you can choose \"defgh\" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a."}, "positive_code": [{"source_code": "let () =\n Scanf.scanf \"%s %s \" @@ fun a b ->\n if a = b then\n print_endline \"-1\"\n else\n let la = String.length a and lb = String.length b in\n Printf.printf \"%d\\n\" (max la lb)\n"}], "negative_code": [], "src_uid": "f288d7dc8cfcf3c414232a1b1fcdff3e"} {"nl": {"description": "Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1,\u2009a2,\u2009...,\u2009an of n integer numbers \u2014 saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that: Each pencil belongs to exactly one box; Each non-empty box has at least k pencils in it; If pencils i and j belong to the same box, then |ai\u2009-\u2009aj|\u2009\u2264\u2009d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |ai\u2009-\u2009aj|\u2009\u2264\u2009d and they belong to different boxes. Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print \"YES\" if there exists such a distribution. Otherwise print \"NO\".", "input_spec": "The first line contains three integer numbers n, k and d (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105, 0\u2009\u2264\u2009d\u2009\u2264\u2009109) \u2014 the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively. The second line contains n integer numbers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 saturation of color of each pencil.", "output_spec": "Print \"YES\" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print \"NO\".", "sample_inputs": ["6 3 10\n7 2 7 7 4 2", "6 2 3\n4 5 3 13 4 10", "3 2 5\n10 16 22"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10.In the second example you can split pencils of saturations [4,\u20095,\u20093,\u20094] into 2 boxes of size 2 and put the remaining ones into another box."}, "positive_code": [{"source_code": "\n(* codeforces.com/contest/985/problem/E *)\n\nmodule type Seg_tree_T = sig\n type t\n val mappend: t -> t -> t\n val to_string: t -> string\nend\n\nmodule type Seg_tree_S = sig\n type t\n type elt\n\n val create: int -> elt -> t\n val size: t -> int\n val set: t -> int -> elt -> unit\n val query: t -> int * int -> elt\nend\n\nmodule Seg_tree (T: Seg_tree_T): Seg_tree_S with type elt = T.t = struct\n type elt = T.t\n type t = int * elt array\n \n let rec pow a = function\n | 0 -> 1\n | 1 -> a\n | n -> \n let b = pow a (n / 2) in\n b * b * (if n mod 2 = 0 then 1 else a)\n \n let log2 a = log a /. log 2.\n \n let create size init =\n let power = size |> float_of_int |> log2 |> ceil |> int_of_float in\n let length = pow 2 (power + 1) in\n size, Array.make (length + 1) init\n \n let size = fst\n \n let set (len, tree) idx value =\n let rec f i l r =\n (*Printf.printf \"set f: %d %d %d\\n\" i l r;*)\n if idx < l || idx >= r\n then tree.(i)\n else\n if r - l = 1\n then begin tree.(i) <- value; value end\n else\n let lv = f (2 * i) l ((l + r) / 2) in\n let rv = f (2 * i + 1) ((l + r) / 2) r in\n let v = T.mappend lv rv in\n tree.(i) <- v; v\n in\n f 1 0 len |> ignore\n \n let query (len, tree) (lr, rr): T.t =\n let rec f i l r: T.t =\n if l >= lr && r <= rr\n then tree.(i)\n else\n let m = (l + r) / 2 in\n if m <= lr\n then f (i * 2 + 1) m r\n else if m >= rr\n then f (i * 2) l m\n else T.mappend\n (f (i * 2) l m)\n (f (i * 2 + 1) m r)\n in\n f 1 0 len\n\nend\n\nmodule Monoid_bool: Seg_tree_T with type t = bool = struct\n type t = bool\n let mappend = (||)\n let to_string = string_of_bool\nend\n\nmodule ST = Seg_tree(Monoid_bool)\n \n(* github.com/janestreet/base/blob/master/src/binary_search.ml *)\nlet bisearch (data: int array) ((lr, rr): int * int) (min_value: int): int option =\n let rec f l r =\n if l > r\n then None\n else\n if l = r\n then if data.(l) >= min_value then Some l else None\n else\n let m = l + (r - l) / 2 in\n if data.(m) >= min_value\n then f l m\n else f (m + 1) r\n in\n f lr (rr - 1)\n \n\nlet _ =\n Printexc.record_backtrace true;\n let n, k, d = Scanf.scanf \" %d %d %d\" (fun a b c -> a, b, c) in\n let a = Array.init n (fun _ -> Scanf.scanf \" %d\" (fun i -> i)) in\n Array.sort compare a;\n \n let dp = ST.create (n + 1) false in\n ST.set dp 0 true;\n let rec f i =\n if i > n\n then ()\n else\n if i < k\n then f (i + 1)\n else\n let j = bisearch a (0, (i - k + 1)) (a.(i - 1) - d) in\n match j with\n | Some j ->\n (if i - k + 1 > j\n then\n ST.set dp i (ST.query dp (j, (i - k + 1)))\n else ());\n f (i + 1)\n | _ -> f (i + 1)\n in\n f 0;\n (if ST.query dp (n, n + 1) then \"YES\" else \"NO\") |> print_endline\n \n"}], "negative_code": [], "src_uid": "c25549c415a78b7f6b6db1299daa0b50"} {"nl": {"description": "In the pet store on sale there are: $$$a$$$ packs of dog food; $$$b$$$ packs of cat food; $$$c$$$ packs of universal food (such food is suitable for both dogs and cats). Polycarp has $$$x$$$ dogs and $$$y$$$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.", "input_spec": "The first line of input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ lines are given, each containing a description of one test case. Each description consists of five integers $$$a, b, c, x$$$ and $$$y$$$ ($$$0 \\le a,b,c,x,y \\le 10^8$$$).", "output_spec": "For each test case in a separate line, output: YES, if suitable food can be bought for each of $$$x$$$ dogs and for each of $$$y$$$ cats; NO else. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).", "sample_inputs": ["7\n\n1 1 4 2 3\n\n0 0 0 0 0\n\n5 5 0 4 6\n\n1 1 1 1 1\n\n50000000 50000000 100000000 100000000 100000000\n\n0 0 0 100000000 100000000\n\n1 3 2 2 5"], "sample_outputs": ["YES\nYES\nNO\nYES\nYES\nNO\nNO"], "notes": null}, "positive_code": [{"source_code": "let nextInt () = Scanf.scanf \" %d\" (fun x->x);;\r\nlet nextTestCase () = \r\n let a=nextInt () in\r\n let b=nextInt () in\r\n let c=nextInt () in\r\n let x=nextInt () in\r\n let y=nextInt () in\r\n a, b, c, x, y\r\n;;\r\nlet rec enoughFood = function\r\n | a,b,c,0,y->\r\n if (b+c>=y) then true\r\n else false\r\n | a,b,c,x,y->\r\n if (a>=x) then enoughFood ((a-x),b,c,0,y)\r\n else if (a+c>=x) then enoughFood (0,b,(a+c-x),0,y)\r\n else false\r\n;;\r\nlet rec getResults = function\r\n | 0 -> 0\r\n | n ->\r\n let hasEnough=enoughFood (nextTestCase ()) in\r\n if (hasEnough) then begin\r\n print_string \"YES\\n\";\r\n getResults (n-1)\r\n end\r\n else begin\r\n print_string \"NO\\n\";\r\n getResults (n-1)\r\n end\r\n;;\r\nlet test_cases = nextInt() in\r\ngetResults test_cases\r\n;;\r\n "}], "negative_code": [], "src_uid": "7ac27da2546a50d453f7bb6cacef1068"} {"nl": {"description": "There are n cities situated along the main road of Berland. Cities are represented by their coordinates \u2014 integer numbers a1,\u2009a2,\u2009...,\u2009an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money \u2014 he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.", "input_spec": "The first line contains one integer number n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The second line contains n integer numbers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109). All numbers ai are pairwise distinct.", "output_spec": "Print two integer numbers \u2014 the minimal distance and the quantity of pairs with this distance.", "sample_inputs": ["4\n6 -3 0 4", "3\n-2 0 2"], "sample_outputs": ["2 1", "2 2"], "notes": "NoteIn the first example the distance between the first city and the fourth city is |4\u2009-\u20096|\u2009=\u20092, and it is the only pair with this distance."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0L in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s)\n done;\n Array.sort compare a;\n in\n let md = ref 2000000001L in\n let mc = ref 0 in\n for i = 0 to n - 2 do\n let d = Int64.abs (a.(i) -| a.(i + 1)) in\n\tif d < !md then (\n\t md := d;\n\t mc := 1;\n\t) else if d = !md then (\n\t incr mc\n\t)\n done;\n Printf.printf \"%Ld %d\\n\" !md !mc\n"}], "negative_code": [], "src_uid": "5f89678ae1deb1d9eaafaab55a64197f"} {"nl": {"description": "Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar \"Jupiter\". According to the sweepstake rules, each wrapping has an integer written on it \u2014 the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy \u2014 as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost): a mug (costs a points), a towel (costs b points), a bag (costs c points), a bicycle (costs d points), a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1,\u2009p2,\u2009...,\u2009pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009109). The third line contains 5 integers a, b, c, d, e (1\u2009\u2264\u2009a\u2009<\u2009b\u2009<\u2009c\u2009<\u2009d\u2009<\u2009e\u2009\u2264\u2009109) \u2014 the prizes' costs.", "output_spec": "Print on the first line 5 integers, separated by a space \u2014 the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer \u2014 the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["3\n3 10 4\n2 4 10 15 20", "4\n10 4 39 2\n3 5 10 11 12"], "sample_outputs": ["1 1 1 0 0 \n1", "3 0 1 0 3 \n0"], "notes": "NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3\u2009-\u20092\u2009+\u200910\u2009-\u200910\u2009+\u20094\u2009-\u20094\u2009=\u20091 points remains."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet (--) debut fin =\n let rec range aux start en =\n if start > en then aux\n else range (en::aux) start (en-1)\n in range [] debut fin;;\n\nlet res = Array.make 6 Int64.zero;;\n\ntype lot = {\n index: int;\n value: int64;\n}\n\nlet best_index tabl money =\n List.find (fun el -> el.value <= money) tabl;;\n\nlet rec process_data lots arr money = \n match best_index lots money with\n | {index = 5; value = _} -> begin\n match arr with \n | [] -> money\n | head :: tail ->\n process_data lots tail (Int64.add money head)\n end\n | won ->\n res.(won.index) <- Int64.add res.(won.index) (Int64.div money won.value);\n process_data lots arr (Int64.rem money won.value);;\n\n(*#trace process_data;;*)\n\nlet taille = read_int () in\nlet input = (1 -- taille) \n |> List.map (fun _ -> Int64.of_int (read_int ())) in\nlet lots = ({index = 5; value = Int64.zero} ::\n ((0 -- 4) \n |> List.map (fun i -> {index = i; value = Int64.of_int (read_int ())})))\n |> List.sort (fun x y -> compare y.value x.value) in\nlet money_left = process_data lots input Int64.zero in\nfor i = 0 to 4 do\n Printf.printf \"%s \" (Int64.to_string res.(i))\ndone;\nPrintf.printf \"\\n%s\\n\" (Int64.to_string money_left);;\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet (--) debut fin =\n let rec range aux start en =\n if start > en then aux\n else range (en::aux) start (en-1)\n in range [] debut fin;;\n\nlet res = Array.make 6 0;;\n\ntype lot = {\n index: int;\n value: int;\n}\n\nlet best_index tabl money =\n List.find (fun el -> el.value <= money) tabl;;\n\nlet rec process_data lots arr money = \n match best_index lots money with\n | {index = 5; value = _} -> begin\n match arr with \n | [] -> money\n | head :: tail ->\n process_data lots tail (money + head)\n end\n | won ->\n res.(won.index) <- res.(won.index) + (money / won.value);\n process_data lots arr (money mod won.value);;\n\n(*#trace process_data;;*)\n\nlet taille = read_int () in\nlet input = (1 -- taille) \n |> List.map (fun _ -> read_int ()) in\nlet lots = ({index = 5; value = 0} ::\n ((0 -- 4) \n |> List.map (fun i -> {index = i; value = read_int ()})))\n |> List.sort (fun x y -> compare y.value x.value) in\nlet money_left = process_data lots input 0 in\nfor i = 0 to 4 do\n Printf.printf \"%d \" res.(i)\ndone;\nPrintf.printf \"\\n%d\\n\" money_left;;\n"}], "src_uid": "1ae2942b72ebb7c55359c41e141900d7"} {"nl": {"description": "NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles $$$n$$$ and the radius of the inner circle $$$r$$$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $$$R$$$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture.", "input_spec": "The first and the only line of the input file contains two numbers $$$n$$$ and $$$r$$$ ($$$3 \\leq n \\leq 100$$$, $$$1 \\leq r \\leq 100$$$)\u00a0\u2014 the number of the outer circles and the radius of the inner circle respectively.", "output_spec": "Output a single number $$$R$$$\u00a0\u2014 the radius of the outer circle required for building the required picture. Your answer will be accepted if its relative or absolute error does not exceed $$$10^{-6}$$$. Formally, if your answer is $$$a$$$ and the jury's answer is $$$b$$$. Your answer is accepted if and only when $$$\\frac{|a-b|}{max(1, |b|)} \\le 10^{-6}$$$.", "sample_inputs": ["3 1", "6 1", "100 100"], "sample_outputs": ["6.4641016", "1.0000000", "3.2429391"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_float _ = bscanf Scanning.stdib \" %f \" (fun x -> x)\n\nlet () =\n let n = read_float () and r = read_float () in\n let pi = acos (-1.) in\n let x = sin (pi /. n) in\n let ans = r *. x /. (1. -. x) in\n printf \"%f\\n\" ans"}, {"source_code": "let ( ** ) = Pervasives.( ** )\nlet pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328;;\nScanf.scanf \" %f %f\" @@ fun n r ->\n let u = pi /. (2. *. n) in\n let q = (sin u -. cos u) ** 2. in\n let p = r *. sin (pi /. n) in\n Printf.printf \"%.18f\" @@ p /. q"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)\n let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328\nlet () =\n let n,r = g2 0 in\n let u = (pi /. (2.*.(Int64.to_float n))) in\n let q = (sin u -. cos u) ** 2. in\n let p = (Int64.to_float r) *. sin (pi /. (Int64.to_float n))\n in\n printf \"%.18f\" @@ p /. q\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_float _ = bscanf Scanning.stdib \" %f \" (fun x -> x)\n\nlet pi = 2.0 *. (atan2 1.0 0.0)\n \nlet () =\n let n = read_int() in\n let r0 = read_float() in\n\n let alpha = pi /. (float n) in\n let salpha = sin alpha in\n\n let r = salpha /. (1.0 -. salpha) in\n\n printf \"%.8f\\n\" (r0 *. r)\n"}], "negative_code": [], "src_uid": "e27cff5d681217460d5238bf7ef6a876"} {"nl": {"description": "In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it \u2014 a and b. The order of the numbers is not important. Let's consider a\u2009\u2264\u2009b for the sake of definiteness. The players can cast one of the two spells in turns: Replace b with b\u2009-\u2009ak. Number k can be chosen by the player, considering the limitations that k\u2009>\u20090 and b\u2009-\u2009ak\u2009\u2265\u20090. Number k is chosen independently each time an active player casts a spell. Replace b with b\u00a0mod\u00a0a. If a\u2009>\u2009b, similar moves are possible.If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses.To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second.", "input_spec": "The first line contains a single integer t \u2014 the number of input data sets (1\u2009\u2264\u2009t\u2009\u2264\u2009104). Each of the next t lines contains two integers a, b (0\u2009\u2264\u2009a,\u2009b\u2009\u2264\u20091018). The numbers are separated by a space. Please do not use the %lld specificator to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specificator.", "output_spec": "For any of the t input sets print \"First\" (without the quotes) if the player who moves first wins. Print \"Second\" (without the quotes) if the player who moves second wins. Print the answers to different data sets on different lines in the order in which they are given in the input. ", "sample_inputs": ["4\n10 21\n31 10\n0 1\n10 30"], "sample_outputs": ["First\nSecond\nSecond\nFirst"], "notes": "NoteIn the first sample, the first player should go to (11,10). Then, after a single move of the second player to (1,10), he will take 10 modulo 1 and win.In the second sample the first player has two moves to (1,10) and (21,10). After both moves the second player can win.In the third sample, the first player has no moves.In the fourth sample, the first player wins in one move, taking 30 modulo 10."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let cases = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for ca = 1 to cases do\n let a = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let a = max a b\n and b = min a b in\n let rec solve a b =\n\tif b = 0L\n\tthen false\n\telse if b = 1L\n\tthen true\n\telse (\n\t let s = solve b (Int64.rem a b) in\n\t if not s\n\t then true\n\t else (\n\t let a = Int64.div a b in\n\t\tInt64.rem (Int64.rem a (Int64.add b 1L)) 2L = 0L\n\t )\n\t)\n in\n\tif solve a b\n\tthen Printf.printf \"First\\n\"\n\telse Printf.printf \"Second\\n\"\n done\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let cases = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for ca = 1 to cases do\n let a = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let a = max a b\n and b = min a b in\n let rec solve a b =\n\tif b = 0L\n\tthen false\n\telse if b = 1L\n\tthen true\n\telse (\n\t let s = solve b (Int64.rem a b) in\n\t if not s\n\t then true\n\t else (\n\t let a = ref (Int64.div a b) in\n\t let sum = ref 0 in\n\t\twhile !a > 0L do\n\t\t if Int64.rem (Int64.rem !a b) 2L <> 0L\n\t\t then incr sum;\n\t\t a := Int64.div !a b\n\t\tdone;\n\t\tif !sum mod 2 <> 0\n\t\tthen false\n\t\telse true\n\t )\n\t)\n in\n\tif solve a b\n\tthen Printf.printf \"First\\n\"\n\telse Printf.printf \"Second\\n\"\n done\n"}], "src_uid": "5f5b320c7f314bd06c0d2a9eb311de6c"} {"nl": {"description": "As Famil Door\u2019s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings!The sequence of round brackets is called valid if and only if: the total number of opening brackets is equal to the total number of closing brackets; for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets. Gabi bought a string s of length m (m\u2009\u2264\u2009n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p\u2009+\u2009s\u2009+\u2009q, that is add the string p at the beginning of the string s and string q at the end of the string s.Now he wonders, how many pairs of strings p and q exists, such that the string p\u2009+\u2009s\u2009+\u2009q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 109\u2009+\u20097.", "input_spec": "First line contains n and m (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u2009n\u2009-\u2009m\u2009\u2264\u20092000)\u00a0\u2014 the desired length of the string and the length of the string bought by Gabi, respectively. The second line contains string s of length m consisting of characters '(' and ')' only.", "output_spec": "Print the number of pairs of string p and q such that p\u2009+\u2009s\u2009+\u2009q is a valid sequence of round brackets modulo 109\u2009+\u20097.", "sample_inputs": ["4 1\n(", "4 4\n(())", "4 3\n((("], "sample_outputs": ["4", "1", "0"], "notes": "NoteIn the first sample there are four different valid pairs: p\u2009=\u2009\"(\", q\u2009=\u2009\"))\" p\u2009=\u2009\"()\", q\u2009=\u2009\")\" p\u2009=\u2009\"\", q\u2009=\u2009\"())\" p\u2009=\u2009\"\", q\u2009=\u2009\")()\" In the second sample the only way to obtain a desired string is choose empty p and q.In the third sample there is no way to get a valid sequence of brackets."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet p = 1_000_000_007L\nlet long x = Int64.of_int x\nlet ( %% ) a b = Int64.rem a b\nlet ( ** ) a b = (Int64.mul a b) %% p\nlet ( ++ ) a b = let x = Int64.add a b in if x

j then ac else sum (i+1) j f (ac ++ (f i))\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let m = read_int () in \n let s = read_string () in\n\n let len = n-m in\n let offs = n-m in\n let count = Array.make_matrix (len+1) (offs+1) 0L in\n\n count.(0).(0) <- 1L;\n for i=0 to offs-1 do\n for j = 0 to offs do\n let c = count.(i).(j) in\n if j+1 <= offs then count.(i+1).(j+1) <- count.(i+1).(j+1) ++ c;\n if j-1 >= 0 then count.(i+1).(j-1) <- count.(i+1).(j-1) ++ c;\n done \n done;\n\n let rec counts i delta depth = if i = m then (delta,depth) else\n let delta = delta + (if s.[i] = '(' then 1 else -1) in\n let depth = max depth (-delta) in\n counts (i+1) delta depth\n in\n\n let (delta, dlr) = counts 0 0 0 in\n let drl = max 0 (dlr + delta) in\n\n let lo = max (max 0 (drl - delta)) (max (-delta) dlr) in\n let hi = min offs (offs - delta) in\n\n let answer = sum 0 len (fun i ->\n sum lo hi (fun p -> count.(i).(p) ** count.(len-i).(p+delta)) 0L\n ) 0L in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "ea6f55b3775076fcba6554b743b1a8ae"} {"nl": {"description": "Let $$$n$$$ be an integer. Consider all permutations on integers $$$1$$$ to $$$n$$$ in lexicographic order, and concatenate them into one big sequence $$$p$$$. For example, if $$$n = 3$$$, then $$$p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$$$. The length of this sequence will be $$$n \\cdot n!$$$.Let $$$1 \\leq i \\leq j \\leq n \\cdot n!$$$ be a pair of indices. We call the sequence $$$(p_i, p_{i+1}, \\dots, p_{j-1}, p_j)$$$ a subarray of $$$p$$$. Its length is defined as the number of its elements, i.e., $$$j - i + 1$$$. Its sum is the sum of all its elements, i.e., $$$\\sum_{k=i}^j p_k$$$. You are given $$$n$$$. Find the number of subarrays of $$$p$$$ of length $$$n$$$ having sum $$$\\frac{n(n+1)}{2}$$$. Since this number may be large, output it modulo $$$998244353$$$ (a prime number). ", "input_spec": "The only line contains one integer $$$n$$$\u00a0($$$1 \\leq n \\leq 10^6$$$), as described in the problem statement.", "output_spec": "Output a single integer\u00a0\u2014 the number of subarrays of length $$$n$$$ having sum $$$\\frac{n(n+1)}{2}$$$, modulo $$$998244353$$$.", "sample_inputs": ["3", "4", "10"], "sample_outputs": ["9", "56", "30052700"], "notes": "NoteIn the first sample, there are $$$16$$$ subarrays of length $$$3$$$. In order of appearance, they are:$$$[1, 2, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 3]$$$, $$$[1, 3, 2]$$$, $$$[3, 2, 2]$$$, $$$[2, 2, 1]$$$, $$$[2, 1, 3]$$$, $$$[1, 3, 2]$$$, $$$[3, 2, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 3]$$$, $$$[1, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[1, 2, 3]$$$, $$$[2, 3, 2]$$$, $$$[3, 2, 1]$$$. Their sums are $$$6$$$, $$$6$$$, $$$7$$$, $$$6$$$, $$$7$$$, $$$5$$$, $$$6$$$, $$$6$$$, $$$8$$$, $$$6$$$, $$$7$$$, $$$5$$$, $$$6$$$, $$$6$$$, $$$7$$$, $$$6$$$. As $$$\\frac{n(n+1)}{2} = 6$$$, the answer is $$$9$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet a = make 1000010 0L\nlet b = make 1000010 0L\nlet md = 998244353L\nlet () =\n let n = gi 0 in\n if n<=2L then printf \"%Ld\\n\" n\n else (\n a.(1) <- n;\n a.(2) <- (n*(n-2L)) mod md;\n repi 3 (i32 n) (fun i ->\n b.(i) <- (i64 i * i64 (i-$2)) mod md\n );\n let pw = ref 1L in\n repi 3 (i32 n) (fun i ->\n pw := (!pw * (n-i64 i+3L)) mod md;\n a.(i) <- (!pw * b.(i32 n -$ i +$ 2)) mod md;\n );\n let s = ref 0L in\n repi 1 (2+$i32 n) (fun i ->\n s := ((!s + (i64 i * a.(i)) mod md) mod md);\n );\n printf \"%Ld\\n\" !s;\n )\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "9d4caff95ab182055f83c79dd88e599a"} {"nl": {"description": "A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n\u2009-\u20091 the inequality |hi\u2009-\u2009hi\u2009+\u20091|\u2009\u2264\u20091 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi\u2009-\u2009hi\u2009+\u20091|\u2009\u2264\u20091.", "input_spec": "The first line contains two space-separated numbers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009108, 1\u2009\u2264\u2009m\u2009\u2264\u2009105)\u00a0\u2014 the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1\u2009\u2264\u2009di\u2009\u2264\u2009n, 0\u2009\u2264\u2009hdi\u2009\u2264\u2009108)\u00a0\u2014 the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m\u2009-\u20091 the following condition holds: di\u2009<\u2009di\u2009+\u20091.", "output_spec": "If the notes aren't contradictory, print a single integer \u2014 the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).", "sample_inputs": ["8 2\n2 0\n7 0", "8 3\n2 0\n7 0\n8 3"], "sample_outputs": ["2", "IMPOSSIBLE"], "notes": "NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0,\u20090,\u20091,\u20092,\u20091,\u20091,\u20090,\u20091).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let m = read_int () in\n let dh = Array.init m (fun _ -> read_pair()) in\n\n let rec checkpairs i best = if i=m-1 then best else (\n (* check dh.(i) and dh.(i+1) *)\n let (t1,h1) = dh.(i) in\n let (t2,h2) = dh.(i+1) in\n let (h1, h2) = (min h1 h2, max h1 h2) in\n let dt = t2 - t1 in\n let dh = h2 - h1 in\n if dh > dt then -1 else (\n let e = dt - dh in\n let this_height = h2 + (e/2) in\n checkpairs (i+1) (max best this_height)\n )\n )\n in\n\n let best = checkpairs 0 0 in\n\n if best = -1 then printf \"IMPOSSIBLE\\n\" else (\n let (t0,h0) = dh.(0) in\n let (tl,hl) = dh.(m-1) in\n\n let opt0 = h0 + (t0-1) in\n let opt1 = hl + (n-tl) in\n \n printf \"%d\\n\" (max best (max opt0 opt1))\n )\n"}], "negative_code": [], "src_uid": "77b5bed410d621fb56c2eaebccff5108"} {"nl": {"description": "All cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the responsibility of a special seating program. It was found out that the large majority of Berland's inhabitants go to the cinema in order to watch a movie, that's why they want to sit as close to the hall center as possible. Moreover, a company of M people, who come to watch a movie, want necessarily to occupy M successive seats in one row. Let's formulate the algorithm, according to which the program chooses seats and sells tickets. As the request for M seats comes, the program should determine the row number x and the segment [yl,\u2009yr] of the seats numbers in this row, where yr\u2009-\u2009yl\u2009+\u20091\u2009=\u2009M. From all such possible variants as a final result the program should choose the one with the minimum function value of total seats remoteness from the center. Say, \u2014 the row and the seat numbers of the most \"central\" seat. Then the function value of seats remoteness from the hall center is . If the amount of minimum function values is more than one, the program should choose the one that is closer to the screen (i.e. the row number x is lower). If the variants are still multiple, it should choose the one with the minimum yl. If you did not get yet, your task is to simulate the work of this program. ", "input_spec": "The first line contains two integers N and K (1\u2009\u2264\u2009N\u2009\u2264\u20091000,\u20091\u2009\u2264\u2009K\u2009\u2264\u200999) \u2014 the amount of requests and the hall size respectively. The second line contains N space-separated integers Mi from the range [1,\u2009K] \u2014 requests to the program.", "output_spec": "Output N lines. In the i-th line output \u00ab-1\u00bb (without quotes), if it is impossible to find Mi successive seats in one row, otherwise output three numbers x,\u2009yl,\u2009yr. Separate the numbers with a space.", "sample_inputs": ["2 1\n1 1", "4 3\n1 2 3 1"], "sample_outputs": ["1 1 1\n-1", "2 2 2\n1 1 2\n3 1 3\n2 1 1"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let a = Array.make_matrix m m false in\n for cc = 1 to n do\n let x = read_int 0 in\n let rec go i j (anss,ansi,ansj as ans) =\n if i = m then\n ans\n else if j > m-x then\n go (i+1) 0 ans\n else\n let rec go2 jj s =\n if jj-j = x then\n true,s+(abs (m/2-i) * x)\n else if a.(i).(jj) then\n false,0\n else\n go2 (jj+1) (s + abs (m/2-jj))\n in\n let ok,s = go2 j 0 in\n if ok then\n go i (j+1) (min (s,i,j) ans)\n else\n go i (j+1) ans\n in\n let anss,ansi,ansj = go 0 0 (max_int,-1,-1) in\n if anss = max_int then\n print_endline \"-1\"\n else (\n for j = ansj to ansj+x-1 do\n a.(ansi).(j) <- true\n done;\n Printf.printf \"%d %d %d\\n\" (ansi+1) (ansj+1) (ansj+x)\n )\n done\n"}], "negative_code": [], "src_uid": "2db7891a2fa4e78fd9d145304a36b9aa"} {"nl": {"description": "In Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of \"aaaa\", \"aa\", \"aaa\" is \"a\", the root of \"aabb\", \"bab\", \"baabb\", \"ab\" is \"ab\". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^3$$$)\u00a0\u2014 the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \\ldots, s_n$$$\u00a0\u2014 the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.", "output_spec": "Output one integer\u00a0\u2014 the number of different objects mentioned in the given ancient Aramic script.", "sample_inputs": ["5\na aa aaa ab abb", "3\namer arem mrea"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first test, there are two objects mentioned. The roots that represent them are \"a\",\"ab\".In the second test, there is only one object, its root is \"amer\", the other strings are just permutations of \"amer\"."}, "positive_code": [{"source_code": "\nmodule SetChar = Set.Make(struct\n type t = char\n let compare = Char.compare\n end)\n\nmodule SetRoot = Set.Make(SetChar)\n\nlet list_init n f =\n Array.init n f |> Array.to_list\n\nlet string_to_list (src: string): char list =\n let ret = ref [] in\n String.iter (fun c -> ret := c :: !ret) src;\n !ret\n\nlet rootize word =\n string_to_list word |> SetChar.of_list\n\nlet () =\n let n = Scanf.scanf \"%d \" (fun i -> i) in\n let words = list_init n (fun i -> Scanf.scanf \" %s\" (fun i -> i)) in\n let roots = List.map rootize words in\n let set_roots = SetRoot.of_list roots in\n SetRoot.cardinal set_roots |> string_of_int |> print_endline\n"}], "negative_code": [], "src_uid": "cf1eb164c4c970fd398ef9e98b4c07b1"} {"nl": {"description": "Vasiliy lives at point (a,\u2009b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi,\u2009yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.", "input_spec": "The first line of the input contains two integers a and b (\u2009-\u2009100\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009100)\u00a0\u2014 coordinates of Vasiliy's home. The second line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of available Beru-taxi cars nearby. The i-th of the following n lines contains three integers xi, yi and vi (\u2009-\u2009100\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009100, 1\u2009\u2264\u2009vi\u2009\u2264\u2009100)\u00a0\u2014 the coordinates of the i-th car and its speed. It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.", "output_spec": "Print a single real value\u00a0\u2014 the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["0 0\n2\n2 0 1\n0 2 2", "1 3\n3\n3 3 2\n-2 3 6\n-2 7 10"], "sample_outputs": ["1.00000000000000000000", "0.50000000000000000000"], "notes": "NoteIn the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.In the second sample, cars 2 and 3 will arrive simultaneously."}, "positive_code": [{"source_code": "let expon\n= fun x1 x2 ->\n let foi = float_of_int in\n (foi (x1 - x2)) ** 2.0\n\nlet distance\n= fun (x1, y1) (x2, y2) ->\n sqrt ((expon x1 x2) +. (expon y1 y2))\n\nlet _\n= let a, b = Scanf.scanf \"%d %d\\n\" (fun x y -> (x, y)) in\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let oneCase : unit -> float\n = fun () ->\n let x, y, v = Scanf.scanf \"%d %d %d\\n\" (fun x y z -> (x, y, z)) in\n (distance (a, b) (x, y)) /. (float_of_int v)\n in\n let firstCase = oneCase () in\n let rec minmin : int -> float -> float\n = fun i m ->\n if i <= 0 then m\n else(\n let mm = min m (oneCase ()) in\n minmin (i - 1) mm\n )\n in\n let mmmm = (minmin (n - 1) firstCase) in\n Printf.printf \"%.9f\" mmmm"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet ( -- ) (x1,y1) (x2,y2) = (x1-.x2, y1-.y2)\nlet ( ++ ) (x1,y1) (x2,y2) = (x1+.x2, y1+.y2) \nlet len (x,y) = sqrt(x*.x +. y*.y)\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let a = float (read_int()) in\n let b = float (read_int()) in \n let n = read_int () in\n let data = Array.init n (fun _ ->\n let x = float (read_int()) in\n let y = float (read_int()) in\n let v = float (read_int()) in\n ((x,y),v)\n ) in\n\n let answer = minf 0 (n-1) (fun i ->\n let (p,v) = data.(i) in\n let d = len (p -- (a,b)) in\n d /. v\n ) in\n\n printf \"%.20f\\n\" answer\n"}], "negative_code": [{"source_code": "type point = (int * int)\n\nlet taxi_distance : point -> point -> int\n= fun (x1, y1) (x2, y2) -> (abs (x1 - x2)) + (abs (y1 - y2))\n\n\nlet _\n= let a, b = Scanf.scanf \"%d %d\\n\" (fun x y -> (x, y)) in\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let oneCase : unit -> float\n = fun () ->\n let x, y, v = Scanf.scanf \"%d %d %d\\n\" (fun x y z -> (x, y, z)) in\n (taxi_distance (a, b) (x, y) |> float_of_int) /. (float_of_int v)\n in\n let firstCase = oneCase () in\n let rec minmin : int -> float -> float\n = fun i m ->\n if i <= 0 then m\n else(\n let mm = min m (oneCase ()) in\n minmin (i - 1) mm\n )\n in\n let mmmm = (minmin (n - 1) firstCase) in\n Printf.printf \"%.9f\" mmmm\n"}, {"source_code": "type point = (int * int)\n\nlet taxi_distance : point -> point -> int\n= fun (x1, y1) (x2, y2) -> (abs (x1 - x2)) + (abs (y1 - y2))\n\n\nlet _\n= let a, b = Scanf.scanf \"%d %d\\n\" (fun x y -> (x, y)) in\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let oneCase : unit -> float\n = fun () ->\n let x, y, v = Scanf.scanf \"%d %d %d\\n\" (fun x y z -> (x, y, z)) in\n (taxi_distance (a, b) (x, y) |> float_of_int) /. (float_of_int v)\n in\n let firstCase = oneCase () in\n let rec minmin : int -> float -> float\n = fun i m ->\n if i <= 0 then m\n else(\n let mm = min m (oneCase ()) in\n minmin (i - 1) mm\n )\n in\n let mmmm = (minmin (n - 1) firstCase) in\n Printf.printf \"%.12f\" mmmm"}], "src_uid": "a74c65acd41ff9bb845062222135c60a"} {"nl": {"description": "Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai\u2009>\u20090, then ai bourles are deposited to Luba's account. If ai\u2009<\u20090, then ai bourles are withdrawn. And if ai\u2009=\u20090, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be \u00ab-1\u00bb.Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai\u2009=\u20090) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!", "input_spec": "The first line contains two integers n, d (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009d\u2009\u2264\u2009109) \u2014the number of days and the money limitation. The second line contains n integer numbers a1,\u2009a2,\u2009... an (\u2009-\u2009104\u2009\u2264\u2009ai\u2009\u2264\u2009104), where ai represents the transaction in i-th day.", "output_spec": "Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.", "sample_inputs": ["5 10\n-1 5 0 -5 3", "3 4\n-10 0 20", "5 10\n-5 0 10 -11 0"], "sample_outputs": ["0", "-1", "2"], "notes": null}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\ntype 'a pri_queue =\nNode of 'a * 'a pri_queue * 'a pri_queue * int |\nNull\nexception Empty_Queue \nlet empty_queue = Null\nlet is_empty q = q = Null\nlet size q =\nmatch q with\nNull ->0 |\nNode (_,_,_,n) ->n\nlet getmax h =\nmatch h with\nNull ->raise Empty_Queue |\nNode (r,_,_,_) -> r\nlet set_root h r =\nmatch h with\n\nNull ->Node (r,Null,Null,1) |\nNode (_,l,p,n) ->Node (r,l,p,n)\nlet rec put h x =\nmatch h with\nNull ->Node (x,Null,Null,1) |\nNode (r,l,p,n) ->\nif size l <= size p then\nNode((max x r),(put l (min x r)),p,(n+1))\nelse\nNode((max x r),l,(put p (min x r)),(n+1))\nlet rec removemax h =\nmatch h with\nNull ->raise Empty_Queue |\nNode (_,Null,Null,_) ->Null |\nNode (_,l,Null,_) ->l |\nNode (_,Null,p,_) ->p |\nNode (_,(Node (rl,_,_,_) as l),\n(Node (rp,_,_,_) as p),n) ->\nif rl >= rp then\nNode (rl,removemax l,p,n - 1)\nelse\nNode (rp,l,removemax p,n - 1);;\nlet n = scan_int() and d= scan_int() and czy = ref 1 and dodaj = ref 0 and wyn = ref 0 and sum = ref 0 and q = ref empty_queue in\nlet tb = Array.make (n+1) 0 in\nbegin\n for i=1 to n do \n tb.(i) <- scan_int();\n sum := !sum + tb.(i); \n q := put !q (!sum, i)\n done;\n sum := 0;\n for i=1 to n do \n if tb.(i) <> 0 then sum := !sum + tb.(i)\n else if !sum < 0 then begin\n let a = ref (getmax !q) in \n while (snd(!a)) < i do q := removemax !q; a := getmax !q done;\n wyn := !wyn +1; \n sum := !sum + (d - (fst(!a)) - !dodaj); \n dodaj := d - fst(!a);\n if !sum < 0 then czy := 0 end;\n if !sum > d then czy := 0\n done;\n if !czy = 0 then print_int (-1)\n else print_int (!wyn)\nend\n\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int () and d = scan_int();;\n\nlet x = Array.make n 0 and lim = Array.make n Int32.zero;;\nlet sumek = ref Int32.zero;;\n\nfor i = 0 to n - 1 do\n x.(i) <- scan_int();\n sumek := Int32.add !sumek (Int32.of_int x.(i));\n lim.(i) <- Int32.sub (Int32.of_int d) (!sumek);\ndone;;\n\n\nfor i = n - 2 downto 0 do\n lim.(i) <- min lim.(i) lim.(i + 1);\ndone;;\n\nlet koncz () = \n print_string(\"-1\");\n exit 0;;\n\nif lim.(0) < Int32.zero then koncz();;\n\nlet wyn = ref 0 and dod = ref Int32.zero;;\nsumek := Int32.zero;\nfor i = 0 to n - 1 do\n if x.(i) == 0 && Int32.add !sumek !dod < Int32.zero then begin\n dod := lim.(i);\n incr wyn;\n if Int32.add !sumek !dod < Int32.zero then koncz();\n end;\n sumek := Int32.add !sumek (Int32.of_int x.(i));\ndone;;\n\nprint_int !wyn;;\n\n(*\n4 1000000000\n-100 0 -250000000 0\n*)\n"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int () and d = scan_int();;\n\nlet x = Array.make n 0 and lim = Array.make n 0;;\nlet sumek = ref 0;;\n\nfor i = 0 to n - 1 do\n x.(i) <- scan_int();\n sumek := !sumek + x.(i);\n lim.(i) <- d - !sumek;\ndone;;\n\n\nfor i = n - 2 downto 0 do\n lim.(i) <- min lim.(i) lim.(i + 1);\ndone;;\n\nlet koncz () = \n print_string(\"-1\");\n exit 0;;\n\nif lim.(0) < 0 then koncz();;\n\nlet wyn = ref 0 and dod = ref 0;;\nsumek := 0;\nfor i = 0 to n - 1 do\n if x.(i) == 0 && !sumek + !dod < 0 then begin\n dod := lim.(i);\n incr wyn;\n if !sumek + !dod < 0 then koncz();\n end;\n sumek := !sumek + x.(i);\ndone;;\n\nprint_int !wyn;;\n\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int () and d = scan_int();;\n\nlet x = Array.make n 0 and lim = Array.make n 0;;\nlet sumek = ref 0;;\n\nfor i = 0 to n - 1 do\n x.(i) <- scan_int();\n sumek := !sumek + x.(i);\n lim.(i) <- max d (d - !sumek);\ndone;;\n\n\nfor i = n - 2 downto 0 do\n lim.(i) <- min lim.(i) lim.(i + 1);\ndone;;\n\nlet koncz () = \n print_string(\"-1\");\n exit 0;;\n\nif lim.(0) < 0 then koncz();;\n\nlet wyn = ref 0 and dod = ref 0;;\nsumek := 0;\nfor i = 0 to n - 1 do\n if x.(i) == 0 && !sumek + !dod < 0 then begin\n dod := lim.(i);\n incr wyn;\n if !sumek + !dod < 0 then koncz();\n end;\n sumek := !sumek + x.(i);\ndone;;\n\nprint_int !wyn;;\n\n(*\n4 1000000000\n-100 0 -250000000 0\n*)\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int () and d = scan_int();;\n\nlet x = Array.make n 0 and lim = Array.make n 0;;\nlet sumek = ref 0;;\n\nfor i = 0 to n - 1 do\n x.(i) <- scan_int();\n sumek := !sumek + x.(i);\n lim.(i) <- d - !sumek;\ndone;;\n\n\nfor i = n - 2 downto 0 do\n lim.(i) <- min lim.(i) lim.(i + 1);\ndone;;\n\nlet koncz =\n print_string(\"-1\");\n exit 0;;\n\nif lim.(0) < 0 then koncz\n\nlet wyn = ref 0 and dod = ref 0;;\nsumek := 0;\nfor i = 0 to n - 1 do\n if x.(i) == 0 && !sumek + !dod < 0 then begin\n dod := lim.(i);\n incr wyn;\n if !sumek + !dod < 0 then koncz\n end;\n sumek := !sumek + x.(i);\ndone;;\n\nprint_int !wyn;;\n\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int () and d = scan_int();;\n\nlet x = Array.make n 0 and lim = Array.make n 0;;\nlet sumek = ref 0;;\n\nfor i = 0 to n - 1 do\n x.(i) <- scan_int();\n sumek := !sumek + x.(i);\n lim.(i) <- min d (d - !sumek);\ndone;;\n\n\nfor i = n - 2 downto 0 do\n lim.(i) <- min lim.(i) lim.(i + 1);\ndone;;\n\nlet koncz () = \n print_string(\"-1\");\n exit 0;;\n\nif lim.(0) < 0 then koncz();;\n\nlet wyn = ref 0 and dod = ref 0;;\nsumek := 0;\nfor i = 0 to n - 1 do\n if x.(i) == 0 && !sumek + !dod < 0 then begin\n dod := lim.(i);\n incr wyn;\n if !sumek + !dod < 0 then koncz();\n end;\n sumek := !sumek + x.(i);\ndone;;\n\nprint_int !wyn;;\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int () and d = scan_int();;\n\nlet x = Array.make n 0 and lim = Array.make n 0;;\nlet sumek = ref 0;;\n\nfor i = 0 to n - 1 do\n x.(i) <- scan_int();\n sumek := !sumek + x.(i);\n lim.(i) <- d - !sumek;\ndone;;\n\n\nfor i = n - 2 downto 0 do\n lim.(i) <- min lim.(i) lim.(i + 1);\ndone;;\n\nlet wyn = ref 0 and dod = ref 0;;\nsumek := 0;\nfor i = 0 to n - 1 do\n if x.(i) == 0 && !sumek + !dod < 0 then begin\n dod := lim.(i);\n incr wyn;\n if !sumek + !dod < 0 then begin\n print_string(\"-1\");\n exit 0;\n end;\n end;\n sumek := !sumek + x.(i);\ndone;;\n\nprint_int !wyn;;\n\n"}], "src_uid": "c112321ea5e5603fd0c95c4f01808db1"} {"nl": {"description": "A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li,\u2009ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a,\u2009b] covers segment [c,\u2009d], if they meet this condition a\u2009\u2264\u2009c\u2009\u2264\u2009d\u2009\u2264\u2009b. ", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li,\u2009ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109) \u2014 the borders of the i-th segment. It is guaranteed that no two segments coincide.", "output_spec": "Print a single integer \u2014 the number of the segment that covers all other segments in the set. If there's no solution, print -1. The segments are numbered starting from 1 in the order in which they appear in the input.", "sample_inputs": ["3\n1 1\n2 2\n3 3", "6\n1 5\n2 3\n1 10\n7 10\n7 7\n10 10"], "sample_outputs": ["-1", "3"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 242B BigOtres done *)\n\nopen String;;\nopen Int64;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_string \" \"; print_int i)) li;;\nlet printarri ai = Array.iter (fun i -> (print_string \" \"; print_int i)) ai;;\nlet debug = false;;\n\nlet rec checkOtr i n mna mxb idx =\n\tif i > n then idx\n\telse \n\t\tlet a = grl() in \n\t\tlet b = grl() in\n\t\tif a <= mna && mxb <= b then checkOtr (i+1) n a b i\n\t\telse \n\t\t\tlet idx = if mna <= a && b <= mxb then idx else -1 in\n\t\t\tlet mna = min a mna in\n\t\t\tlet mxb = max b mxb in\n\t\t\tcheckOtr (i+1) n mna mxb idx;; \n\nlet main () =\n\tlet n = gr() in\n\tlet a = grl() in\n\tlet b = grl() in\n\tlet idx = checkOtr 2 n a b 1 in\n\tprint_int idx;;\n\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet () = \n let n = read_int() in\n let input = Array.init n \n (fun _ -> let l = read_int() in let r = read_int() in (l,r)) in\n let minleft = minf 0 (n-1) (fun i -> let (l,r)=input.(i) in l) in\n let maxright = maxf 0 (n-1) (fun i -> let (l,r)=input.(i) in r) in\n \n let rec findit i = if i=n then None else\n let (l,r) = input.(i) in\n if l<=minleft && r>=maxright then Some i else findit (i+1)\n in\n\n let ans = \n match findit 0 with\n |\tNone -> -1\n | Some i -> i+1\n in\n Printf.printf \"%d\\n\" ans\n"}], "negative_code": [], "src_uid": "e702594a8e993e135ea8ca78eb3ecd66"} {"nl": {"description": "DZY loves strings, and he enjoys collecting them.In China, many people like to use strings containing their names' initials, for example: xyz, jcvb, dzy, dyh.Once DZY found a lucky string s. A lot of pairs of good friends came to DZY when they heard about the news. The first member of the i-th pair has name ai, the second one has name bi. Each pair wondered if there is a substring of the lucky string containing both of their names. If so, they want to find the one with minimum length, which can give them good luck and make their friendship last forever.Please help DZY for each pair find the minimum length of the substring of s that contains both ai and bi, or point out that such substring doesn't exist.A substring of s is a string slsl\u2009+\u20091... sr for some integers l,\u2009r (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009|s|). The length of such the substring is (r\u2009-\u2009l\u2009+\u20091).A string p contains some another string q if there is a substring of p equal to q.", "input_spec": "The first line contains a string s (1\u2009\u2264\u2009|s|\u2009\u2264\u200950000). The second line contains a non-negative integer q (0\u2009\u2264\u2009q\u2009\u2264\u2009100000) \u2014 the number of pairs. Each of the next q lines describes a pair, the line contains two space-separated strings ai and bi (1\u2009\u2264\u2009|ai|,\u2009|bi|\u2009\u2264\u20094). It is guaranteed that all the strings only consist of lowercase English letters.", "output_spec": "For each pair, print a line containing a single integer \u2014 the minimum length of the required substring. If there is no such substring, output -1.", "sample_inputs": ["xudyhduxyz\n3\nxyz xyz\ndyh xyz\ndzy xyz", "abcabd\n3\na c\nab abc\nab d", "baabcabaaa\n2\nabca baa\naa aba"], "sample_outputs": ["3\n8\n-1", "2\n3\n3", "6\n4"], "notes": "NoteThe shortest substrings in the first sample are: xyz, dyhduxyz.The shortest substrings in the second sample are: ca, abc and abd.The shortest substrings in the third sample are: baabca and abaa."}, "positive_code": [{"source_code": "(* Sketch of my algorithm for this problem.\n \n Do a scan of the input string and compute for each query string a\n sorted list of the indices of the centers of these strings (the\n centers could be half integers so you probably double them to make\n them integers). Then convert these lists into arrays of indices\n (so we can do binary search on them).\n\n Now, answering a query consists of taking the two corresponding\n lists A and B, and finding the closest pair (a,b) where a is from A\n and b is from B. We can do this by different methods depending on\n the sizes A and B. If |A| and |B| are about equal, we can just do\n a linear scan to find the closest pair. If, say A is a lot smaller,\n then we can lookup each element of A in B using binary search.\n\n Also, we use a hash table to ensure that the same query is only\n analyzed once.\n\n Notice that the input string can contain at most 200K substrings of\n length 1,2,3, or 4. So the total length of all the lists computed\n above is at most 200K. The worst case will occur when there are\n about 500 query strings that occur about 500 times each. So each\n query will take O(1000) to analyze. So the whole algorithm is O(100M).\n\n Looking at the match editorial later (http://codeforces.com/blog/entry/12959).\n They give a running time of O(S Sqrt(Q)) which means O(50K * 300) =\n O(15M). But it loses at least a factor of four because they are\n consisering query strings of length at most 1. So I don't think\n the algorithm is actually different.\n\n*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet str_to_numb s = \n let n = String.length s in\n let rec loop i ac = if i=n then ac else\n loop (i+1) (26 * ac + (l2n s.[i]))\n in\n let code = loop 0 0 in\n code + [|0;26;26+26*26;26+26*26+26*26*26|].(n-1)\n\nlet () = \n let ns = (str_to_numb \"zzzz\") + 1 in\n let is_query = Array.make ns false in\n let s = read_string () in\n let n = String.length s in\n let q = read_int () in\n let query = Array.init q (\n fun _ -> \n let a = read_string() in\n let b = read_string() in\n let (a,b) = (min a b, max a b) in\n let (an,bn) = (str_to_numb a, str_to_numb b) in\n is_query.(an) <- true;\n is_query.(bn) <- true;\n (a,an,b,bn)\n ) in\n\n let indices = Array.make ns [] in\n\n for l=1 to 4 do\n for i=n-l downto 0 do\n let t = String.sub s i l in\n let index = 2*i + l - 1 in\n let tn = str_to_numb t in\n if is_query.(tn) then indices.(tn) <- index :: indices.(tn);\n done\n done;\n\n let index_arrays = Array.make ns [||] in\n for i=0 to ns-1 do\n if is_query.(i) then index_arrays.(i) <- Array.of_list indices.(i)\n done;\n\n let query_table = Hashtbl.create 10 in\n\n let rec log x = if x<=1 then 0 else 1 + (log (x lsr 1)) in\n\n let bsearch a b la lb = \n let rec bs x i j =\n (* ind hyp is i \n\tlet x = a.(l) in\n\tif x<=b.(0) then b.(0) - x else if x>=b.(lb-1) then x-b.(lb-1) else bs x 0 (lb-1)\n )\n in\n\n let linsearch a b la lb =\n let rec loop i j ac = if i=la || j=lb then ac\n else if a.(i) < b.(j) then loop (i+1) j (min ac (b.(j) - a.(i)))\n else if a.(i) > b.(j) then loop i (j+1) (min ac (a.(i) - b.(j)))\n else 0\n in\n loop 0 0 max_int\n in\n\n let solve_query a an b bn = \n let la = Array.length index_arrays.(an) in\n let lb = Array.length index_arrays.(bn) in\n let (la,lb,a,b,an,bn) = if la < lb then (la,lb,a,b,an,bn) else (lb,la,b,a,bn,an) in\n (* decide which will be faster: linear scan or binary search *)\n if la=0 || lb=0 then -1 else\n let do_bsearch = la * (log lb) <= la + lb in\n let centerdist = (if do_bsearch then bsearch else linsearch) index_arrays.(an) index_arrays.(bn) la lb in\n let (alen,blen) = (String.length a, String.length b) in\n let leftend = min (-alen) (-centerdist -blen) in\n let rightend = max alen (-centerdist + blen) in\n (rightend - leftend) / 2\n in\n \n for i=0 to q-1 do\n let (a,an,b,bn) = query.(i) in\n if Hashtbl.mem query_table (an,bn) \n then printf \"%d\\n\" (Hashtbl.find query_table (an,bn)) \n else \n let ans = solve_query a an b bn in\n Hashtbl.add query_table (an,bn) ans;\n printf \"%d\\n\" ans\n done;\n"}], "negative_code": [{"source_code": "(* Sketch of my algorithm for this problem.\n \n Do a scan of the input string and compute for each query string a\n sorted list of the indices of the centers of these strings (the\n centers could be half integers so you probably double them to make\n them integers). Then convert these lists into arrays of indices\n (so we can do binary search on them).\n\n Now, answering a query consists of taking the two corresponding\n lists A and B, and finding the closest pair (a,b) where a is from A\n and b is from B. We can do this by different methods depending on\n the sizes A and B. If |A| and |B| are about equal, we can just do\n a linear scan to find the closest pair. If, say A is a lot smaller,\n then we can lookup each element of A in B using binary search.\n\n Also, we use a hash table to ensure that the same query is only\n analyzed once.\n\n Notice that the input string can contain at most 200K substrings of\n length 1,2,3, or 4. So the total length of all the lists computed\n above is at most 200K. The worst case will occur when there are\n about 500 query strings that occur about 500 times each. So each\n query will take O(1000) to analyze. So the whole algorithm is O(100M).\n\n Looking at the match editorial later (http://codeforces.com/blog/entry/12959).\n They give a running time of O(S Sqrt(Q)) which means O(50K * 300) =\n O(15M). But it loses at least a factor of four because they are\n consisering query strings of length at most 1. So I don't think\n the algorithm is actually different.\n\n*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet str_to_numb s = \n let n = String.length s in\n let rec loop i ac = if i=n then ac else\n loop (i+1) (26 * ac + (l2n s.[i]))\n in\n loop 1 (1 + (l2n s.[0]))\n\nlet () = \n let ns = (str_to_numb \"zzzz\") + 1 in\n let is_query = Array.make ns false in\n let s = read_string () in\n let n = String.length s in\n let q = read_int () in\n let query = Array.init q (\n fun _ -> \n let a = read_string() in\n let b = read_string() in\n let (a,b) = (min a b, max a b) in\n let (an,bn) = (str_to_numb a, str_to_numb b) in\n is_query.(an) <- true;\n is_query.(bn) <- true;\n (a,an,b,bn)\n ) in\n\n let indices = Array.make ns [] in\n\n for l=1 to 4 do\n for i=n-l downto 0 do\n let t = String.sub s i l in\n let index = 2*i + l - 1 in\n let tn = str_to_numb t in\n if is_query.(tn) then indices.(tn) <- index :: indices.(tn);\n done\n done;\n\n let index_arrays = Array.make ns [||] in\n for i=0 to ns-1 do\n if is_query.(i) then index_arrays.(i) <- Array.of_list indices.(i)\n done;\n\n let query_table = Hashtbl.create 10 in\n\n let rec log x = if x<=1 then 0 else 1 + (log (x lsr 1)) in\n\n let bsearch a b la lb = \n let rec bs x i j =\n (* ind hyp is i \n\tlet x = a.(l) in\n\tif x<=b.(0) then b.(0) - x else if x>=b.(lb-1) then x-b.(lb-1) else bs x 0 (lb-1)\n )\n in\n\n let linsearch a b la lb =\n let rec loop i j ac = if i=la || j=lb then ac\n else if a.(i) < b.(j) then loop (i+1) j (min ac (b.(j) - a.(i)))\n else if a.(i) > b.(j) then loop i (j+1) (min ac (a.(i) - b.(j)))\n else 0\n in\n loop 0 0 max_int\n in\n\n let solve_query a an b bn = \n let la = Array.length index_arrays.(an) in\n let lb = Array.length index_arrays.(bn) in\n let (la,lb,a,b,an,bn) = if la < lb then (la,lb,a,b,an,bn) else (lb,la,b,a,bn,an) in\n (* decide which will be faster: linear scan or binary search *)\n if la=0 || lb=0 then -1 else\n let do_bsearch = la * (log lb) <= la + lb in\n(* let centerdist = (if do_bsearch then bsearch else linsearch) index_arrays.(an) index_arrays.(bn) la lb in *)\n let centerdist = linsearch index_arrays.(an) index_arrays.(bn) la lb in\n let (alen,blen) = (String.length a, String.length b) in\n let leftend = min (-alen) (-centerdist -blen) in\n let rightend = max alen (-centerdist + blen) in\n (rightend - leftend) / 2\n in\n \n for i=0 to q-1 do\n let (a,an,b,bn) = query.(i) in\n if Hashtbl.mem query_table (an,bn) \n then printf \"%d\\n\" (Hashtbl.find query_table (an,bn)) \n else \n let ans = solve_query a an b bn in\n Hashtbl.add query_table (an,bn) ans;\n printf \"%d\\n\" ans\n done;\n"}, {"source_code": "(* Sketch of my algorithm for this problem.\n \n Do a scan of the input string and compute for each query string a\n sorted list of the indices of the centers of these strings (the\n centers could be half integers so you probably double them to make\n them integers). Then convert these lists into arrays of indices\n (so we can do binary search on them).\n\n Now, answering a query consists of taking the two corresponding\n lists A and B, and finding the closest pair (a,b) where a is from A\n and b is from B. We can do this by different methods depending on\n the sizes A and B. If |A| and |B| are about equal, we can just do\n a linear scan to find the closest pair. If, say A is a lot smaller,\n then we can lookup each element of A in B using binary search.\n\n Also, we use a hash table to ensure that the same query is only\n analyzed once.\n\n Notice that the input string can contain at most 200K substrings of\n length 1,2,3, or 4. So the total length of all the lists computed\n above is at most 200K. The worst case will occur when there are\n about 500 query strings that occur about 500 times each. So each\n query will take O(1000) to analyze. So the whole algorithm is O(100M).\n\n Looking at the match editorial later (http://codeforces.com/blog/entry/12959).\n They give a running time of O(S Sqrt(Q)) which means O(50K * 300) =\n O(15M). But it loses at least a factor of four because they are\n consisering query strings of length at most 1. So I don't think\n the algorithm is actually different.\n\n*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet str_to_numb s = \n let n = String.length s in\n let rec loop i ac = if i=n then ac else\n loop (i+1) (26 * ac + (l2n s.[i]))\n in\n loop 1 (1 + (l2n s.[0]))\n\nlet () = \n let ns = (str_to_numb \"zzzz\") + 1 in\n let is_query = Array.make ns false in\n let s = read_string () in\n let n = String.length s in\n let q = read_int () in\n let query = Array.init q (\n fun _ -> \n let a = read_string() in\n let b = read_string() in\n let (a,b) = (min a b, max a b) in\n let (an,bn) = (str_to_numb a, str_to_numb b) in\n is_query.(an) <- true;\n is_query.(bn) <- true;\n (a,an,b,bn)\n ) in\n\n let indices = Array.make ns [] in\n\n for l=1 to 4 do\n for i=n-l downto 0 do\n let t = String.sub s i l in\n let index = 2*i + l - 1 in\n let tn = str_to_numb t in\n if is_query.(tn) then indices.(tn) <- index :: indices.(tn);\n done\n done;\n\n let index_arrays = Array.make ns [||] in\n for i=0 to ns-1 do\n if is_query.(i) then index_arrays.(i) <- Array.of_list indices.(i)\n done;\n\n let query_table = Hashtbl.create 10 in\n\n let rec log x = if x<=1 then 0 else 1 + (log (x lsr 1)) in\n\n let bsearch a b la lb = \n let rec bs x i j =\n (* ind hyp is i \n\tlet x = a.(l) in\n\tif x<=b.(0) then b.(0) - x else if x>=b.(lb-1) then x-b.(lb-1) else bs x 0 (lb-1)\n )\n in\n\n let linsearch a b la lb =\n let rec loop i j ac = if i=la || j=lb then ac\n else if a.(i) < b.(j) then loop (i+1) j (min ac (b.(j) - a.(i)))\n else if a.(i) > b.(j) then loop i (j+1) (min ac (a.(i) - b.(j)))\n else 0\n in\n loop 0 0 max_int\n in\n\n let solve_query a an b bn = \n let la = Array.length index_arrays.(an) in\n let lb = Array.length index_arrays.(bn) in\n let (la,lb,a,b,an,bn) = if la < lb then (la,lb,a,b,an,bn) else (lb,la,b,a,bn,an) in\n (* decide which will be faster: linear scan or binary search *)\n if la=0 || lb=0 then -1 else\n let do_bsearch = la * (log lb) <= la + lb in\n let centerdist = (if do_bsearch then bsearch else linsearch) index_arrays.(an) index_arrays.(bn) la lb in\n let (alen,blen) = (String.length a, String.length b) in\n let leftend = min (-alen) (-centerdist -blen) in\n let rightend = max alen (-centerdist + blen) in\n (rightend - leftend) / 2\n in\n \n for i=0 to q-1 do\n let (a,an,b,bn) = query.(i) in\n if Hashtbl.mem query_table (an,bn) \n then printf \"%d\\n\" (Hashtbl.find query_table (an,bn)) \n else \n let ans = solve_query a an b bn in\n Hashtbl.add query_table (an,bn) ans;\n printf \"%d\\n\" ans\n done;\n"}, {"source_code": "(* Sketch of my algorithm for this problem.\n \n Do a scan of the input string and compute for each query string a\n sorted list of the indices of the centers of these strings (the\n centers could be half integers so you probably double them to make\n them integers). Then convert these lists into arrays of indices\n (so we can do binary search on them).\n\n Now, answering a query consists of taking the two corresponding\n lists A and B, and finding the closest pair (a,b) where a is from A\n and b is from B. We can do this by different methods depending on\n the sizes A and B. If |A| and |B| are about equal, we can just do\n a linear scan to find the closest pair. If, say A is a lot smaller,\n then we can lookup each element of A in B using binary search.\n\n Also, we use a hash table to ensure that the same query is only\n analyzed once.\n\n Notice that the input string can contain at most 200K substrings of\n length 1,2,3, or 4. So the total length of all the lists computed\n above is at most 200K. The worst case will occur when there are\n about 500 query strings that occur about 500 times each. So each\n query will take O(1000) to analyze. So the whole algorithm is O(100M).\n\n Looking at the match editorial later (http://codeforces.com/blog/entry/12959).\n They give a running time of O(S Sqrt(Q)) which means O(50K * 300) =\n O(15M). But it loses at least a factor of four because they are\n consisering query strings of length at most 1. So I don't think\n the algorithm is actually different.\n\n*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet str_to_numb s = \n let n = String.length s in\n let rec loop i ac = if i=n then ac else\n loop (i+1) (26 * ac + (l2n s.[i]))\n in\n loop 1 (1 + (l2n s.[0]))\n\nlet () = \n let ns = (str_to_numb \"zzzz\") + 1 in\n let is_query = Array.make ns false in\n let s = read_string () in\n let n = String.length s in\n let q = read_int () in\n let query = Array.init q (\n fun _ -> \n let a = read_string() in\n let b = read_string() in\n let (a,b) = (min a b, max a b) in\n let (an,bn) = (str_to_numb a, str_to_numb b) in\n is_query.(an) <- true;\n is_query.(bn) <- true;\n (a,an,b,bn)\n ) in\n\n let indices = Array.make ns [] in\n\n for l=1 to 4 do\n for i=n-l downto 0 do\n let t = String.sub s i l in\n let index = 2*i + l - 1 in\n let tn = str_to_numb t in\n if is_query.(tn) then indices.(tn) <- index :: indices.(tn);\n done\n done;\n\n let index_arrays = Array.make ns [||] in\n for i=0 to ns-1 do\n if is_query.(i) then index_arrays.(i) <- Array.of_list indices.(i)\n done;\n\n let query_table = Hashtbl.create 10 in\n\n let rec log x = if x<=1 then 0 else 1 + (log (x lsr 1)) in\n\n let bsearch a b la lb = \n let rec bs x i j =\n (* ind hyp is i \n\tlet x = a.(l) in\n\tif x<=b.(0) then b.(0) - x else if x>=b.(lb-1) then x-b.(lb-1) else bs x 0 (lb-1)\n )\n in\n\n let linsearch a b la lb =\n let rec loop i j ac = if i=la || j=lb then ac\n else if a.(i) < b.(j) then loop (i+1) j (min ac (b.(j) - a.(i)))\n else if a.(i) > b.(j) then loop i (j+1) (min ac (a.(i) - b.(j)))\n else 0\n in\n loop 0 0 max_int\n in\n\n let solve_query a an b bn = \n let la = Array.length index_arrays.(an) in\n let lb = Array.length index_arrays.(bn) in\n let (la,lb,a,b,an,bn) = if la < lb then (la,lb,a,b,an,bn) else (lb,la,b,a,bn,an) in\n (* decide which will be faster: linear scan or binary search *)\n if la=0 || lb=0 then -1 else\n let do_bsearch = la * (log lb) <= la + lb in\n(* let centerdist = (if do_bsearch then bsearch else linsearch) index_arrays.(an) index_arrays.(bn) la lb in *)\n let centerdist = bsearch index_arrays.(an) index_arrays.(bn) la lb in\n let (alen,blen) = (String.length a, String.length b) in\n let leftend = min (-alen) (-centerdist -blen) in\n let rightend = max alen (-centerdist + blen) in\n (rightend - leftend) / 2\n in\n \n for i=0 to q-1 do\n let (a,an,b,bn) = query.(i) in\n if Hashtbl.mem query_table (an,bn) \n then printf \"%d\\n\" (Hashtbl.find query_table (an,bn)) \n else \n let ans = solve_query a an b bn in\n Hashtbl.add query_table (an,bn) ans;\n printf \"%d\\n\" ans\n done;\n"}], "src_uid": "36dbadbc143d507c3b30bb9ea3222dd7"} {"nl": {"description": "You are given a chess board with $$$n$$$ rows and $$$n$$$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.A knight is a chess piece that can attack a piece in cell ($$$x_2$$$, $$$y_2$$$) from the cell ($$$x_1$$$, $$$y_1$$$) if one of the following conditions is met: $$$|x_1 - x_2| = 2$$$ and $$$|y_1 - y_2| = 1$$$, or $$$|x_1 - x_2| = 1$$$ and $$$|y_1 - y_2| = 2$$$. Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them). A duel of knights is a pair of knights of different colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.", "input_spec": "The first line contains one integer $$$n$$$ ($$$3 \\le n \\le 100$$$) \u2014 the number of rows (and columns) in the board.", "output_spec": "Print $$$n$$$ lines with $$$n$$$ characters in each line. The $$$j$$$-th character in the $$$i$$$-th line should be W, if the cell ($$$i$$$, $$$j$$$) contains a white knight, or B, if it contains a black knight. The number of duels should be maximum possible. If there are multiple optimal answers, print any of them.", "sample_inputs": ["3"], "sample_outputs": ["WBW\nBBB\nWBW"], "notes": "NoteIn the first example, there are $$$8$$$ duels: the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$3$$$, $$$2$$$); the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$); the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$3$$$, $$$2$$$); the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$); the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$1$$$, $$$2$$$); the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$); the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$1$$$, $$$2$$$); the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$). "}, "positive_code": [{"source_code": "let neighbors limit i j =\n let delta = [(2,1);(2,-1);(-2,1);(-2,-1);(1,2);(1,-2);(-1,-2);(-1,2)] in\n let l = List.map (fun (dx,dy) -> (dx+i,dy+j)) delta in\n List.filter (fun (i,j) -> i >= 0 && i < limit && j >= 0 && j < limit) l\n\nlet rec check limit array b (i,j) =\n match array.(i).(j) with\n | _, `Unseen ->\n array.(i).(j) <- (b, `Seen);\n let l = neighbors limit i j in\n List.iter (check limit array (not b)) l\n | _ -> ()\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n let array = Array.make_matrix n n (false,`Unseen) in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n match array.(i).(j) with\n | b,`Unseen ->\n check n array (not b) (i,j)\n | _ -> ()\n done;\n done;\n let rec pp_line fmt line =\n let to_string b = if b then \"W\" else \"B\" in\n match line with\n | [] -> ()\n | (b,_)::l -> Format.fprintf fmt \"%s%a\" (to_string b) pp_line l\n in\n let rec pp_arr fmt array =\n match array with\n | [] -> ()\n | line::array ->\n let line = Array.to_list line in\n Format.fprintf fmt \"%a@.%a\" pp_line line pp_arr array;\n in\n Format.printf \"%a@.\" pp_arr (Array.to_list array)\n"}], "negative_code": [], "src_uid": "09991e8e16cd395c7ce459817a385988"} {"nl": {"description": "Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r,\u2009c). The tail of the snake is located at (1,\u20091), then it's body extends to (1,\u2009m), then goes down 2 rows to (3,\u2009m), then goes left to (3,\u20091) and so on.Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').Consider sample tests in order to understand the snake pattern.", "input_spec": "The only line contains two integers: n and m (3\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950). n is an odd number.", "output_spec": "Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.", "sample_inputs": ["3 3", "3 4", "5 3", "9 9"], "sample_outputs": ["###\n..#\n###", "####\n...#\n####", "###\n..#\n###\n#..\n###", "#########\n........#\n#########\n#........\n#########\n........#\n#########\n#........\n#########"], "notes": null}, "positive_code": [{"source_code": "let input () = Scanf.scanf \"%d %d\" (fun n m -> (n, m))\n\nlet get_parity row =\n if row mod 2 = 0\n then\n if row / 2 mod 2 = 0\n then\n `even_left\n else\n `even_right\n else\n `odd\n\nlet make_line parity m = \n match parity with\n |`even_left -> \"#\" ^ (String.make (m - 1) '.')\n |`even_right -> (String.make (m - 1) '.') ^ \"#\"\n |`odd -> String.make m '#'\n\nlet solve (n, m) = \n let rec loop i = \n if i <= n \n then\n let line = make_line (get_parity i) m in\n Printf.printf \"%s\\n\" line;\n loop (i + 1)\n else\n ()\n in loop 1\n\nlet () = solve (input ())\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let m = read_int () in\n let rec solve pos str m = function\n | 0 -> str\n | n ->\n if (n mod 2) = 1 then\n solve pos (str ^ (String.make m '#') ^ \"\\n\") m (n - 1)\n else\n if pos then\n solve false (str ^ (String.make (m - 1) '.') ^ \"#\\n\") m (n - 1)\n else\n solve true (str ^ \"#\" ^ (String.make (m - 1) '.') ^ \"\\n\") m (n - 1)\n in Printf.printf \"%s\" (solve true \"\" m n)\n\n"}, {"source_code": "let () =\n Scanf.scanf \"%d %d\\n\" (fun n m ->\n let line = String.make m '#' in\n let empty = String.make (m - 1) '.' in\n for i = 1 to n do\n if i mod 2 = 1 then\n print_endline line\n else\n if i mod 4 = 0 then begin\n print_char '#';\n print_endline empty\n end else begin\n print_string empty;\n print_endline \"#\"\n end\n done\n )\n"}, {"source_code": "let id x = x in\n\nlet rec range lo hi =\n if lo >= hi then []\n else lo :: range (lo + 1) hi in\n\nlet n = Scanf.scanf \" %d\" id in\nlet m = Scanf.scanf \" %d\" id in\n\nlet rec stringn s n = match n with\n1 -> s\n| _ -> s ^ stringn s (n - 1) in\n\nlet get i = if i mod 2 = 0 then stringn \"#\" m\n else if i mod 4 = 1 then stringn \".\" (m - 1) ^ \"#\"\n else \"#\" ^ stringn \".\" (m - 1) in\n\nn\n|> range 0\n|> List.map get\n|> List.iter print_endline ;;\n(*\nPrintf.printf \" %d %d\" n m ;; *)\n"}], "negative_code": [], "src_uid": "2a770c32d741b3440e7f78cd5670d54d"} {"nl": {"description": "You are given n integers a1,\u2009a2,\u2009...,\u2009an. Find the number of pairs of indexes i,\u2009j (i\u2009<\u2009j) that ai\u2009+\u2009aj is a power of 2 (i. e. some integer x exists so that ai\u2009+\u2009aj\u2009=\u20092x).", "input_spec": "The first line contains the single positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of integers. The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print the number of pairs of indexes i,\u2009j (i\u2009<\u2009j) that ai\u2009+\u2009aj is a power of 2.", "sample_inputs": ["4\n7 3 2 1", "3\n1 1 1"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first example the following pairs of indexes include in answer: (1,\u20094) and (2,\u20094).In the second example all pairs of indexes (i,\u2009j) (where i\u2009<\u2009j) include in answer."}, "positive_code": [{"source_code": "(* Darooha style *)\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\n(*\nlet ( *| ) = Int64.mul\nlet ( +| ) = Int64.add\nlet ( -| ) = Int64.sub\nlet ( /| ) = Int64.div\nlet ( %| ) = Int64.rem\n*)\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nopen Printf\nopen Scanf\n\nlet get h k =\n try Hashtbl.find h k with\n | Not_found -> 0\n \nlet set h k v = Hashtbl.replace h k v\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- read_int()\n done;\n let h = Hashtbl.create n in\n for i = 0 to n - 1 do\n set h a.(i) (get h a.(i) + 1)\n done;\n let res = ref 0L in\n Hashtbl.iter (fun k v ->\n\t\tlet pw2 = ref 1 in\n\t\tfor _ = 1 to 30 do\n\t\t\tpw2 := !pw2 * 2;\n\t\t\tlet k2 = !pw2 - k in\n\t\t\tif k < k2 then\n\t\t\t\tres := (long v) ** (long (get h (!pw2 - k))) ++ !res\n\t\t\telse if k = k2 then\n\t\t\t\tres := (long v) ** (long (v - 1)) // 2L ++ !res\n\t\tdone\n\t) h;\n printf \"%Ld\\n\" !res\n"}, {"source_code": "(* Darooha style \nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n*)\nlet ( *| ) = Int64.mul\nlet ( +| ) = Int64.add\nlet ( -| ) = Int64.sub\nlet ( /| ) = Int64.div\nlet ( %| ) = Int64.rem\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nopen Printf\nopen Scanf\n\nlet get h k =\n try Hashtbl.find h k with\n | Not_found -> 0\n \nlet set h k v = Hashtbl.replace h k v\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- read_int()\n done;\n let h = Hashtbl.create n in\n for i = 0 to n - 1 do\n set h a.(i) (get h a.(i) + 1)\n done;\n let res = ref 0L in\n Hashtbl.iter (fun k v ->\n\t\tlet pw2 = ref 1 in\n\t\tfor _ = 1 to 30 do\n\t\t\tpw2 := !pw2 * 2;\n\t\t\tlet k2 = !pw2 - k in\n\t\t\tif k < k2 then\n\t\t\t\tres := (long v) *| (long (get h (!pw2 - k))) +| !res\n\t\t\telse if k = k2 then\n\t\t\t\tres := (long v) *| (long (v - 1)) /| 2L +| !res\n\t\tdone\n\t) h;\n printf \"%Ld\\n\" !res\n"}, {"source_code": "let ( ** ) = Int64.mul\nlet ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( // ) = Int64.div\nlet ( %% ) = Int64.rem\n\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nopen Printf\nopen Scanf\n\nlet get h k =\n try Hashtbl.find h k with\n | Not_found -> 0\n \nlet set h k v = Hashtbl.replace h k v\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- read_int()\n done;\n let h = Hashtbl.create n in\n for i = 0 to n - 1 do\n set h a.(i) (get h a.(i) + 1)\n done;\n let res = ref 0L in\n Hashtbl.iter (fun k v ->\n\t\tlet pw2 = ref 1 in\n\t\tfor _ = 1 to 30 do\n\t\t\tpw2 := !pw2 * 2;\n\t\t\tlet k2 = !pw2 - k in\n\t\t\tif k < k2 then\n\t\t\t\tres := (long v) ** (long (get h (!pw2 - k))) ++ !res\n\t\t\telse if k = k2 then\n\t\t\t\tres := (long v) ** (long (v - 1)) // 2L ++ !res\n\t\tdone\n\t) h;\n printf \"%Ld\\n\" !res\n"}, {"source_code": "(* Darooha style *)\nlet ( ** ) = Int64.mul\nlet ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( // ) = Int64.div\nlet ( %% ) = Int64.rem\n\n(*\nlet ( *| ) a b = Int64.mul\nlet ( +| ) a b = Int64.add\nlet ( -| ) a b = Int64.sub\nlet ( /| ) a b = Int64.div\nlet ( %| ) a b = Int64.rem\n*)\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nopen Printf\nopen Scanf\n\nlet get h k =\n try Hashtbl.find h k with\n | Not_found -> 0\n \nlet set h k v = Hashtbl.replace h k v\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- read_int()\n done;\n let h = Hashtbl.create n in\n for i = 0 to n - 1 do\n set h a.(i) (get h a.(i) + 1)\n done;\n let res = ref 0L in\n Hashtbl.iter (fun k v ->\n\t\tlet pw2 = ref 1 in\n\t\tfor _ = 1 to 30 do\n\t\t\tpw2 := !pw2 * 2;\n\t\t\tlet k2 = !pw2 - k in\n\t\t\tif k < k2 then\n\t\t\t\tres := (long v) ** (long (get h (!pw2 - k))) ++ !res\n\t\t\telse if k = k2 then\n\t\t\t\tres := (long v) ** (long (v - 1)) // 2L ++ !res\n\t\tdone\n\t) h;\n printf \"%Ld\\n\" !res\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let ht = Hashtbl.create n in\n let _ =\n for i = 0 to n - 1 do\n let c =\n\ttry\n\t Hashtbl.find ht a.(i)\n\twith\n\t | Not_found -> 0\n in\n\tHashtbl.replace ht a.(i) (c + 1)\n done\n in\n let res = ref 0L in\n Hashtbl.iter\n (fun x c ->\n\t for i = 1 to 30 do\n\t try\n\t if 1 lsl i - x = x\n\t then res := !res +| Int64.of_int c *| Int64.of_int (c - 1)\n\t else\n\t let c2 = Hashtbl.find ht (1 lsl i - x) in\n\t\t res := !res +| Int64.of_int c *| Int64.of_int c2;\n\t with\n\t | Not_found -> ()\n\t done;\n ) ht;\n res := !res /| 2L;\n Printf.printf \"%Ld\\n\" !res\n"}], "negative_code": [], "src_uid": "b812d2d3a031dadf3d850605d2e78e33"} {"nl": {"description": "There is a square field of size $$$n \\times n$$$ in which two cells are marked. These cells can be in the same row or column.You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.For example, if $$$n=4$$$ and a rectangular field looks like this (there are asterisks in the marked cells):$$$$$$ \\begin{matrix} . & . & * & . \\\\ . & . & . & . \\\\ * & . & . & . \\\\ . & . & . & . \\\\ \\end{matrix} $$$$$$Then you can mark two more cells as follows$$$$$$ \\begin{matrix} * & . & * & . \\\\ . & . & . & . \\\\ * & . & * & . \\\\ . & . & . & . \\\\ \\end{matrix} $$$$$$If there are several possible solutions, then print any of them.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 400$$$). Then $$$t$$$ test cases follow. The first row of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 400$$$)\u00a0\u2014 the number of rows and columns in the table. The following $$$n$$$ lines each contain $$$n$$$ characters '.' or '*' denoting empty and marked cells, respectively. It is guaranteed that the sums of $$$n$$$ for all test cases do not exceed $$$400$$$. It is guaranteed that there are exactly two asterisks on the field. They can be in the same row/column. It is guaranteed that the solution exists.", "output_spec": "For each test case, output $$$n$$$ rows of $$$n$$$ characters\u00a0\u2014 a field with four asterisks marked corresponding to the statements. If there multiple correct answers, print any of them.", "sample_inputs": ["6\n4\n..*.\n....\n*...\n....\n2\n*.\n.*\n2\n.*\n.*\n3\n*.*\n...\n...\n5\n.....\n..*..\n.....\n.*...\n.....\n4\n....\n....\n*...\n*..."], "sample_outputs": ["*.*.\n....\n*.*.\n....\n**\n**\n**\n**\n*.*\n*.*\n...\n.....\n.**..\n.....\n.**..\n.....\n....\n....\n**..\n**.."], "notes": null}, "positive_code": [{"source_code": "(* https://codeforces.com/contest/1512/problem/B *)\n\ntype point = {\n x : int;\n y : int\n}\n\ntype rectangle = {\n x1 : int;\n x2 : int;\n y1 : int;\n y2 : int\n}\n\nlet make_rectangle { x=x1; y=y1 } { x=x2; y=y2 } =\n let min_x = min x1 x2 and\n max_x = max x1 x2 and\n min_y = min y1 y2 and\n max_y = max y1 y2 in\n if min_x = max_x\n then (\n let x = if min_x = 0 then 1 else 0 in\n { x1 = x; x2 = min_x; y1 = min_y; y2 = max_y }\n )\n else if min_y = max_y\n then (\n let y = if min_y = 0 then 1 else 0 in\n { x1 = min_x; x2 = max_x; y1 = y; y2 = min_y }\n )\n else { x1 = min_x; x2 = max_x; y1 = min_y; y2 = max_y }\n\nlet print_rectangle side rect =\n let line i =\n if i = rect.y1 || i = rect.y2\n then String.init side (fun i -> if i = rect.x1 || i = rect.x2 then '*' else '.')\n else String.make side '.' in\n let rec loop i =\n if i < side\n then (\n Printf.printf \"%s\\n\" (line i);\n loop (i+1)\n ) in\n loop 0\n\nlet get_rect side =\n let rec find_star str i acc =\n if i < String.length str\n then find_star str (i+1) (if str.[i] = '*' then (i::acc) else acc)\n else acc in\n let rec helper i points =\n if i = side\n then points\n else (\n let line = read_line () in\n let xs = find_star line 0 [] in\n helper (i+1) ((List.map (fun x -> { x=x; y=i }) xs) @ points)\n ) in\n helper 0 []\n\nlet solve_n nb_cases =\n let rec helper i =\n if i > 0\n then (\n let side = read_int () in\n let [p1; p2] = get_rect side in\n make_rectangle p1 p2\n |> print_rectangle side;\n helper (i-1)\n ) in\n helper nb_cases\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "negative_code": [], "src_uid": "d8fb3822b983b8a8ffab341aee74f56f"} {"nl": {"description": "During a New Year special offer the \"Sudislavl Bars\" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar \"Mosquito Shelter\". Of course, all the promocodes differ.As the \"Mosquito Shelter\" opens only at 9, and partying in Sudislavl usually begins at as early as 6, many problems may arise as to how to type a promotional code without errors. It is necessary to calculate such maximum k, that the promotional code could be uniquely identified if it was typed with no more than k errors. At that, k\u2009=\u20090 means that the promotional codes must be entered exactly.A mistake in this problem should be considered as entering the wrong numbers. For example, value \"123465\" contains two errors relative to promocode \"123456\". Regardless of the number of errors the entered value consists of exactly six digits.", "input_spec": "The first line of the output contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of promocodes. Each of the next n lines contains a single promocode, consisting of exactly 6 digits. It is guaranteed that all the promocodes are distinct. Promocodes can start from digit \"0\".", "output_spec": "Print the maximum k (naturally, not exceeding the length of the promocode), such that any promocode can be uniquely identified if it is typed with at most k mistakes.", "sample_inputs": ["2\n000000\n999999", "6\n211111\n212111\n222111\n111111\n112111\n121111"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first sample k\u2009<\u20093, so if a bar customer types in value \"090909\", then it will be impossible to define which promocode exactly corresponds to it."}, "positive_code": [{"source_code": "let l = ref [];;\nlet n = read_int() in for i = 1 to n do l := !l @ [read_line()] done;;\nlet comp s1 s2 = \n let rec compi s1 s2 i = \n if i == String.length s1 then 0\n else if (String.get s1 i) != (String.get s2 i) then (compi s1 s2 (i + 1)) + 1\n else (compi s1 s2 (i + 1))\n in ((compi s1 s2 0) - 1) / 2;;\nlet rec min_list lis = \n match lis with \n hd :: tl -> min (min_list tl) hd\n | [] -> 10000\n;;\nlet rec f li =\n if (List.length li == 1) then 6 else\n match li with\n hd :: tl -> min (min_list (List.map (comp hd) tl)) (f tl)\n | [] -> 1000000 \n;;\nPrintf.printf \"%d\\n\" (f !l)\n;;\n"}], "negative_code": [{"source_code": "let l = ref [];;\nlet n = read_int() in for i = 1 to n do l := !l @ [read_line()] done;;\nlet comp s1 s2 = \n let rec compi s1 s2 i = \n if i == String.length s1 then 0\n else if (String.get s1 i) != (String.get s2 i) then (compi s1 s2 (i + 1)) + 1\n else (compi s1 s2 (i + 1))\n in ((compi s1 s2 0) - 1) / 2;;\nlet rec min_list lis = \n match lis with \n hd :: tl -> min (min_list tl) hd\n | [] -> 10000\n;;\nlet rec f li =\n match li with\n hd :: tl -> min (min_list (List.map (comp hd) tl)) (f tl)\n | [] -> 1000000 \n;;\nPrintf.printf \"%d\\n\" (f !l)\n;;\n"}], "src_uid": "0151c42a653421653486c93efe87572d"} {"nl": {"description": "One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $$$1\\times1$$$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 100$$$): the number of grids of the games. Each of the next $$$T$$$ lines contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$): the size of the side of the grid of the game. ", "output_spec": "For each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.", "sample_inputs": ["2\n3\n4"], "sample_outputs": ["2\n3"], "notes": "NoteFor $$$3\\times3$$$ grid ponies can make two following moves: "}, "positive_code": [{"source_code": "open Scanf;;\nopen Printf;;\n\nlet read_int () = bscanf Scanning.stdin \"%d \" (fun x -> x)\n\nlet solve n = (n + 2) / 2 in\n let t = read_int () in\n for i = 0 to t - 1 do\n printf \"%d\\n\" (read_int () |> solve)\n done;;"}], "negative_code": [], "src_uid": "eb39ac8d703516c7f81f95a989791b21"} {"nl": {"description": "Little C loves number \u00ab3\u00bb very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.", "input_spec": "A single line containing one integer $$$n$$$ ($$$3 \\leq n \\leq 10^9$$$) \u2014 the integer Little C has.", "output_spec": "Print $$$3$$$ positive integers $$$a,b,c$$$ in a single line, such that $$$a+b+c=n$$$ and none of them is a multiple of $$$3$$$. It can be proved that there is at least one solution. If there are multiple solutions, print any of them.", "sample_inputs": ["3", "233"], "sample_outputs": ["1 1 1", "77 77 79"], "notes": null}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\n\nlet () =\n\tlet n = get_i64 0 in\n\t(\n\t\tif (n - 2L) mod 3L = 0L then (\n\t\t\tprintf \"1 2 %Ld\" (n-3L)\n\t\t) else (\n\t\t\tprintf \"1 1 %Ld\" (n-2L)\n\t\t)\n\t)\n\n\n\n\n"}, {"source_code": "let () =\n\tlet module Ident = struct\n\t\texternal id : 'a -> 'a = \"%identity\" (* test *)\n\tend in\n\tlet open Printf in\n\tScanf.scanf \" %d\" @@ fun n ->\n\t\tif (n-2) mod 3 = 0 then printf \"1 2 %d\\n\" @@ Ident.id (n-3)\n\t\telse printf \"1 1 %d\\n\" @@ Ident.id (n-2)\n"}, {"source_code": "let n = int_of_string (input_line stdin) ;;\n\nif (n - 2) mod 3 != 0 then\n Printf.printf \"%d %d %d\\n\" 1 1 (n - 2)\nelse\n Printf.printf \"%d %d %d\\n\" 2 2 (n - 4) ;;"}], "negative_code": [{"source_code": "let () =\n\tlet module Ident = struct\n\t\texternal id : 'a -> 'a = \"%identity\" (* test *)\n\tend in\n\tlet open Printf in\n\tScanf.scanf \" %d\" @@ fun n ->\n\t\tif n-2 mod 3 = 0 then printf \"1 2 %d\\n\" @@ Ident.id (n-3)\n\t\telse printf \"1 1 %d\\n\" @@ Ident.id (n-2)"}], "src_uid": "91d5147fb602298e08cbdd9f86d833f8"} {"nl": {"description": "Vasya is an administrator of a public page of organization \"Mouse and keyboard\" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500\u2009000)\u00a0\u2014 the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500\u2009000.", "output_spec": "Print the resulting hashtags in any of the optimal solutions.", "sample_inputs": ["3\n#book\n#bigtown\n#big", "3\n#book\n#cool\n#cold", "4\n#car\n#cart\n#art\n#at", "3\n#apple\n#apple\n#fruit"], "sample_outputs": ["#b\n#big\n#big", "#book\n#co\n#cold", "#\n#\n#art\n#at", "#apple\n#apple\n#fruit"], "notes": "NoteWord a1,\u2009a2,\u2009...,\u2009am of length m is lexicographically not greater than word b1,\u2009b2,\u2009...,\u2009bk of length k, if one of two conditions hold: at first position i, such that ai\u2009\u2260\u2009bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and m\u2009\u2264\u2009k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two."}, "positive_code": [{"source_code": "let print_array a =\n\tlet n = Array.length a in\n\tfor k = 0 to n - 1 do\n\t\tprint_endline a.(k);\n\tdone;\n;;\n\n\nlet read_array n =\n\tlet arr = Array.make n \"\" in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %s\" (fun v -> arr.(k) <- v;);\n\t\tdone;\n\t\tarr\n\tend\n;;\n\n\nlet longest_common_prefix_length l r =\n\tlet n = min (String.length l) (String.length r) in\n\tlet k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)\n\tbegin\n\t\twhile (!k < n) && ((String.get l !k) = (String.get r !k) ) do\n\t\t\tk := !k + 1;\n\t\tdone;\n\t\t!k\n\tend\n;;\n\n\nlet max_lex_predecessor l r =\n\tlet nl = String.length l in\n\tlet nr = String.length r in\n\tlet m = longest_common_prefix_length l r in\n\tif (m = nl) || ((m < nr) && (String.get l m) < (String.get r m)) then l\n\telse (String.sub l 0 m)\n;;\n\n\nlet truncate_hashtags a = \n\tlet n = Array.length a in\n\tlet b = Array.make n \"\" in\n\tbegin\n\t\tb.(n-1) <- a.(n-1);\n\t\tfor k=(n-2) downto 0 do\n\t\t\tb.(k) <- (max_lex_predecessor a.(k) b.(k+1));\n\t\tdone;\n\t\tb\n\tend\n;;\n\n\nlet load_and_process_hashtags n =\n\tlet a = read_array n in\n\tlet b = truncate_hashtags a in\n\tprint_array b\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i \" load_and_process_hashtags\n;;\n\n\nread_input ()\n"}, {"source_code": "let print_array a =\n\tlet n = Array.length a in\n\tfor k = 0 to n - 1 do\n\t\tprint_endline a.(k);\n\tdone;\n;;\n\n\nlet read_array n =\n\tlet arr = Array.make n \"\" in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %s\" (fun v -> arr.(k) <- v;);\n\t\tdone;\n\t\tarr\n\tend\n;;\n\n\nlet longest_common_prefix_length l r =\n\tlet n = min (String.length l) (String.length r) in\n\tlet k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)\n\tbegin\n\t\twhile (!k < n) && ((String.get l !k) = (String.get r !k) ) do\n\t\t\tk := !k + 1;\n\t\tdone;\n\t\t!k\n\tend\n;;\n\n\nlet max_lex_predecessor_length l r =\n\tlet nl = String.length l in\n\tlet nr = String.length r in\n\tlet m = longest_common_prefix_length l r in\n\tif (m = nl) || (m = nr) then m\n\telse if (String.get l m) < (String.get r m) then nl \n\telse m\n;;\n\n\nlet max_lex_predecessor l r =\n\tlet nl = String.length l in\n\tlet m = max_lex_predecessor_length l r in\n\tif m = nl then l else (String.sub l 0 m)\n;;\n\n\nlet truncate_hashtags a = \n\tlet n = Array.length a in\n\tlet b = Array.make n \"\" in\n\tbegin\n\t\tb.(n-1) <- a.(n-1);\n\t\tfor k=(n-2) downto 0 do\n\t\t\tb.(k) <- (max_lex_predecessor a.(k) b.(k+1));\n\t\tdone;\n\t\tb\n\tend\n;;\n\n\nlet load_and_process_hashtags n =\n\tlet a = read_array n in\n\tlet b = truncate_hashtags a in\n\tprint_array b\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i \" load_and_process_hashtags\n;;\n\n\nread_input ()\n"}, {"source_code": "let print_array a =\n\tlet n = Array.length a in\n\tfor k = 0 to n - 1 do\n\t\tprint_endline a.(k);\n\tdone;\n;;\n\n\nlet read_array n =\n\tlet arr = Array.make n \"\" in\n\tlet last_v = ref \"\" in\n\tbegin\n\t\tfor k = 0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %s\" (fun v -> \n\t\t\t\tbegin\n\t\t\t\t\tarr.(k) <- if v = !last_v then !last_v else v;\n\t\t\t\t\tlast_v := v;\n\t\t\t\tend\n\t\t\t);\n\t\tdone;\n\t\tarr\n\tend\n;;\n\n\nlet longest_common_prefix_length l r =\n\tlet n = min (String.length l) (String.length r) in\n\tlet k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)\n\tbegin\n\t\twhile (!k < n) && ((String.get l !k) = (String.get r !k) ) do\n\t\t\tk := !k + 1;\n\t\tdone;\n\t\t!k\n\tend\n;;\n\n\nlet truncate_hashtags a = \n\tlet n = Array.length a in\n\tbegin\n\t\tfor k=(n-2) downto 0 do\n\t\t\tlet l = a.(k) in\n\t\t\tlet r = a.(k+1) in\n\t\t\tif (l != r) && (String.compare l r) >= 1 then\n\t\t\tbegin\n\t\t\t\ta.(k) <- (String.sub l 0 (longest_common_prefix_length l r));\n\t\t\tend;\n\t\tdone;\n\t\ta\n\tend\n;;\n\n\nlet load_and_process_hashtags n =\n\tlet a = read_array n in\n\tlet b = truncate_hashtags a in\n\tprint_array b\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i \" load_and_process_hashtags\n;;\n\n\nread_input ()\n"}, {"source_code": "let print_array a =\n\tlet n = Array.length a in\n\tfor k = 0 to n - 1 do\n\t\tprint_endline a.(k);\n\tdone;\n;;\n\n\nlet read_array n =\n\tlet arr = Array.make n \"\" in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %s\" (fun v -> arr.(k) <- v;);\n\t\tdone;\n\t\tarr\n\tend\n;;\n\n\nlet longest_common_prefix_length l r =\n\tlet n = min (String.length l) (String.length r) in\n\tlet k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)\n\tbegin\n\t\twhile (!k < n) && ((String.get l !k) = (String.get r !k) ) do\n\t\t\tk := !k + 1;\n\t\tdone;\n\t\t!k\n\tend\n;;\n\n\nlet max_lex_predecessor_length l r =\n\tlet nl = String.length l in\n\tlet nr = String.length r in\n\tlet m = longest_common_prefix_length l r in\n\tif (m = nl) || (m = nr) then m\n\telse if (String.get l m) < (String.get r m) then nl \n\telse m\n;;\n\n\nlet max_lex_predecessor l r =\n\tlet m = max_lex_predecessor_length l r in\n\tString.sub l 0 m\n;;\n\n\nlet truncate_hashtags a = \n\tlet n = Array.length a in\n\tlet b = Array.make n \"\" in\n\tbegin\n\t\tb.(n-1) <- a.(n-1);\n\t\tfor k=(n-2) downto 0 do\n\t\t\tb.(k) <- (max_lex_predecessor a.(k) b.(k+1));\n\t\tdone;\n\t\tb\n\tend\n;;\n\n\nlet load_and_process_hashtags n =\n\tlet a = read_array n in\n\tlet b = truncate_hashtags a in\n\tprint_array b\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i \" load_and_process_hashtags\n;;\n\n\nread_input ()\n"}, {"source_code": "let print_array a =\n\tlet n = Array.length a in\n\tfor k = 0 to n - 1 do\n\t\tprint_endline a.(k);\n\tdone;\n;;\n\n\nlet read_array n =\n\tlet arr = Array.make n \"\" in\n\tbegin\n\t\tfor k = 0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %s\" (fun v -> arr.(k) <- v;);\n\t\tdone;\n\t\tarr\n\tend\n;;\n\n\nlet longest_common_prefix_length l r =\n\tlet n = min (String.length l) (String.length r) in\n\tlet k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)\n\tbegin\n\t\twhile (!k < n) && ((String.get l !k) = (String.get r !k) ) do\n\t\t\tk := !k + 1;\n\t\tdone;\n\t\t!k\n\tend\n;;\n\n\nlet max_lex_predecessor l r =\n\tlet nl = String.length l in\n\tlet nr = String.length r in\n\tlet m = longest_common_prefix_length l r in\n\tif (m = nl) || ((m < nr) && (String.get l m) < (String.get r m)) then l\n\telse (String.sub l 0 m)\n;;\n\n\nlet truncate_hashtags a = \n\tlet n = Array.length a in\n\tbegin\n\t\tfor k=(n-2) downto 0 do\n\t\t\ta.(k) <- (max_lex_predecessor a.(k) a.(k+1));\n\t\tdone;\n\t\ta\n\tend\n;;\n\n\nlet load_and_process_hashtags n =\n\tlet a = read_array n in\n\tlet b = truncate_hashtags a in\n\tprint_array b\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i \" load_and_process_hashtags\n;;\n\n\nread_input ()\n"}, {"source_code": "let print_array a =\n\tlet n = Array.length a in\n\tfor k = 0 to n - 1 do\n\t\tprint_endline a.(k);\n\tdone;\n;;\n\n\nlet read_array n =\n\tlet arr = Array.make n \"\" in\n\tbegin\n\t\tfor k = 0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %s\" (fun v -> arr.(k) <- v;);\n\t\tdone;\n\t\tarr\n\tend\n;;\n\n\nlet longest_common_prefix_length l r =\n\tlet n = min (String.length l) (String.length r) in\n\tlet k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)\n\tbegin\n\t\twhile (!k < n) && ((String.get l !k) = (String.get r !k) ) do\n\t\t\tk := !k + 1;\n\t\tdone;\n\t\t!k\n\tend\n;;\n\n\nlet truncate_hashtags a = \n\tlet n = Array.length a in\n\tbegin\n\t\tfor k=(n-2) downto 0 do\n\t\t\tlet l = a.(k) in\n\t\t\tlet r = a.(k+1) in\n\t\t\tif (String.compare l r) >= 1 then\n\t\t\tbegin\n\t\t\t\ta.(k) <- (String.sub l 0 (longest_common_prefix_length l r));\n\t\t\tend\n\t\tdone;\n\t\ta\n\tend\n;;\n\n\nlet load_and_process_hashtags n =\n\tlet a = read_array n in\n\tlet b = truncate_hashtags a in\n\tprint_array b\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i \" load_and_process_hashtags\n;;\n\n\nread_input ()\n"}], "negative_code": [], "src_uid": "27baf9b1241c0f8e3a2037b18f39fe34"} {"nl": {"description": "Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.", "input_spec": "The first line contains integer q (1\u2009\u2264\u2009q\u2009\u2264\u20091000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.", "output_spec": "In the first line output the integer n \u2014 the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.", "sample_inputs": ["5\nMisha ILoveCodeforces\nVasya Petrov\nPetrov VasyaPetrov123\nILoveCodeforces MikeMirzayanov\nPetya Ivanov"], "sample_outputs": ["3\nPetya Ivanov\nMisha MikeMirzayanov\nVasya VasyaPetrov123"], "notes": null}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let fwd = Hashtbl.create n in\n let rev = Hashtbl.create n in\n for i = 1 to n do\n Scanf.scanf \"%[^ ] %s\\n\" (fun o n ->\n if Hashtbl.mem rev o then begin\n let s = Hashtbl.find rev o in\n Hashtbl.add rev n s;\n Hashtbl.remove rev o;\n Hashtbl.replace fwd s n\n end else begin\n Hashtbl.add fwd o n;\n Hashtbl.add rev n o\n end\n )\n done;\n Printf.printf \"%d\\n\" (Hashtbl.length fwd);\n Hashtbl.iter (Printf.printf \"%s %s\\n\") fwd\n)\n"}], "negative_code": [], "src_uid": "bdd98d17ff0d804d88d662cba6a61e8f"} {"nl": {"description": "Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \\leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \\leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one.", "input_spec": "The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \\leq n \\leq 100\\,000$$$, $$$1 \\leq m \\leq 200\\,000$$$)\u00a0\u2014 the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\leq a_i, b_i \\leq n$$$, $$$a_i \\neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide.", "output_spec": "Output one line\u00a0\u2014 \"Yes\" if the image is rotationally symmetrical, and \"No\" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower).", "sample_inputs": ["12 6\n1 3\n3 7\n5 7\n7 11\n9 11\n11 3", "9 6\n4 5\n5 6\n7 8\n8 9\n1 2\n2 3", "10 3\n1 2\n3 2\n7 2", "10 2\n1 6\n2 7"], "sample_outputs": ["Yes", "Yes", "No", "Yes"], "notes": "NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n let chord = Array.init m (fun _ -> let (a,b) = read_pair() in (a-1,b-1)) in\n\n let table = Hashtbl.create 10 in\n for i=0 to m-1 do\n let (a,b) = chord.(i) in\n Hashtbl.add table (a,b) true;\n Hashtbl.add table (b,a) true; \n done;\n\n let rec find_divisors ac i =\n if i*i > n then ac else (\n let ac = if n mod i = 0 then\n\t (if i=1 || i*i=n then (i::ac) else (n/i)::(i::ac))\n\telse ac\n in\n find_divisors ac (i+1)\n )\n in\n\n let divisors = find_divisors [] 1 in\n\n let test_symmetry d =\n (* test with the given divisor *)\n forall 0 (m-1) (fun i ->\n let (a,b) = chord.(i) in\n try Hashtbl.find table ((a+d) mod n, (b+d) mod n) with Not_found -> false\n )\n in\n\n let answer = List.exists test_symmetry divisors in\n\n if answer then printf \"Yes\\n\" else printf \"No\\n\"\n"}], "negative_code": [], "src_uid": "dd7a7a4e5feb50ab6abb93d90c559c2b"} {"nl": {"description": "You have an array $$$a_1, a_2, \\dots, a_n$$$. All $$$a_i$$$ are positive integers.In one step you can choose three distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$i \\neq j$$$; $$$i \\neq k$$$; $$$j \\neq k$$$) and assign the sum of $$$a_j$$$ and $$$a_k$$$ to $$$a_i$$$, i.\u00a0e. make $$$a_i = a_j + a_k$$$.Can you make all $$$a_i$$$ lower or equal to $$$d$$$ using the operation above any number of times (possibly, zero)?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$3 \\le n \\le 100$$$; $$$1 \\le d \\le 100$$$)\u00a0\u2014 the number of elements in the array $$$a$$$ and the value $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$)\u00a0\u2014 the array $$$a$$$.", "output_spec": "For each test case, print YES, if it's possible to make all elements $$$a_i$$$ less or equal than $$$d$$$ using the operation above. Otherwise, print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).", "sample_inputs": ["3\n5 3\n2 3 2 5 4\n3 4\n2 4 4\n5 4\n2 1 5 3 6"], "sample_outputs": ["NO\nYES\nYES"], "notes": "NoteIn the first test case, we can prove that we can't make all $$$a_i \\le 3$$$.In the second test case, all $$$a_i$$$ are already less or equal than $$$d = 4$$$.In the third test case, we can, for example, choose $$$i = 5$$$, $$$j = 1$$$, $$$k = 2$$$ and make $$$a_5 = a_1 + a_2 = 2 + 1 = 3$$$. Array $$$a$$$ will become $$$[2, 1, 5, 3, 3]$$$.After that we can make $$$a_3 = a_5 + a_2 = 3 + 1 = 4$$$. Array will become $$$[2, 1, 4, 3, 3]$$$ and all elements are less or equal than $$$d = 4$$$."}, "positive_code": [{"source_code": "open Str\nopen Big_int\nopen Num\n\nlet multitest = true\n\nmodule Shortcuts = struct\n let loop n f = for i = 0 to n - 1 do f i; done\n\nend\n\nmodule Helper = struct\n open Shortcuts\n\n let read_s () = Scanf.scanf \"%s\\n\" (fun x -> x)\n\n let read_int ?endl () =\n match endl with\n | None -> Scanf.scanf \"%d \" (fun x -> x)\n | Some () -> Scanf.scanf \"%d\\n\" (fun x -> x)\n\n let read_array n =\n let a = Array.make n 0 in\n loop (n-1) (fun i -> a.(i) <- read_int ());\n a.(n-1) <- read_int ~endl:() ();\n a\n\nend\n\nmodule Ext = struct\n module List = struct\n let rec make n x =\n if (n <= 0) then []\n else x :: make (n-1) x\n\n end\n\nend\n\nmodule Alg = struct\n let rec gcd x y =\n if y <> 0 then (gcd y (x mod y))\n else (abs x)\n\n let lcm x y =\n if x = 0 || y = 0 then 0\n else abs (x * y) / (gcd x y)\n\nend\n\nlet solve _ =\n let open Shortcuts in\n let open Helper in\n let open Printf in\n let open Ext in\n let open Alg in\n (* ***** Solution code here ***** *)\n let n = read_int () in\n let d = read_int ~endl:() () in\n let a = read_array n in\n Array.sort compare a;\n if (a.(n-1) <= d || a.(0) + a.(1) <= d) then printf \"YES\\n\"\n else printf \"NO\\n\";\n (* ***** ******************* ***** *)\n;;\n\nlet () =\n let open Helper in\n let open Shortcuts in\n let t = if multitest then read_int ~endl:() () else 1 in\n loop t solve;;\n"}], "negative_code": [], "src_uid": "044c2a3bafe4f47036ee81f2e40f639a"} {"nl": {"description": "You are given a problemset consisting of $$$n$$$ problems. The difficulty of the $$$i$$$-th problem is $$$a_i$$$. It is guaranteed that all difficulties are distinct and are given in the increasing order.You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $$$a_{i_1}, a_{i_2}, \\dots, a_{i_p}$$$ be the difficulties of the selected problems in increasing order. Then for each $$$j$$$ from $$$1$$$ to $$$p-1$$$ $$$a_{i_{j + 1}} \\le a_{i_j} \\cdot 2$$$ should hold. It means that the contest consisting of only one problem is always valid.Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of problems in the problemset. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 difficulties of the problems. It is guaranteed that difficulties of the problems are distinct and are given in the increasing order.", "output_spec": "Print a single integer \u2014 maximum number of problems in the contest satisfying the condition in the problem statement.", "sample_inputs": ["10\n1 2 5 6 7 10 21 23 24 49", "5\n2 10 50 110 250", "6\n4 7 12 100 150 199"], "sample_outputs": ["4", "1", "3"], "notes": "NoteDescription of the first example: there are $$$10$$$ valid contests consisting of $$$1$$$ problem, $$$10$$$ valid contests consisting of $$$2$$$ problems ($$$[1, 2], [5, 6], [5, 7], [5, 10], [6, 7], [6, 10], [7, 10], [21, 23], [21, 24], [23, 24]$$$), $$$5$$$ valid contests consisting of $$$3$$$ problems ($$$[5, 6, 7], [5, 6, 10], [5, 7, 10], [6, 7, 10], [21, 23, 24]$$$) and a single valid contest consisting of $$$4$$$ problems ($$$[5, 6, 7, 10]$$$).In the second example all the valid contests consist of $$$1$$$ problem.In the third example are two contests consisting of $$$3$$$ problems: $$$[4, 7, 12]$$$ and $$$[100, 150, 199]$$$."}, "positive_code": [{"source_code": "let __ocaml_lex_tables = {\n Lexing.lex_base = \n \"\\000\\000\\010\\000\\002\\000\\255\\255\";\n Lexing.lex_backtrk = \n \"\\001\\000\\002\\000\\001\\000\\255\\255\";\n Lexing.lex_default = \n \"\\255\\255\\255\\255\\255\\255\\000\\000\";\n Lexing.lex_trans = \n \"\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\002\\000\\002\\000\\002\\000\\002\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\002\\000\\000\\000\\002\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\\n \\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\\n \\001\\000\\001\\000\\001\\000\\001\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\003\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\";\n Lexing.lex_check = \n \"\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\000\\000\\000\\000\\002\\000\\002\\000\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\000\\000\\255\\255\\002\\000\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\\n \\001\\000\\001\\000\\001\\000\\001\\000\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\000\\000\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\";\n Lexing.lex_base_code = \n \"\";\n Lexing.lex_backtrk_code = \n \"\";\n Lexing.lex_default_code = \n \"\";\n Lexing.lex_trans_code = \n \"\";\n Lexing.lex_check_code = \n \"\";\n Lexing.lex_code = \n \"\";\n}\n\nlet rec next lexbuf =\n __ocaml_lex_next_rec lexbuf 0\nand __ocaml_lex_next_rec lexbuf __ocaml_lex_state =\n match Lexing.engine __ocaml_lex_tables __ocaml_lex_state lexbuf with\n | 0 ->\n# 6 \"lex_int.mll\"\n ( (-1) )\n# 100 \"lex_int.ml\"\n\n | 1 ->\n# 7 \"lex_int.mll\"\n (next lexbuf)\n# 105 \"lex_int.ml\"\n\n | 2 ->\nlet\n# 8 \"lex_int.mll\"\n s\n# 111 \"lex_int.ml\"\n= Lexing.sub_lexeme lexbuf lexbuf.Lexing.lex_start_pos lexbuf.Lexing.lex_curr_pos in\n# 8 \"lex_int.mll\"\n ( int_of_string s )\n# 115 \"lex_int.ml\"\n\n | __ocaml_lex_state -> lexbuf.Lexing.refill_buff lexbuf; \n __ocaml_lex_next_rec lexbuf __ocaml_lex_state\n\n;;\n\nlet main() =\n let lex = Lexing.from_channel stdin in\n let ri() = next lex in\n let n = ri () in\n let a = Array.init n (fun i -> ri ()) in\n let check x y =\n let x64 = Int64.of_int x in\n let y64 = Int64.of_int y in\n (Int64.compare (Int64.add x64 x64) y64) >= 0\n in\n let rec f res last cnt = function\n [] -> max res cnt\n | (x :: xs) ->\n if (cnt = 0) || (check last x) then f res x (cnt + 1) xs\n else f (max res cnt) x 1 xs\n in\n Printf.printf \"%d\\n\" (f 0 0 0 (Array.to_list a))\n;;\n\nlet _ = main()\n"}], "negative_code": [], "src_uid": "5088d1d358508ea3684902c8e32443a3"} {"nl": {"description": "Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i\u2009+\u20091 to ai inclusive. No tickets are sold at the last station.Let \u03c1i,\u2009j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values \u03c1i,\u2009j among all pairs 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n.", "input_spec": "The first line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of stations. The second line contains n\u2009-\u20091 integer ai (i\u2009+\u20091\u2009\u2264\u2009ai\u2009\u2264\u2009n), the i-th of them means that at the i-th station one may buy tickets to each station from i\u2009+\u20091 to ai inclusive.", "output_spec": "Print the sum of \u03c1i,\u2009j among all pairs of 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n.", "sample_inputs": ["4\n4 4 4", "5\n2 3 5 5"], "sample_outputs": ["6", "17"], "notes": "NoteIn the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.Consider the second sample: \u03c11,\u20092\u2009=\u20091 \u03c11,\u20093\u2009=\u20092 \u03c11,\u20094\u2009=\u20093 \u03c11,\u20095\u2009=\u20093 \u03c12,\u20093\u2009=\u20091 \u03c12,\u20094\u2009=\u20092 \u03c12,\u20095\u2009=\u20092 \u03c13,\u20094\u2009=\u20091 \u03c13,\u20095\u2009=\u20091 \u03c14,\u20095\u2009=\u20091 Thus the answer equals 1\u2009+\u20092\u2009+\u20093\u2009+\u20093\u2009+\u20091\u2009+\u20092\u2009+\u20092\u2009+\u20091\u2009+\u20091\u2009+\u20091\u2009=\u200917."}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\nlet print_int x = Printf.printf \"%d \" x;;\nlet print_int64 x = Printf.printf \"%Ld \" x;;\nlet print s = Printf.printf \"%s\" s;;\n\nmodule type S = sig\n val set : int -> int -> unit\n val get : int -> int \n val inc : int -> int -> unit\n val max_range : int -> int -> int \n val max_range_value : int -> int -> int\nend\n\nmodule MakeSegTree (M: (sig val size : int end)) : S = struct\n let n = M.size\n let nn = 3 * n\n \n let arr = Array.make n 0 \n let delta = Array.make nn 0\n\n let set i v = arr.(i) <- v\n let get i = arr.(i)\n\n let rec update c b e i =\n let upd c = \n if arr.(delta.(2*c)) < arr.(delta.(2*c+1)) then\n delta.(c) <- delta.(2*c+1)\n else \n delta.(c) <- delta.(2*c) in \n if (b > e || i > e || i < b) then ()\n else if ((i = b) && (i = e)) then delta.(c) <- i\n else if i <= (b+e)/2 then begin\n update (2*c) b ((b+e)/2) i; upd c\n end else begin \n update (2*c+1) (((b+e)/2)+1) e i; upd c\n end \n \n let inc i v =\n arr.(i) <- v;\n update 1 0 (n-1) i\n\n let rec query c b e i j = \n if (b > e || i > j || b > j || i > e) then -1 else\n if i <= b && e <= j then delta.(c) \n else\n let first = query (2*c) b ((b+e)/2) i j in\n let second = query (2*c+1) ((b+e)/2+1) e i j in\n match first,second with\n | -1,_ -> second\n | _,-1 -> first\n | _,_ -> \n if arr.(first) < arr.(second) then second \n else first \n\n let max_range i j = \n query 1 0 (n-1) i j\n\n let max_range_value i j =\n let ind = max_range i j in\n arr.(ind)\nend\n\nlet () =\n let n = read_int () in\n let module Size = struct \n let size = n\n end in\n let module Segtree = MakeSegTree(Size) in\n let dummy = Array.make (n-1) () in \n let arr = Array.map (fun _ -> read_int() -1) dummy in\n let add_to_seg i e =\n Segtree.inc i e in\n Array.iteri add_to_seg arr;\n Segtree.inc (n-1) 0;\n let dp = Array.make n Int64.zero in\n for i = n-2 downto 0 do\n let ma = Segtree.max_range (i+1) arr.(i) in\n dp.(i) <- Int64.add dp.(ma) (Int64.of_int (- (arr.(i) - ma) + (n - i - 1)));\n (*print_int i;\n print_int ma;\n print_int64 dp.(i);\n print_int64 (Int64.of_int ((arr.(i) - ma) + (n - i - 1))); \n print \"\\n\"; *)\n done;\n print_int64 (Array.fold_left Int64.add Int64.zero dp);;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet long = Int64.of_int\n\nlet parent v = v/2\nlet lc v = 2*v\nlet rc v = 2*v+1\n\nlet superceil n =\n let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in\n 1 + (loop (n-1) 0)\n\nlet max2 (h1,p1) (h2,p2) = let (x,y) = max (h1,-p1) (h2,-p2) in (x,-y)\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun i -> if i=n-1 then i else -1 + read_int()) in\n\n let nn = superceil n in\n\n let t = Array.make (2*nn) (0,0) in \n\n let rec insert ar (x,i) =\n let rec loop j = if j>0 then (\n ar.(j) <- max2 ar.(j) (x,i);\n loop (parent j)\n ) in\n loop (i+nn)\n in\n\n let max_in_range i j =\n let rec f v l r ql qr =\n let m = (l+r)/2 in\n if l=ql && r=qr then t.(v) else\n\tlet t1 = if ql<=m then f (lc v) l m ql (min m qr) else (0,0) in\n\tlet t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else (0,0) in\n\tmax2 t1 t2\n in\n f 1 0 (nn-1) i j\n in\n\n for i=0 to n-1 do\n insert t (a.(i),i)\n done;\n\n let dist = Array.make n 0L in\n (* dist.(i) is the sum over all j>i of the number of hops from i to j *)\n\n for i=n-2 downto 0 do\n let k = a.(i) in\n let (_,j) = max_in_range (i+1) k in\n (* dist.(i) <- (k-i) + dist.(j) - (k-j) + (n-1-k) *)\n dist.(i) <- (long (j+n-k-i-1)) ++ dist.(j)\n done;\n\n let answer = sum 0 (n-2) (fun i -> dist.(i)) 0L in\n printf \"%Ld\\n\" answer\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\nlet print_int x = Printf.printf \"%d \" x;;\nlet print_int64 x = Printf.printf \"%Ld \" x;;\nlet print s = Printf.printf \"%s\" s;;\n\nmodule type S = sig\n val set : int -> int -> unit\n val get : int -> int \n val inc : int -> int -> unit\n val max_range : int -> int -> int \n val max_range_value : int -> int -> int\nend\n\nmodule MakeSegTree (M: (sig val size : int end)) : S = struct\n let n = M.size\n let nn = 3 * n\n \n let arr = Array.make n 0 \n let delta = Array.make nn 0\n\n let set i v = arr.(i) <- v\n let get i = arr.(i)\n\n let rec update c b e i =\n let upd c = \n if arr.(delta.(2*c)) < arr.(delta.(2*c+1)) then\n delta.(c) <- delta.(2*c+1)\n else \n delta.(c) <- delta.(2*c) in \n if (b > e || i > e || i < b) then ()\n else if ((i = b) && (i = e)) then delta.(c) <- i\n else if i <= (b+e)/2 then begin\n update (2*c) b ((b+e)/2) i; upd c\n end else begin \n update (2*c+1) (((b+e)/2)+1) e i; upd c\n end \n \n let inc i v =\n arr.(i) <- v;\n update 1 0 (n-1) i\n\n let rec query c b e i j = \n if (b > e || i > j || b > j || i > e) then -1 else\n if i <= b && e <= j then delta.(c) \n else\n let first = query (2*c) b ((b+e)/2) i j in\n let second = query (2*c+1) ((b+e)/2+1) e i j in\n match first,second with\n | -1,_ -> second\n | _,-1 -> first\n | _,_ -> \n if arr.(first) < arr.(second) then second \n else first \n\n let max_range i j = \n query 1 0 (n-1) i j\n\n let max_range_value i j =\n let ind = max_range i j in\n arr.(ind)\nend\n\nlet () =\n let n = read_int () in\n let module Size = struct \n let size = n\n end in\n let module Segtree = MakeSegTree(Size) in\n let dummy = Array.make (n-1) () in \n let arr = Array.map (fun _ -> read_int() -1) dummy in\n let add_to_seg i e =\n Segtree.inc i e in\n Array.iteri add_to_seg arr;\n Segtree.inc (n-1) 0;\n let dp = Array.make n Int64.zero in\n for i = n-2 downto 0 do\n let ma = Segtree.max_range (i+1) arr.(i) in\n dp.(i) <- Int64.sub dp.(ma) (Int64.of_int ((arr.(i) - ma) + (n - i - 1)));\n done;\n print_int64 (Array.fold_left Int64.add Int64.zero dp);;\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\nlet print_int x = Printf.printf \"%d \" x;;\nlet print s = Printf.printf \"%s\" s;;\n\nmodule type S = sig\n val set : int -> int -> unit\n val get : int -> int \n val inc : int -> int -> unit\n val max_range : int -> int -> int \n val max_range_value : int -> int -> int\nend\n\nmodule MakeSegTree (M: (sig val size : int end)) : S = struct\n let n = M.size\n let nn = 3 * n\n \n let arr = Array.make n 0 \n let delta = Array.make nn 0\n\n let set i v = arr.(i) <- v\n let get i = arr.(i)\n\n let rec update c b e i =\n let upd c = \n if arr.(delta.(2*c)) < arr.(delta.(2*c+1)) then\n delta.(c) <- delta.(2*c+1)\n else \n delta.(c) <- delta.(2*c) in \n if (b > e || i > e || i < b) then ()\n else if ((i = b) && (i = e)) then delta.(c) <- i\n else if i <= (b+e)/2 then begin\n update (2*c) b ((b+e)/2) i; upd c\n end else begin \n update (2*c+1) (((b+e)/2)+1) e i; upd c\n end \n \n let inc i v =\n arr.(i) <- v;\n update 1 0 (n-1) i\n\n let rec query c b e i j = \n if (b > e || i > j || b > j || i > e) then -1 else\n if i <= b && e <= j then delta.(c) \n else\n let first = query (2*c) b ((b+e)/2) i j in\n let second = query (2*c+1) ((b+e)/2+1) e i j in\n match first,second with\n | -1,_ -> second\n | _,-1 -> first\n | _,_ -> \n if arr.(first) < arr.(second) then second \n else first \n\n let max_range i j = \n query 1 0 (n-1) i j\n\n let max_range_value i j =\n let ind = max_range i j in\n arr.(ind)\nend\n\nlet () =\n let n = read_int () in\n let module Size = struct \n let size = n\n end in\n let module Segtree = MakeSegTree(Size) in\n let dummy = Array.make (n-1) () in \n let arr = Array.map read_int dummy in\n let add_to_seg i e =\n Segtree.inc i e in\n Array.iteri add_to_seg arr;\n let dp = Array.make (n-1) 1 in\n let process cur e =\n let res,i = cur in\n let ran = arr.(i) in\n let ma = Segtree.max_range (i+1) (ran-1) in\n if ran < n then dp.(ma) <- dp.(ma) + e;\n (*print_int ma;\n print_int e;\n print_int (res + e*(n-i-1));\n print \"\\n\";*)\n (res + e*(n-i-1)),(i+1) in\n let res,_ = Array.fold_left process (0,0) dp in\n print_int res;;\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\nlet print_int x = Printf.printf \"%d \" x;;\nlet print s = Printf.printf \"%s\" s;;\n\nmodule type S = sig\n val set : int -> int -> unit\n val get : int -> int \n val inc : int -> int -> unit\n val max_range : int -> int -> int \n val max_range_value : int -> int -> int\nend\n\nmodule MakeSegTree (M: (sig val size : int end)) : S = struct\n let n = M.size\n let nn = 3 * n\n \n let arr = Array.make n 0 \n let delta = Array.make nn 0\n\n let set i v = arr.(i) <- v\n let get i = arr.(i)\n\n let rec update c b e i =\n let upd c = \n if arr.(delta.(2*c)) < arr.(delta.(2*c+1)) then\n delta.(c) <- delta.(2*c+1)\n else \n delta.(c) <- delta.(2*c) in \n if (b > e || i > e || i < b) then ()\n else if ((i = b) && (i = e)) then delta.(c) <- i\n else if i <= (b+e)/2 then begin\n update (2*c) b ((b+e)/2) i; upd c\n end else begin \n update (2*c+1) (((b+e)/2)+1) e i; upd c\n end \n \n let inc i v =\n arr.(i) <- v;\n update 1 0 (n-1) i\n\n let rec query c b e i j = \n if (b > e || i > j || b > j || i > e) then -1 else\n if i <= b && e <= j then delta.(c) \n else\n let first = query (2*c) b ((b+e)/2) i j in\n let second = query (2*c+1) ((b+e)/2+1) e i j in\n match first,second with\n | -1,_ -> second\n | _,-1 -> first\n | _,_ -> \n if arr.(first) < arr.(second) then second \n else first \n\n let max_range i j = \n query 1 0 (n-1) i j\n\n let max_range_value i j =\n let ind = max_range i j in\n arr.(ind)\nend\n\nlet () =\n let n = read_int () in\n let module Size = struct \n let size = n\n end in\n let module Segtree = MakeSegTree(Size) in\n let dummy = Array.make (n-1) () in \n let arr = Array.map (fun _ -> read_int() -1) dummy in\n let add_to_seg i e =\n Segtree.inc i e in\n Array.iteri add_to_seg arr;\n Segtree.inc (n-1) 0;\n let dp = Array.make n 0 in\n for i = n-2 downto 0 do\n let ma = Segtree.max_range (i+1) arr.(i) in\n dp.(i) <- dp.(ma) - (arr.(i) - ma) + (n - i - 1);\n done;\n print_int (Array.fold_left (fun a b -> a + b) 0 dp);;\n"}], "src_uid": "88f8f2c2f68589654709800ea9b19ecf"} {"nl": {"description": "This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computersPolycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. (1) \u2014 bus, (2) \u2014 ring, (3) \u2014 star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. ", "input_spec": "The first line contains two space-separated integers n and m (4\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a03\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n) \u2014 the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself.", "output_spec": "In a single line print the network topology name of the given graph. If the answer is the bus, print \"bus topology\" (without the quotes), if the answer is the ring, print \"ring topology\" (without the quotes), if the answer is the star, print \"star topology\" (without the quotes). If no answer fits, print \"unknown topology\" (without the quotes).", "sample_inputs": ["4 3\n1 2\n2 3\n3 4", "4 4\n1 2\n2 3\n3 4\n4 1", "4 3\n1 2\n1 3\n1 4", "4 4\n1 2\n2 3\n3 1\n1 4"], "sample_outputs": ["bus topology", "ring topology", "star topology", "unknown topology"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces contest 292 B - SMS Center *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n else Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet rec readlist n acc = match n with | 0 -> List.rev acc | _ -> readlist (n -1) (gr() :: acc);;\nlet debug = false;;\n\nlet n = gr();; (* size network *)\nlet m = gr();; (* number edges *)\n\nlet adj = Array.make (n +1) [];;\n\nlet rec readpairs n acc = match n with\n | 0 -> List.rev acc\n | _ ->\n let a = gr() in\n let b = gr() in\n readpairs (n -1) ((a, b) :: acc);;\n\nlet rec setadj lpr = match lpr with\n | [] -> ()\n | hd :: tl ->\n let (a, b) = hd in\n (\n adj.(a) <- b :: adj.(a);\n adj.(b) <- a :: adj.(b);\n setadj tl\n );;\n\nlet rec findone i acc =\n if i > n then acc\n else\n let ln = List.length adj.(i) in\n let nacc = if ln = 1 then (i :: acc) else acc in\n findone (i +1) nacc;;\n\nlet nextInSeq prev aa =\n match adj.(aa) with\n | a :: b :: [] ->\n if a = prev then b\n else if b = prev then a\n else raise (Failure \"not connected to prev\")\n | _ -> -1;;\n\nlet rec countLoop start prev cur cnt =\n let nxt = nextInSeq prev cur in\n if nxt = start then cnt\n\t\telse if nxt = -1 then (-1)\n else countLoop start cur nxt (cnt +1);;\n\nlet main() =\n let prs = readpairs m [] in\n let _ = setadj prs in\n let lone = findone 0 [] in\n let nones = List.length lone in\n\t\t(* let _ = print_int nones in *)\n if nones = 0 then\n (\n (* can be only loop *)\n let start = 1 in\n let a = (List.hd adj.(start)) in\n let nloop = countLoop start start a 0 in\n if nloop = n-2 then print_string \"ring topology\"\n else print_string \"unknown topology\"\n )\n else if nones = 2 then\n (\n (* checking bus config *)\n let a = List.hd lone in\n let b = List.hd (List.tl lone) in\n let anxt = (List.hd adj.(a)) in\n let nseq = countLoop b a anxt 0 in\n if nseq = n -3 then print_string \"bus topology\"\n else print_string \"unknown topology\"\n )\n else if nones = n -1 then\n (\n (* checking star *)\n let a = List.hd lone in\n let center = (List.hd adj.(a)) in\n let nstar = List.length adj.(center) in\n if nstar = n -1 then print_string \"star topology\"\n else print_string \"unknown topology\"\n )\n else\n print_string \"unknown topology\";;\n\nmain();;\n"}], "negative_code": [], "src_uid": "7bb088ce5e4e2101221c706ff87841e4"} {"nl": {"description": "Your favorite shop sells $$$n$$$ Kinder Surprise chocolate eggs. You know that exactly $$$s$$$ stickers and exactly $$$t$$$ toys are placed in $$$n$$$ eggs in total.Each Kinder Surprise can be one of three types: it can contain a single sticker and no toy; it can contain a single toy and no sticker; it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.", "input_spec": "The first line contains the single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of queries. Next $$$T$$$ lines contain three integers $$$n$$$, $$$s$$$ and $$$t$$$ each ($$$1 \\le n \\le 10^9$$$, $$$1 \\le s, t \\le n$$$, $$$s + t \\ge n$$$) \u2014 the number of eggs, stickers and toys. All queries are independent.", "output_spec": "Print $$$T$$$ integers (one number per query) \u2014 the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toy", "sample_inputs": ["3\n10 5 7\n10 10 10\n2 1 1"], "sample_outputs": ["6\n1\n2"], "notes": "NoteIn the first query, we have to take at least $$$6$$$ eggs because there are $$$5$$$ eggs with only toy inside and, in the worst case, we'll buy all of them.In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg.In the third query, we have to buy both eggs: one with a sticker and one with a toy."}, "positive_code": [{"source_code": "module Big = struct\n\n let ( ++ ) = Int64.add\n let ( -- ) = Int64.sub\n let ( ** ) = Int64.mul\n let ( // ) = Int64.div\n\n let babs = Int64.abs\n let rem = Int64.rem\n\nend\n\nmodule Helper = struct\n\n type t_type =\n | Int of int\n | Long of Int64.t\n\n let read_int ?endl () =\n match endl with\n | None -> Scanf.scanf \"%d \" (fun x -> x)\n | Some () -> Scanf.scanf \"%d\\n\" (fun x -> x)\n\n let read_long ?endl () =\n match endl with\n | None -> Scanf.scanf \"%Ld \" (fun x -> x)\n | Some () -> Scanf.scanf \"%Ld\\n\" (fun x -> x)\n\n let read_int_array n =\n let res = Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n Scanf.scanf \"\\n\" (fun _ -> ());\n res\n\n let read_long_array n =\n let res = Array.init n (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x)) in\n Scanf.scanf \"\\n\" (fun _ -> ());\n res\n\n let read_char_array n =\n let res = Array.init n (fun _ -> Scanf.scanf \"%c\" (fun x -> x)) in\n Scanf.scanf \"\\n\" (fun _ -> ());\n res\n\n let debug = function\n | Int x -> Printf.printf \"%d\\n\" x\n | Long x -> Printf.printf \"%Ld\\n\" x\n\n type 'a return = { return : 'b . 'a -> 'b }\n\n (* From Jane Street Tech Blog *)\n let with_return (type t) (f : _ -> t) =\n let module M = struct exception Return of t end in\n let return = { return = (fun x -> raise (M.Return x)); } in\n try f return with M.Return x -> x\n (* with_return (fun r -> do_somthing; if return_condition then r.return (); *)\n\n let loop n f = for i = 0 to n - 1 do f i; done\n\n let find_nb f a =\n let res = ref 0 in\n Array.iteri (fun i x -> if f i x then incr res) a;\n !res\n\nend\n\nlet () =\n let open Helper in\n let open Big in\n let t = read_int ~endl:() () in\n loop t (fun _ ->\n let n = read_long () in\n let s = read_long () in\n let t = read_long () in\n let x = s ++ t -- n in\n let s = s -- x in\n let t = t -- x in\n debug (Long ((max s t)++1L))\n )\n;;\n"}], "negative_code": [], "src_uid": "fb0a4c8f737c36596c2d8c1ae0d1e34e"} {"nl": {"description": "Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type). If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of friends. Then follow n data blocks that describe each friend's phone books. Each block is presented in the following form: first goes the line that contains integer si and string namei (0\u2009\u2264\u2009si\u2009\u2264\u2009100) \u2014 the number of phone numbers in the phone book of the i-th friend and the name of the i-th friend. The name is a non-empty sequence of uppercase and lowercase Latin letters, containing no more than 20 characters. Next si lines contain numbers as \"XX-XX-XX\", where X is arbitrary digits from 0 to 9.", "output_spec": "In the first line print the phrase \"If you want to call a taxi, you should call: \". Then print names of all friends whose phone books contain maximal number of taxi phone numbers. In the second line print the phrase \"If you want to order a pizza, you should call: \". Then print names of all friends who have maximal number of pizza phone numbers. In the third line print the phrase \"If you want to go to a cafe with a wonderful girl, you should call: \". Then print names of all friends who have maximal number of girls' phone numbers. Print the names in the order in which they are given in the input data. Separate two consecutive names with a comma and a space. Each line should end with exactly one point. For clarifications concerning the output form, see sample tests. It is necessary that you follow the output form strictly. Extra spaces are not allowed.", "sample_inputs": ["4\n2 Fedorov\n22-22-22\n98-76-54\n3 Melnikov\n75-19-09\n23-45-67\n99-99-98\n7 Rogulenko\n22-22-22\n11-11-11\n33-33-33\n44-44-44\n55-55-55\n66-66-66\n95-43-21\n3 Kaluzhin\n11-11-11\n99-99-99\n98-65-32", "3\n5 Gleb\n66-66-66\n55-55-55\n01-01-01\n65-43-21\n12-34-56\n3 Serega\n55-55-55\n87-65-43\n65-55-21\n5 Melnik\n12-42-12\n87-73-01\n36-04-12\n88-12-22\n82-11-43", "3\n3 Kulczynski\n22-22-22\n65-43-21\n98-12-00\n4 Pachocki\n11-11-11\n11-11-11\n11-11-11\n98-76-54\n0 Smietanka"], "sample_outputs": ["If you want to call a taxi, you should call: Rogulenko.\nIf you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.\nIf you want to go to a cafe with a wonderful girl, you should call: Melnikov.", "If you want to call a taxi, you should call: Gleb.\nIf you want to order a pizza, you should call: Gleb, Serega.\nIf you want to go to a cafe with a wonderful girl, you should call: Melnik.", "If you want to call a taxi, you should call: Pachocki.\nIf you want to order a pizza, you should call: Kulczynski, Pachocki.\nIf you want to go to a cafe with a wonderful girl, you should call: Kulczynski."], "notes": "NoteIn the first sample you are given four friends. Fedorov's phone book contains one taxi number and one pizza delivery number, Melnikov's phone book only has 3 numbers of girls, Rogulenko's one has 6 taxi numbers and one pizza delivery number, Kaluzhin's one contains 2 taxi numbers and one pizza delivery number.Thus, if you need to order a taxi, you should obviously call Rogulenko, if you need to order a pizza you should call anybody of the following: Rogulenko, Fedorov, Kaluzhin (each of them has one number). Melnikov has maximal number of phone numbers of girls. "}, "positive_code": [{"source_code": "let main () =\n let check a p =\n let rec loop i =\n i = 0 || p a.[i - 1] a.[i] && loop (i - 1)\n in\n loop (String.length a - 1)\n in\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, [|taxi; pizza; girl |] else\n let a = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in\n if check a (=) then loop (r - 1) (taxi + 1) pizza girl else\n if check a (>) then loop (r - 1) taxi (pizza + 1) girl \n else loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc flag k pos = function\n | (name, target) :: tl ->\n if target.(pos) = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc false k pos tl\n ) else proc flag k pos tl\n | _ -> print_endline \".\"\n in\n\n let comp k = (fun (_, a1) (_, a2) -> compare a2.(k) a1.(k)) in\n\n let l = Array.to_list arr in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort (comp 0) l with\n | (_, a) :: _ -> proc true a.(0) 0 l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort (comp 1) l with\n | (_, a) :: _ -> proc true a.(1) 1 l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort (comp 2) l with\n | (_, a) :: _ -> proc true a.(2) 2 l\n | _ -> ())\n;;\nmain ()\n"}, {"source_code": "let main () =\n let check a p =\n let rec loop i =\n i = 0 || p a.[i - 1] a.[i] && loop (i - 1)\n in\n loop (String.length a - 1)\n in\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, [|taxi; pizza; girl |] else\n let a = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in\n if check a (=) then loop (r - 1) (taxi + 1) pizza girl else\n if check a (>) then loop (r - 1) taxi (pizza + 1) girl \n else loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc flag k pos = function\n | (name, target) :: tl ->\n if target.(pos) = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc false k pos tl\n ) else proc flag k pos tl\n | _ -> print_endline \".\"\n in\n\n let comp k = (fun (_, a1) (_, a2) -> compare a2.(k) a1.(k)) in\n\n let l = Array.to_list arr in\n for i = 0 to 2 do\n print_string [| \"If you want to call a taxi, you should call: \";\n \"If you want to order a pizza, you should call: \";\n \"If you want to go to a cafe with a wonderful girl, you should call: \" |].(i);\n match List.sort (comp i) l with\n | (_, a) :: _ -> proc true a.(i) i l\n | _ -> ()\n done\n;;\nmain ()\n"}, {"source_code": "let main () =\n let map n s =\n let s1 = 8 lsl (int_of_char s.[0] - 48) in\n let s2 = 8 lsl (int_of_char s.[1] - 48) in\n let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in\n if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, taxi, pizza, girl else\n let a = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in\n if a.[0] = a.[1] && a.[0] = a.[2] &&\n a.[0] = a.[3] && a.[0] = a.[4] &&\n a.[0] = a.[5] then loop (r - 1) (taxi + 1) pizza girl else\n if a.[0] > a.[1] && a.[1] > a.[2] &&\n a.[2] > a.[3] && a.[3] > a.[4] &&\n a.[4] > a.[5] then loop (r - 1) taxi (pizza + 1) girl \n else loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc1 flag k = function\n | (name, taxi, _, _) :: tl ->\n if taxi = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc1 false k tl\n ) else proc1 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc2 flag k = function\n | (name, _, pizza, _) :: tl ->\n if pizza = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc2 false k tl\n ) else proc2 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc3 flag k = function\n | (name, _, _, girl) :: tl ->\n if girl = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc3 false k tl\n ) else proc3 flag k tl\n | _ -> print_endline \".\"\n in\n\n let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in\n let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in\n let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in\n\n let l = Array.to_list arr in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort comp1 l with\n | (_, k, _, _) :: _ -> proc1 true k l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort comp2 l with\n | (_, _, k, _) :: _ -> proc2 true k l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort comp3 l with\n | (_, _, _, k) :: _ -> proc3 true k l\n | _ -> ())\n;;\nmain ()\n"}, {"source_code": "let main () =\n let check a p =\n let rec loop i =\n i = 0 || p a.[i - 1] a.[i] && loop (i - 1)\n in\n loop (String.length a - 1)\n in\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, taxi, pizza, girl else\n let a = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in\n if check a (=) then loop (r - 1) (taxi + 1) pizza girl else\n if check a (>) then loop (r - 1) taxi (pizza + 1) girl \n else loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc1 flag k = function\n | (name, taxi, _, _) :: tl ->\n if taxi = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc1 false k tl\n ) else proc1 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc2 flag k = function\n | (name, _, pizza, _) :: tl ->\n if pizza = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc2 false k tl\n ) else proc2 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc3 flag k = function\n | (name, _, _, girl) :: tl ->\n if girl = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc3 false k tl\n ) else proc3 flag k tl\n | _ -> print_endline \".\"\n in\n\n let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in\n let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in\n let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in\n\n let l = Array.to_list arr in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort comp1 l with\n | (_, k, _, _) :: _ -> proc1 true k l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort comp2 l with\n | (_, _, k, _) :: _ -> proc2 true k l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort comp3 l with\n | (_, _, _, k) :: _ -> proc3 true k l\n | _ -> ())\n;;\nmain ()\n"}, {"source_code": "let main () =\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, taxi, pizza, girl else\n let a = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in\n if a.[0] = a.[1] && a.[0] = a.[2] &&\n a.[0] = a.[3] && a.[0] = a.[4] &&\n a.[0] = a.[5] then loop (r - 1) (taxi + 1) pizza girl else\n if a.[0] > a.[1] && a.[1] > a.[2] &&\n a.[2] > a.[3] && a.[3] > a.[4] &&\n a.[4] > a.[5] then loop (r - 1) taxi (pizza + 1) girl \n else loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc1 flag k = function\n | (name, taxi, _, _) :: tl ->\n if taxi = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc1 false k tl\n ) else proc1 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc2 flag k = function\n | (name, _, pizza, _) :: tl ->\n if pizza = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc2 false k tl\n ) else proc2 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc3 flag k = function\n | (name, _, _, girl) :: tl ->\n if girl = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc3 false k tl\n ) else proc3 flag k tl\n | _ -> print_endline \".\"\n in\n\n let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in\n let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in\n let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in\n\n let l = Array.to_list arr in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort comp1 l with\n | (_, k, _, _) :: _ -> proc1 true k l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort comp2 l with\n | (_, _, k, _) :: _ -> proc2 true k l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort comp3 l with\n | (_, _, _, k) :: _ -> proc3 true k l\n | _ -> ())\n;;\nmain ()"}, {"source_code": "\nlet main () = \n let kolvo = int_of_string (read_line ()) in\n\t(* \u0417\u0430\u043f\u043e\u043b\u043d\u044f\u0435\u043c \u043c\u0430\u0441\u0441\u0438\u0432 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u044f\u043c\u0438 \u0432 \u0444\u043e\u0440\u043c\u0430\u0442\u0435 \u0424\u0430\u043c\u0438\u043b\u0438\u044f, \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u044b \u0442\u0430\u043a\u0441\u0438, \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u044b \u043f\u0438\u0446\u0446\u044b, \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u044b \u0434\u0435\u0432\u043e\u0447\u0435\u043a *)\n let my_array = Array.init kolvo (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, taxi, pizza, girl else\n let temp = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in\n if temp.[0] = temp.[1] && temp.[0] = temp.[2] &&\n temp.[0] = temp.[3] && temp.[0] = temp.[4] &&\n temp.[0] = temp.[5] then loop (r - 1) (taxi + 1) pizza girl else\n if temp.[0] > temp.[1] && temp.[1] > temp.[2] &&\n temp.[2] > temp.[3] && temp.[3] > temp.[4] &&\n temp.[4] > temp.[5] then loop (r - 1) taxi (pizza + 1) girl \n else loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc1 flag k = function | (name, taxi, _, _) :: tl ->\n if taxi = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc1 false k tl\n ) else proc1 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc2 flag k = function\n | (name, _, pizza, _) :: tl ->\n if pizza = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc2 false k tl\n ) else proc2 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc3 flag k = function\n | (name, _, _, girl) :: tl ->\n if girl = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc3 false k tl\n ) else proc3 flag k tl\n | _ -> print_endline \".\"\n in\n\n let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in\n let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in\n let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in\n\n let l = Array.to_list my_array in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort comp1 l with\n | (_, k, _, _) :: _ -> proc1 true k l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort comp2 l with\n | (_, _, k, _) :: _ -> proc2 true k l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort comp3 l with\n | (_, _, _, k) :: _ -> proc3 true k l\n | _ -> ())\n;;\nmain ()"}, {"source_code": "let main () =\n\n\n let rec proc1 flag k = function\n | (name, taxi, _, _) :: tl ->\n if taxi = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc1 false k tl\n ) else proc1 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc2 flag k = function\n | (name, _, pizza, _) :: tl ->\n if pizza = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc2 false k tl\n ) else proc2 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc3 flag k = function\n | (name, _, _, girl) :: tl ->\n if girl = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc3 false k tl\n ) else proc3 flag k tl\n | _ -> print_endline \".\"\n in\n\n let map n s =\n let s1 = 8 lsl (int_of_char s.[0] - 48) in\n let s2 = 8 lsl (int_of_char s.[1] - 48) in\n let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in\n if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, taxi, pizza, girl else\n let a = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in\n if a.[0] = a.[1] && a.[0] = a.[2] &&\n a.[0] = a.[3] && a.[0] = a.[4] &&\n a.[0] = a.[5] then loop (r - 1) (taxi + 1) pizza girl else\n if a.[0] > a.[1] && a.[1] > a.[2] &&\n a.[2] > a.[3] && a.[3] > a.[4] &&\n a.[4] > a.[5] then loop (r - 1) taxi (pizza + 1) girl \n else loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n \n\n let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in\n let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in\n let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in\n\n let l = Array.to_list arr in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort comp1 l with\n | (_, k, _, _) :: _ -> proc1 true k l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort comp2 l with\n | (_, _, k, _) :: _ -> proc2 true k l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort comp3 l with\n | (_, _, _, k) :: _ -> proc3 true k l\n | _ -> ())\n;;\nmain ()"}, {"source_code": "let main () =\n let map n s =\n let s1 = 8 lsl (int_of_char s.[0] - 48) in\n let s2 = 8 lsl (int_of_char s.[1] - 48) in\n let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in\n if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, taxi, pizza, girl else\n let a = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in\n if a.[0] = a.[1] && a.[0] = a.[2] &&\n a.[0] = a.[3] && a.[0] = a.[4] &&\n a.[0] = a.[5] then loop (r - 1) (taxi + 1) pizza girl else\n if a.[0] > a.[1] && a.[1] > a.[2] &&\n a.[2] > a.[3] && a.[3] > a.[4] &&\n a.[4] > a.[5] then loop (r - 1) taxi (pizza + 1) girl \n else loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc1 flag k = function\n | (name, taxi, _, _) :: tl ->\n if taxi = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc1 false k tl\n ) else proc1 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc2 flag k = function\n | (name, _, pizza, _) :: tl ->\n if pizza = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc2 false k tl\n ) else proc2 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc3 flag k = function\n | (name, _, _, girl) :: tl ->\n if girl = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc3 false k tl\n ) else proc3 flag k tl\n | _ -> print_endline \".\"\n in\n\n let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in\n let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in\n let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in\n\n let l = Array.to_list arr in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort comp1 l with\n | (_, k, _, _) :: _ -> proc1 true k l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort comp2 l with\n | (_, _, k, _) :: _ -> proc2 true k l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort comp3 l with\n | (_, _, _, k) :: _ -> proc3 true k l\n | _ -> ())\n;;\nmain ()"}], "negative_code": [{"source_code": "let main () =\n let map n s =\n let s1 = 8 lsl (int_of_char s.[0]) in\n let s2 = 8 lsl (int_of_char s.[1]) in\n let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in\n if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, taxi, pizza, girl else\n let a1, a2, a3 = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1, a2, a3) in\n if a1 = a2 && a2 = a3 then loop (r - 1) (taxi + 1) pizza girl else\n if a1 > a2 && a2 > a3 && (map (map (map 0 a1) a2) a3) land 7 = 6\n then loop (r - 1) taxi (pizza + 1) girl else\n loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc1 flag k = function\n | (name, taxi, _, _) :: tl ->\n if taxi = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc1 false k tl\n ) else proc1 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc2 flag k = function\n | (name, _, pizza, _) :: tl ->\n if pizza = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc2 false k tl\n ) else proc2 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc3 flag k = function\n | (name, _, _, girl) :: tl ->\n if girl = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc3 false k tl\n ) else proc3 flag k tl\n | _ -> print_endline \".\"\n in\n\n let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in\n let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in\n let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in\n\n let l = Array.to_list arr in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort comp1 l with\n | (_, k, _, _) :: _ -> proc1 true k l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort comp2 l with\n | (_, _, k, _) :: _ -> proc2 true k l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort comp3 l with\n | (_, _, _, k) :: _ -> proc3 true k l\n | _ -> ())\n;;\nmain ()\n"}, {"source_code": "let main () =\n let map n s =\n let s1 = 8 lsl (int_of_char s.[0] - 48) in\n let s2 = 8 lsl (int_of_char s.[1] - 48) in\n let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in\n if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, taxi, pizza, girl else\n let a1, a2, a3 = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1, a2, a3) in\n if a1 = a2 && a2 = a3 then loop (r - 1) (taxi + 1) pizza girl else\n if a1 > a2 && a2 > a3 && (map (map (map 0 a1) a2) a3) land 7 = 6\n then loop (r - 1) taxi (pizza + 1) girl else\n loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc1 flag k = function\n | (name, taxi, _, _) :: tl ->\n if taxi = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc1 false k tl\n ) else proc1 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc2 flag k = function\n | (name, _, pizza, _) :: tl ->\n if pizza = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc2 false k tl\n ) else proc2 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc3 flag k = function\n | (name, _, _, girl) :: tl ->\n if girl = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc3 false k tl\n ) else proc3 flag k tl\n | _ -> print_endline \".\"\n in\n\n let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in\n let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in\n let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in\n\n let l = Array.to_list arr in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort comp1 l with\n | (_, k, _, _) :: _ -> proc1 true k l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort comp2 l with\n | (_, _, k, _) :: _ -> proc2 true k l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort comp3 l with\n | (_, _, _, k) :: _ -> proc3 true k l\n | _ -> ())\n;;\nmain ()\n"}, {"source_code": "let main () =\n let map n s =\n let s1 = 8 lsl (int_of_char s.[0] - 48) in\n let s2 = 8 lsl (int_of_char s.[1] - 48) in\n let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in\n if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in\n \n let n = int_of_string (read_line ()) in\n let arr = Array.init n (fun _ ->\n let (d, name) = Scanf.sscanf (read_line ()) \"%d %s\" (fun d name -> d, name) in\n let rec loop r taxi pizza girl =\n if r = 0 then name, taxi, pizza, girl else\n let a1, a2, a3 = Scanf.sscanf (read_line ()) \"%2s-%2s-%2s\" (fun a1 a2 a3 -> a1, a2, a3) in\n if a1 = a2 && a2 = a3 && int_of_string a1 mod 11 = 0 then loop (r - 1) (taxi + 1) pizza girl else\n if a1 > a2 && a2 > a3 && (map (map (map 0 a1) a2) a3) land 7 = 6\n then loop (r - 1) taxi (pizza + 1) girl else\n loop (r - 1) taxi pizza (girl + 1)\n in\n loop d 0 0 0\n )\n in\n\n let rec proc1 flag k = function\n | (name, taxi, _, _) :: tl ->\n if taxi = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc1 false k tl\n ) else proc1 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc2 flag k = function\n | (name, _, pizza, _) :: tl ->\n if pizza = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc2 false k tl\n ) else proc2 flag k tl\n | _ -> print_endline \".\"\n in\n\n let rec proc3 flag k = function\n | (name, _, _, girl) :: tl ->\n if girl = k then (\n Printf.printf \"%s%s\" (if flag then \"\" else \", \") name;\n proc3 false k tl\n ) else proc3 flag k tl\n | _ -> print_endline \".\"\n in\n\n let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in\n let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in\n let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in\n\n let l = Array.to_list arr in\n print_string \"If you want to call a taxi, you should call: \";\n (match List.sort comp1 l with\n | (_, k, _, _) :: _ -> proc1 true k l\n | _ -> ());\n\n print_string \"If you want to order a pizza, you should call: \";\n (match List.sort comp2 l with\n | (_, _, k, _) :: _ -> proc2 true k l\n | _ -> ());\n\n print_string \"If you want to go to a cafe with a wonderful girl, you should call: \";\n (match List.sort comp3 l with\n | (_, _, _, k) :: _ -> proc3 true k l\n | _ -> ())\n;;\nmain ()\n"}], "src_uid": "4791a795119c185b3aec91b6f8af8f03"} {"nl": {"description": "Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105). The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the initial group that is given to Toastman.", "output_spec": "Print a single integer \u2014 the largest possible score.", "sample_inputs": ["3\n3 1 5", "1\n10"], "sample_outputs": ["26", "10"], "notes": "NoteConsider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions."}, "positive_code": [{"source_code": "(**D. The Child and Sequence*)\n\nopen Scanf;;\nopen Num;;\nopen Printf;;\nopen Array;;\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x);;\n\nlet a = Array.create n 0;;\n\nlet total = ref (num_of_int 0);;\nfor i = 0 to n-1 do\n let ni = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n a.(i) <- ni; total:=!total +/ (num_of_int ni)\ndone\n ;;\n\nif n=1 then\n printf \"%s\\n\" (string_of_num !total)\nelse\n begin\n\n let () = Array.fast_sort (fun x y -> x-y) a in\n (*Array.iter(fun i -> printf \"%d\\n\" i) a;*)\n let rec cal_score m pn score total_v =\n match m with\n | 2 -> total_v +/ score\n | _ ->cal_score (m-1) (pn+1) (score+/total_v) (total_v -/\n (num_of_int\n a.(pn)) )\n in \n let rslt = cal_score n 0 (num_of_int 0) !total\n in\n print_string (string_of_num (rslt +/ !total) );\n print_endline \"\";\n end\n;;\n"}], "negative_code": [{"source_code": "(**D. The Child and Sequence*)\n\nopen Scanf;;\nopen Num;;\nopen Printf;;\nopen Array;;\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x);;\n\nlet a = Array.create n 0;;\n\nlet total = ref 0;;\nfor i = 0 to n-1 do\n let ni = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n a.(i) <- ni; total:=!total + ni\ndone\n ;;\n\nif n=1 then\n printf \"%d\\n\" !total\nelse\n begin\n\n let () = Array.fast_sort (fun x y -> x-y) a in\n (*Array.iter(fun i -> printf \"%d\\n\" i) a;*)\n let rec cal_score m pn score total_v =\n match m with\n | 2 -> total_v +/ score\n | _ ->cal_score (m-1) (pn+1) (score+/total_v) (total_v -/\n (num_of_int\n a.(pn)) )\n in \n let rslt = cal_score n 0 (num_of_int 0) (num_of_int !total)\n in\n print_string (string_of_num (rslt +/ (num_of_int !total)) );\n print_endline \"\";\n end\n;;\n"}, {"source_code": "(**D. The Child and Sequence*)\n\nopen Scanf;;\nopen Num;;\nopen Printf;;\nopen Array;;\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x);;\n\nlet a = Array.create n 0;;\n\nlet total = ref 0;;\nfor i = 0 to n-1 do\n let ni = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n a.(i) <- ni; total:=!total + ni\ndone\n ;;\n\nif n=1 then\n printf \"%d\\n\" !total\nelse\n begin\n\n let () = Array.fast_sort (fun x y -> x-y) a in\n (*Array.iter(fun i -> printf \"%d\\n\" i) a;*)\n let rec cal_score m pn score total_v =\n match m with\n | 2 -> total_v + score\n | _ ->cal_score (m-1) (pn+1) (score+total_v) (total_v - a.(pn))\n in \n let rslt = cal_score n 0 0 !total\n in\n printf \"%d\\n\" (rslt + !total)\n end\n;;\n"}], "src_uid": "4266948a2e793b4b461156af226e98fd"} {"nl": {"description": "A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string \"aab\" is an anagram of the string \"aba\" and the string \"aaa\" is not.The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string \"aba\" has six substrings: \"a\", \"b\", \"a\", \"ab\", \"ba\", \"aba\".You are given a string s, consisting of lowercase Latin letters and characters \"?\". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the \"?\" characters by Latin letters. Each \"?\" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = \u00ababa\u00bb, then the string \"a??\" is good, and the string \u00ab?bc\u00bb is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).", "input_spec": "The first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters \"?\". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.", "output_spec": "Print the single number representing the number of good substrings of string s. Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.", "sample_inputs": ["bb??x???\naab", "ab?c\nacb"], "sample_outputs": ["2", "2"], "notes": "NoteConsider the first sample test. Here the string s has two good substrings: \"b??\" (after we replace the question marks we get \"baa\"), \"???\" (after we replace the question marks we get \"baa\").Let's consider the second sample test. Here the string s has two good substrings: \"ab?\" (\"?\" can be replaced by \"c\"), \"b?c\" (\"?\" can be replaced by \"a\")."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet () =\n let s = read_string() in\n let p = read_string() in\n let m = String.length s in\n let n = String.length p in\n let () = if m '?' then hists.(j) <- hists.(j)+1\n done\n in\n let rec goodh i = if i=26 then true else histp.(i) >= hists.(i) && goodh(i+1)\n in\n let rec scan j ac =\n let inc = if goodh 0 then 1 else 0 in\n if j = m then inc + ac else (\n if s.[j]<> '?' then hists.(ci s.[j]) <- hists.(ci s.[j])+1;\n if s.[j-n] <> '?' then hists.(ci s.[j-n]) <- hists.(ci s.[j-n])-1;\n scan (j+1) (ac+inc)\n )\n in\n Printf.printf \"%d\\n\" (scan n 0)\n"}, {"source_code": "(* codeforces 103. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let s = read_string() in\n let p = read_string() in\n\n let m = String.length s in\n let n = String.length p in\n\n let () = if m < n then (Printf.printf \"0\\n\"; exit 1) in\n\n let histp = Array.make 26 0 in\n let hists = Array.make 26 0 in\n\n let ctoint c = (int_of_char c) - (int_of_char 'a') in\n \n let () =\n for i=0 to n-1 do\n let j = ctoint p.[i] in\n histp.(j) <- histp.(j) + 1\n done\n in\n\n let () =\n for i=0 to n-1 do\n let j = ctoint s.[i] in\n if s.[i] <> '?' then hists.(j) <- hists.(j) + 1\n done\n in\n\n let rec goodh i = if i=26 then true else histp.(i) >= hists.(i) && goodh (i+1) in\n\n let rec scan j ac = \n let inc = if goodh 0 then 1 else 0 in\n if j=m then inc + ac else (\n\tif s.[j] <> '?' then hists.(ctoint s.[j]) <- hists.(ctoint s.[j]) + 1;\n\tif s.[j-n] <> '?' then hists.(ctoint s.[j-n]) <- hists.(ctoint s.[j-n]) - 1;\n\tscan (j+1) (ac+inc)\n )\n in\n\n Printf.printf \"%d\\n\" (scan n 0)\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let s = read_string() in\n let p = read_string() in\n let m = String.length s in\n let n = String.length p in\n let () = if m '?' then hists.(j) <- hists.(j)+1\n\tdone\n in\n let rec goodh i = if i=26 then true else histp.(i) >= hists.(i) && goodh(i+1)\n in\n let rec scan j ac = \n\tlet inc = if goodh 0 then 1 else 0 in\n\tif j = m then inc + ac else (\n\t if s.[j]<> '?' then hists.(ci s.[j]) <- hists.(ci s.[j])+1;\n\t if s.[j-n] <> '?' then hists.(ci s.[j-n]) <- hists.(ci s.[j-n])+1;\n\t scan (j+1) (ac+inc)\n\t)\n in\n Printf.printf \"%d\\n\" (scan n 0)\n\t \n"}, {"source_code": "(* codeforces 103. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let s = read_string() in\n let p = read_string() in\n\n let m = String.length s in\n let n = String.length p in\n\n let histp = Array.make 26 0 in\n let hists = Array.make 26 0 in\n\n let ctoint c = (int_of_char c) - (int_of_char 'a') in\n \n let () =\n for i=0 to n-1 do\n let j = ctoint p.[i] in\n histp.(j) <- histp.(j) + 1\n done\n in\n\n let () =\n for i=0 to n-1 do\n let j = ctoint s.[i] in\n if s.[i] <> '?' then hists.(j) <- hists.(j) + 1\n done\n in\n\n let rec goodh i = if i=26 then true else histp.(i) >= hists.(i) && goodh (i+1) in\n\n let rec scan j ac = \n let inc = if goodh 0 then 1 else 0 in\n if j=m then inc + ac else (\n\tif s.[j] <> '?' then hists.(ctoint s.[j]) <- hists.(ctoint s.[j]) + 1;\n\tif s.[j-n] <> '?' then hists.(ctoint s.[j-n]) <- hists.(ctoint s.[j-n]) - 1;\n\tscan (j+1) (ac+inc)\n )\n in\n\n Printf.printf \"%d\\n\" (scan n 0)\n"}], "src_uid": "9ed2a081b65df66629fcf0d4fc0bb02c"} {"nl": {"description": "You are given a rectangular grid of lattice points from (0,\u20090) to (n,\u2009m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.A polyline defined by points p1,\u2009p2,\u2009p3,\u2009p4 consists of the line segments p1\u2009p2,\u2009p2\u2009p3,\u2009p3\u2009p4, and its length is the sum of the lengths of the individual line segments.", "input_spec": "The only line of the input contains two integers n and m (0\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000). It is guaranteed that grid contains at least 4 different points.", "output_spec": "Print 4 lines with two integers per line separated by space \u2014 coordinates of points p1,\u2009p2,\u2009p3,\u2009p4 in order which represent the longest possible polyline. Judge program compares your answer and jury's answer with 10\u2009-\u20096 precision.", "sample_inputs": ["1 1", "0 10"], "sample_outputs": ["1 1\n0 0\n1 0\n0 1", "0 1\n0 10\n0 0\n0 9"], "notes": null}, "positive_code": [{"source_code": "let print xs =\n List.iter (fun (x, y) ->\n Printf.printf \"%d %d\\n\" x y) xs\n;;\n\nlet foi = float_of_int ;;\nlet sq x = x *. x ;;\nlet norm x y = sqrt (sq x +. sq y)\n\nlet f1 x y =\n let x, y = foi x, foi y in\n max x y +. 2. *. norm x y\n;;\n\nlet f2 x y =\n let x, y = foi x, foi y in\n norm x y +. 2. *. norm (x -. 1.) y\n;;\n\nlet f3 x y =\n let x, y = foi x, foi y in\n norm x y +. 2. *. norm x (y -. 1.)\n;;\n\nlet () =\n Scanf.scanf \"%d %d \" (fun n m ->\n if n = 0 then\n print [(0, 1); (0, m); (0, 0); (0, m - 1)]\n else if m = 0 then\n print [(1, 0); (n, 0); (0, 0); (n - 1, 0)]\n else if f1 n m > max (f2 n m) (f3 n m) then\n if n >= m then\n print [(0, 0); (n, m); (0, m); (n, 0)]\n else\n print [(0, 0); (n, m); (n, 0); (0, m)]\n else if f2 n m > f3 n m then\n print [(n - 1, m); (0, 0); (n, m); (1, 0)]\n else \n print [(n, m - 1); (0, 0); (n, m); (0, 1)])\n;;\n"}], "negative_code": [{"source_code": "let print xs =\n List.iter (fun (x, y) ->\n Printf.printf \"%d %d\\n\" x y) xs\n;;\n\nlet foi = float_of_int ;;\nlet sq x = x *. x ;;\nlet norm x y = sqrt (sq x +. sq y)\n\nlet f1 x y =\n let x, y = foi x, foi y in\n max x y +. 2. *. norm x y\n;;\n\nlet f2 x y =\n let x, y = foi x, foi y in\n norm x y +. norm (x -. 1.) y +. norm x (y -. 1.)\n;;\n \nlet () =\n Scanf.scanf \"%d %d \" (fun n m ->\n if n = 0 then\n print [(0, 1); (0, m); (0, 0); (0, m - 1)]\n else if m = 0 then\n print [(1, 0); (n, 0); (0, 0); (n - 1, 0)]\n else if f1 n m > f2 n m then\n if n >= m then\n print [(0, 0); (n, m); (0, m); (n, 0)]\n else\n print [(0, 0); (n, m); (n, 0); (0, m)]\n else \n print [(n - 1, m); (0, 0); (n, m); (1, 0)])\n;\n"}], "src_uid": "78d54d76cb113cf74ea89fb77471859b"} {"nl": {"description": "Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.Help Vasya to recover the initial set of cards with numbers.", "input_spec": "The single line contains three space-separated integers: n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the initial number of cards on the table, d (|d|\u2009\u2264\u2009104) \u2014 the number on the card that was left on the table after all the magical actions, and l (1\u2009\u2264\u2009l\u2009\u2264\u2009100) \u2014 the limits for the initial integers.", "output_spec": "If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.", "sample_inputs": ["3 3 2", "5 -4 3", "5 -4 4"], "sample_outputs": ["2 1 2", "-1", "2 4 1 4 1"], "notes": null}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\n\nlet rec loop n d l x a = \n if n <= 0 then Printf.printf(\"\\n\")\n else\n if d > x then\n if a = -1 then begin Printf.printf \"1 \"; loop (n-1) d l x (a*(-1)) end\n else let z = min (d-x) (l-1) in\n begin Printf.printf \"%d \" (z+1); loop (n-1) d l (x+z) (a*(-1)) end\n else if d < x then\n if a = 1 then begin Printf.printf \"1 \"; loop (n-1) d l x (a*(-1)) end\n else let z = min (x-d) (l-1) in\n begin Printf.printf \"%d \" (z+1); loop (n-1) d l (x-z) (a*(-1)) end\n else begin Printf.printf \"1 \"; loop (n-1) d l x (a*(-1)) end\n \n\nlet _ = \n let (n,d,l) = read3() in\n if ( (n+1)/2 - (n/2) - (l-1)*(n/2) > d || (n+1)/2 - (n/2) + (l-1)*((n+1)/2) < d )\n then Printf.printf \"-1\\n\"\n else\n loop n d l ( (n+1)/2 - n/2 ) 1;;\n"}, {"source_code": "let read_one () = Scanf.scanf \" %d\" (fun x -> x)\nlet read_two () = Scanf.scanf \" %d %d\" (fun x y -> (x,y)) \nlet read_three () = Scanf.scanf \"%d %d %d\" (fun x y z -> (x,y,z))\n\nlet read_many n =\n let rec helper i acc =\n if i >= n then List.rev acc\n else Scanf.scanf \" %d\" (fun n -> helper (i+1) (n::acc)) in\n helper 0 []\n\nlet list_iteri f lst = List.fold_left (fun j b -> f j b; j+1) 0 lst\n\nlet even n = n mod 2 = 0\n\nlet rec solve cur tar left l =\n if left <= 0 then [] \n else if cur = tar then \n if even left then\n 1 :: 1 :: ( solve cur tar (left - 2) l)\n else \n 1 :: 2 :: 1 :: (solve cur tar (left - 3) l)\n else if cur > tar then\n let sub = min (cur + 1 - tar) l in\n let new_cur = cur + 1 - sub in\n if new_cur = tar && left = 3 then\n\tlet sub = sub + 1 in\n\t1 :: sub :: 1 :: []\n else\n 1 :: sub :: (solve new_cur tar (left - 2) l)\n else (* cur > tar *)\n let add = min l (tar + 1 - cur) in\n let new_cur = cur + add - 1 in\n if new_cur = tar && left = 3 then\n let add = add - 1 in\n add :: 1 :: 1 :: []\n else if left = 1 then\n let add = tar - cur in\n add :: [] \n else\n add :: 1 :: (solve new_cur tar (left - 2) l)\n\nlet main =\n let (n,d,l) = read_three() in\n let min_d = (n - n / 2) - (n / 2) * l in\n let max_d = (n - n / 2) * l - (n / 2) in\n if min_d > d || max_d < d then \n Printf.printf \"-1\\n\"\n else \n let print j b = \n if j = n - 1 then Printf.printf \"%d\\n\" b\n else Printf.printf \"%d \" b in\n ignore (list_iteri print (solve 0 d n l));\n \n\n"}], "negative_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\n\nlet rec loop n d l x a = \n if n <= 0 then Printf.printf(\"\\n\")\n else\n if d > x then\n if a = -1 then begin Printf.printf \"1 \"; loop (n-1) d l x (a*(-1)) end\n else let z = min (d-x) (l-1) in\n begin Printf.printf \"%d \" (z+1); loop (n-1) d l (x+z) (a*(-1)) end\n else if d < x then\n if a = 1 then begin Printf.printf \"1 \"; loop (n-1) d l x (a*(-1)) end\n else let z = min (x-d) (l-1) in\n begin Printf.printf \"%d \" (z+1); loop (n-1) d l (x-z) (a*(-1)) end\n else begin Printf.printf \"1 \"; loop (n-1) d l x (a*(-1)) end\n \n\nlet _ = \n let (n,d,l) = read3() in\n Printf.printf \"%d %d %d\\n\" n d l;\n if ( (n+1)/2 - (n/2) - (l-1)*(n/2) > d || (n+1)/2 - (n/2) + (l-1)*((n+1)/2) < d )\n then Printf.printf \"-1\\n\"\n else\n loop n d l ( (n+1)/2 - n/2 ) 1;;\n"}], "src_uid": "a20d59a0db07cbb5692f01d28e41a3a1"} {"nl": {"description": "Dwarfs have planted a very interesting plant, which is a triangle directed \"upwards\". This plant has an amusing feature. After one year a triangle plant directed \"upwards\" divides into four triangle plants: three of them will point \"upwards\" and one will point \"downwards\". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process. Help the dwarfs find out how many triangle plants that point \"upwards\" will be in n years.", "input_spec": "The first line contains a single integer n (0\u2009\u2264\u2009n\u2009\u2264\u20091018) \u2014 the number of full years when the plant grew. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout streams or the %I64d specifier.", "output_spec": "Print a single integer \u2014 the remainder of dividing the number of plants that will point \"upwards\" in n years by 1000000007 (109\u2009+\u20097).", "sample_inputs": ["1", "2"], "sample_outputs": ["3", "10"], "notes": "NoteThe first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one."}, "positive_code": [{"source_code": "let m = 1000000007L\n\nlet mmod n =\n let r = Int64.rem n m in\n if r >= 0L\n then r\n else Int64.add r m\n\nlet msquare a =\n let n = Array.length a in\n let r = Array.make_matrix n n 0L in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tfor k = 0 to n - 1 do\n\t r.(i).(j) <-\n\t mmod (Int64.add r.(i).(j) (Int64.mul a.(i).(k) a.(k).(j)))\n\tdone;\n done\n done;\n r\n\nlet powermod r b n =\n let w = Array.length r in\n let r = ref r in\n let b = ref b in\n let n = ref n in\n let t = ref 0L in\n while !n > 0L do\n if Int64.rem !n 2L <> 0L then (\n\tlet r2 = Array.make w 0L in\n\t for i = 0 to w - 1 do\n\t t := 0L;\n\t for j = 0 to w - 1 do\n\t t := mmod (Int64.add !t (Int64.mul !r.(j) !b.(j).(i)))\n\t done;\n\t r2.(i) <- !t;\n\t done;\n\t r := r2;\n );\n b := msquare !b;\n n := Int64.div !n 2L;\n done;\n !r\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let r = [| 1L; 0L|] in\n let b =\n [| [|3L; 1L|];\n [|1L; 3L|];\n |]\n in\n let res = powermod r b n in\n Printf.printf \"%Ld\\n\" res.(0)\n"}], "negative_code": [], "src_uid": "782b819eb0bfc86d6f96f15ac09d5085"} {"nl": {"description": "Ilya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of cards Ilya has. Each of the next n lines contains two non-negative space-separated integers \u2014 ai and bi (0\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009104) \u2014 the numbers, written at the top and the bottom of the i-th card correspondingly.", "output_spec": "Print the single number \u2014 the maximum number of points you can score in one round by the described rules.", "sample_inputs": ["2\n1 0\n2 0", "3\n1 0\n2 0\n0 2"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first sample none of two cards brings extra moves, so you should play the one that will bring more points.In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards."}, "positive_code": [{"source_code": "let main () =\n let n = read_int () in\n let arr = Array.init n (fun _ -> Scanf.sscanf (read_line ()) \"%d %d\" (fun a b -> b, a)) in\n Array.sort (fun a b -> compare b a) arr;\n let list = Array.to_list arr in\n let rec loop r acc = function\n | [] -> acc\n | (a, b) :: tl -> if r = 0 then acc else loop (r - 1 + a) (b + acc) tl\n in\n let ans = loop 1 0 list in\n Printf.printf \"%d\\n\" ans\n;;\nmain ()\n"}, {"source_code": "let rec input_cards n lst =\n if n = 0 then lst\n else input_cards (n-1) ((Scanf.scanf \" %d %d\" (fun x y -> (x, y))) :: lst)\n\nlet sort_cards cards =\n let compare_cards a b =\n if a = b then 0\n else if (snd a) > (snd b) then -1\n else if (snd a) = (snd b) && (fst a) > (fst b) then -1\n else 1\n in\n List.sort compare_cards cards\n\nlet rec solve cards opportunity points =\n match cards with\n | [] -> points\n | h :: t ->\n if opportunity = 0 then points\n else solve t (opportunity + (snd h) - 1) (points + (fst h))\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let cards = input_cards n [] in\n Printf.printf \"%d\\n\" (solve (sort_cards cards) 1 0)\n \n"}], "negative_code": [], "src_uid": "4abdd16670a796be3a0bff63b9798fed"} {"nl": {"description": "Mitya has a rooted tree with $$$n$$$ vertices indexed from $$$1$$$ to $$$n$$$, where the root has index $$$1$$$. Each vertex $$$v$$$ initially had an integer number $$$a_v \\ge 0$$$ written on it. For every vertex $$$v$$$ Mitya has computed $$$s_v$$$: the sum of all values written on the vertices on the path from vertex $$$v$$$ to the root, as well as $$$h_v$$$\u00a0\u2014 the depth of vertex $$$v$$$, which denotes the number of vertices on the path from vertex $$$v$$$ to the root. Clearly, $$$s_1=a_1$$$ and $$$h_1=1$$$.Then Mitya erased all numbers $$$a_v$$$, and by accident he also erased all values $$$s_v$$$ for vertices with even depth (vertices with even $$$h_v$$$). Your task is to restore the values $$$a_v$$$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $$$a_v$$$ for all vertices in the tree.", "input_spec": "The first line contains one integer $$$n$$$\u00a0\u2014 the number of vertices in the tree ($$$2 \\le n \\le 10^5$$$). The following line contains integers $$$p_2$$$, $$$p_3$$$, ... $$$p_n$$$, where $$$p_i$$$ stands for the parent of vertex with index $$$i$$$ in the tree ($$$1 \\le p_i < i$$$). The last line contains integer values $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$-1 \\le s_v \\le 10^9$$$), where erased values are replaced by $$$-1$$$.", "output_spec": "Output one integer\u00a0\u2014 the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.", "sample_inputs": ["5\n1 1 1 1\n1 -1 -1 -1 -1", "5\n1 2 3 1\n1 -1 2 -1 -1", "3\n1 2\n2 -1 1"], "sample_outputs": ["1", "2", "-1"], "notes": null}, "positive_code": [{"source_code": "let rec fix f x = f (fix f) x\nlet (++),(--),max_int = Int64.(add,sub,max_int);;\nScanf.(Array.(scanf \" %d\" @@ fun n ->\n let edg = make n [] in\n ignore @@\n init (n-1) (fun i ->\n let j = scanf \" %d\" @@ fun v -> v in (\n let i,j = i+1,j-1 in\n edg.(i) <- j :: edg.(i);\n edg.(j) <- i :: edg.(j)));\n (* iteri (fun i ls ->\n Printf.printf \"%d: \" i;\n List.iter (Printf.printf \"%d \") ls;\n print_newline ()\n ) edg; *)\n let s = init n @@ fun _ -> scanf \" %Ld\" @@ fun v -> v in\n let undef = -7L in\n let a = make n undef in\n let visited = make n false in\n fix (fun f i even par ->\n visited.(i) <- true;\n if not even then (\n if i=0 then (\n a.(i) <- s.(i)\n ) else (\n a.(i) <- s.(i) -- s.(par)\n );\n List.iter (fun j ->\n if not @@ visited.(j) then f j (not even) i\n ) edg.(i)\n ) else (\n let sh = s.(par) in\n let smin = List.fold_left (fun mn j ->\n if par=j then mn\n else min mn s.(j)\n ) max_int edg.(i) in\n let smin = if smin = max_int then sh else smin in\n let si = smin -- sh in\n if si < 0L then (print_string \"-1\"; exit 0);\n s.(i) <- smin;\n a.(i) <- smin -- s.(par);\n List.iter (fun j ->\n if not @@ visited.(j) then f j (not even) i\n ) edg.(i)\n )\n ) 0 false 0;\n (* iter (Printf.printf \"%d \") a;\n print_newline ();\n iter (Printf.printf \"%d \") s;\n print_newline (); *)\n Printf.printf \"%Ld\" @@ fold_left (++) 0L a\n))"}], "negative_code": [{"source_code": "let rec fix f x = f (fix f) x;;\nScanf.(Array.(scanf \" %d\" @@ fun n ->\n let edg = make n [] in\n ignore @@\n init (n-1) (fun i ->\n let j = scanf \" %d\" @@ fun v -> v in (\n let i,j = i+1,j-1 in\n edg.(i) <- j :: edg.(i);\n edg.(j) <- i :: edg.(j)));\n (* iteri (fun i ls ->\n Printf.printf \"%d: \" i;\n List.iter (Printf.printf \"%d \") ls;\n print_newline ()\n ) edg; *)\n let s = init n @@ fun _ -> scanf \" %d\" @@ fun v -> v in\n let undef = -7 in\n let a = make n undef in\n let visited = make n false in\n fix (fun f i even par ->\n visited.(i) <- true;\n if not even then (\n if i=0 then (\n a.(i) <- s.(i)\n ) else (\n a.(i) <- s.(i) - s.(par)\n );\n List.iter (fun j ->\n if not @@ visited.(j) then f j (not even) i\n ) edg.(i)\n ) else (\n let sh = s.(par) in\n let smin = List.fold_left (fun mn j ->\n if par=j then mn\n else min mn s.(j)\n ) max_int edg.(i) in\n let smin = if smin = max_int then sh else smin in\n let si = smin - sh in\n if si < 0 then (print_string \"-1\"; exit 0);\n s.(i) <- smin;\n a.(i) <- smin - s.(par);\n List.iter (fun j ->\n if not @@ visited.(j) then f j (not even) i\n ) edg.(i)\n )\n ) 0 false 0;\n (* iter (Printf.printf \"%d \") a;\n print_newline ();\n iter (Printf.printf \"%d \") s;\n print_newline (); *)\n print_int @@ fold_left (+) 0 a\n))"}], "src_uid": "7d5ecacc037c9b0e6de2e86b20638674"} {"nl": {"description": "Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.Chouti remembered that $$$n$$$ persons took part in that party. To make the party funnier, each person wore one hat among $$$n$$$ kinds of weird hats numbered $$$1, 2, \\ldots n$$$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.After the party, the $$$i$$$-th person said that there were $$$a_i$$$ persons wearing a hat differing from his own.It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $$$b_i$$$ be the number of hat type the $$$i$$$-th person was wearing, Chouti wants you to find any possible $$$b_1, b_2, \\ldots, b_n$$$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$), the number of persons in the party. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le n-1$$$), the statements of people.", "output_spec": "If there is no solution, print a single line \"Impossible\". Otherwise, print \"Possible\" and then $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le n$$$). If there are multiple answers, print any of them.", "sample_inputs": ["3\n0 0 0", "5\n3 3 2 2 2", "4\n0 1 2 3"], "sample_outputs": ["Possible\n1 1 1", "Possible\n1 1 2 2 2", "Impossible"], "notes": "NoteIn the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind $$$1$$$.In the answer to the second example, the first and the second person wore the hat with type $$$1$$$ and all other wore a hat of type $$$2$$$.So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their own.In the third example, it can be shown that no solution exists.In the first and the second example, other possible configurations are possible."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(struct type t= int64 let compare = rv compare end)\nmodule IMap2=Map.Make(Int64)\nlet () =\n let n = gi 0 in let a = iia n in\n let mp = ref IMap.empty in\n iter (fun v ->\n mp := IMap.add v (1L+try IMap.find v !mp with _ -> 0L) !mp\n ) a;\n let itoc = ref IMap2.empty in\n let color = ref 1L in\n IMap.iter (fun k c ->\n (* if k=0L then (\n let r = ref [] in\n rep 1L c (fun i -> r := (!color,k) :: !r; color += 1L);\n itoc := IMap2.add k !r !itoc\n ) else ( *)\n if c mod (n-k) <> 0L then (\n printf \"Impossible\"; exit 0\n );\n let r = ref [] in\n rep 1L (c/(n-k)) (fun i -> r := (!color,n-k) :: !r; color += 1L);\n (* r := (!color,c) :: !r; color += 1L; *)\n itoc := IMap2.add k !r !itoc;\n (* printf \"added: %Ld : \" k;\n print_list (fun (k,v) -> sprintf \"%Ld:%Ld\" k v) !r; *)\n (* ) *)\n ) !mp;\n let res = make (i32 n) 0L in\n iteri (fun i v ->\n (* printf \"%d:%Ld\\n\" i v; *)\n (* let ls = IMap2.find v !itoc in\n let (c,rest)::tl = ls in\n printf \"ls: \"; print_list (fun (k,v) -> sprintf \"%Ld,%Ld\" k v) ls; *)\n let c,rest,tl = match IMap2.find v !itoc with\n | (c,rest)::tl -> c,rest,tl\n | _ -> fail 0 in\n (* printf \"%Ld \" c; *)\n res.(i) <- c;\n (* print_array ist res; *)\n if rest=1L then itoc := IMap2.add v tl !itoc\n else itoc := IMap2.add v ((c,rest-1L)::tl) !itoc\n ) a;\n printf \"Possible\\n\";\n print_array ist res\n (* let p = mapi (fun i v -> (v,i)) a in\n sort (rv compare) p;\n let b = make (i32 n) 0L in\n let prev = ref 0L in\n iteri (fun i v ->\n if i=0 then (\n\n ) else (\n\n )\n ) p; *)\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "f49667ef00cd0da6a6fad67a19d92f1e"} {"nl": {"description": "Sereja has got an array, consisting of n integers, a1,\u2009a2,\u2009...,\u2009an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi\u2009=\u2009xi. Increase each array element by yi. In other words, perform n assignments ai\u2009=\u2009ai\u2009+\u2009yi (1\u2009\u2264\u2009i\u2009\u2264\u2009n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.", "input_spec": "The first line contains integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1\u2009\u2264\u2009ti\u2009\u2264\u20093) that represents the operation type. If ti\u2009=\u20091, then it is followed by two integers vi and xi, (1\u2009\u2264\u2009vi\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009xi\u2009\u2264\u2009109). If ti\u2009=\u20092, then it is followed by integer yi (1\u2009\u2264\u2009yi\u2009\u2264\u2009104). And if ti\u2009=\u20093, then it is followed by integer qi (1\u2009\u2264\u2009qi\u2009\u2264\u2009n).", "output_spec": "For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.", "sample_inputs": ["10 11\n1 2 3 4 5 6 7 8 9 10\n3 2\n3 9\n2 10\n3 1\n3 10\n1 1 10\n2 10\n2 10\n3 1\n3 10\n3 9"], "sample_outputs": ["2\n9\n11\n20\n30\n40\n39"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.scanf \" %d\" (fun x -> x)\nlet read_string _ = Scanf.scanf \" %s\" (fun x -> x)\n\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n \n let implode l =\n let result = String.create (List.length l) in\n let rec imp i = function\n | [] -> result\n | c :: l -> result.[i] <- c; imp (i + 1) l in\n imp 0 l;;\n \nlet (--) i j = \n let rec aux n acc =\n if n < i then acc else aux (n-1) (n :: acc)\n in aux j []\n \nlet () = \n let n = read_int () in\n let m = read_int () in\n \n let bit = Array.init (n + 1) (fun _ -> 0L) in\n \n let update x v = \n let x = ref x in\n while !x <= n do\n bit.(!x) <- Int64.add bit.(!x) v;\n x := !x + (!x land (~- !x));\n done\n in\n \n let sum x =\n let x = ref x in\n let ret = ref 0L in\n while !x > 0 do\n ret := Int64.add !ret bit.(!x);\n x := !x - (!x land (~- !x));\n done;\n !ret\n in\n \n let arr = Array.init n (fun _ -> Int64.of_int (read_int ())) in\n \n for i = 0 to n-1 do\n update (i+1) arr.(i);\n update (i+2) (Int64.neg arr.(i));\n done;\n \n for i = 1 to m do\n let t = read_int () in\n match t with \n | 1 -> \n let x = read_int () in\n let v = (Int64.of_int (read_int ())) in\n let curr = sum x in\n update x (Int64.neg curr);\n update (x+1) curr;\n update x v;\n update (x+1) (Int64.neg v);\n | 2 ->\n let y = Int64.of_int (read_int ()) in\n update 1 y;\n | 3 ->\n let q = read_int () in\n let curr = sum q in\n Printf.printf \"%Ld\\n\" curr; \n | _ -> assert false\n done;\n"}, {"source_code": "\nlet () =\n let (@@) f x = f x in\n let (|>) x f = f x in\n let split_by_spaces = Str.split @@ Str.regexp_string \" \" in\n let n, m = match read_line () |> split_by_spaces |> List.map int_of_string with\n | [n; m] -> n, m\n | _ -> failwith \"Error on line 1\"\n in\n let arr = read_line () |> split_by_spaces |> List.map Int64.of_string |> Array.of_list in\n let inc = ref 0L in\n assert (Array.length arr = n);\n for k = 1 to m do\n match read_line () |> split_by_spaces |> List.map int_of_string with\n | [1; v; x] -> arr.(v - 1) <- Int64.(sub (of_int x) !inc)\n | [2; y] -> inc := Int64.(add !inc @@ of_int y)\n | [3; q] -> print_endline @@ Int64.(to_string @@ add arr.(q - 1) !inc)\n | _ -> failwith @@ \"Error on line \" ^ string_of_int @@ k + 2;\n done\n\n\n"}, {"source_code": "\nlet (+) = Int64.add\nlet (-) = Int64.sub\n\ntype state = {\n arr : int64 array;\n mutable inc : int64\n}\n\nlet assign state v x =\n state.arr.(v) <- (x - state.inc)\n\nlet increment state y =\n state.inc <- state.inc + y\n\nlet print state q =\n print_endline (Int64.to_string (state.arr.(q) + state.inc))\n\nlet () =\n let open Pervasives in\n let split_by_spaces = Str.split (Str.regexp_string \" \") in\n let n, m = match split_by_spaces (read_line ()) with\n | [n; m] -> int_of_string n, int_of_string m\n | _ -> failwith \"Error on line 1\"\n in\n let int_list_of_string_list = List.map int_of_string in\n let int64_list_of_string_list = List.map Int64.of_string in\n let state =\n { arr = Array.of_list (int64_list_of_string_list (split_by_spaces (read_line ())));\n inc = 0L }\n in\n assert (Array.length state.arr = n);\n let k = ref 0 in\n try while true do\n (match int_list_of_string_list (split_by_spaces (read_line ())) with\n | [1; v; x] -> assign state (v - 1) (Int64.of_int x)\n | [2; y] -> increment state (Int64.of_int y)\n | [3; q] -> print state (q - 1)\n | _ -> failwith (\"Error on line \" ^ (string_of_int (!k + 2))));\n k := !k + 1\n done with End_of_file -> assert (!k = m)\n\n\n"}, {"source_code": "\nlet () =\n let (@@) f x = f x in\n let (|>) x f = f x in\n let open List in\n let open Int64 in\n let split_by_spaces = Str.split @@ Str.regexp_string \" \" in\n read_line () |> split_by_spaces |> map int_of_string |> tl |> hd |> fun m ->\n read_line () |> split_by_spaces |> map of_string |> Array.of_list |> fun arr ->\n let inc = ref 0L in\n for k = 1 to m do\n read_line () |> split_by_spaces |> List.map int_of_string |> function\n | [1; v; x] -> arr.(v - 1) <- sub (of_int x) !inc\n | [2; y] -> inc := add !inc @@ of_int y\n | [3; q] -> print_endline @@ to_string @@ add arr.(q - 1) !inc\n | _ -> failwith @@ \"Error on line \" ^ string_of_int @@ k + 2\n done\n\n\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.scanf \" %d\" (fun x -> x)\nlet read_string _ = Scanf.scanf \" %s\" (fun x -> x)\n\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n \n let implode l =\n let result = String.create (List.length l) in\n let rec imp i = function\n | [] -> result\n | c :: l -> result.[i] <- c; imp (i + 1) l in\n imp 0 l;;\n \nlet (--) i j = \n let rec aux n acc =\n if n < i then acc else aux (n-1) (n :: acc)\n in aux j []\n \nlet () = \n let n = read_int () in\n let m = read_int () in\n \n let bit = Array.init (n + 1) (fun _ -> 0) in\n \n let update x v = \n let x = ref x in\n while !x <= n do\n bit.(!x) <- bit.(!x) + v;\n x := !x + (!x land (~- !x));\n done\n in\n \n let sum x =\n let x = ref x in\n let ret = ref 0 in\n while !x > 0 do\n ret := !ret + bit.(!x);\n x := !x - (!x land (~- !x));\n done;\n !ret\n in\n \n let arr = Array.init n read_int in\n \n for i = 0 to n-1 do\n update (i+1) arr.(i);\n update (i+2) (-arr.(i));\n done;\n \n for i = 1 to m do\n let t = read_int () in\n match t with \n | 1 -> \n let x = read_int () in\n let v = read_int () in\n let curr = sum x in\n update x (-curr);\n update (x+1) curr;\n update x v;\n update (x+1) (-v);\n | 2 ->\n let y = read_int () in\n update 1 y;\n | 3 ->\n let q = read_int () in\n let curr = sum q in\n Printf.printf \"%d\\n\" curr; \n | _ -> assert false\n done;\n"}, {"source_code": "\ntype state = {\n arr : int array;\n mutable inc : int\n}\n\nlet assign state v x =\n state.arr.(v) <- (x - state.inc)\n\nlet increment state y =\n state.inc <- state.inc + y\n\nlet print state q =\n print_endline (string_of_int (state.arr.(q) + state.inc))\n\nlet () =\n let split_by_spaces = Str.split (Str.regexp_string \" \") in\n let n, m = match split_by_spaces (read_line ()) with\n | [n; m] -> int_of_string n, int_of_string m\n | _ -> failwith \"Error on line 1\"\n in\n let int_list_of_string_list = List.map int_of_string in\n let state =\n { arr = Array.of_list (int_list_of_string_list (split_by_spaces (read_line ())));\n inc = 0 }\n in\n assert (Array.length state.arr = n);\n let k = ref 0 in\n try while true do\n (match int_list_of_string_list (split_by_spaces (read_line ())) with\n | [1; v; x] -> assign state (v - 1) x\n | [2; y] -> increment state y\n | [3; q] -> print state (q - 1)\n | _ -> failwith (\"Error on line \" ^ (string_of_int (!k + 2))));\n incr k\n done with End_of_file -> assert (!k = m)\n\n\n"}], "src_uid": "48f3ff32a11770f3b168d6e15c0df813"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$b$$$.In one move, you can choose some integer $$$k$$$ from $$$1$$$ to $$$10$$$ and add it to $$$a$$$ or subtract it from $$$a$$$. In other words, you choose an integer $$$k \\in [1; 10]$$$ and perform $$$a := a + k$$$ or $$$a := a - k$$$. You may use different values of $$$k$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case, print the answer: the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.", "sample_inputs": ["6\n5 5\n13 42\n18 4\n1337 420\n123456789 1000000000\n100500 9000"], "sample_outputs": ["0\n3\n2\n92\n87654322\n9150"], "notes": "NoteIn the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: $$$13 \\rightarrow 23 \\rightarrow 32 \\rightarrow 42$$$ (add $$$10$$$, add $$$9$$$, add $$$10$$$).In the third test case of the example, the following sequence of moves can be applied: $$$18 \\rightarrow 10 \\rightarrow 4$$$ (subtract $$$8$$$, subtract $$$6$$$)."}, "positive_code": [{"source_code": "let read_int () : int =\n Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve (a : int) (b : int) : int =\n ((abs (a - b)) + 9) / 10\n\nlet () =\n let t = read_int () in\n for i = 1 to t do\n let a = read_int () in\n let b = read_int () in\n print_endline ( string_of_int (solve a b))\n done;\n"}, {"source_code": "let () =\n let t = read_line () |> int_of_string in\n for i = 1 to t do\n let [a; b] =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map String.trim\n |> List.map int_of_string\n in\n let n = abs (b - a) in\n (n + 9) / 10\n |> string_of_int\n |> print_endline\n done\n"}], "negative_code": [], "src_uid": "d67a97a3b69d599b03d3fce988980646"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$k$$$. You are asked to choose maximum number of distinct integers from $$$1$$$ to $$$n$$$ so that there is no subset of chosen numbers with sum equal to $$$k$$$.A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.", "input_spec": "The first line contains the number of test cases $$$T$$$ ($$$1 \\le T \\le 100$$$). Each of the next $$$T$$$ lines contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 1000$$$) \u2014 the description of test cases.", "output_spec": "For each test case output two lines. In the first line output a single integer $$$m$$$ \u2014 the number of chosen integers. In the second line output $$$m$$$ distinct integers from $$$1$$$ to $$$n$$$ \u2014 the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order.", "sample_inputs": ["3\n3 2\n5 3\n1 1"], "sample_outputs": ["2\n3 1 \n3\n4 5 2 \n0"], "notes": null}, "positive_code": [{"source_code": "let l = ref []\n\nlet () = \n for i=1 to (read_int ()) do\n l := (Scanf.scanf \" %d %d\" (fun x y -> x,y))::!l\n done\n\nlet rec getListfromArray a n k i =\n if i > n\n then []\n else if i > k \n then \n (i)::(getListfromArray a n k (i+1))\n else if i < k-1\n then if a.(i) = 1 then (i+1)::(getListfromArray a n k (i+1)) else getListfromArray a n k (i+1)\n else getListfromArray a n k (i+1)\n\nlet rec printList l = \n match l with \n | h::t -> (Printf.printf \"%d \" h; printList t)\n | _ -> print_newline ()\n\nlet findList (n,k) = \n let a = Array.make (k-1) 0 in\n let () = for i=1 to (k-1) do if a.(i-1) <> 1 then a.(k-i-1) <- 1 done in\n let l = getListfromArray a n k 0 in\n let () = print_endline (string_of_int (List.length l)) in\n printList l\n\nlet rec testCases l =\n match l with\n | h::t -> (testCases t; findList h)\n | _ -> ()\n\nlet rec testAll l = \n match l with\n | h::t -> (testAll t; findList h)\n | _ -> ()\n\nlet () = testAll !l"}, {"source_code": "(* https://codeforces.com/contest/1493/problem/A *)\n\nlet solution m k =\n let nums = Array.make m true in\n nums.(k-1) <- false;\n let rec helper i =\n if i < 0\n then ()\n else if (i+1) > k\n then helper (i-1)\n else if (i+1) = k\n then helper (i-1)\n else if (i+1) < k && nums.(i)\n then begin\n let index = k - (i+1) - 1 in\n if index <> i\n then nums.(k-(i+1)-1) <- false;\n helper (i-1) \n end in\n helper (m-1);\n Array.mapi (fun i e -> if e then Some (i+1) else None) nums\n |> Array.to_list\n |> List.filter (fun e -> e <> None)\n |> List.map (fun (Some e) -> e)\n\nlet input_case () =\n read_line () |> Str.split (Str.regexp \" \") |> List.map int_of_string\n\nlet print_sol arr =\n List.iter (fun e -> Printf.printf \"%d \" e) arr\n\nlet () =\n let cases = read_int () in\n for i = 1 to cases do\n let m::k::_ = input_case () in\n let sol = solution m k in\n Printf.printf \"%d\\n\" (List.length sol);\n print_sol sol;\n print_newline ()\n done\n"}], "negative_code": [], "src_uid": "d08e39db62215d7817113aaa384e3f59"} {"nl": {"description": "How to make a cake you'll never eat.Ingredients. 2 carrots 0 calories 100 g chocolate spread 1 pack of flour 1 egg Method. Put calories into the mixing bowl. Take carrots from refrigerator. Chop carrots. Take chocolate spread from refrigerator. Put chocolate spread into the mixing bowl. Combine pack of flour into the mixing bowl. Fold chocolate spread into the mixing bowl. Add chocolate spread into the mixing bowl. Put pack of flour into the mixing bowl. Add egg into the mixing bowl. Fold pack of flour into the mixing bowl. Chop carrots until choped. Pour contents of the mixing bowl into the baking dish. Serves 1.", "input_spec": "The only line of input contains a sequence of integers a0,\u2009a1,\u2009... (1\u2009\u2264\u2009a0\u2009\u2264\u2009100, 0\u2009\u2264\u2009ai\u2009\u2264\u20091000 for i\u2009\u2265\u20091).", "output_spec": "Output a single integer.", "sample_inputs": ["4 1 2 3 4"], "sample_outputs": ["30"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let rdint =\n let l = ref 0 in\n let i = ref 0 in\n let s = String.create 65536 in\n let refill () =\n let n = input stdin s 0 65536 in\n i := 0;\n l := n in\n refill ();\n\n fun () ->\n let rec loop2 j k t f =\n let fin j t f =\n let _ = i := j in\n t * f in\n\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop2 !i !l t f else fin j t f\n ) else if s.[j] >= '0' && s.[j] <= '9' then\n loop2 (j + 1) k (t * 10 + Char.code s.[j] - 48) f\n else fin j t f in\n\n let rec loop1 j k =\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop1 !i !l else 0\n ) else if s.[j] = '-' then loop2 (j + 1) k 0 (-1)\n else if s.[j] >= '0' && s.[j] <= '9' then loop2 (j + 1) k (Char.code s.[j] - 48) 1\n else loop1 (j + 1) k in\n loop1 !i !l\n in\n\n let main () =\n let rec loop i k acc =\n if i = 0 then Printf.printf \"%d\\n\" acc else loop (i - 1) (k + 1) (acc + k * rdint ())\n in\n loop (rdint ()) 1 0\n in\n main ()\n\n"}], "negative_code": [], "src_uid": "f9f25190916bf4294f7458140b264cb5"} {"nl": {"description": "There are $$$n$$$ people sitting in a circle, numbered from $$$1$$$ to $$$n$$$ in the order in which they are seated. That is, for all $$$i$$$ from $$$1$$$ to $$$n-1$$$, the people with id $$$i$$$ and $$$i+1$$$ are adjacent. People with id $$$n$$$ and $$$1$$$ are adjacent as well.The person with id $$$1$$$ initially has a ball. He picks a positive integer $$$k$$$ at most $$$n$$$, and passes the ball to his $$$k$$$-th neighbour in the direction of increasing ids, that person passes the ball to his $$$k$$$-th neighbour in the same direction, and so on until the person with the id $$$1$$$ gets the ball back. When he gets it back, people do not pass the ball any more.For instance, if $$$n = 6$$$ and $$$k = 4$$$, the ball is passed in order $$$[1, 5, 3, 1]$$$. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $$$1 + 5 + 3 = 9$$$.Find and report the set of possible fun values for all choices of positive integer $$$k$$$. It can be shown that under the constraints of the problem, the ball always gets back to the $$$1$$$-st player after finitely many steps, and there are no more than $$$10^5$$$ possible fun values for given $$$n$$$.", "input_spec": "The only line consists of a single integer $$$n$$$\u00a0($$$2 \\leq n \\leq 10^9$$$)\u00a0\u2014 the number of people playing with the ball.", "output_spec": "Suppose the set of all fun values is $$$f_1, f_2, \\dots, f_m$$$. Output a single line containing $$$m$$$ space separated integers $$$f_1$$$ through $$$f_m$$$ in increasing order.", "sample_inputs": ["6", "16"], "sample_outputs": ["1 5 9 21", "1 10 28 64 136"], "notes": "NoteIn the first sample, we've already shown that picking $$$k = 4$$$ yields fun value $$$9$$$, as does $$$k = 2$$$. Picking $$$k = 6$$$ results in fun value of $$$1$$$. For $$$k = 3$$$ we get fun value $$$5$$$ and with $$$k = 1$$$ or $$$k = 5$$$ we get $$$21$$$. In the second sample, the values $$$1$$$, $$$10$$$, $$$28$$$, $$$64$$$ and $$$136$$$ are achieved for instance for $$$k = 16$$$, $$$8$$$, $$$4$$$, $$$10$$$ and $$$11$$$, respectively."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nlet divisors v = (* O(sqrt n) *)\n let rec f0 i a =\n if i*i > v then a\n else if i*i = v && v mod i = 0L then i::a\n else if v mod i = 0L then f0 (i+1L) (i::(v/i)::a)\n else f0 (i+1L) a in f0 1L []\nlet () =\n let n = gi 0 in\n let div = divisors n in\n let w0 = (n * (n+1L)) / 2L in\n let r = ref [w0] in\n List.iter (fun v ->\n (* printf \"%Ld\\n\" v; *)\n if v<>1L then (\n r := ((n*(n+2L-v)) / (2L*v))::!r;\n )\n ) div;\n List.sort compare !r |> print_list ist\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "2ae1a4d4f2e58b359c898d1ff38edb9e"} {"nl": {"description": "A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\\dots,p_n]$$$, which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) and, moreover, each number appears exactly once. For example, $$$p=[3,1,4,2,5]$$$ is a permutation of length $$$5$$$.For a given number $$$n$$$ ($$$n \\ge 2$$$), find a permutation $$$p$$$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $$$2$$$ and $$$4$$$, inclusive. Formally, find such permutation $$$p$$$ that $$$2 \\le |p_i - p_{i+1}| \\le 4$$$ for each $$$i$$$ ($$$1 \\le i < n$$$).Print any such permutation for the given integer $$$n$$$ or determine that it does not exist.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is described by a single line containing an integer $$$n$$$ ($$$2 \\le n \\le 1000$$$).", "output_spec": "Print $$$t$$$ lines. Print a permutation that meets the given requirements. If there are several such permutations, then print any of them. If no such permutation exists, print -1.", "sample_inputs": ["6\n10\n2\n4\n6\n7\n13"], "sample_outputs": ["9 6 10 8 4 7 3 1 5 2 \n-1\n3 1 4 2 \n5 3 6 2 4 1 \n5 1 3 6 2 4 7 \n13 9 7 11 8 4 1 3 5 2 6 10 12"], "notes": null}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n \nopen Printf\n\nlet init (x : int) (f : int -> 'a) : 'a list =\n let rec build k =\n if k = x then []\n else (f k) :: build (k + 1) in\n build 0\n;;\n \nlet run () = \n let n = scan_int () in\n if n = 3 || n = 2 then print_endline \"-1\"\n else begin\n let ans = \n (\n let lst = ref [] in\n if n mod 4 = 0 then\n (let cur = ref 4 in\n while !cur <= n do\n let t = !cur in\n lst := (t - 1) :: (t - 3) :: t :: (t - 2) :: !lst;\n cur := !cur + 4;\n done;\n !lst)\n else if n mod 4 = 1 then\n (lst := 1 :: !lst;\n let cur = ref 5 in\n while !cur <= n do\n let t = !cur in\n lst := (t - 1) :: (t - 3) :: t :: (t - 2) :: !lst;\n cur := !cur + 4;\n done;\n !lst)\n else if n mod 4 = 2 then begin\n lst := 1 :: !lst;\n let cur = ref 5 in\n while !cur <= n do\n let t = !cur in\n lst := (t - 1) :: (t - 3) :: t :: (t - 2) :: !lst;\n cur := !cur + 4;\n done;\n lst := n :: !lst;\n !lst\n end\n else begin\n lst := [5; 1; 3; 6; 2; 4; 7];\n let cur = ref 11 in\n while !cur <= n do\n let t = !cur in\n lst := (t - 1) :: (t - 3) :: t :: (t - 2) :: !lst;\n cur := !cur + 4;\n done;\n !lst;\n end\n )in\n List.iter (printf \"%d \") (List.rev ans);\n print_endline \"\"\n end\n;;\n \nlet () =\n let t = scan_int () in\n for i = 1 to t do\n run ()\n done\n;;\n"}], "negative_code": [], "src_uid": "9b8a5d9a6cfd6b3b5d0839eeece6f777"} {"nl": {"description": "Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.It takes the first swimmer exactly $$$a$$$ minutes to swim across the entire pool and come back, exactly $$$b$$$ minutes for the second swimmer and $$$c$$$ minutes for the third. Hence, the first swimmer will be on the left side of the pool after $$$0$$$, $$$a$$$, $$$2a$$$, $$$3a$$$, ... minutes after the start time, the second one will be at $$$0$$$, $$$b$$$, $$$2b$$$, $$$3b$$$, ... minutes, and the third one will be on the left side of the pool after $$$0$$$, $$$c$$$, $$$2c$$$, $$$3c$$$, ... minutes.You came to the left side of the pool exactly $$$p$$$ minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ lines contains test case descriptions, one per line. Each line contains four integers $$$p$$$, $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \\leq p, a, b, c \\leq 10^{18}$$$), time in minutes after the start, when you came to the pool and times in minutes it take the swimmers to cross the entire pool and come back.", "output_spec": "For each test case, output one integer\u00a0\u2014 how long you have to wait (in minutes) before one of the swimmers arrives at the left side of the pool.", "sample_inputs": ["4\n9 5 4 8\n2 6 10 9\n10 2 5 10\n10 9 9 9"], "sample_outputs": ["1\n4\n0\n8"], "notes": "NoteIn the first test case, the first swimmer is on the left side in $$$0, 5, 10, 15, \\ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 4, 8, 12, \\ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 8, 16, 24, \\ldots$$$ minutes after the start time. You arrived at the pool in $$$9$$$ minutes after the start time and in a minute you will meet the first swimmer on the left side.In the second test case, the first swimmer is on the left side in $$$0, 6, 12, 18, \\ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 10, 20, 30, \\ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 9, 18, 27, \\ldots$$$ minutes after the start time. You arrived at the pool $$$2$$$ minutes after the start time and after $$$4$$$ minutes meet the first swimmer on the left side.In the third test case, you came to the pool $$$10$$$ minutes after the start time. At the same time, all three swimmers are on the left side. A rare stroke of luck!In the fourth test case, all swimmers are located on the left side in $$$0, 9, 18, 27, \\ldots$$$ minutes after the start time. You arrived at the pool $$$10$$$ minutes after the start time and after $$$8$$$ minutes meet all three swimmers on the left side."}, "positive_code": [{"source_code": "(** https://codeforces.com/contest/1492/problem/0 *)\n\nlet read_case () =\n let p::swimmers = \n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map Int64.of_string in\n (p, swimmers) in\n\nlet solve_case (p, swimmers) =\n let times =\n List.map\n (fun swimmer -> \n if Int64.rem p swimmer = Int64.zero \n then Int64.zero\n else Int64.sub swimmer (Int64.rem p swimmer))\n swimmers in\n let rec min_time curr tms =\n match tms with\n | [] -> curr\n | time::rest -> min_time (if time < curr then time else curr) rest in\n match times with\n | h::t -> min_time h t in\n\nlet solve_n n =\n let rec helper i =\n if i = 0\n then ()\n else begin\n read_case ()\n |> solve_case\n |> Int64.to_string\n |> print_endline;\n helper (i-1)\n end in\n helper n in\n\nlet nb_cases = read_int () in\nsolve_n nb_cases\n"}], "negative_code": [], "src_uid": "293f9b996eee9f76d4bfdeda85685baa"} {"nl": {"description": "String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings \"DOG\" and \"GOD\" are anagrams, so are strings \"BABA\" and \"AABB\", but strings \"ABBAC\" and \"CAABA\" are not.You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.The lexicographic order of strings is the familiar to us \"dictionary\" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1\u2009=\u2009q1, p2\u2009=\u2009q2, ..., pk\u2009-\u20091\u2009=\u2009qk\u2009-\u20091, pk\u2009<\u2009qk for some k (1\u2009\u2264\u2009k\u2009\u2264\u2009n). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.", "input_spec": "The input consists of two lines. The first line contains string s, the second line contains string t. The strings have the same length (from 1 to 105 characters) and consist of uppercase English letters.", "output_spec": "In the first line print z \u2014 the minimum number of replacement operations, needed to get an anagram of string t from string s. In the second line print the lexicographically minimum anagram that could be obtained in z operations.", "sample_inputs": ["ABA\nCBA", "CDBABC\nADCABD"], "sample_outputs": ["1\nABC", "2\nADBADC"], "notes": "NoteThe second sample has eight anagrams of string t, that can be obtained from string s by replacing exactly two letters: \"ADBADC\", \"ADDABC\", \"CDAABD\", \"CDBAAD\", \"CDBADA\", \"CDDABA\", \"DDAABC\", \"DDBAAC\". These anagrams are listed in the lexicographical order. The lexicographically minimum anagram is \"ADBADC\"."}, "positive_code": [{"source_code": "let input = open_in \"input.txt\" ;;\nlet output = open_out \"output.txt\" ;;\n\nlet read_string () = Scanf.fscanf input \" %s \" (fun x -> x) ;;\n\nlet s = read_string () and t = read_string () ;;\n\nlet index c = int_of_char c - int_of_char 'A' ;;\nlet letter i = char_of_int (i + int_of_char 'A') ;;\n\nlet freqs = Array.make 26 0 and freqt = Array.make 26 0 ;;\nfor i = 0 to String.length s - 1 do\n freqs.(index s.[i]) <- freqs.(index s.[i]) + 1 ;\n freqt.(index t.[i]) <- freqt.(index t.[i]) + 1\ndone ;;\n \nlet (z, result) = \n let rec next_available i =\n if i > 25 then -1\n else if freqt.(i) > freqs.(i) then i \n else next_available (i + 1)\n and r = String.create (String.length s) \n in let rec loop i a cur =\n if i = String.length s then (a, r)\n else let c = index s.[i] in\n (* Need to replace this character *)\n if freqt.(c) = 0 || freqs.(c) > freqt.(c) && cur < c then \n (\n r.[i] <- letter cur ;\n freqt.(cur) <- freqt.(cur) - 1 ;\n freqs.(c) <- freqs.(c) - 1;\n loop (i + 1) (a + 1) (next_available cur)\n )\n (* Need to save this character *)\n else\n (\n r.[i] <- letter c ;\n freqt.(c) <- freqt.(c) - 1 ;\n freqs.(c) <- freqs.(c) - 1;\n loop (i + 1) a cur\n )\n in loop 0 0 (next_available 0) ;;\n \nPrintf.fprintf output \"%d\\n%s\\n\" z result ;;"}, {"source_code": "let chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_str () = Scanf.bscanf chan \" %s \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet toint c = (int_of_char c) - (int_of_char 'A')\nlet tochar i = char_of_int ((int_of_char 'A') + i)\n\nlet () = \n let s = read_str() in\n let t = read_str() in\n let n = String.length s in\n let hs = Array.make 26 0 in\n let h = Array.make 26 0 in\n \n let () = \n for i=0 to n-1 do\n let (c,d) = (toint s.[i], toint t.[i]) in\n\ths.(c) <- hs.(c) + 1;\n\th.(c) <- h.(c) + 1;\n\th.(d) <- h.(d) - 1\n done\n in\n\n let tot = sum 0 25 (fun i-> abs h.(i)) in\n let () = print_string (Printf.sprintf \"%d\\n\" (tot/2)) in\n\n let () =\n for i=0 to n-1 do\n let c = toint s.[i] in\n\tif h.(c) <= 0 then (\n\t print_string (Printf.sprintf \"%c\" (tochar c));\n\t) else (\n\t let rec loop j = if h.(j) < 0 then j else loop (j+1) in\n\t let d = loop 0 in\n\t if d > c && hs.(c) > h.(c) then (\n\t print_string (Printf.sprintf \"%c\" (tochar c));\n\t ) else (\n\t h.(d) <- h.(d) + 1;\n\t h.(c) <- h.(c) - 1;\n\t print_string (Printf.sprintf \"%c\" (tochar d))\n\t )\n\t);\n\ths.(c) <- hs.(c) - 1\n done\n in\n print_string \"\\n\"\n"}], "negative_code": [{"source_code": "let chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_str () = Scanf.bscanf chan \" %s \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet toint c = (int_of_char c) - (int_of_char 'A')\nlet tochar i = char_of_int ((int_of_char 'A') + i)\n\nlet () = \n let s = read_str() in\n let t = read_str() in\n let n = String.length s in\n let hs = Array.make n 0 in\n let h = Array.make n 0 in\n \n let () = \n for i=0 to n-1 do\n let (c,d) = (toint s.[i], toint t.[i]) in\n\ths.(c) <- hs.(c) + 1;\n\th.(c) <- h.(c) + 1;\n\th.(d) <- h.(d) - 1\n done\n in\n\n let () =\n for i=0 to n-1 do\n let c = toint s.[i] in\n\tif h.(c) <= 0 then (\n\t print_string (Printf.sprintf \"%c\" (tochar c));\n\t) else (\n\t let rec loop j = if h.(j) < 0 then j else loop (j+1) in\n\t let d = loop 0 in\n\t if d > c && hs.(c) > h.(c) then (\n\t print_string (Printf.sprintf \"%c\" (tochar c));\n\t ) else (\n\t h.(d) <- h.(d) + 1;\n\t h.(c) <- h.(c) - 1;\n\t print_string (Printf.sprintf \"%c\" (tochar d))\n\t )\n\t);\n\ths.(c) <- hs.(c) - 1\n done\n in\n print_string \"\\n\"\n"}], "src_uid": "b9766f25c8ae179c30521770422ce18b"} {"nl": {"description": "Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1,\u2009p2,\u2009...,\u2009pm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches p1, it'll move to p2, again, choosing one of the shortest ways, then to p3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.", "input_spec": "The first line of input contains the only positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) which equals the number of unit segments the robot traveled. The second line contains the movements protocol, which consists of n letters, each being equal either L, or R, or U, or D. k-th letter stands for the direction which Robot traveled the k-th unit segment in: L means that it moved to the left, R\u00a0\u2014 to the right, U\u00a0\u2014 to the top and D\u00a0\u2014 to the bottom. Have a look at the illustrations for better explanation.", "output_spec": "The only line of input should contain the minimum possible length of the sequence.", "sample_inputs": ["4\nRURD", "6\nRRULDD", "26\nRRRULURURUULULLLDLDDRDRDLD", "3\nRLL", "4\nLRLR"], "sample_outputs": ["2", "2", "7", "2", "4"], "notes": "NoteThe illustrations to the first three tests are given below. The last example illustrates that each point in the sequence should be counted as many times as it is presented in the sequence."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet () = \n let n = read_int () in\n let path = read_string () in\n\n let path = Array.init n (fun i ->\n match path.[i] with 'R' -> 0 | 'U' -> 1 | 'L' -> 2 | 'D' -> 3 | _ -> failwith \"bad input\"\n ) in\n\n let used = Array.make 4 false in\n let cc i = if used.(i) then 1 else 0 in\n let clear () = for i=0 to 3 do used.(i) <- false done in\n let count () = (cc 0) + (cc 1) + (cc 2) + (cc 3) in\n\n let rec loop i ac = if i=n then ac else (\n if used.(path.(i)) then loop (i+1) ac\n else (\n let c = count () in\n if c = 0 then (\n\tused.(path.(i)) <- true;\n\tloop (i+1) ac\n )\n else if c = 1 then (\n\tif used.((2+path.(i)) mod 4) then (\n\t clear ();\n\t used.(path.(i)) <- true;\n\t loop (i+1) (ac+1)\n\t) else (\n\t used.(path.(i)) <- true;\n\t loop (i+1) ac\t \n\t)\n )\n else (\n\tclear ();\n\tused.(path.(i)) <- true;\n\tloop (i+1) (ac+1)\n )\n ) \n ) in\n\n printf \"%d\\n\" (1+(loop 0 0))\n"}], "negative_code": [], "src_uid": "b1c7ca90ce9a67605fa058d4fd38c2f2"} {"nl": {"description": "User ainta decided to paint a wall. The wall consists of n2 tiles, that are arranged in an n\u2009\u00d7\u2009n table. Some tiles are painted, and the others are not. As he wants to paint it beautifully, he will follow the rules below. Firstly user ainta looks at the wall. If there is at least one painted cell on each row and at least one painted cell on each column, he stops coloring. Otherwise, he goes to step 2. User ainta choose any tile on the wall with uniform probability. If the tile he has chosen is not painted, he paints the tile. Otherwise, he ignores it. Then he takes a rest for one minute even if he doesn't paint the tile. And then ainta goes to step 1. \u00a0However ainta is worried if it would take too much time to finish this work. So he wants to calculate the expected time needed to paint the wall by the method above. Help him find the expected time. You can assume that choosing and painting any tile consumes no time at all. ", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7103; 0\u2009\u2264\u2009m\u2009\u2264\u2009min(n2,\u20092\u00b7104)) \u2014 the size of the wall and the number of painted cells. Next m lines goes, each contains two integers ri and ci (1\u2009\u2264\u2009ri,\u2009ci\u2009\u2264\u2009n) \u2014 the position of the painted cell. It is guaranteed that the positions are all distinct. Consider the rows of the table are numbered from 1 to n. Consider the columns of the table are numbered from 1 to n.", "output_spec": "In a single line print the expected time to paint the wall in minutes. Your answer will be considered correct if it has at most 10\u2009-\u20094 absolute or relative error.", "sample_inputs": ["5 2\n2 3\n4 1", "2 2\n1 1\n1 2", "1 1\n1 1"], "sample_outputs": ["11.7669491886", "2.0000000000", "0.0000000000"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int()in\n let m = read_int() in\n let rowempty = Array.make n 1 in\n let colempty = Array.make n 1 in\n for i=1 to m do\n let r = read_int() in\n let c = read_int() in\n rowempty.(r-1) <- 0;\n colempty.(c-1) <- 0;\n done;\n\n let r = sum 0 (n-1) (fun i -> rowempty.(i)) in\n let c = sum 0 (n-1) (fun i -> colempty.(i)) in\n\n let dp = Array.make_matrix (r+1) (c+1) None in\n \n let rec calc r c = \n if r<0 || c<0 then 0.0 else\n match dp.(r).(c) with Some x -> x | None ->\n\tlet answer = \n\t if r=0 && c=0 then 0.0 else (\n\t let cells = float (n * (r+c) - r*c) in\n\t let area = float (n*n) in\n\t let p = cells /. area in\n\t (* prob that we hit a useful one. 1/p is E(time till we hit) *)\n\t \n\t (* now, given that we hit a useful one what is the probability of the\n\t three different types .... *)\n\t let pboth = (float (r*c)) /. cells in\n\t let pcol = ((float (c*(n-r))) /. cells) in\n\t let prow = ((float (r*(n-c))) /. cells) in\n\t \n\t (1.0 /. p) +. \n\t pboth *. (calc (r-1) (c-1)) +.\n\t pcol *. (calc r (c-1)) +.\n\t prow *. (calc (r-1) c)\n\t )\n\tin\n\tdp.(r).(c) <- Some answer;\n\tanswer\n in\n\n printf \"%15.10f\\n\" (calc r c)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int()in\n let m = read_int() in\n let rowempty = Array.make n 1 in\n let colempty = Array.make n 1 in\n for i=1 to m do\n let r = read_int() in\n let c = read_int() in\n rowempty.(r-1) <- 0;\n colempty.(c-1) <- 0;\n done;\n\n let r = sum 0 (n-1) (fun i -> rowempty.(i)) in\n let c = sum 0 (n-1) (fun i -> colempty.(i)) in\n\n let dp = Array.make_matrix (r+1) (c+1) None in\n \n let rec calc r c = \n if r<0 || c<0 then 0.0 else\n match dp.(r).(c) with Some x -> x | None ->\n\tlet answer = \n\t if r=0 && c=0 then 0.0 else (\n\t let cells = float (n * (r+c) - r*c) in\n\t let area = float (n*n) in\n\t let p = cells /. area in\n\t (* prob that we hit a useful one. 1/p is E(time till we hit) *)\n\t \n\t (* now, given that we hit a useful one what is the probability of the\n\t three different types .... *)\n\t let pboth = (float (r*c)) /. cells in\n\t let pcol = ((float (c*(n-r))) /. cells) in\n\t let prow = ((float (r*(n-c))) /. cells) in\n\t \n\t (1.0 /. p) +. \n\t pboth *. (calc (r-1) (c-1)) +.\n\t pcol *. (calc r (c-1)) +.\n\t prow *. (calc (r-1) c)\n\t )\n\tin\n\tdp.(r).(c) <- Some answer;\n\tanswer\n in\n\n printf \"%15.10f\\n\" (calc r c)\n"}], "negative_code": [], "src_uid": "8bad8086f69da165d8de4db93fe6931f"} {"nl": {"description": "Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line.", "input_spec": "The single line contains two integers n and m (3\u2009\u2264\u2009m\u2009\u2264\u2009100,\u2009m\u2009\u2264\u2009n\u2009\u2264\u20092m).", "output_spec": "If there is no solution, print \"-1\". Otherwise, print n pairs of integers \u2014 the coordinates of points of any set with the convexity of m. The coordinates shouldn't exceed 108 in their absolute value.", "sample_inputs": ["4 3", "6 3", "6 6", "7 4"], "sample_outputs": ["0 0\n3 0\n0 3\n1 1", "-1", "10 0\n-10 0\n10 1\n9 1\n9 -1\n0 -2", "176166 6377\n709276 539564\n654734 174109\n910147 434207\n790497 366519\n606663 21061\n859328 886001"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet pi = 2.0 *. (atan2 1.0 0.0) \n\nlet () =\n let n = read_int() in\n let m = read_int() in\n\n let outer = Array.make m (0.0,0.0) in\n let inner = Array.make (n-m) (0.0,0.0) in\n\n let eps = 0.000001 in\n\n let r = 10000000.0 in\n let r' = r -. 1000.0 in\n\n let delta = (2.0 *. pi) /. (float m) in\n\n for i=0 to m-1 do\n let alpha = (float i) *. delta in\n\touter.(i) <- (r *. (cos alpha) , r *. (sin alpha))\n done;\n\n for i=0 to (n-m)-1 do \n let alpha = (float i) *. delta in\n\tinner.(i) <- (r' *. (cos (alpha+.eps)) , r' *. (sin (alpha+.eps)))\n done;\n\n if (n,m) = (6,3) || (n,m) = (5,3) then (\n Printf.printf \"-1\\n\"\n ) else (\n for i=0 to m-1 do\n\tlet (x,y) = outer.(i) in\n\tlet (x,y) = (int_of_float x, int_of_float y) in\n\t Printf.printf \"%d %d\\n\" x y\n done;\n \n for i=0 to (n-m)-1 do\n\tlet (x,y) = inner.(i) in\n\tlet (x,y) = (int_of_float x, int_of_float y) in\n\t Printf.printf \"%d %d\\n\" x y\n done\n )\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet pi = 2.0 *. (atan2 1.0 0.0) \n\nlet () =\n let n = read_int() in\n let m = read_int() in\n\n let outer = Array.make m (0.0,0.0) in\n\n let eps = 0.0001 in\n\n let r = 10000000.0 in\n let r' = r -. 1000.0 in\n\n let delta = (2.0 *. pi) /. (float m) in\n\n for i=0 to m-1 do\n let alpha = (float i) *. delta in\n\touter.(i) <- (r *. (cos alpha) , r *. (sin alpha))\n done;\n\n let inner = Array.make (n-m) (0.0,0.0) in\n\n for i=0 to (n-m)-1 do \n\tlet alpha = (float i) *. delta in\n\t inner.(i) <- (r' *. (cos (alpha+.eps)) , r' *. (sin (alpha+.eps)))\n done;\n\n if (n,m) = (6,3) || (n,m) = (5,3) then (\n\tPrintf.printf \"-1\\n\"\n ) else (\n\tfor i=0 to m-1 do\n\t let (x,y) = outer.(i) in\n\t let (x,y) = (int_of_float x, int_of_float y) in\n\t Printf.printf \"%d %d\\n\" x y\n\tdone;\n \n\tfor i=0 to (n-m)-1 do\n\t let (x,y) = inner.(i) in\n\t let (x,y) = (int_of_float x, int_of_float y) in\n\t Printf.printf \"%d %d\\n\" x y\n\tdone\n )\n"}], "src_uid": "2e9f2bd3c02ba6ba41882334deb35631"} {"nl": {"description": "The Fair Nut likes kvass very much. On his birthday parents presented him $$$n$$$ kegs of kvass. There are $$$v_i$$$ liters of kvass in the $$$i$$$-th keg. Each keg has a lever. You can pour your glass by exactly $$$1$$$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $$$s$$$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $$$s$$$ liters of kvass.", "input_spec": "The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1 \\le n \\le 10^3$$$, $$$1 \\le s \\le 10^{12}$$$)\u00a0\u2014 the number of kegs and glass volume. The second line contains $$$n$$$ integers $$$v_1, v_2, \\ldots, v_n$$$ ($$$1 \\le v_i \\le 10^9$$$)\u00a0\u2014 the volume of $$$i$$$-th keg.", "output_spec": "If the Fair Nut cannot pour his glass by $$$s$$$ liters of kvass, print $$$-1$$$. Otherwise, print a single integer\u00a0\u2014 how much kvass in the least keg can be.", "sample_inputs": ["3 3\n4 3 5", "3 4\n5 3 4", "3 7\n1 2 3"], "sample_outputs": ["3", "2", "-1"], "notes": "NoteIn the first example, the answer is $$$3$$$, the Fair Nut can take $$$1$$$ liter from the first keg and $$$2$$$ liters from the third keg. There are $$$3$$$ liters of kvass in each keg.In the second example, the answer is $$$2$$$, the Fair Nut can take $$$3$$$ liters from the first keg and $$$1$$$ liter from the second keg.In the third example, the Fair Nut can't pour his cup by $$$7$$$ liters, so the answer is $$$-1$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,s = g2 0 in let a = iia n in\n let sum = fold_left (+) 0L a in\n if s > sum then (printf \"-1\"; exit 0)\n else if s=sum then (printf \"0\"; exit 0);\n let mn = fold_left min max_i64 a in\n let left = sum - mn*n in\n if s <= left then (printf \"%Ld\" mn; exit 0);\n let d = ceildiv (s-left) n in\n printf \"%Ld\" @@ mn - d\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "23c63d1fea568a75663450e0c6f23a29"} {"nl": {"description": "Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob \u2014 from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the amount of bars on the table. The second line contains a sequence t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009ti\u2009\u2264\u20091000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).", "output_spec": "Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.", "sample_inputs": ["5\n2 9 8 2 7"], "sample_outputs": ["2 3"], "notes": null}, "positive_code": [{"source_code": "let solve (a:int array) = \n\tlet n = Array.length a in\n\tlet rec find l l_sum r r_sum = \n\t\tif l>r then l,(n-l)\n\t\telse if l_sum<=r_sum then find (l+1) (l_sum + a.(l)) r r_sum\n\t\telse find l l_sum (r-1) (r_sum+a.(r))\n\tin\n\tlet l, r = find 0 0 (n-1) 0 in\n\tPrintf.printf \"%d %d\\n\" (l) (n-l);;\n\n\nlet trim (line: string) =\n\t(* trim leading white space *)\n\tlet line = Str.replace_first (Str.regexp \"^[ \\t\\n\\r]+\") \"\" line in\n\t(* trim trailing white space *)\n\tlet line = Str.replace_first (Str.regexp \"[ \\t\\n\\r]+$\") \"\" line in\n\tline\n;;\n\n\nlet ints_of_string (line: string) = \n\tArray.of_list (List.map int_of_string (Str.split (Str.regexp \" \") (trim line)))\n;;\n\n\nlet _ = \n\tlet _ = int_of_string (read_line()) in\n\tlet a = ints_of_string (read_line()) in\n\tsolve a\n\n\t\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet ubound a n =\n let rec go l h =\n if l = h then\n l\n else\n let m = (l+h)/2 in\n if (if m > 0 then a.(m-1) else 0) <= a.(n-1)-a.(m) then\n go (m+1) h\n else\n go l m\n in go 0 n\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n for i = 1 to n-1 do\n a.(i) <- a.(i)+a.(i-1)\n done;\n let x = ubound a n in\n Printf.printf \"%d %d\\n\" x (n-x)\n"}], "negative_code": [{"source_code": "let solve (a:int array) = \n let n = Array.length a in\n let s = Array.fold_left (fun s x -> s + x) 0 a in\n let half = s / 2 in \n let rec find idx s = \n if s+a.(idx)>half then idx\n else find (idx+1) (s + a.(idx))\n in\n let l = find 0 0 in\n print_int l;\n print_string \" \";\n print_int (n-l);\n print_newline ()\n ;;\n\n\nlet trim (line: string) =\n (* trim leading white space *)\n let line = Str.replace_first (Str.regexp \"^[ \\t\\n\\r]+\") \"\" line in\n (* trim trailing white space *)\n let line = Str.replace_first (Str.regexp \"[ \\t\\n\\r]+$\") \"\" line in\n line\n;;\n\n\nlet ints_of_string (line: string) = \n Array.of_list (List.map int_of_string (Str.split (Str.regexp \" \") (trim line)))\n;;\n\n\nlet _ = \n let n = int_of_string (read_line()) in\n let a = ints_of_string (read_line()) in\n solve a\n\n \n"}, {"source_code": "let solve (a:int array) = \n\tlet n = Array.length a in\n\tlet s = Array.fold_left (fun s x -> s + x) 0 a in\n\tlet half = (1+ s) / 2 in \n\tlet rec find idx s = \n\t\tif (idx >= n || s+a.(idx)>half) then idx\n\t\telse find (idx+1) (s + a.(idx))\n\tin\n\tlet l = find 1 (a.(0)) in\n\tPrintf.printf \"%d %d\\n\" l (n-l);;\n\t(*\n\tprint_int l;\n\tprint_string \" \";\n\tprint_int (n-l);\n\tprint_newline ()\n\t;;\n*)\n\nlet trim (line: string) =\n\t(* trim leading white space *)\n\tlet line = Str.replace_first (Str.regexp \"^[ \\t\\n\\r]+\") \"\" line in\n\t(* trim trailing white space *)\n\tlet line = Str.replace_first (Str.regexp \"[ \\t\\n\\r]+$\") \"\" line in\n\tline\n;;\n\n\nlet ints_of_string (line: string) = \n\tArray.of_list (List.map int_of_string (Str.split (Str.regexp \" \") (trim line)))\n;;\n\n\nlet _ = \n\tlet n = int_of_string (read_line()) in\n\tlet a = ints_of_string (read_line()) in\n\tsolve a\n\n\t\n"}, {"source_code": "let solve (a:int array) = \n let n = Array.length a in\n let s = Array.fold_left (fun s x -> s + x) 0 a in\n let half = (1+ s) / 2 in \n let rec find idx s = \n if (idx >= n || s+a.(idx)>half) then idx\n else find (idx+1) (s + a.(idx))\n in\n let l = find 0 0 in\n Printf.printf \"%d %d\\n\" l (n-l);;\n (*\n print_int l;\n print_string \" \";\n print_int (n-l);\n print_newline ()\n ;;\n*)\n\nlet trim (line: string) =\n (* trim leading white space *)\n let line = Str.replace_first (Str.regexp \"^[ \\t\\n\\r]+\") \"\" line in\n (* trim trailing white space *)\n let line = Str.replace_first (Str.regexp \"[ \\t\\n\\r]+$\") \"\" line in\n line\n;;\n\n\nlet ints_of_string (line: string) = \n Array.of_list (List.map int_of_string (Str.split (Str.regexp \" \") (trim line)))\n;;\n\n\nlet _ = \n let n = int_of_string (read_line()) in\n let a = ints_of_string (read_line()) in\n solve a\n\n \n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet ubound a n =\n let rec go l h =\n if l = h then\n l\n else\n let m = (l+h)/2 in\n if a.(m) <= a.(n-1)-a.(m) then\n go (m+1) h\n else\n go l m\n in go 0 n\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n for i = 1 to n-1 do\n a.(i) <- a.(i)+a.(i-1)\n done;\n let x = ubound a n in\n Printf.printf \"%d %d\\n\" x (n-x)\n"}], "src_uid": "8f0172f742b058f5905c0a02d79000dc"} {"nl": {"description": "Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following: Add the integer xi to the first ai elements of the sequence. Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1) Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!", "input_spec": "The first line contains a single integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1\u2009\u2264\u2009ti\u2009\u2264\u20093), denoting the type of the operation (see above). If ti\u2009=\u20091, it will be followed by two integers ai,\u2009xi (|xi|\u2009\u2264\u2009103;\u00a01\u2009\u2264\u2009ai). If ti\u2009=\u20092, it will be followed by a single integer ki (|ki|\u2009\u2264\u2009103). If ti\u2009=\u20093, it will not be followed by anything. It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence.", "output_spec": "Output n lines each containing the average of the numbers in the sequence after the corresponding operation. The answer will be considered correct if its absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["5\n2 1\n3\n2 3\n2 1\n3", "6\n2 1\n1 2 20\n2 2\n1 2 -3\n3\n3"], "sample_outputs": ["0.500000\n0.000000\n1.500000\n1.333333\n1.500000", "0.500000\n20.500000\n14.333333\n12.333333\n17.500000\n17.000000"], "notes": "NoteIn the second sample, the sequence becomes "}, "positive_code": [{"source_code": "(******************************* Splay tree code ********************************)\n\ntype tree = \n Empty | Node of tree * float * tree * int\n(* left key right size *)\ntype direction = Left | Right\ntype path = Item of tree * direction\n\nlet size = function Empty -> 0 | Node(_, _, _, size) -> size\n\nlet getroot = function \n | Node(left, k, right, _) -> (left, k, right)\n | _ -> failwith \"called getroot on Empty\"\n\nlet correct n y = match n with Empty -> Empty\n | Node(l,k,r,s) -> Node(l,k+.y,r,s)\n\n(*\nlet getkey = function\n | Empty -> 0\n | Node(_, key, _, _) -> key\n*)\n\nlet glue (l, key, r) = \n let (l,r) = (correct l (-.key), correct r (-.key)) in\n Node(l, key, r, ((size l) + (size r) + 1))\n\nlet snip = function\n | Node(l, key, r, s) -> Node(correct l key, key, correct r key, 0)\n | _ -> failwith \"called snip on Empty\"\n\nlet connect (l, key, r) = Node(l, key, r, 0)\n\nlet splay t rank = \n (* splay the node of the given rank (which are numbered starting at 0)\n to the root *)\n\n (* The following splay function takes as input the currently splayed\n tree (so far) t, and a path list. It takes one or two steps up,\n and calls itself recursively. *)\n let rec rsplay = function\n | (t,[]) -> glue (getroot t)\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->\n\trsplay (connect(tL,tK,glue(tR,bK,glue(bR,cK,cR))), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->\n rsplay (connect(glue(glue(cL,cK,bL), bK, tL),tK,tR), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->\n\trsplay (connect(tL,tK,glue(tR,bK,bR)), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->\n\trsplay (connect(glue(bL,bK,tL),tK,tR), tail)\n\t \n | (_,_) -> failwith \"Splay_failed (Should not happen)\"\n in\n\n let rec build_path t r path = (* r = the rank of the target node in the current tree t *)\n let t = snip t in\n match t with \n\t| Empty -> failwith \"failed build_path\"\n\t| Node(left, _, right, _) ->\n\t let sl = size left in\n\t if r < sl then build_path left r (Item(t, Left)::path)\n\t else if r = sl then (t,path)\n\t else build_path right (r-sl-1) (Item(t, Right)::path)\n in\n if t=Empty then t else rsplay (build_path t rank [])\n\nlet append t k = glue(t, k, Empty)\n\n(* let key_of_rank t rank = getkey (splay t rank) *)\n\nlet add_to_root delta t = \n if t = Empty then t else\n let (l,k,r) = getroot t in \n Node (l, k+.delta, r, size t)\n\n(*************************************************************************)\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = let u = read_int 0 in (u,read_int 0)\n\nlet () =\n let printave t total = \n Printf.printf \"%.6f\\n\" (total/. (float (size t)));\n in\n\n let n = read_int 0 in\n let t = append Empty 0.0 in\n let rec loop i total t = if i=n then () else\n match read_int 0 with \n | 1 -> \n\t let a = read_int 0 in (* increment the first a elements by x *)\n\t let x = float (read_int 0) in\n\t let t = splay t (a-1) in\n\t let t = snip t in\n\t let (l,k,r) = getroot t in\n\t let l = add_to_root x l in\n\t let t = glue(l,k+.x,r) in\n\t let total = total +. (float a)*.x in\n\t printave t total;\n\t loop (i+1) total t\n | 2 -> \n\t let k = float (read_int 0) in\n\t let total = total +. k in\n\t let t = append t k in\n\t printave t total;\n\t loop (i+1) total t\n | 3 ->\n\t let s = size t in\n\t let t = splay t (s-1) in\n\t let t = snip t in\n\t let (l,k,_) = getroot t in\n\t let t = l in\n\t let total = total -. k in\n\t printave t total;\t \n\t loop (i+1) total t\n | _ -> failwith \"bad input\"\n\t \n in\n ignore (loop 0 0.0 t)\n"}], "negative_code": [{"source_code": "(******************************* Splay tree code ********************************)\n\ntype tree = \n Empty | Node of tree * int * tree * int\n(* left key right size *)\ntype direction = Left | Right\ntype path = Item of tree * direction\n\nlet size = function Empty -> 0 | Node(_, _, _, size) -> size\n\nlet getroot = function \n | Node(left, k, right, _) -> (left, k, right)\n | _ -> failwith \"called getroot on Empty\"\n\nlet correct n y = match n with Empty -> Empty\n | Node(l,k,r,s) -> Node(l,k+y,r,s)\n\nlet getkey = function\n | Empty -> 0\n | Node(_, key, _, _) -> key\n\nlet glue (l, key, r) = \n let (l,r) = (correct l (-key), correct r (-key)) in\n Node(l, key, r, ((size l) + (size r) + 1))\n\nlet snip = function\n | Node(l, key, r, s) -> Node(correct l key, key, correct r key, 0)\n | _ -> failwith \"called snip on Empty\"\n\nlet connect (l, key, r) = Node(l, key, r, 0)\n\nlet splay t rank = \n (* splay the node of the given rank (which are numbered starting at 0)\n to the root *)\n\n (* The following splay function takes as input the currently splayed\n tree (so far) t, and a path list. It takes one or two steps up,\n and calls itself recursively. *)\n let rec rsplay = function\n | (t,[]) -> glue (getroot t)\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->\n\trsplay (connect(tL,tK,glue(tR,bK,glue(bR,cK,cR))), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->\n rsplay (connect(glue(glue(cL,cK,bL), bK, tL),tK,tR), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->\n\trsplay (connect(tL,tK,glue(tR,bK,bR)), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->\n\trsplay (connect(glue(bL,bK,tL),tK,tR), tail)\n\t \n | (_,_) -> failwith \"Splay_failed (Should not happen)\"\n in\n\n let rec build_path t r path = (* r = the rank of the target node in the current tree t *)\n let t = snip t in\n match t with \n\t| Empty -> failwith \"failed build_path\"\n\t| Node(left, _, right, _) ->\n\t let sl = size left in\n\t if r < sl then build_path left r (Item(t, Left)::path)\n\t else if r = sl then (t,path)\n\t else build_path right (r-sl-1) (Item(t, Right)::path)\n in\n if t=Empty then t else rsplay (build_path t rank [])\n\nlet append t k = glue(t, k, Empty)\n\nlet key_of_rank t rank = getkey (splay t rank)\n\nlet add_to_root delta t = \n if t = Empty then t else\n let (l,k,r) = getroot t in \n Node (l, k+delta, r, size t)\n\n(*************************************************************************)\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = let u = read_int 0 in (u,read_int 0)\n\nlet () =\n let printave t total = \n let len = size t in\n Printf.printf \"%.6f\\n\" ((float total) /. (float len));\n in\n\n let n = read_int 0 in\n let t = append Empty 0 in\n let rec loop i total t = if i=n then () else\n match read_int 0 with \n | 1 -> \n\t let a = read_int 0 in (* increment the first a elements by x *)\n\t let x = read_int 0 in\n\t let t = splay t (a-1) in\n\t let t = snip t in\n\t let (l,k,r) = getroot t in\n\t let l = add_to_root x l in\n\t let t = glue(l,k+x,r) in\n\t let total = total + a*x in\n\t printave t total;\n\t loop (i+1) total t\n | 2 -> \n\t let k = read_int 0 in\n\t let total = total + k in\n\t let t = append t k in\n\t printave t total;\n\t loop (i+1) total t\n | 3 ->\n\t let s = size t in\n\t let t = splay t (s-1) in\n\t let t = snip t in\n\t let (l,k,_) = getroot t in\n\t let t = l in\n\t let total = total - k in\n\t printave t total;\t \n\t loop (i+1) total t\n | _ -> failwith \"bad input\"\n\t \n in\n ignore (loop 0 0 t)\n"}], "src_uid": "d43d4fd6c1e2722da185f34d902ace97"} {"nl": {"description": "Masha has $$$n$$$ types of tiles of size $$$2 \\times 2$$$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size $$$m \\times m$$$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square $$$s$$$ that for each pair $$$(i, j)$$$ the condition $$$s[i][j] = s[j][i]$$$ holds. I.e. it is true that the element written in the $$$i$$$-row and $$$j$$$-th column equals to the element written in the $$$j$$$-th row and $$$i$$$-th column.Your task is to determine if Masha can construct a square of size $$$m \\times m$$$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le m \\le 100$$$) \u2014 the number of types of tiles and the size of the square Masha wants to construct. The next $$$2n$$$ lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines. The first line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ \u2014 the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ \u2014 the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type. It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input.", "output_spec": "For each test case print the answer: \"YES\" (without quotes) if Masha can construct the square of size $$$m \\times m$$$ which is a symmetric matrix. Otherwise, print \"NO\" (withtout quotes).", "sample_inputs": ["6\n3 4\n1 2\n5 6\n5 7\n7 4\n8 9\n9 8\n2 5\n1 1\n1 1\n2 2\n2 2\n1 100\n10 10\n10 10\n1 2\n4 5\n8 4\n2 2\n1 1\n1 1\n1 2\n3 4\n1 2\n1 1\n1 1"], "sample_outputs": ["YES\nNO\nYES\nNO\nYES\nYES"], "notes": "NoteThe first test case of the input has three types of tiles, they are shown on the picture below. Masha can construct, for example, the following square of size $$$4 \\times 4$$$ which is a symmetric matrix: "}, "positive_code": [{"source_code": "let rec case t =\n if t > 0 then\n let check a b c d = \n if b = c then 1 else 0\n in let rec input acc ntimes =\n if ntimes = 0 then acc\n else input (acc + Scanf.scanf \"%d %d\\n%d %d\\n\" (fun a b c d -> check a b c d)) (ntimes - 1)\n in Scanf.scanf \"%d %d\\n\" (fun n m -> if (input 0 n > 0) && (m mod 2 = 0) then Printf.printf \"YES\\n\" else Printf.printf(\"NO\\n\"); case (t - 1))\nin Scanf.scanf \"%d\\n\" (fun t -> case t)"}], "negative_code": [], "src_uid": "f46f6fa28d0a7023da3bad0d222ce393"} {"nl": {"description": "Pushok the dog has been chasing Imp for a few hours already. Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string \"sh\" as a subsequence in it, in other words, the number of such pairs (i,\u2009j), that i\u2009<\u2009j and and . The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.Help Imp to find the maximum noise he can achieve by changing the order of the strings.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of strings in robot's memory. Next n lines contain the strings t1,\u2009t2,\u2009...,\u2009tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.", "output_spec": "Print a single integer\u00a0\u2014 the maxumum possible noise Imp can achieve by changing the order of the strings.", "sample_inputs": ["4\nssh\nhs\ns\nhhhs", "2\nh\ns"], "sample_outputs": ["18", "1"], "notes": "NoteThe optimal concatenation in the first sample is ssshhshhhs."}, "positive_code": [{"source_code": "\nlet identity x = x\n\nlet read_lines (n: int): string list =\n let rec read_single l i =\n if i == n then l\n else read_single (Scanf.scanf \"%s\\n\" identity :: l) (i + 1)\n in read_single [] 0\n\nlet count_of (cc: char) (src: string): int =\n let ret = ref 0 in\n String.iter (fun c -> if c == cc then ret := !ret + 1) src;\n !ret\n\nlet preprocess_lines (src: string list): (string * int * int) list =\n List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src\n\nlet postprocess_lines (src: (string * int * int) list): string list =\n List.map (fun (str, s, h) -> str) src\n\nlet sort_lines (src: (string * int * int) list): (string * int * int) list =\n let l, il = List.partition (fun (ss, s, h) -> h != 0) src in\n let l = List.map (fun (ss, s, h) -> (ss, s, h, (float_of_int s) /. (float_of_int h))) l in\n let comparator (_, _, _, lr) (_, _, _, rr) = -(compare lr rr) in\n let l = List.sort comparator l in\n il @ List.map (fun (ss, s, h, _) -> (ss, s, h)) l\n (* let comparator (lss, ls, lh) (rss, rs, rh) =\n if lh > rh\n then 1\n else if lh < rh\n then -1\n else if ls > rs\n then -1\n else if ls < rs\n then 1\n else 0\n in List.sort comparator src *)\n\nlet join_lines (src: string list): string =\n String.concat \"\" src\n\nlet count_subseq (src: string): Int64.t =\n let open Int64 in\n let (+) = Int64.add in\n let ret = ref zero in\n let cur_s = ref zero in\n String.iter (function\n | 's' -> cur_s := !cur_s + Int64.one\n | 'h' -> ret := !ret + !cur_s\n | _ -> ()\n ) src;\n !ret\n\nlet debug_string (src: string): string =\n print_endline src;\n src\n\nlet () =\n Scanf.scanf \"%u\\n\" identity |>\n read_lines |>\n preprocess_lines |>\n sort_lines |>\n postprocess_lines |>\n join_lines |>\n (* debug_string |> *)\n count_subseq |> Int64.to_string |>\n print_endline"}], "negative_code": [{"source_code": "\nlet identity x = x\n\nlet read_lines (n: int): string list =\n let rec read_single l i =\n if i == n then l\n else read_single (Scanf.scanf \"%s\\n\" identity :: l) (i + 1)\n in read_single [] 0\n\nlet count_of (cc: char) (src: string): int =\n let ret = ref 0 in\n String.iter (fun c -> if c == cc then ret := !ret + 1) src;\n !ret\n\nlet preprocess_lines (src: string list): (string * int * int) list =\n List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src\n\nlet postprocess_lines (src: (string * int * int) list): string list =\n List.map (fun (str, s, h) -> str) src\n\nlet sort_lines (src: (string * int * int) list): (string * int * int) list =\n let l, il = List.partition (fun (ss, s, h) -> h != 0) src in\n let l = List.map (fun (ss, s, h) -> (ss, s, h, (float_of_int s) /. (float_of_int h))) l in\n let comparator (_, _, _, lr) (_, _, _, rr) = -(compare lr rr) in\n let l = List.sort comparator l in\n il @ List.map (fun (ss, s, h, _) -> (ss, s, h)) l\n (* let comparator (lss, ls, lh) (rss, rs, rh) =\n if lh > rh\n then 1\n else if lh < rh\n then -1\n else if ls > rs\n then -1\n else if ls < rs\n then 1\n else 0\n in List.sort comparator src *)\n\nlet join_lines (src: string list): string =\n String.concat \"\" src\n\nlet count_subseq (src: string): int =\n let ret = ref 0 in\n let cur_s = ref 0 in\n String.iter (function\n | 's' -> cur_s := !cur_s + 1\n | 'h' -> ret := !ret + !cur_s\n | _ -> ()\n ) src;\n !ret\n\nlet debug_string (src: string): string =\n print_endline src;\n src\n\nlet () =\n Scanf.scanf \"%u\\n\" identity |>\n read_lines |>\n preprocess_lines |>\n sort_lines |>\n postprocess_lines |>\n join_lines |>\n debug_string |>\n count_subseq |> string_of_int |>\n print_endline"}, {"source_code": "\nlet identity x = x\n\nlet read_lines (n: int): string list =\n let rec read_single l i =\n if i == n then l\n else read_single (Scanf.scanf \"%s\\n\" identity :: l) (i + 1)\n in read_single [] 0\n\nlet count_of (cc: char) (src: string): int =\n let ret = ref 0 in\n String.iter (fun c -> if c == cc then ret := !ret + 1) src;\n !ret\n\nlet preprocess_lines (src: string list): (string * int * int) list =\n List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src\n\nlet postprocess_lines (src: (string * int * int) list): string list =\n List.map (fun (str, s, h) -> str) src\n\nlet sort_lines (src: (string * int * int) list): (string * int * int) list =\n let comparator (lss, ls, lh) (rss, rs, rh) =\n if lh > rh\n then 1\n else if lh < rh\n then -1\n else if ls > rs\n then -1\n else if ls < rs\n then 1\n else 0\n in List.sort comparator src\n\nlet join_lines (src: string list): string =\n String.concat \"\" src\n\nlet count_subseq (src: string): int =\n let ret = ref 0 in\n let cur_s = ref 0 in\n String.iter (function\n | 's' -> cur_s := !cur_s + 1\n | 'h' -> ret := !ret + !cur_s\n | _ -> ()\n ) src;\n !ret\n\nlet () =\n Scanf.scanf \"%u\\n\" identity;\n Scanf.scanf \"%s\\n\" identity;\n Scanf.scanf \"%s\\n\" identity;\n Scanf.scanf \"%s\\n\" identity;\n Scanf.scanf \"%s\\n\" identity |> print_endline;\n(* \nlet () =\n Scanf.scanf \"%u\\n\" identity |>\n read_lines |>\n preprocess_lines |>\n sort_lines |>\n postprocess_lines |>\n join_lines |>\n count_subseq |> string_of_int |>\n print_endline *)"}, {"source_code": "\nlet identity x = x\nlet () =\n Scanf.scanf \"%u\" identity;\n print_endline \"h\";"}, {"source_code": "\nlet identity x = x\n\nlet read_lines (n: int): string list =\n let rec read_single l i =\n if i == n then l\n else read_single (Scanf.scanf \"%s\\n\" identity :: l) (i + 1)\n in read_single [] 0\n\nlet count_of (cc: char) (src: string): int =\n let ret = ref 0 in\n String.iter (fun c -> if c == cc then ret := !ret + 1) src;\n !ret\n\nlet preprocess_lines (src: string list): (string * int * int) list =\n List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src\n\nlet postprocess_lines (src: (string * int * int) list): string list =\n List.map (fun (str, s, h) -> str) src\n\nlet sort_lines (src: (string * int * int) list): (string * int * int) list =\n let l, il = List.partition (fun (ss, s, h) -> h != 0) src in\n let l = List.map (fun (ss, s, h) -> (ss, s, h, (float_of_int s) /. (float_of_int h))) l in\n let comparator (_, _, _, lr) (_, _, _, rr) = -(compare lr rr) in\n let l = List.sort comparator l in\n il @ List.map (fun (ss, s, h, _) -> (ss, s, h)) l\n (* let comparator (lss, ls, lh) (rss, rs, rh) =\n if lh > rh\n then 1\n else if lh < rh\n then -1\n else if ls > rs\n then -1\n else if ls < rs\n then 1\n else 0\n in List.sort comparator src *)\n\nlet join_lines (src: string list): string =\n String.concat \"\" src\n\nlet count_subseq (src: string): int =\n let ret = ref 0 in\n let cur_s = ref 0 in\n String.iter (function\n | 's' -> cur_s := !cur_s + 1\n | 'h' -> ret := !ret + !cur_s\n | _ -> ()\n ) src;\n !ret\n\nlet debug_string (src: string): string =\n print_endline src;\n src\n\nlet () =\n Scanf.scanf \"%u\\n\" identity |>\n read_lines |>\n preprocess_lines |>\n sort_lines |>\n postprocess_lines |>\n join_lines |>\n (* debug_string |> *)\n count_subseq |> string_of_int |>\n print_endline"}, {"source_code": "\nlet identity x = x\n\nlet read_lines (n: int): string list =\n let rec read_single l i =\n if i == n then l\n else read_single (Scanf.scanf \"%s\\n\" identity :: l) (i + 1)\n in read_single [] 0\n\nlet count_of (cc: char) (src: string): int =\n let ret = ref 0 in\n String.iter (fun c -> if c == cc then ret := !ret + 1) src;\n !ret\n\nlet preprocess_lines (src: string list): (string * int * int) list =\n List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src\n\nlet postprocess_lines (src: (string * int * int) list): string list =\n List.map (fun (str, s, h) -> str) src\n\nlet sort_lines (src: (string * int * int) list): (string * int * int) list =\n let comparator (lss, ls, lh) (rss, rs, rh) =\n if lh > rh\n then 1\n else if lh < rh\n then -1\n else if ls > rs\n then -1\n else if ls < rs\n then 1\n else 0\n in List.sort comparator src\n\nlet join_lines (src: string list): string =\n String.concat \"\" src\n\nlet count_subseq (src: string): int =\n let ret = ref 0 in\n let cur_s = ref 0 in\n String.iter (function\n | 's' -> cur_s := !cur_s + 1\n | 'h' -> ret := !ret + !cur_s\n | _ -> ()\n ) src;\n !ret\n\nlet () =\n Scanf.scanf \"%u\\n\" identity |>\n read_lines |>\n preprocess_lines |>\n sort_lines |>\n postprocess_lines |>\n join_lines |>\n count_subseq |> string_of_int |>\n print_endline"}, {"source_code": "\nlet identity x = x\n\nlet read_lines (n: int): string list =\n let rec read_single l i =\n if i == n then l\n else read_single (input_line stdin :: l) (i + 1)\n in read_single [] 0\n\nlet count_of (cc: char) (src: string): int =\n let ret = ref 0 in\n String.iter (fun c -> if c == cc then ret := !ret + 1) src;\n !ret\n\nlet preprocess_lines (src: string list): (string * int * int) list =\n List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src\n\nlet postprocess_lines (src: (string * int * int) list): string list =\n List.map (fun (str, s, h) -> str) src\n\nlet sort_lines (src: (string * int * int) list): (string * int * int) list =\n let comparator (lss, ls, lh) (rss, rs, rh) =\n if lh > rh\n then 1\n else if lh < rh\n then -1\n else if ls > rs\n then -1\n else if ls < rs\n then 1\n else 0\n in List.sort comparator src\n\nlet join_lines (src: string list): string =\n String.concat \"\" src\n\nlet count_subseq (src: string): int =\n let ret = ref 0 in\n let cur_s = ref 0 in\n String.iter (function\n | 's' -> cur_s := !cur_s + 1\n | 'h' -> ret := !ret + !cur_s\n | _ -> ()\n ) src;\n !ret\n\nlet () =\n Scanf.scanf \"%u\" identity |>\n string_of_int |>\n print_endline\n"}], "src_uid": "f88cf470095f250ffeb57feae7697e36"} {"nl": {"description": "Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \\to 2 \\to \\ldots n \\to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\\to$$$ take-off from the $$$1$$$-st planet $$$\\to$$$ landing to the $$$2$$$-nd planet $$$\\to$$$ $$$2$$$-nd planet $$$\\to$$$ take-off from the $$$2$$$-nd planet $$$\\to$$$ $$$\\ldots$$$ $$$\\to$$$ landing to the $$$n$$$-th planet $$$\\to$$$ the $$$n$$$-th planet $$$\\to$$$ take-off from the $$$n$$$-th planet $$$\\to$$$ landing to the $$$1$$$-st planet $$$\\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \\cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 1000$$$)\u00a0\u2014 number of planets. The second line contains the only integer $$$m$$$ ($$$1 \\le m \\le 1000$$$)\u00a0\u2014 weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.", "output_spec": "If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\\frac{|p - q|}{\\max{(1, |q|)}} \\le 10^{-6}$$$.", "sample_inputs": ["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"], "sample_outputs": ["10.0000000000", "-1", "85.4800000000"], "notes": "NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth."}, "positive_code": [{"source_code": "\nlet option_get ~default = function\n | Some a -> a\n | None -> default\n\nlet bisearch_num (callback: float -> bool) ((l, r): float * float): float option =\n let rec f l r =\n let m = (l +. r) /. 2. in\n (* ATTENTION: this base case ... *)\n if abs_float (r -. l) <= 1e-6 then if callback r then Some r else None\n else if callback m then f l m else f m r\n in\n f l r\n\nlet () =\n (* n - #planet including Earth & Mars *)\n (* mr - mass of payload *)\n let n, mr = Scanf.scanf \" %d %f\" (fun x y -> x, y) in\n let a = Array.init n (fun _ -> Scanf.scanf \" %f\" (fun i -> i)) in\n let b = Array.init n (fun _ -> Scanf.scanf \" %f\" (fun i -> i)) in\n\n let f rem =\n let rec f i rem =\n if i = n then rem\n else\n let rem = rem -. (rem +. mr) /. b.(i) in\n let rem = rem -. (rem +. mr) /. a.(i) in\n f (i + 1) rem\n in f 0 rem >= 0.\n in\n bisearch_num f (0., 1_000_000_001.) |>\n option_get ~default:(-1.) |>\n Printf.printf \"%.06f\\n\"\n"}], "negative_code": [{"source_code": "\nlet option_get ~default = function\n | Some a -> a\n | None -> default\n\nlet bisearch_num (callback: float -> bool) ((l, r): float * float): float option =\n let rec f l r =\n let m = (l +. r) /. 2. in\n (* ATTENTION: this base case ... *)\n if abs_float (r -. l) <= 1e-6 then if callback r then Some r else None\n else if callback m then f l m else f m r\n in\n f l r\n\nlet () =\n (* n - #planet including Earth & Mars *)\n (* mr - mass of payload *)\n let n, mr = Scanf.scanf \" %d %f\" (fun x y -> x, y) in\n let a = Array.init n (fun _ -> Scanf.scanf \" %f\" (fun i -> i)) in\n let b = Array.init n (fun _ -> Scanf.scanf \" %f\" (fun i -> i)) in\n\n let f rem =\n let rec f i rem =\n if i = n then rem\n else\n let rem = rem -. (rem +. mr) /. b.(i) in\n let rem = rem -. (rem +. mr) /. a.(i) in\n f (i + 1) rem\n in f 0 rem >= 0.\n in\n bisearch_num f (0., 1_000_000_000.) |>\n option_get ~default:(-1.) |>\n Printf.printf \"%.06f\\n\"\n"}, {"source_code": "\nlet option_get ~default = function\n | Some a -> a\n | None -> default\n\nlet bisearch_num (callback: float -> bool) ((l, r): float * float): float option =\n let rec f l r =\n let m = (l +. r) /. 2. in\n if abs_float (r -. l) <= 1e-6 then if callback m then Some m else None\n else if callback m then f l m else f m r\n in f l r\n \nlet () =\n (* n - #planet including Earth & Mars *)\n (* mr - mass of payload *)\n let n, mr = Scanf.scanf \" %d %f\" (fun x y -> x, y) in\n let a = Array.init n (fun _ -> Scanf.scanf \" %f\" (fun i -> i)) in\n let b = Array.init n (fun _ -> Scanf.scanf \" %f\" (fun i -> i)) in\n\n let f rem =\n let rec f i rem =\n if i = n then rem\n else\n let rem = rem -. (rem +. mr) /. b.(i) in\n let rem = rem -. (rem +. mr) /. a.(i) in\n f (i + 1) rem\n in f 0 rem >= 0.\n in\n bisearch_num f (0., 1_000_000_000.) |>\n option_get ~default:(-1.) |>\n Printf.printf \"%.06f\\n\"\n"}], "src_uid": "d9bd63e03bf51ed87ba73cd15e8ce58d"} {"nl": {"description": "According to a new ISO standard, a flag of every country should have a chequered field n\u2009\u00d7\u2009m, each square should be of one of 10 colours, and the flag should be \u00abstriped\u00bb: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.", "input_spec": "The first line of the input contains numbers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100), n \u2014 the amount of rows, m \u2014 the amount of columns on the flag of Berland. Then there follows the description of the flag: each of the following n lines contain m characters. Each character is a digit between 0 and 9, and stands for the colour of the corresponding square.", "output_spec": "Output YES, if the flag meets the new ISO standard, and NO otherwise.", "sample_inputs": ["3 3\n000\n111\n222", "3 3\n000\n000\n111", "3 3\n000\n111\n002"], "sample_outputs": ["YES", "NO", "NO"], "notes": null}, "positive_code": [{"source_code": "\nexception No;;\nlet check_one_line l= \n List.fold_left (fun a b -> \n if a !=b \n then raise No \n else a) \n (List.hd l) \n l;;\n\nlet check_two_line l = \n List.fold_left (fun a b -> \n check_one_line b;\n if (List.hd a)==(List.hd b) \n then raise No else b) \n [10;10] \n l;;\n\n\n\nlet rec get_line_wrap m = \n let rec get_line m r = \n if m==0 then r \n else get_line (m-1) ((Scanf.scanf \"%c\" (fun c -> Char.code c - Char.code '0'))::r)\n in\n let \n a = get_line m [];\n in\n Scanf.scanf \"%c\" (fun c -> c);\n a;;\n\nlet get_lines_wrap n m =\n let rec get_lines n m r= \n if n<=0 then r \n else get_lines (n-1) m ((get_line_wrap m) :: r)\n in\n get_lines n m [];;\n\nlet () = \n let l = Scanf.scanf \"%d %d\\n\" get_lines_wrap in \n try \n check_two_line l;Printf.printf \"Yes\\n\" \n with No -> Printf.printf \"No\\n\";;\n"}, {"source_code": "\nexception No;;\nlet check_one_line l= \n List.fold_left (fun a b -> \n if a !=b \n then raise No \n else a) \n (List.hd l) \n l;;\n\nlet check_two_line l = \n List.fold_left (fun a b -> \n check_one_line b;\n if (List.hd a)==(List.hd b) \n then raise No else b) \n [10;10] \n l;;\n\nlet rec get_line m = \n if m==0 then [] \n else (Scanf.scanf \"%c\" (fun c -> Char.code c - Char.code '0')):: (get_line (m-1));;\n\nlet rec get_line_wrap m = \n let \n a = get_line m;\n in\n Scanf.scanf \"%c\" (fun c -> c);\n a;;\n\nlet rec get_lines n m = \n if n<=0 then [] \n else get_line_wrap m :: get_lines (n-1) m;;\n\nlet () = \n let l = Scanf.scanf \"%d %d\\n\" get_lines in \n try \n check_two_line l;Printf.printf \"Yes\\n\" \n with No -> Printf.printf \"No\\n\";;\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let a = Array.init n read_str in\n let rec go i j =\n if i = n then\n true\n else if j = m then\n go (i+1) 0\n else if j > 0 && a.(i).[j-1] <> a.(i).[j] then\n false\n else if i > 0 && j = 0 && a.(i-1).[0] = a.(i).[0] then\n false\n else\n go i (j+1)\n in\n print_endline (if go 0 0 then \"YES\" else \"NO\")\n"}], "negative_code": [], "src_uid": "80d3da5aba371f4d572ea928025c5bbd"} {"nl": {"description": "Petya has recently started working as a programmer in the IT city company that develops computer games.Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px,\u2009py), a nonzero vector with coordinates (vx,\u2009vy), positive scalars a,\u2009b,\u2009c,\u2009d,\u2009a\u2009>\u2009c.The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px,\u2009py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px,\u2009py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx,\u2009vy) vector.Enumerate the arrow points coordinates in counter-clockwise order starting from the tip. ", "input_spec": "The only line of the input contains eight integers px,\u2009py,\u2009vx,\u2009vy (\u2009-\u20091000\u2009\u2264\u2009px,\u2009py,\u2009vx,\u2009vy\u2009\u2264\u20091000,\u2009vx2\u2009+\u2009vy2\u2009>\u20090), a,\u2009b,\u2009c,\u2009d (1\u2009\u2264\u2009a,\u2009b,\u2009c,\u2009d\u2009\u2264\u20091000,\u2009a\u2009>\u2009c).", "output_spec": "Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10\u2009-\u20099.", "sample_inputs": ["8 8 0 2 8 3 4 5"], "sample_outputs": ["8.000000000000 11.000000000000\n4.000000000000 8.000000000000\n6.000000000000 8.000000000000\n6.000000000000 3.000000000000\n10.000000000000 3.000000000000\n10.000000000000 8.000000000000\n12.000000000000 8.000000000000"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let px = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let py = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let vx = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let vy = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let d = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let sqr x = x *. x in\n let norm = sqrt (sqr vx +. sqr vy) in\n let vx = vx /. norm in\n let vy = vy /. norm in\n let print x y =\n Printf.printf \"%.9f %.9f\\n\"\n (px +. x *. vx -. y *. vy)\n (py +. x *. vy +. y *. vx)\n in\n print b 0.0;\n print 0.0 (a /. 2.0);\n print 0.0 (c /. 2.0);\n print (-.d) (c /. 2.0);\n print (-.d) (-.c /. 2.0);\n print 0.0 (-.c /. 2.0);\n print 0.0 (-.a /. 2.0);\n"}], "negative_code": [], "src_uid": "2cb1e7e4d25f624da934bce5c628a7ee"} {"nl": {"description": "One must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees.One of such magic schools consists of n tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've brought with you have space for no more than k huge prizes.Besides the fact that you want to take all the prizes home, you also want to perform well. You will consider your performance good if you win at least l tours.In fact, years of organizing contests proved to the organizers that transporting huge prizes is an issue for the participants. Alas, no one has ever invented a spell that would shrink the prizes... So, here's the solution: for some tours the winner gets a bag instead of a huge prize. Each bag is characterized by number ai \u2014 the number of huge prizes that will fit into it.You already know the subject of all tours, so you can estimate the probability pi of winning the i-th tour. You cannot skip the tour under any circumstances.Find the probability that you will perform well on the contest and will be able to take all won prizes home (that is, that you will be able to fit all the huge prizes that you won into the bags that you either won or brought from home).", "input_spec": "The first line contains three integers n, l, k (1\u2009\u2264\u2009n\u2009\u2264\u2009200,\u20090\u2009\u2264\u2009l,\u2009k\u2009\u2264\u2009200) \u2014 the number of tours, the minimum number of tours to win, and the number of prizes that you can fit in the bags brought from home, correspondingly. The second line contains n space-separated integers, pi (0\u2009\u2264\u2009pi\u2009\u2264\u2009100) \u2014 the probability to win the i-th tour, in percents. The third line contains n space-separated integers, ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009200) \u2014 the capacity of the bag that will be awarded to you for winning the i-th tour, or else -1, if the prize for the i-th tour is a huge prize and not a bag.", "output_spec": "Print a single real number \u2014 the answer to the problem. The answer will be accepted if the absolute or relative error does not exceed 10\u2009-\u20096.", "sample_inputs": ["3 1 0\n10 20 30\n-1 -1 2", "1 1 1\n100\n123"], "sample_outputs": ["0.300000000000", "1.000000000000"], "notes": "NoteIn the first sample we need either win no tour or win the third one. If we win nothing we wouldn't perform well. So, we must to win the third tour. Other conditions will be satisfied in this case. Probability of wining the third tour is 0.3.In the second sample we win the only tour with probability 1.0, and go back home with bag for it."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n 0.0 in\n let a = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n p.(i) <- float_of_int (Scanf.bscanf sb \"%d \" (fun s -> s)) /. 100.0;\n done;\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n done;\n in\n let b = Array.init (n + 1)\n (fun _ -> Array.make_matrix (n + 1) (2 * n + 1) 0.0)\n in\n let k = min k n in\n b.(0).(0).(k + n) <- 1.0;\n for i = 0 to n - 1 do\n for j = 0 to n do\n\tfor m = 0 to 2 * n do\n\t if b.(i).(j).(m) <> 0.0 then (\n\t if a.(i) < 0\n\t then (\n\t b.(i + 1).(j + 1).(m - 1) <-\n\t\tb.(i + 1).(j + 1).(m - 1) +. b.(i).(j).(m) *. p.(i);\n\t b.(i + 1).(j).(m) <-\n\t\tb.(i + 1).(j).(m) +. b.(i).(j).(m) *. (1.0 -. p.(i));\n\t ) else (\n\t let aa = m + a.(i) in\n\t let aa = if aa > 2 * n then 2 * n else aa in\n\t\tb.(i + 1).(j + 1).(aa) <-\n\t\t b.(i + 1).(j + 1).(aa) +. b.(i).(j).(m) *. p.(i);\n\t\tb.(i + 1).(j).(m) <-\n\t\t b.(i + 1).(j).(m) +. b.(i).(j).(m) *. (1.0 -. p.(i));\n\t )\n\t )\n\tdone\n done\n done;\n let res = ref 0.0 in\n for i = l to n do\n\tfor j = n to 2 * n do\n\t res := !res +. b.(n).(i).(j)\n\tdone\n done;\n Printf.printf \"%.9f\\n\" !res\n\n"}], "negative_code": [], "src_uid": "23604db874ed5b7c007ea4a837bf9c88"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$b$$$. In one turn, you can do one of the following operations: Take an integer $$$c$$$ ($$$c > 1$$$ and $$$a$$$ should be divisible by $$$c$$$) and replace $$$a$$$ with $$$\\frac{a}{c}$$$; Take an integer $$$c$$$ ($$$c > 1$$$ and $$$b$$$ should be divisible by $$$c$$$) and replace $$$b$$$ with $$$\\frac{b}{c}$$$. Your goal is to make $$$a$$$ equal to $$$b$$$ using exactly $$$k$$$ turns.For example, the numbers $$$a=36$$$ and $$$b=48$$$ can be made equal in $$$4$$$ moves: $$$c=6$$$, divide $$$b$$$ by $$$c$$$ $$$\\Rightarrow$$$ $$$a=36$$$, $$$b=8$$$; $$$c=2$$$, divide $$$a$$$ by $$$c$$$ $$$\\Rightarrow$$$ $$$a=18$$$, $$$b=8$$$; $$$c=9$$$, divide $$$a$$$ by $$$c$$$ $$$\\Rightarrow$$$ $$$a=2$$$, $$$b=8$$$; $$$c=4$$$, divide $$$b$$$ by $$$c$$$ $$$\\Rightarrow$$$ $$$a=2$$$, $$$b=2$$$. For the given numbers $$$a$$$ and $$$b$$$, determine whether it is possible to make them equal using exactly $$$k$$$ turns.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is contains three integers $$$a$$$, $$$b$$$ and $$$k$$$ ($$$1 \\le a, b, k \\le 10^9$$$).", "output_spec": "For each test case output: \"Yes\", if it is possible to make the numbers $$$a$$$ and $$$b$$$ equal in exactly $$$k$$$ turns; \"No\" otherwise. The strings \"Yes\" and \"No\" can be output in any case.", "sample_inputs": ["8\n36 48 2\n36 48 3\n36 48 4\n2 8 1\n2 8 2\n1000000000 1000000000 1000000000\n1 2 1\n2 2 1"], "sample_outputs": ["YES\nYES\nYES\nYES\nYES\nNO\nYES\nNO"], "notes": null}, "positive_code": [{"source_code": "module Stdlib = Pervasives\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\n\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet rec repeat f state = function\r\n | 0 -> ()\r\n | n -> let () = f state in repeat f state (n - 1);;\r\n\r\nlet create_sieve n =\r\n let primes = Array.make (n + 1) 0 and primes_count = ref 0 and ancs = Array.make (n + 1) 0 in\r\n let () =\r\n for i = 2 to n do\r\n begin\r\n if ancs.(i) = 0 then\r\n let () = ancs.(i) <- i and () = primes.(!primes_count) <- i in incr primes_count\r\n else ();\r\n let j = ref 0 in\r\n while !j < !primes_count && i * primes.(!j) <= n && primes.(!j) <= ancs.(i) do\r\n let () = ancs.(i * primes.(!j)) <- primes.(!j) in incr j\r\n done\r\n end\r\n done\r\n in\r\n (Array.sub primes 0 !primes_count |> Array.to_list, ancs, n)\r\n\r\nlet rec fact_folder ancs value acc =\r\n if value = 1 then acc else fact_folder ancs (value / ancs.(value)) (acc + 1);;\r\n\r\nlet rec helper ((_, ancs, primlimit) as sieve) primes value acc =\r\n match primes with\r\n | [] -> if value = 1 then acc else acc + 1\r\n | prime::primes_tail as primes ->\r\n if value <= primlimit then fact_folder ancs value acc\r\n else if value mod prime = 0 then helper sieve primes (value / prime) (acc + 1)\r\n else helper sieve primes_tail value acc;;\r\n\r\nlet calc_primes_count ((primes, _, _) as sieve) value = helper sieve primes value 0\r\n\r\nlet solution (inp, outp, sieve) =\r\n let (a, b, c) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let result =\r\n if c = 1 then a != b && (a mod b = 0 || b mod a = 0)\r\n else\r\n let count_a = calc_primes_count sieve a and count_b = calc_primes_count sieve b in\r\n count_a + count_b >= c\r\n in\r\n let answer = if result then \"YES\\n\" else \"NO\\n\" in\r\n let () = Printf.fprintf outp \"%s\" answer in\r\n ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let primlimit = 31623 in\r\n let sieve = create_sieve primlimit in\r\n let state = (inp, outp, sieve) in\r\n repeat solution state tests_count;;\r\n"}, {"source_code": "module Stdlib = Pervasives\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\n\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet rec repeat f state = function\r\n | 0 -> ()\r\n | n -> let () = f state in repeat f state (n - 1);;\r\n\r\nlet create_sieve n =\r\n let primes = Array.make (n + 1) 0 and primes_count = ref 0 and ancs = Array.make (n + 1) 0 in\r\n let () =\r\n for i = 2 to n do\r\n begin\r\n if ancs.(i) = 0 then\r\n let () = ancs.(i) <- i and () = primes.(!primes_count) <- i in incr primes_count\r\n else ();\r\n let j = ref 0 in\r\n while !j < !primes_count && i * primes.(!j) <= n && primes.(!j) <= ancs.(i) do\r\n let () = ancs.(i * primes.(!j)) <- primes.(!j) in incr j\r\n done\r\n end\r\n done\r\n in\r\n (Array.sub primes 0 !primes_count |> Array.to_list, ancs, n)\r\n\r\nlet rec fact_folder ancs value acc =\r\n if value = 1 then acc else fact_folder ancs (value / ancs.(value)) (acc + 1);;\r\n\r\nlet rec helper ((_, ancs, primlimit) as sieve) primes value acc =\r\n match primes with\r\n | [] -> if value = 1 then acc else acc + 1\r\n | prime::primes_tail as primes ->\r\n if value <= primlimit then fact_folder ancs value acc\r\n else if value mod prime = 0 then helper sieve primes (value / prime) (acc + 1)\r\n else helper sieve primes_tail value acc;;\r\n\r\nlet calc_primes_count ((primes, _, _) as sieve) value = helper sieve primes value 0\r\n\r\nlet solution (inp, outp, sieve) =\r\n let (a, b, c) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let result =\r\n if c = 1 then\r\n if a != b && (a mod b = 0 || b mod a = 0) then true else false\r\n else\r\n let count_a = calc_primes_count sieve a and count_b = calc_primes_count sieve b in\r\n count_a + count_b >= c\r\n in\r\n let answer = if result then \"YES\\n\" else \"NO\\n\" in\r\n let () = Printf.fprintf outp \"%s\" answer in\r\n ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let primlimit = 31623 in\r\n let sieve = create_sieve primlimit in\r\n let state = (inp, outp, sieve) in\r\n repeat solution state tests_count;;\r\n"}, {"source_code": "module Stdlib = Pervasives\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\n\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet rec repeat f state = function\r\n | 0 -> ()\r\n | n ->\r\n let () = f state in\r\n repeat f state (n - 1);;\r\n\r\ntype sieve = int list * int array * int;;\r\n\r\nlet create_sieve n =\r\n let primes = Array.make (n + 1) 0 and primes_count = ref 0 and ancs = Array.make (n + 1) 0 in\r\n let () =\r\n for i = 2 to n do\r\n begin\r\n if ancs.(i) = 0 then\r\n let () = ancs.(i) <- i and () = primes.(!primes_count) <- i in\r\n incr primes_count\r\n else ();\r\n let j = ref 0 in\r\n while !j < !primes_count && i * primes.(!j) <= n && primes.(!j) <= ancs.(i) do\r\n let () = ancs.(i * primes.(!j)) <- primes.(!j) in\r\n incr j\r\n done\r\n end\r\n done\r\n in\r\n (Array.sub primes 0 !primes_count |> Array.to_list, ancs, n)\r\n\r\nlet rec fact_folder ancs value acc =\r\n if value = 1 then acc\r\n else fact_folder ancs (value / ancs.(value)) (acc + 1);;\r\n\r\n let rec helper ((_, ancs, primlimit) as sieve) primes value acc =\r\n match primes with\r\n | [] -> if value = 1 then acc else acc + 1\r\n | prime::primes_tail as primes ->\r\n if value <= primlimit then fact_folder ancs value acc\r\n else if value mod prime = 0 then helper sieve primes (value / prime) (acc + 1)\r\n else helper sieve primes_tail value acc;;\r\n\r\nlet calc_primes_count ((primes, _, _) as sieve) value =\r\n helper sieve primes value 0\r\n\r\nlet solution (inp, outp, sieve) =\r\n let (a, b, c) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let result =\r\n if c = 1 then\r\n if a != b && (a mod b = 0 || b mod a = 0) then true else false\r\n else\r\n let count_a = calc_primes_count sieve a and count_b = calc_primes_count sieve b in\r\n count_a + count_b >= c\r\n in\r\n let answer = if result then \"YES\\n\" else \"NO\\n\" in\r\n let () = Printf.fprintf outp \"%s\" answer in\r\n ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let primlimit = 31623 in\r\n let sieve = create_sieve primlimit in\r\n let state = (inp, outp, sieve) in\r\n repeat solution state tests_count;;\r\n"}, {"source_code": "module Stdlib = Pervasives\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet rec repeat f state = function\r\n | 0 -> ()\r\n | n ->\r\n let () = f state in\r\n repeat f state (n - 1);;\r\n\r\ntype sieve = int list * int array * int;;\r\n\r\nlet create_sieve n =\r\n let primes = Array.make (n + 1) 0 and primes_count = ref 0 and ancs = Array.make (n + 1) 0 in\r\n let () =\r\n for i = 2 to n do\r\n begin\r\n if ancs.(i) = 0 then\r\n let () = ancs.(i) <- i and () = primes.(!primes_count) <- i in\r\n incr primes_count\r\n else ();\r\n let j = ref 0 in\r\n while !j < !primes_count && i * primes.(!j) <= n && primes.(!j) <= ancs.(i) do\r\n let () = ancs.(i * primes.(!j)) <- primes.(!j) in\r\n incr j\r\n done\r\n end\r\n done\r\n in\r\n (Array.sub primes 0 !primes_count |> Array.to_list, ancs, n)\r\n\r\nlet rec fact_folder ancs value acc =\r\n if value = 1 then acc\r\n else fact_folder ancs (value / ancs.(value)) (acc + 1);;\r\n\r\n let rec helper ((_, ancs, primlimit) as sieve) primes value acc =\r\n match primes with\r\n | [] -> if value = 1 then acc else acc + 1\r\n | prime::primes_tail as primes ->\r\n if value <= primlimit then fact_folder ancs value acc\r\n else if value mod prime = 0 then helper sieve primes (value / prime) (acc + 1)\r\n else helper sieve primes_tail value acc;;\r\n\r\nlet calc_primes_count ((primes, _, _) as sieve) value =\r\n helper sieve primes value 0\r\n\r\nlet solution (inp, outp, sieve) =\r\n let (a, b, c) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let result =\r\n if c = 1 then\r\n if a != b && (a mod b = 0 || b mod a = 0) then true else false\r\n else\r\n let count_a = calc_primes_count sieve a and count_b = calc_primes_count sieve b in\r\n count_a + count_b >= c\r\n in\r\n let answer = if result then \"YES\" else \"NO\" in\r\n let () = Printf.fprintf outp \"%s\\n\" answer in\r\n ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let primlimit = 31623 in\r\n let sieve = create_sieve primlimit in\r\n let state = (inp, outp, sieve) in\r\n repeat solution state tests_count;;\r\n"}, {"source_code": "module Stdlib = Pervasives\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet gc_defaults = Gc.get ();;\r\n\r\nlet () =\r\n Gc.set\r\n { gc_defaults with\r\n minor_heap_size = 1024 * 1024\r\n ; major_heap_increment = 1024 * 1024\r\n };;\r\n\r\nlet rec repeat f state = function\r\n | 0 -> ()\r\n | n ->\r\n let () = f state in\r\n repeat f state (n - 1);;\r\n\r\ntype sieve = int list * int array * int;; (* primes, ancestors, primlimit *)\r\n\r\nlet create_sieve n =\r\n let primes = Array.make (n + 1) 0 and primes_count = ref 0 and ancs = Array.make (n + 1) 0 in\r\n let () =\r\n for i = 2 to n do\r\n begin\r\n if ancs.(i) = 0 then\r\n let () = ancs.(i) <- i and () = primes.(!primes_count) <- i in\r\n incr primes_count\r\n else ();\r\n let j = ref 0 in\r\n while !j < !primes_count && i * primes.(!j) <= n && primes.(!j) <= ancs.(i) do\r\n let () = ancs.(i * primes.(!j)) <- primes.(!j) in\r\n incr j\r\n done\r\n end\r\n done\r\n in\r\n ( Array.sub primes 0 !primes_count |> Array.to_list , ancs , n )\r\n\r\nlet calc_primes_count ((primes, _, _) as sieve) value =\r\n let rec fact_folder ancs value acc =\r\n if value = 1 then acc\r\n else fact_folder ancs (value / ancs.(value)) (acc + 1)\r\n in\r\n let rec helper ((_, ancs, primlimit) as sieve) primes value acc =\r\n match primes with\r\n | [] -> if value = 1 then acc else acc + 1\r\n | prime::primes_tail as primes ->\r\n if value <= primlimit then fact_folder ancs value acc\r\n else if value mod prime = 0 then helper sieve primes (value / prime) (acc + 1)\r\n else helper sieve primes_tail value acc\r\n in\r\n helper sieve primes value 0\r\n\r\nlet solution (inp, outp, sieve) =\r\n let (_primes, _ancs, _primlimit) = sieve in\r\n let (a, b, c) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let result =\r\n if c = 1 then\r\n if a != b && (a mod b = 0 || b mod a = 0) then true else false\r\n else\r\n let count_a = calc_primes_count sieve a and count_b = calc_primes_count sieve b in\r\n count_a + count_b >= c\r\n in\r\n let answer = if result then \"YES\" else \"NO\" in\r\n let () = Printf.fprintf outp \"%s\\n\" answer in\r\n(* let () = Printf.fprintf outp \"Val A: %d; Val B: %d\\n\" a b in\r\n let () = Printf.fprintf outp \"Count A: %d; Count B: %d\\n\" count_a count_b in\r\n *) ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n (* let primlimit = 20 in *)\r\n let primlimit = 31623 in\r\n let sieve = create_sieve primlimit in\r\n let state = (inp, outp, sieve) in\r\n repeat solution state tests_count;;\r\n"}, {"source_code": "module Stdlib = Pervasives\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet gc_defaults = Gc.get ();;\r\n\r\nlet () =\r\n Gc.set\r\n { gc_defaults with\r\n minor_heap_size = 1024 * 1024 * 16\r\n ; major_heap_increment = 1024 * 1024 * 32\r\n };;\r\n\r\nlet rec repeat f state = function\r\n | 0 -> ()\r\n | n ->\r\n let () = f state in\r\n repeat f state (n - 1);;\r\n\r\ntype sieve = int list * int array * int;; (* primes, ancestors, primlimit *)\r\n\r\nlet create_sieve n =\r\n let primes = Array.make (n + 1) 0 and primes_count = ref 0 and ancs = Array.make (n + 1) 0 in\r\n let () =\r\n for i = 2 to n do\r\n begin\r\n if ancs.(i) = 0 then\r\n let () = ancs.(i) <- i and () = primes.(!primes_count) <- i in\r\n incr primes_count\r\n else ();\r\n let j = ref 0 in\r\n while !j < !primes_count && i * primes.(!j) <= n && primes.(!j) <= ancs.(i) do\r\n let () = ancs.(i * primes.(!j)) <- primes.(!j) in\r\n incr j\r\n done\r\n end\r\n done\r\n in\r\n ( Array.sub primes 0 !primes_count |> Array.to_list , ancs , n )\r\n\r\nlet calc_primes_count ((primes, _, _) as sieve) value =\r\n let rec fact_folder ancs value acc =\r\n if value = 1 then acc\r\n else fact_folder ancs (value / ancs.(value)) (acc + 1)\r\n in\r\n let rec helper ((_, ancs, primlimit) as sieve) primes value acc =\r\n match primes with\r\n | [] -> if value = 1 then acc else acc + 1\r\n | prime::primes_tail as primes ->\r\n if value <= primlimit then fact_folder ancs value acc\r\n else if value mod prime = 0 then helper sieve primes (value / prime) (acc + 1)\r\n else helper sieve primes_tail value acc\r\n in\r\n helper sieve primes value 0\r\n\r\nlet solution (inp, outp, sieve) =\r\n let (_primes, _ancs, _primlimit) = sieve in\r\n let (a, b, c) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let result =\r\n if c = 1 then\r\n if a != b && (a mod b = 0 || b mod a = 0) then true else false\r\n else\r\n let count_a = calc_primes_count sieve a and count_b = calc_primes_count sieve b in\r\n count_a + count_b >= c\r\n in\r\n let answer = if result then \"YES\" else \"NO\" in\r\n let () = Printf.fprintf outp \"%s\\n\" answer in\r\n(* let () = Printf.fprintf outp \"Val A: %d; Val B: %d\\n\" a b in\r\n let () = Printf.fprintf outp \"Count A: %d; Count B: %d\\n\" count_a count_b in\r\n *) ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n (* let primlimit = 20 in *)\r\n let primlimit = 31623 in\r\n let sieve = create_sieve primlimit in\r\n let state = (inp, outp, sieve) in\r\n repeat solution state tests_count;;\r\n"}, {"source_code": "module Stdlib = Pervasives\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet rec repeat f state = function\r\n | 0 -> ()\r\n | n ->\r\n let () = f state in\r\n repeat f state (n - 1);;\r\n\r\ntype sieve = int list * int array * int;; (* primes, ancestors, primlimit *)\r\n\r\nlet create_sieve n =\r\n let primes = Array.make (n + 1) 0 and primes_count = ref 0 and ancs = Array.make (n + 1) 0 in\r\n let () =\r\n for i = 2 to n do\r\n begin\r\n if ancs.(i) = 0 then\r\n let () = ancs.(i) <- i and () = primes.(!primes_count) <- i in\r\n incr primes_count\r\n else ();\r\n let j = ref 0 in\r\n while !j < !primes_count && i * primes.(!j) <= n && primes.(!j) <= ancs.(i) do\r\n let () = ancs.(i * primes.(!j)) <- primes.(!j) in\r\n incr j\r\n done\r\n end\r\n done\r\n in\r\n ( Array.sub primes 0 !primes_count |> Array.to_list , ancs , n )\r\n\r\nlet calc_primes_count ((primes, _, _) as sieve) value =\r\n let rec fact_folder ancs value acc =\r\n if value = 1 then acc\r\n else fact_folder ancs (value / ancs.(value)) (acc + 1)\r\n in\r\n let rec helper ((_, ancs, primlimit) as sieve) primes value acc =\r\n match primes with\r\n | [] -> if value = 1 then acc else acc + 1\r\n | prime::primes_tail as primes ->\r\n if value <= primlimit then fact_folder ancs value acc\r\n else if value mod prime = 0 then helper sieve primes (value / prime) (acc + 1)\r\n else helper sieve primes_tail value acc\r\n in\r\n helper sieve primes value 0\r\n\r\nlet solution (inp, outp, sieve) =\r\n let (_primes, _ancs, _primlimit) = sieve in\r\n let (a, b, c) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let result =\r\n if c = 1 then\r\n if a != b && (a mod b = 0 || b mod a = 0) then true else false\r\n else\r\n let count_a = calc_primes_count sieve a and count_b = calc_primes_count sieve b in\r\n count_a + count_b >= c\r\n in\r\n let answer = if result then \"YES\" else \"NO\" in\r\n let () = Printf.fprintf outp \"%s\\n\" answer in\r\n(* let () = Printf.fprintf outp \"Val A: %d; Val B: %d\\n\" a b in\r\n let () = Printf.fprintf outp \"Count A: %d; Count B: %d\\n\" count_a count_b in\r\n *) ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n (* let primlimit = 20 in *)\r\n let primlimit = 31623 in\r\n let sieve = create_sieve primlimit in\r\n let state = (inp, outp, sieve) in\r\n repeat solution state tests_count;;\r\n"}, {"source_code": "module Stdlib = Pervasives\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet rec repeat f state = function\r\n | 0 -> ()\r\n | n ->\r\n let () = f state in\r\n repeat f state (n - 1);;\r\n\r\ntype sieve = int list * int array * int;; (* primes, ancestors, primlimit *)\r\n\r\nlet create_sieve n =\r\n let primes = Array.make (n + 1) 0 and primes_count = ref 0 and ancs = Array.make (n + 1) 0 in\r\n let () =\r\n for i = 2 to n do\r\n begin\r\n if ancs.(i) = 0 then\r\n let () = ancs.(i) <- i and () = primes.(!primes_count) <- i in\r\n incr primes_count\r\n else ();\r\n let j = ref 0 in\r\n while !j < !primes_count && i * primes.(!j) <= n && primes.(!j) <= ancs.(i) do\r\n let () = ancs.(i * primes.(!j)) <- primes.(!j) in\r\n incr j\r\n done\r\n end\r\n done\r\n in\r\n ( Array.sub primes 0 !primes_count |> Array.to_list , ancs , n )\r\n\r\nlet calc_primes_count ((primes, _, _) as sieve) value =\r\n let rec fact_folder ancs value acc =\r\n if value = 1 then acc\r\n else fact_folder ancs (value / ancs.(value)) (acc + 1)\r\n in\r\n let rec helper ((_, ancs, primlimit) as sieve) primes value acc =\r\n match primes with\r\n | [] -> if value = 1 then acc else acc + 1\r\n | prime::primes_tail as primes ->\r\n if value <= primlimit then fact_folder ancs value acc\r\n else if value mod prime = 0 then helper sieve primes (value / prime) (acc + 1)\r\n else helper sieve primes_tail value acc\r\n in\r\n helper sieve primes value 0\r\n\r\nlet solution (inp, outp, sieve) =\r\n let (_primes, _ancs, _primlimit) = sieve in\r\n let (a, b, c) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let count_a = calc_primes_count sieve a and count_b = calc_primes_count sieve b in\r\n let result =\r\n if c = 1 then if a != b && (a mod b = 0 || b mod a = 0) then true else false\r\n else count_a + count_b >= c\r\n in\r\n let () =\r\n if result then Printf.fprintf outp \"YES\\n\"\r\n else Printf.fprintf outp \"NO\\n\"\r\n in\r\n(* let () = Printf.fprintf outp \"Val A: %d; Val B: %d\\n\" a b in\r\n let () = Printf.fprintf outp \"Count A: %d; Count B: %d\\n\" count_a count_b in\r\n *) ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n (* let primlimit = 20 in *)\r\n let primlimit = 31623 in\r\n let sieve = create_sieve primlimit in\r\n let state = (inp, outp, sieve) in\r\n repeat solution state tests_count;;\r\n"}, {"source_code": "(* 6:26 *)\n\nopen Printf\nopen Scanf\n\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a\n\nlet factor n = \n let rec loop n p ac = \n if n=1 then ac\n else if p*p > n then (n::ac)\n else if n mod p = 0 then loop (n/p) p (p::ac)\n else loop n (p+1) ac\n in\n List.rev (loop n 2 [])\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let (a,b) = read_pair () in\n let k = read_int () in\n\n let g = gcd a b in\n\n let answer =\n if k = 1 then if a=b then false else g=a || g=b else\n\tlet nfa = List.length (factor a) in\n\tlet nfb = List.length (factor b) in\n\tlet maxmoves = nfa + nfb in\n\tlet minmoves = if a=b then 0 else if g = a || g = b then 1 else 2 in\n\tif k < minmoves then false\n\telse if k > maxmoves then false\n\telse if k = maxmoves then true\n\telse if k = maxmoves-1 then nfa >= 2 || nfb >=2\n\telse true\n in\n if answer then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}], "negative_code": [{"source_code": "module Stdlib = Pervasives\r\nlet std_in = Stdlib.stdin and std_out = Stdlib.stdout;;\r\n(* let std_in = Stdlib.open_in \"input.txt\" and std_out = Stdlib.stdout;; *)\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet rec repeat f state = function\r\n | 0 -> ()\r\n | n ->\r\n let () = f state in\r\n repeat f state (n - 1);;\r\n\r\ntype sieve = int list * int array * int;; (* primes, ancestors, primlimit *)\r\n\r\nlet create_sieve n =\r\n let primes = Array.make (n + 1) 0 and primes_count = ref 0 and ancs = Array.make (n + 1) 0 in\r\n let () =\r\n for i = 2 to n do\r\n begin\r\n if ancs.(i) = 0 then\r\n let () = ancs.(i) <- i and () = primes.(!primes_count) <- i in\r\n incr primes_count\r\n else ();\r\n let j = ref 0 in\r\n while !j < !primes_count && i * primes.(!j) <= n && primes.(!j) <= ancs.(i) do\r\n let () = ancs.(i * primes.(!j)) <- primes.(!j) in\r\n incr j\r\n done\r\n end\r\n done\r\n in\r\n ( Array.sub primes 0 !primes_count |> Array.to_list , ancs , n )\r\n\r\nlet calc_primes_count ((primes, _, _) as sieve) value =\r\n let rec fact_folder ancs value acc =\r\n if value = 1 then acc\r\n else fact_folder ancs (value / ancs.(value)) (acc + 1)\r\n in\r\n let rec helper ((_, ancs, primlimit) as sieve) primes value acc =\r\n match primes with\r\n | [] -> if value = 1 then acc else acc + 1\r\n | prime::primes_tail as primes ->\r\n if value <= primlimit then fact_folder ancs value acc\r\n else if value mod prime = 0 then helper sieve primes (value / prime) (acc + 1)\r\n else helper sieve primes_tail value acc\r\n in\r\n helper sieve primes value 0\r\n\r\nlet solution (inp, outp, sieve) =\r\n let (_primes, _ancs, _primlimit) = sieve in\r\n let (a, b, c) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let count_a = calc_primes_count sieve a and count_b = calc_primes_count sieve b in\r\n let result =\r\n if c mod 2 = 1 && a = b then false\r\n else\r\n let add_a = if a > 1 then 1 else 0 in\r\n let add_b = if b > 1 then 1 else 0 in\r\n count_a + count_b >= c - add_a - add_b\r\n in\r\n let () =\r\n if result then Printf.fprintf outp \"YES\\n\"\r\n else Printf.fprintf outp \"NO\\n\"\r\n in\r\n(* let () = Printf.fprintf outp \"Val A: %d; Val B: %d\\n\" a b in\r\n let () = Printf.fprintf outp \"Count A: %d; Count B: %d\\n\" count_a count_b in\r\n *) ();;\r\n\r\nlet () =\r\n let inp = std_in and outp = std_out in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n (* let primlimit = 20 in *)\r\n let primlimit = 31623 in\r\n let sieve = create_sieve primlimit in\r\n let state = (inp, outp, sieve) in\r\n repeat solution state tests_count;;\r\n"}, {"source_code": "(* 6:26 *)\n\nopen Printf\nopen Scanf\n\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a\n\nlet factor n = \n let rec loop n p ac = \n if n=1 then ac\n else if p*p > n then (n::ac)\n else if n mod p = 0 then loop (n/p) p (p::ac)\n else loop n (p+1) ac\n in\n List.rev (loop n 2 [])\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let (a,b) = read_pair () in\n let k = read_int () in\n\n let g = gcd a b in\n\n let answer = \n let nfa = List.length (factor a) in\n let nfb = List.length (factor b) in\n let maxmoves = nfa + nfb in\n let minmoves = if a=b then 0 else if g = a || g = b then 1 else 2 in\n if k < minmoves then false\n else if k > maxmoves then false\n else if k = maxmoves then true\n else if k = maxmoves-1 then nfa >= 2 || nfb >=2\n else true\n in\n if answer then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}], "src_uid": "b58a18119ac8375f9ad21a282292a76c"} {"nl": {"description": "You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like \"010101 ...\" or \"101010 ...\" (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of \"1011101\" are \"0\", \"1\", \"11111\", \"0111\", \"101\", \"1001\", but not \"000\", \"101010\" and \"11100\".You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$s$$$. The second line of the test case contains $$$n$$$ characters '0' and '1' \u2014 the string $$$s$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer: in the first line print one integer $$$k$$$ ($$$1 \\le k \\le n$$$) \u2014 the minimum number of subsequences you can divide the string $$$s$$$ to. In the second line print $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le k$$$), where $$$a_i$$$ is the number of subsequence the $$$i$$$-th character of $$$s$$$ belongs to. If there are several answers, you can print any.", "sample_inputs": ["4\n4\n0011\n6\n111111\n5\n10101\n8\n01010000"], "sample_outputs": ["2\n1 2 2 1 \n6\n1 2 3 4 5 6 \n1\n1 1 1 1 1 \n4\n1 1 1 1 1 2 3 4"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n \nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_str _ = bscanf Scanning.stdin \"%s \" (fun x -> x)\n \n \nlet solve() =\n let n = read_int() in\n let s = read_str() in\n let ans_arr = Array.make n 0 in\n let answer = ref 0 in\n let list_0 = Array.make n 0 in\n let list_1 = Array.make n 0 in\n let id_list_0 = ref (-1) in\n let id_list_1 = ref (-1) in\n for i = 0 to n - 1 do\n if s.[i] = '0' then (\n if !id_list_1 = -1 then (\n answer := !answer + 1;\n ans_arr.(i) <- !answer;\n ) else (\n ans_arr.(i) <- list_1.(!id_list_1);\n id_list_1 := !id_list_1 - 1;\n );\n id_list_0 := !id_list_0 + 1;\n list_0.(!id_list_0) <- ans_arr.(i);\n ) else (\n if !id_list_0 = -1 then (\n answer := !answer + 1;\n ans_arr.(i) <- !answer;\n ) else (\n ans_arr.(i) <- list_0.(!id_list_0);\n id_list_0 := !id_list_0 - 1;\n );\n id_list_1 := !id_list_1 + 1;\n list_1.(!id_list_1) <- ans_arr.(i);\n )\n done;\n printf \"%d\\n\" !answer;\n for i = 0 to n - 1 do\n printf \"%d \" ans_arr.(i)\n done;\n printf \"\\n\"\n \nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}], "negative_code": [], "src_uid": "de57b6b1aa2b6ec4686d1348988c0c63"} {"nl": {"description": "There are $$$n$$$ pieces of tangerine peel, the $$$i$$$-th of them has size $$$a_i$$$. In one step it is possible to divide one piece of size $$$x$$$ into two pieces of positive integer sizes $$$y$$$ and $$$z$$$ so that $$$y + z = x$$$.You want that for each pair of pieces, their sizes differ strictly less than twice. In other words, there should not be two pieces of size $$$x$$$ and $$$y$$$, such that $$$2x \\le y$$$. What is the minimum possible number of steps needed to satisfy the condition?", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The description of test cases follows. The first line of each test case contains the integer $$$n$$$ ($$$1 \\le n \\le 100$$$). Then one line follows, containing $$$n$$$ integers $$$a_1 \\le a_2 \\le \\ldots \\le a_n$$$ ($$$1 \\le a_i \\le 10^7$$$).", "output_spec": "For each test case, output a single line containing the minimum number of steps.", "sample_inputs": ["3\n\n5\n\n1 2 3 4 5\n\n1\n\n1033\n\n5\n\n600 900 1300 2000 2550"], "sample_outputs": ["10\n0\n4"], "notes": "NoteIn the first test case, we initially have a piece of size $$$1$$$, so all final pieces must have size $$$1$$$. The total number of steps is: $$$0 + 1 + 2 + 3 + 4 = 10$$$.In the second test case, we have just one piece, so we don't need to do anything, and the answer is $$$0$$$ steps.In the third test case, one of the possible cut options is: $$$600,\\ 900,\\ (600 | 700),\\ (1000 | 1000),\\ (1000 | 1000 | 550)$$$. You can see this option in the picture below. The maximum piece has size $$$1000$$$, and it is less than $$$2$$$ times bigger than the minimum piece of size $$$550$$$. $$$4$$$ steps are done. We can show that it is the minimum possible number of steps. "}, "positive_code": [{"source_code": "open Printf\r\nopen Scanf\r\n\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\n\r\n\r\nlet () = \r\n let t = read_int () in\r\n for ct = 1 to t do\r\n let n = read_int() in\r\n let a = Array.init n (fun i->read_int() ) in\r\n let min in_a = Array.fold_left (fun a b -> if a < b then a else b) in_a.(0) in_a in\r\n let mina = min a in\r\n let sum in_a = Array.fold_left (fun a b -> a+b) 0 in_a in\r\n\r\n let b = Array.map (fun x -> (x+2*mina-2) / (2*mina-1) - 1 ) a in\r\n\r\n printf \"%d\\n\" (sum b)\r\n done;\r\n"}], "negative_code": [], "src_uid": "128d9ad5e5dfe4943e16fcc6a103e51b"} {"nl": {"description": "Today is Devu's birthday. For celebrating the occasion, he bought n sweets from the nearby market. He has invited his f friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend. He wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed n sweets to his friends such that ith friend is given ai sweets. He wants to make sure that there should not be any positive integer x\u2009>\u20091, which divides every ai.Please find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo 1000000007 (109\u2009+\u20097).To make the problem more interesting, you are given q queries. Each query contains an n, f pair. For each query please output the required number of ways modulo 1000000007 (109\u2009+\u20097).", "input_spec": "The first line contains an integer q representing the number of queries (1\u2009\u2264\u2009q\u2009\u2264\u2009105). Each of the next q lines contains two space space-separated integers n, f (1\u2009\u2264\u2009f\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "For each query, output a single integer in a line corresponding to the answer of each query.", "sample_inputs": ["5\n6 2\n7 2\n6 3\n6 4\n7 4"], "sample_outputs": ["2\n6\n9\n10\n20"], "notes": "NoteFor first query: n\u2009=\u20096,\u2009f\u2009=\u20092. Possible partitions are [1, 5] and [5, 1].For second query: n\u2009=\u20097,\u2009f\u2009=\u20092. Possible partitions are [1, 6] and [2, 5] and [3, 4] and [4, 3] and [5, 3] and [6, 1]. So in total there are 6 possible ways of partitioning."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet m = 1_000_000_007L\n\nlet maxn = 100_000\n\nlet factor n = \n (* return a list (in decreasing order) of the primes that divide n *)\n let rec loop n p prev ac = \n if n=1 then ac\n else if p*p > n then (if n=prev then ac else (n::ac))\n else if n mod p = 0 then loop (n/p) p p (if p=prev then ac else (p::ac))\n else loop n (p+1) 0 ac\n in\n loop n 2 0 []\n\nlet ( %% ) a b = Int64.rem a b\nlet ( ** ) a b = (Int64.mul a b) %% m\nlet ( ++ ) a b = (Int64.add a b) %% m\nlet ( -- ) a b = ((Int64.sub a b) ++ m) %% m\n\nlet factorial = Array.make (maxn+1) 1L\nlet invfact = Array.make (maxn+1) 1L\n\nlet inv a = \n let rec egcd a b = \n (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g *)\n if a = 0 then (0,1,b) else \n let (x,y,g) = egcd (b mod a) a in \n (y-(b/a)*x, x, g)\n in\n let mint = Int64.to_int m in\n let (x,_,_) = egcd a mint in\n if x >= 0 then x else x+mint\n\nlet init_factorials () =\n for i=1 to maxn do\n let ii = Int64.of_int i in\n factorial.(i) <- factorial.(i-1) ** ii;\n invfact.(i) <- invfact.(i-1) ** (Int64.of_int (inv i))\n done\n\nlet pirates n f =\n (* this is just n-1 choose f-1. *)\n (* we assume that f>=1 and n>=f *)\n factorial.(n-1) ** invfact.(f-1) ** invfact.(n-f)\n\nlet solve (n,f) =\n let factors = Array.of_list (factor n) in\n let nprimes = Array.length factors in\n let rec loop i n =\n if n < f then 0L\n else if i=nprimes then pirates n f\n else (loop (i+1) n) -- (loop (i+1) (n/factors.(i)))\n in\n loop 0 n\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let q = read_int () in\n init_factorials ();\n for i=0 to q-1 do\n printf \"%Ld\\n\" (solve (read_pair()))\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet m = 1_000_000_007L\n\nlet maxn = 100_000\n\nlet factor n = \n (* return a list (in decreasing order) of the primes that divide n *)\n let rec loop n p prev ac = \n if n=1 then ac\n else if p*p > n then (if n=prev then ac else (n::ac))\n else if n mod p = 0 then loop (n/p) p p (if p=prev then ac else (p::ac))\n else loop n (p+1) 0 ac\n in\n loop n 2 0 []\n\nlet ( %% ) a b = Int64.rem a b\nlet ( ** ) a b = (Int64.mul a b) %% m\nlet ( ++ ) a b = (Int64.add a b) %% m\nlet ( -- ) a b = ((Int64.sub a b) ++ m) %% m\n\nlet factorial = Array.make (maxn+1) 1L\nlet invfact = Array.make (maxn+1) 1L\n\nlet inv a = \n let rec egcd a b = \n (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g *)\n if a = 0 then (0,1,b) else \n let (x,y,g) = egcd (b mod a) a in \n (y-(b/a)*x, x, g)\n in\n let mint = Int64.to_int m in\n let (x,_,_) = egcd a mint in\n (x+mint) mod mint\n\nlet init_factorials () =\n for i=1 to maxn do\n let ii = Int64.of_int i in\n factorial.(i) <- factorial.(i-1) ** ii;\n invfact.(i) <- invfact.(i-1) ** (Int64.of_int (inv i))\n done\n\nlet pirates n f =\n (* this is just n-1 choose f-1. *)\n (* we assume that f>=1 and n>=f *)\n factorial.(n-1) ** invfact.(f-1) ** invfact.(n-f)\n\nlet solve (n,f) =\n let factors = Array.of_list (factor n) in\n let nprimes = Array.length factors in\n let rec loop i n =\n if n < f then 0L\n else if i=nprimes then pirates n f\n else (loop (i+1) n) -- (loop (i+1) (n/factors.(i)))\n in\n loop 0 n\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let q = read_int () in\n init_factorials ();\n for i=0 to q-1 do\n printf \"%Ld\\n\" (solve (read_pair()))\n done\n"}], "src_uid": "a00e2e79a3914ee11202a799c9bc01e7"} {"nl": {"description": "Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i\u2009+\u20091 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).", "input_spec": "The first line of input contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u20091\u2009000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1\u2009\u2264\u2009v,\u2009u\u2009\u2264\u20091018,\u2009v\u2009\u2260\u2009u,\u20091\u2009\u2264\u2009w\u2009\u2264\u2009109 states for every description line.", "output_spec": "For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.", "sample_inputs": ["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"], "sample_outputs": ["94\n0\n32"], "notes": "NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32\u2009+\u200932\u2009+\u200930\u2009=\u200994. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). "}, "positive_code": [{"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x) \n\nlet () = \n let q = read_int () in\n\n let h = Hashtbl.create 10 in\n\n let get t = \n try Hashtbl.find h t with Not_found -> 0L\n in\n \n let increment t w = \n Hashtbl.replace h t ((get t) ++ w)\n in\n\n let add_cost u v w =\n let rec loop u v = if u <> v then\n\tlet (u,v) = (max u v, min u v) in\n\tincrement u w;\n\tloop (u//2L) v\n in\n loop u v\n in\n\n let compute_cost u v =\n let rec loop u v ac = if u = v then ac else\n\tlet (u,v) = (max u v, min u v) in\n\tloop (u//2L) v (ac ++ (get u))\n in\n loop u v 0L\n in\n \n for op = 1 to q do\n match read_int() with\n | 1 ->\n\tlet u = read_long() in\n\tlet v = read_long() in\n\tlet w = read_long() in\n\tadd_cost u v w\n | 2 ->\n\tlet u = read_long() in\n\tlet v = read_long() in\n\tprintf \"%Ld\\n\" (compute_cost u v)\n | _ -> failwith \"bad input\"\n done\n \n"}], "negative_code": [], "src_uid": "12814033bec4956e7561767a6778d77e"} {"nl": {"description": "Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some \"forbidden\" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters \"ab\" is forbidden, then any occurrences of substrings \"ab\" and \"ba\" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any \"forbidden\" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is \"removed\" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string \"aba\", we get the string \"ba\", and if we cross out the second letter, we get \"aa\".", "input_spec": "The first line contains a non-empty string s, consisting of lowercase Latin letters \u2014 that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105. The next line contains integer k (0\u2009\u2264\u2009k\u2009\u2264\u200913) \u2014 the number of forbidden pairs of letters. Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.", "output_spec": "Print the single number \u2014 the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.", "sample_inputs": ["ababa\n1\nab", "codeforces\n2\ndo\ncs"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix 27 27 true in\n let res = ref 0 in\n let c2i c = Char.code c - Char.code 'a' in\n for i = 1 to k do\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\ta.(c2i t.[0]).(c2i t.[1]) <- false;\n\ta.(c2i t.[1]).(c2i t.[0]) <- false;\n done;\n let prev = ref 26 in\n let prevc = ref 0 in\n let cur = ref (c2i s.[0]) in\n let curc = ref 1 in\n for i = 1 to String.length s - 1 do\n\tlet c = c2i s.[i] in\n(*Printf.printf \"asd %d: %d %d %d %d %d\\n\" c !prev !prevc !cur !curc !res;*)\n\t if c = !prev && not a.(!prev).(!cur) then (\n\t let t = !cur\n\t and tc = !curc in\n\t cur := !prev;\n\t curc := !prevc;\n\t prev := t;\n\t prevc := tc;\n\t incr curc;\n\t ) else if !curc = 0 then (\n\t cur := c;\n\t curc := 1;\n\t ) else if c = !cur then (\n\t incr curc;\n\t ) else (\n\t if not a.(!prev).(!cur) then (\n\t if !prevc < !curc\n\t then res := !res + !prevc\n\t else res := !res + !curc\n\t );\n\t prev := !cur;\n\t prevc := !curc;\n\t cur := c;\n\t curc := 1;\n\t )\n done;\n if not a.(!prev).(!cur) then (\n\tif !prevc < !curc\n\tthen res := !res + !prevc\n\telse res := !res + !curc\n );\n Printf.printf \"%d\\n\" !res;\n"}, {"source_code": "let main () =\n let s = read_line () in\n let k = read_int () in\n let forbid = Array.create_matrix 26 26 true in\n for i = 1 to k do\n let c = read_line () in\n let a1 = int_of_char c.[0] - int_of_char 'a' in\n let a2 = int_of_char c.[1] - int_of_char 'a' in\n forbid.(a1).(a2) <- false;\n forbid.(a2).(a1) <- false\n done;\n let rec loop arr i =\n if i < 0 then arr else (\n let arr2 = Array.copy arr in\n let c = int_of_char s.[i] - int_of_char 'a' in\n arr2.(c) <- 1;\n for j = 0 to 25 do\n if arr.(j) >= 0 && forbid.(j).(c) then (\n arr2.(c) <- max arr2.(c) (arr.(j) + 1)\n )\n done;\n loop arr2 (i - 1)\n )\n in\n let arr = loop (Array.create 26 (-1)) (String.length s - 1) in\n let ans = String.length s - Array.fold_left max 0 arr in\n Printf.printf \"%d\\n\" ans\n;;\nmain ()\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix 26 26 true in\n let res = ref 0 in\n let c2i c = Char.code c - Char.code 'a' in\n for i = 1 to k do\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\ta.(c2i t.[0]).(c2i t.[1]) <- false;\n\ta.(c2i t.[1]).(c2i t.[0]) <- false;\n done;\n let prev = ref (c2i s.[0]) in\n let prevc = ref 1 in\n let cur = ref 0 in\n let curc = ref 0 in\n for i = 1 to String.length s - 1 do\n\tlet c = c2i s.[i] in\n(*Printf.printf \"asd %d: %d %d %d %d\\n\" c !prev !prevc !cur !curc;*)\n\t if c = !prev then (\n\t let t = !cur\n\t and tc = !curc in\n\t cur := !prev;\n\t curc := !prevc;\n\t prev := t;\n\t prevc := tc;\n\t incr curc;\n\t ) else if !curc = 0 then (\n\t cur := c;\n\t curc := 1;\n\t ) else if c = !cur then (\n\t incr curc;\n\t ) else (\n\t if not a.(!prev).(!cur) then (\n\t if !prevc < !curc\n\t then res := !res + !prevc\n\t else res := !res + !curc\n\t );\n\t prev := !cur;\n\t prevc := !curc;\n\t cur := c;\n\t curc := 1;\n\t )\n done;\n if not a.(!prev).(!cur) then (\n\tif !prevc < !curc\n\tthen res := !res + !prevc\n\telse res := !res + !curc\n );\n Printf.printf \"%d\\n\" !res;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix 26 26 true in\n let res = ref 0 in\n let c2i c = Char.code c - Char.code 'a' in\n for i = 1 to k do\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\ta.(c2i t.[0]).(c2i t.[1]) <- false;\n\ta.(c2i t.[1]).(c2i t.[0]) <- false;\n done;\n let prev = ref (c2i s.[0]) in\n let prevc = ref 1 in\n let cur = ref 0 in\n let curc = ref 0 in\n for i = 1 to String.length s - 1 do\n\tlet c = c2i s.[i] in\n(*Printf.printf \"asd %d: %d %d %d %d\\n\" c !prev !prevc !cur !curc;*)\n\t if c = !prev then (\n\t incr prevc;\n\t ) else if !curc = 0 then (\n\t cur := c;\n\t curc := 1;\n\t ) else if c = !cur then (\n\t incr curc;\n\t ) else (\n\t if not a.(!prev).(!cur) then (\n\t if !prevc < !curc\n\t then res := !res + !prevc\n\t else res := !res + !curc\n\t );\n\t prev := !cur;\n\t prevc := !curc;\n\t cur := c;\n\t curc := 0;\n\t )\n done;\n if not a.(!prev).(!cur) then (\n\tif !prevc < !curc\n\tthen res := !res + !prevc\n\telse res := !res + !curc\n );\n Printf.printf \"%d\\n\" !res;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix 26 26 true in\n let res = ref 0 in\n let c2i c = Char.code c - Char.code 'a' in\n for i = 1 to k do\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\ta.(c2i t.[0]).(c2i t.[1]) <- false;\n\ta.(c2i t.[1]).(c2i t.[0]) <- false;\n done;\n let prev = ref (c2i s.[0]) in\n for i = 1 to String.length s - 1 do\n\tlet c = c2i s.[i] in\n\t if a.(!prev).(c) then (\n\t prev := c\n\t ) else (\n\t incr res\n\t )\n done;\n Printf.printf \"%d\\n\" !res;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix 26 26 true in\n let res = ref 0 in\n let c2i c = Char.code c - Char.code 'a' in\n for i = 1 to k do\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\ta.(c2i t.[0]).(c2i t.[1]) <- false;\n\ta.(c2i t.[1]).(c2i t.[0]) <- false;\n done;\n let prev = ref (c2i s.[0]) in\n let prevc = ref 1 in\n let cur = ref 0 in\n let curc = ref 0 in\n for i = 1 to String.length s - 1 do\n\tlet c = c2i s.[i] in\n(*Printf.printf \"asd %d: %d %d %d %d\\n\" c !prev !prevc !cur !curc;*)\n\t if c = !prev then (\n\t incr prevc;\n\t ) else if !curc = 0 then (\n\t cur := c;\n\t curc := 1;\n\t ) else if c = !cur then (\n\t incr curc;\n\t ) else (\n\t if not a.(!prev).(!cur) then (\n\t if !prevc < !curc\n\t then res := !res + !prevc\n\t else res := !res + !curc\n\t );\n\t prev := !cur;\n\t prevc := !curc;\n\t cur := c;\n\t curc := 1;\n\t )\n done;\n if not a.(!prev).(!cur) then (\n\tif !prevc < !curc\n\tthen res := !res + !prevc\n\telse res := !res + !curc\n );\n Printf.printf \"%d\\n\" !res;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix 26 26 true in\n let res = ref 0 in\n let c2i c = Char.code c - Char.code 'a' in\n for i = 1 to k do\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\ta.(c2i t.[0]).(c2i t.[1]) <- false;\n\ta.(c2i t.[1]).(c2i t.[0]) <- false;\n done;\n let prev = ref (c2i s.[0]) in\n let prevc = ref 1 in\n let cur = ref 0 in\n let curc = ref 0 in\n for i = 1 to String.length s - 1 do\n\tlet c = c2i s.[i] in\n(*Printf.printf \"asd %d: %d %d %d %d %d\\n\" c !prev !prevc !cur !curc !res;*)\n\t if c = !prev && not a.(!prev).(!cur) then (\n\t let t = !cur\n\t and tc = !curc in\n\t cur := !prev;\n\t curc := !prevc;\n\t prev := t;\n\t prevc := tc;\n\t incr curc;\n\t ) else if !curc = 0 then (\n\t cur := c;\n\t curc := 1;\n\t ) else if c = !cur then (\n\t incr curc;\n\t ) else (\n\t if not a.(!prev).(!cur) then (\n\t if !prevc < !curc\n\t then res := !res + !prevc\n\t else res := !res + !curc\n\t );\n\t prev := !cur;\n\t prevc := !curc;\n\t cur := c;\n\t curc := 1;\n\t )\n done;\n if not a.(!prev).(!cur) then (\n\tif !prevc < !curc\n\tthen res := !res + !prevc\n\telse res := !res + !curc\n );\n Printf.printf \"%d\\n\" !res;\n"}], "src_uid": "da2b3450a3ca05a60ea4de6bab9291e9"} {"nl": {"description": "Vanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1\u2009/\u2009x seconds for the first character and 1\u2009/\u2009y seconds for the second one). The i-th monster dies after he receives ai hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.", "input_spec": "The first line contains three integers n,x,y (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009106) \u2014 the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly. Next n lines contain integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the number of hits needed do destroy the i-th monster.", "output_spec": "Print n lines. In the i-th line print word \"Vanya\", if the last hit on the i-th monster was performed by Vanya, \"Vova\", if Vova performed the last hit, or \"Both\", if both boys performed it at the same time.", "sample_inputs": ["4 3 2\n1\n2\n3\n4", "2 1 1\n1\n2"], "sample_outputs": ["Vanya\nVova\nVanya\nBoth", "Both\nBoth"], "notes": "NoteIn the first sample Vanya makes the first hit at time 1\u2009/\u20093, Vova makes the second hit at time 1\u2009/\u20092, Vanya makes the third hit at time 2\u2009/\u20093, and both boys make the fourth and fifth hit simultaneously at the time 1.In the second sample Vanya and Vova make the first and second hit simultaneously at time 1."}, "positive_code": [{"source_code": "\nlet (@@) f a = f a\nlet (|>) x f = f x\n\nlet () =\n let open Int64 in\n let ( * ) = mul in\n let ( / ) = div in\n let ( + ) = add in\n let ( - ) = sub in\n let gcd a b =\n let rec gcd a b =\n if rem a b = zero then b\n else gcd b (rem a b)\n in\n gcd (max a b) (min a b)\n in\n Scanf.scanf \"%d %Ld %Ld\" @@ fun n x y ->\n let gcd = gcd x y in\n let x = x / gcd and y = y / gcd in\n let lcm = x * y in\n let solve a =\n let a = rem a (x + y) in\n let dich f r t =\n let rec dich l r =\n if r - l < (of_int 2) then r\n else\n let p = l + (r - l) / (of_int 2) in\n let f = f p in\n if f < t then dich p r\n else dich l p\n in\n if f zero = t then zero\n else dich zero r\n in\n let r = dich (fun c -> c / x + c / y) lcm a in\n match rem r x = zero, rem r y = zero with\n | true, true -> \"Both\"\n | true, _ -> \"Vova\"\n | _, true -> \"Vanya\"\n | false, false -> assert false\n in\n for i = 1 to n do\n print_endline (Scanf.scanf \" %Ld\" @@ solve)\n done\n"}], "negative_code": [], "src_uid": "f98ea97377a06963d1e6c1c215ca3a4a"} {"nl": {"description": "Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n.Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array a left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by k for each number).The seller can obtain array b from array a if the following conditions hold: bi\u2009>\u20090;\u20020\u2009\u2264\u2009ai\u2009-\u2009bi\u2009\u2264\u2009k for all 1\u2009\u2264\u2009i\u2009\u2264\u2009n.Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105;\u20091\u2009\u2264\u2009k\u2009\u2264\u2009106). The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 array a.", "output_spec": "In the single line print a single number \u2014 the maximum possible beauty of the resulting array.", "sample_inputs": ["6 1\n3 6 10 12 13 16", "5 3\n8 21 52 15 77"], "sample_outputs": ["3", "7"], "notes": "NoteIn the first sample we can obtain the array:3\u20026\u20029\u200212\u200212\u200215In the second sample we can obtain the next array:7\u200221\u200249\u200214\u200277"}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet () =\n let n, k = Scanf.scanf \"%d %d \" (fun n k -> n, k) in\n let arr = Array.init n ~f:(fun _ -> Scanf.scanf \"%d \" ident) in\n let sum = Array.create 2_000_001 0 in\n Array.iter arr ~f:(fun x -> sum.(x) <- sum.(x) + 1);\n let mx = Array.reduce ~f:max arr in\n let mn = Array.reduce ~f:min arr in\n iter_for 1 (Array.length sum - 1) ~f:(fun i -> sum.(i) <- sum.(i) + sum.(i - 1));\n Printf.printf \"%d\\n\" @@ fold_for 2 (mn + 1) ~init:1 ~f:(fun acc_mx div ->\n let in_n = fold_for ~skip:div div (mx + 1)\n ~init:0 ~f:(fun acc i -> acc + sum.(min (i + k) (i + div - 1)) - sum.(i - 1)) in\n if in_n = n then div else acc_mx)\n;;\n"}], "negative_code": [], "src_uid": "b963c125f333eef3ffc885b59e6162c2"} {"nl": {"description": "T is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that n\u2009+\u20091 is a power of 2.In the picture you can see a complete binary tree with n\u2009=\u200915. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1\u2009\u2264\u2009ui\u2009\u2264\u2009n) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if ui\u2009=\u20094 and si\u2009=\u2009\u00abUURL\u00bb, then the answer is 10.", "input_spec": "The first line contains two integer numbers n and q (1\u2009\u2264\u2009n\u2009\u2264\u20091018, q\u2009\u2265\u20091). n is such that n\u2009+\u20091 is a power of 2. The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1\u2009\u2264\u2009ui\u2009\u2264\u2009n), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'. It is guaranteed that the sum of lengths of si (for each i such that 1\u2009\u2264\u2009i\u2009\u2264\u2009q) doesn't exceed 105.", "output_spec": "Print q numbers, i-th number must be the answer to the i-th query.", "sample_inputs": ["15 2\n4\nUURL\n8\nLRLLLLLLLL"], "sample_outputs": ["10\n5"], "notes": null}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet f x = Int64.logand x (Int64.neg x)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let q = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for _c = 1 to q do\n let u = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let u = ref u in\n\tfor i = 0 to String.length s - 1 do\n\t match s.[i] with\n\t | 'U' ->\n\t\tlet d = f !u in\n\t\tlet v1 = !u -| d\n\t\tand v2 = !u +| d in\n\t\t if v1 <= n && f v1 = 2L *| d\n\t\t then u := v1\n\t\t else if v2 <= n && f v2 = 2L *| d\n\t\t then u := v2\n\t | 'L' ->\n\t\tlet d = f !u in\n\t\t if d > 1L\n\t\t then u := !u -| d /| 2L;\n\t | 'R' ->\n\t\tlet d = f !u in\n\t\t if d > 1L\n\t\t then u := !u +| d /| 2L;\n\t | _ -> assert false\n\tdone;\n\tPrintf.printf \"%Ld\\n\" !u\n done;\n"}], "negative_code": [], "src_uid": "dc35bdf56bb0ac341895e543b001b801"} {"nl": {"description": "Permutation p is an ordered set of integers p1,\u2009\u2009p2,\u2009\u2009...,\u2009\u2009pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,\u2009\u2009p2,\u2009\u2009...,\u2009\u2009pn.The decreasing coefficient of permutation p1,\u2009p2,\u2009...,\u2009pn is the number of such i (1\u2009\u2264\u2009i\u2009<\u2009n), that pi\u2009>\u2009pi\u2009+\u20091.You have numbers n and k. Your task is to print the permutation of length n with decreasing coefficient k.", "input_spec": "The single line contains two space-separated integers: n,\u2009k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009k\u2009<\u2009n) \u2014 the permutation length and the decreasing coefficient.", "output_spec": "In a single line print n space-separated integers: p1,\u2009p2,\u2009...,\u2009pn \u2014 the permutation of length n with decreasing coefficient k. If there are several permutations that meet this condition, print any of them. It is guaranteed that the permutation with the sought parameters exists.", "sample_inputs": ["5 2", "3 0", "3 2"], "sample_outputs": ["1 5 2 4 3", "1 2 3", "3 2 1"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f \" (fun x -> x)\n\n\nlet() = \n let n = read_int 0 in\n let k = read_int 0 in\n for i = 1 to n - k - 1 do\n Printf.printf \"%d \" i\n done;\n\n Printf.printf \"%d \" n;\n for i = n - k + 1 to n do\n Printf.printf \"%d \" (n+n-k-i);\n done;\n"}], "negative_code": [], "src_uid": "75cc5b55c51217966cbdd639a68f0724"} {"nl": {"description": "This is an interactive problem.Homer likes arrays a lot and he wants to play a game with you. Homer has hidden from you a permutation $$$a_1, a_2, \\dots, a_n$$$ of integers $$$1$$$ to $$$n$$$. You are asked to find any index $$$k$$$ ($$$1 \\leq k \\leq n$$$) which is a local minimum. For an array $$$a_1, a_2, \\dots, a_n$$$, an index $$$i$$$ ($$$1 \\leq i \\leq n$$$) is said to be a local minimum if $$$a_i < \\min\\{a_{i-1},a_{i+1}\\}$$$, where $$$a_0 = a_{n+1} = +\\infty$$$. An array is said to be a permutation of integers $$$1$$$ to $$$n$$$, if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Initially, you are only given the value of $$$n$$$ without any other information about this permutation.At each interactive step, you are allowed to choose any $$$i$$$ ($$$1 \\leq i \\leq n$$$) and make a query with it. As a response, you will be given the value of $$$a_i$$$. You are asked to find any index $$$k$$$ which is a local minimum after at most $$$100$$$ queries.", "input_spec": null, "output_spec": null, "sample_inputs": ["5\n3\n2\n1\n4\n5"], "sample_outputs": ["? 1\n? 2\n? 3\n? 4\n? 5\n! 3"], "notes": "NoteIn the example, the first line contains an integer $$$5$$$ indicating that the length of the array is $$$n = 5$$$.The example makes five \"?\" queries, after which we conclude that the array is $$$a = [3,2,1,4,5]$$$ and $$$k = 3$$$ is local minimum."}, "positive_code": [{"source_code": "open Printf\r\n\r\ntype dir = DOWN | UP | LMIN | LMAX\r\n\r\nlet read_int _ = int_of_string (read_line())\r\n\r\n \r\nlet () =\r\n let n = read_int() in\r\n\r\n let probe i =\r\n if i=0 then n+1 else if i=n+1 then n+1 else (\r\n printf \"? %d\\n%!\" i;\r\n read_int()\r\n )\r\n in\r\n\r\n let evaluate i =\r\n let a = probe (i-1) in\r\n let b = probe i in\r\n let c = probe (i+1) in\r\n match (a UP\r\n | (false,true) -> LMIN\r\n | (true,false) -> LMAX\r\n | _ -> DOWN\r\n in\r\n\r\n let rec bsearch lo hi =\r\n (* lo is a DOWN, hi is an UP, also lo + 2 <= hi *)\r\n if lo + 2 > hi then failwith \"range bad\";\r\n let m = (lo+hi)/2 in\r\n let x = evaluate m in\r\n match x with\r\n | UP | LMAX -> bsearch lo m\r\n | DOWN -> bsearch m hi\r\n | LMIN -> m\r\n in\r\n\r\n let answer =\r\n if n=1 then 1 else\r\n match (evaluate 1, evaluate n) with\r\n\t| (LMIN,_) -> 1\r\n\t| (_,LMIN) -> n\r\n\t| (DOWN,UP) -> bsearch 1 n\r\n\t| _ -> failwith \"something wrong\"\r\n\r\n in\r\n printf \"! %d\\n%!\" answer\r\n"}], "negative_code": [], "src_uid": "c091ca39dd5708f391b52de63faac6b9"} {"nl": {"description": "Tom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minutes from the start of the screensaver, laptop switches to the \"sleep\" mode and consumes P3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into n time periods [l1,\u2009r1],\u2009[l2,\u2009r2],\u2009...,\u2009[ln,\u2009rn]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [l1,\u2009rn].", "input_spec": "The first line contains 6 integer numbers n, P1, P2, P3, T1, T2 (1\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20090\u2009\u2264\u2009P1,\u2009P2,\u2009P3\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009T1,\u2009T2\u2009\u2264\u200960). The following n lines contain description of Tom's work. Each i-th of these lines contains two space-separated integers li and ri (0\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u20091440, ri\u2009<\u2009li\u2009+\u20091 for i\u2009<\u2009n), which stand for the start and the end of the i-th period of work.", "output_spec": "Output the answer to the problem.", "sample_inputs": ["1 3 2 1 5 10\n0 10", "2 8 4 2 5 10\n20 30\n50 100"], "sample_outputs": ["30", "570"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \"%d \" (fun x -> x);;\n\nlet n = read_int ();;\nlet p1 = read_int ();;\nlet p2 = read_int ();;\nlet p3 = read_int ();;\nlet t1 = read_int ();;\nlet t2 = read_int ();;\n\nlet power_of_period x = \n\tif x > t1 + t2 then p1 * t1 + p2 * t2 + p3 * (x - t1 - t2)\n\telse if x > t1 then p1 * t1 + p2 * (x - t1)\n\telse x * p1\n\n\nlet ans = ref 0;;\nlet last = ref (-1);;\n\nfor i = 1 to n do\n\tlet (l, r) = Scanf.scanf \"%d %d \" (fun x y -> (x, y)) in begin\n\t\tans := !ans + power_of_period (l - (if !last = -1 then l else !last)) + (r - l) * p1;\n\t\tlast := r;\n\tend\ndone;;\n\nPrintf.printf \"%d\\n\" !ans;;"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let p1 = read_int 0 in\n let p2 = read_int 0 in\n let p3 = read_int 0 in\n let t1 = read_int 0 in\n let t2 = read_int 0 in\n let rec go i t s =\n if i >= n then\n s\n else\n let l = read_int 0 in\n let r = read_int 0 in\n let _,s' = if i > 0 then List.fold_left (fun (t,s) (pi,ti) ->\n let d = min ti (l-t) in t+d, s+d*pi\n ) (t,s) [p1,t1; p2,t2; p3,max_int] else t,s in\n go (i+1) r (s'+(r-l)*p1)\n in\n Printf.printf \"%d\\n\" (go 0 0 0)\n"}], "negative_code": [], "src_uid": "7ed9265b56ef6244f95a7a663f7860dd"} {"nl": {"description": "While walking down the street Vanya saw a label \"Hide&Seek\". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 109\u2009+\u20097.To represent the string as a number in numeral system with base 64 Vanya uses the following rules: digits from '0' to '9' correspond to integers from 0 to 9; letters from 'A' to 'Z' correspond to integers from 10 to 35; letters from 'a' to 'z' correspond to integers from 36 to 61; letter '-' correspond to integer 62; letter '_' correspond to integer 63. ", "input_spec": "The only line of the input contains a single word s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009100\u2009000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'.", "output_spec": "Print a single integer\u00a0\u2014 the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 109\u2009+\u20097.", "sample_inputs": ["z", "V_V", "Codeforces"], "sample_outputs": ["3", "9", "130653412"], "notes": "NoteFor a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia.In the first sample, there are 3 possible solutions: z&_\u2009=\u200961&63\u2009=\u200961\u2009=\u2009z _&z\u2009=\u200963&61\u2009=\u200961\u2009=\u2009z z&z\u2009=\u200961&61\u2009=\u200961\u2009=\u2009z "}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let res = ref 1L in\n for i = 0 to n - 1 do\n let c = s.[i] in\n let d =\n\tmatch c with\n\t | '0'..'9' -> Char.code c - Char.code '0'\n\t | 'A'..'Z' -> Char.code c - Char.code 'A' + 10\n\t | 'a'..'z' -> Char.code c - Char.code 'a' + 36\n\t | '-' -> 62\n\t | '_' -> 63\n\t | _ -> assert false\n in\n\tfor i = 0 to 5 do\n\t if d land (1 lsl i) = 0 then (\n\t res := mmod (!res *| 3L)\n\t )\n\tdone;\n done;\n Printf.printf \"%Ld\\n\" !res\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let s = read_string () in\n let n = String.length s in\n\n let rec bitcount x = if x=0 then 0 else (x land 1) + bitcount (x/2) in\n\n let zeros = sum 0 (n-1) (fun i ->\n let c = s.[i] in\n let numb = \n if '0' <= c && c <= '9' then (int_of_char c) - (int_of_char '0')\n else if 'A' <= c && c <= 'Z' then 10 + (int_of_char c) - (int_of_char 'A')\n else if 'a' <= c && c <= 'z' then 36 + (int_of_char c) - (int_of_char 'a')\n else if c = '-' then 62\n else if c = '_' then 63\n else failwith \"bad input\"\n in\n 6 - (bitcount numb)\n ) 0 in\n\n let m = 1_000_000_007L in\n\n let rec ( ^ ) e p = \n if p=0 then 1L else\n let a = e^(p/2) in\n let a2 = (a**a) %% m in\n if (p land 1)=0 then a2 else (e**a2) %% m\n in\n\n printf \"%Ld\\n\" (3L ^ zeros)\n"}], "negative_code": [], "src_uid": "1b336555c94d5d5198abe5426ff6fa7a"} {"nl": {"description": "Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.Codeforces scores are computed as follows: If the maximum point value of a problem is x, and Kevin submitted correctly at minute m but made w wrong submissions, then his score on that problem is . His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack.All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.", "input_spec": "The first line of the input contains five space-separated integers m1, m2, m3, m4, m5, where mi (0\u2009\u2264\u2009mi\u2009\u2264\u2009119) is the time of Kevin's last submission for problem i. His last submission is always correct and gets accepted. The second line contains five space-separated integers w1, w2, w3, w4, w5, where wi (0\u2009\u2264\u2009wi\u2009\u2264\u200910) is Kevin's number of wrong submissions on problem i. The last line contains two space-separated integers hs and hu (0\u2009\u2264\u2009hs,\u2009hu\u2009\u2264\u200920), denoting the Kevin's numbers of successful and unsuccessful hacks, respectively.", "output_spec": "Print a single integer, the value of Kevin's final score.", "sample_inputs": ["20 40 60 80 100\n0 1 2 3 4\n1 0", "119 119 119 119 119\n0 0 0 0 0\n10 0"], "sample_outputs": ["4900", "4930"], "notes": "NoteIn the second sample, Kevin takes 119 minutes on all of the problems. Therefore, he gets of the points on each problem. So his score from solving problems is . Adding in 10\u00b7100\u2009=\u20091000 points from hacks, his total score becomes 3930\u2009+\u20091000\u2009=\u20094930."}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read5 () = Scanf.scanf \"%d %d %d %d %d\\n\" ( fun x y z a b-> x, y, z, a, b);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet licz m w x =\n max (75*x) ( (250 - m)*x - 250*50*w );;\n\nlet _ = \n let (a,b,c,d,e) = read5 ()\n and (f,g,h,i,j) = read5 ()\n and (hs, hu) = read2 ()\n in\n let suma = (licz a f 500) + (licz b g 1000) + (licz c h 1500) + (licz d i 2000) + (licz e j 2500) in\n Printf.printf \"%d\\n\" ( suma/250 + (2*hs-hu)*50 ) ;;\n\n\n"}, {"source_code": "let score m' w' x' =\n let m = float m' and w = float w' and x = float x' in\n max (0.3 *. x) ((1. -. m /. 250.) *. x -. 50. *. w)\n\nlet main () =\n let (m1,m2,m3,m4,m5,w1,w2,w3,w4,w5,hs,hu) = Scanf.scanf\n \"%d %d %d %d %d %d %d %d %d %d %d %d\"\n (fun a b c d e f g h i j k l -> (a,b,c,d,e,f,g,h,i,j,k,l)) in\n let sc = score m1 w1 500 +. score m2 w2 1000 +. score m3 w3 1500 +. score m4 w4 2000 +. score m5 w5 2500 +. 100. *. (float hs) -. 50. *. (float hu) in\n Printf.printf \"%d\" (int_of_float sc);;\n\nmain ();;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n \nlet () = \n let m = Array.init 5 (fun _ -> read_int()) in\n let w = Array.init 5 (fun _ -> read_int()) in\n let hs = read_int() in\n let hu = read_int() in\n\n let x = [|500; 1000; 1500; 2000; 2500|] in\n\n let score i =\n max ((3*x.(i)) / 10) ((x.(i) / 250) * (250-m.(i)) - 50*w.(i))\n in\n\n let total_score = (sum 0 4 score) + 100*hs - 50*hu in\n\n printf \"%d\\n\" total_score\n"}], "negative_code": [], "src_uid": "636a30a2b0038ee1731325a5fc2df73a"} {"nl": {"description": "Polycarp was presented with some sequence of integers $$$a$$$ of length $$$n$$$ ($$$1 \\le a_i \\le n$$$). A sequence can make Polycarp happy only if it consists of different numbers (i.e. distinct numbers).In order to make his sequence like this, Polycarp is going to make some (possibly zero) number of moves.In one move, he can: remove the first (leftmost) element of the sequence. For example, in one move, the sequence $$$[3, 1, 4, 3]$$$ will produce the sequence $$$[1, 4, 3]$$$, which consists of different numbers.Determine the minimum number of moves he needs to make so that in the remaining sequence all elements are different. In other words, find the length of the smallest prefix of the given sequence $$$a$$$, after removing which all values in the sequence will be unique.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of the given sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$) \u2014 elements of the given sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case print your answer on a separate line\u00a0\u2014 the minimum number of elements that must be removed from the beginning of the sequence so that all remaining elements are different.", "sample_inputs": ["5\n\n4\n\n3 1 4 3\n\n5\n\n1 1 1 1 1\n\n1\n\n1\n\n6\n\n6 5 4 3 2 1\n\n7\n\n1 2 1 7 1 2 1"], "sample_outputs": ["1\n4\n0\n0\n5"], "notes": "NoteThe following are the sequences that will remain after the removal of prefixes: $$$[1, 4, 3]$$$; $$$[1]$$$; $$$[1]$$$; $$$[6, 5, 4, 3, 2, 1]$$$; $$$[2, 1]$$$. It is easy to see that all the remaining sequences contain only distinct elements. In each test case, the shortest matching prefix was removed."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x->x);;\r\nlet rec read_list = function\r\n| 0 -> []\r\n| n -> (read_int ()) :: read_list (n-1)\r\n;;\r\nlet run_case = function\r\n| (n) ->\r\n let seq = read_list (n) in \r\n let count_arr = Array.make n 0 in\r\n let rec get_rsuffix = function\r\n | [] -> []\r\n | x::xs ->\r\n count_arr.(x-1) <- (count_arr.(x-1)+1);\r\n if (count_arr.(x-1)<2) then x::get_rsuffix (xs)\r\n else []\r\n in \r\n let rsuffix = get_rsuffix (seq) in\r\n n - List.length (rsuffix)\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| c ->\r\n let n = read_int () in\r\n print_int (run_case (n));\r\n print_newline ();\r\n iter_cases (c-1)\r\n;;\r\n\r\nlet cases = read_int () in \r\niter_cases (cases);;"}], "negative_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x->x);;\r\nlet rec read_list = function\r\n| 0 -> []\r\n| n -> (read_int ()) :: read_list (n-1)\r\n;;\r\nlet run_case = function\r\n| (n) ->\r\n let rseq = List.rev (read_list (n)) in \r\n let count_arr = Array.make n 0 in\r\n let rec get_rsuffix = function\r\n | [] -> []\r\n | x::xs ->\r\n count_arr.(x-1) <- (count_arr.(x-1)+1);\r\n if (count_arr.(x-1)<2) then x::get_rsuffix (xs)\r\n else []\r\n in \r\n let suffix = List.rev (get_rsuffix (rseq)) in\r\n n - List.length (suffix)\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| c ->\r\n let n = read_int () in\r\n print_int (run_case (n));\r\n print_newline ();\r\n iter_cases (c-1)\r\n;;\r\n\r\nlet cases = read_int () in \r\niter_cases (cases);;"}], "src_uid": "4aaa33f77fe1c89ae477bd5cfa04f0bf"} {"nl": {"description": "The research center Q has developed a new multi-core processor. The processor consists of n cores and has k cells of cache memory. Consider the work of this processor.At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within m cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the m cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.", "input_spec": "The first line contains three integers n, m, k (1\u2009\u2264\u2009n,\u2009m,\u2009k\u2009\u2264\u2009100). Then follow n lines describing instructions. The i-th line contains m integers: xi1,\u2009xi2,\u2009...,\u2009xim (0\u2009\u2264\u2009xij\u2009\u2264\u2009k), where xij is the instruction that must be executed by the i-th core at the j-th cycle. If xij equals 0, then the corresponding instruction is \u00abdo nothing\u00bb. But if xij is a number from 1 to k, then the corresponding instruction is \u00abwrite information to the memory cell number xij\u00bb. We assume that the cores are numbered from 1 to n, the work cycles are numbered from 1 to m and the memory cells are numbered from 1 to k.", "output_spec": "Print n lines. In the i-th line print integer ti. This number should be equal to 0 if the i-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked.", "sample_inputs": ["4 3 5\n1 0 0\n1 0 2\n2 3 1\n3 2 0", "3 2 2\n1 2\n1 2\n2 2", "1 1 1\n0"], "sample_outputs": ["1\n1\n3\n0", "1\n1\n0", "0"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int() and k=read_int();;\nlet tab=Array.make (k+1) false;;\nlet temp=Array.make (k+1) 0;;\nlet block=Array.make (n+1) 0;;\nlet mat=Array.make_matrix (n+1) (m+1) 0;;\n\nfor i=1 to n do\n for j=1 to m do\n mat.(i).(j)<-read_int()\n done\ndone;;\n\nlet init vec i j=\nfor p=i to j do\n vec.(p)<-0\ndone;;\n\nfor j=1 to m do\n init temp 1 k;\n for i=1 to n do\n if (block.(i)=0)&&(mat.(i).(j)<>0) then temp.(mat.(i).(j))<-temp.(mat.(i).(j))+1\n done;\n for i=1 to n do\n if (block.(i)=0)&&((temp.(mat.(i).(j))>1)||tab.(mat.(i).(j)))&&(mat.(i).(j)<>0) then (block.(i)<-j;tab.(mat.(i).(j))<-true)\n done\ndone;;\n\nfor i=1 to n do\n print_int block.(i);\n if i<>n then print_newline()\ndone;;"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m 0 in\n let res = Array.make n 0 in\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tlet k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t a.(i).(j) <- k\n done\n done;\n let b = Array.make k false in\n for j = 0 to m - 1 do\n\tlet c = Array.make k 0 in\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 && a.(i).(j) <> 0 then (\n\t c.(a.(i).(j) - 1) <- c.(a.(i).(j) - 1) + 1\n\t )\n\t done;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 && a.(i).(j) <> 0 &&\n\t (c.(a.(i).(j) - 1) > 1 || b.(a.(i).(j) - 1))\n\t then (\n\t res.(i) <- j + 1;\n\t b.(a.(i).(j) - 1) <- true;\n\t )\n\t done;\n done;\n for i = 0 to n - 1 do\n\tPrintf.printf \"%d\\n\" res.(i);\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m 0 in\n let res = Array.make n 0 in\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tlet k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t a.(i).(j) <- k\n done\n done;\n let b = Array.make k false in\n for j = 0 to m - 1 do\n\tlet c = Array.make k 0 in\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 && a.(i).(j) <> 0 then (\n\t c.(a.(i).(j) - 1) <- c.(a.(i).(j) - 1) + 1\n\t )\n\t done;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 && a.(i).(j) <> 0 &&\n\t (c.(a.(i).(j) - 1) > 1 || b.(a.(i).(j) - 1))\n\t then (\n\t res.(i) <- j + 1;\n\t b.(a.(i).(j) - 1) <- true;\n\t )\n\t done;\n done;\n for i = 0 to n - 1 do\n\tPrintf.printf \"%d\\n\" res.(i);\n done\n"}], "negative_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int() and k=read_int();;\nlet tab=Array.make (k+1) false;;\nlet temp=Array.make (k+1) 0;;\nlet block=Array.make (n+1) 0;;\nlet mat=Array.make_matrix (n+1) (m+1) 0;;\n\nfor i=1 to n do\n for j=1 to m do\n mat.(i).(j)<-read_int()\n done\ndone;;\n\nlet init vec i j=\nfor p=i to j do\n vec.(p)<-0\ndone;;\n\nfor j=1 to m do\n init temp 1 k;\n for i=1 to n do\n if (block.(i)=0)&&(mat.(i).(j)<>0) then temp.(mat.(i).(j))<-temp.(mat.(i).(j))+1\n done;\n for i=1 to n do\n if ((block.(i)=0)&&(temp.(mat.(i).(j))>1)||tab.(mat.(i).(j)))&&(mat.(i).(j)<>0) then (block.(i)<-j;tab.(mat.(i).(j))<-true)\n done\ndone;;\n\nfor i=1 to n do\n print_int block.(i);\n if i<>n then print_newline()\ndone;;"}, {"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int() and k=read_int();;\nlet tab=Array.make (k+1) false;;\nlet temp=Array.make (k+1) 0;;\nlet block=Array.make (n+1) 0;;\nlet mat=Array.make_matrix (n+1) (m+1) 0;;\n\nfor i=1 to n do\n for j=1 to m do\n mat.(i).(j)<-read_int()\n done\ndone;;\n\nlet init vec i j=\nfor p=i to j do\n vec.(p)<-0\ndone;;\n\nfor j=1 to m do\n init temp 1 k;\n for i=1 to n do\n if block.(i)=0 then temp.(mat.(i).(j))<-temp.(mat.(i).(j))+1\n done;\n for i=1 to n do\n if (block.(i)=0)&&(temp.(mat.(i).(j))>1)||tab.(mat.(i).(j)) then (block.(i)<-j;tab.(mat.(i).(j))<-true)\n done\ndone;;\n\nfor i=1 to n do\n print_int block.(i);\n if i<>n then print_newline()\ndone;;"}], "src_uid": "6422a70e686c34b4b9b6b5797712998e"} {"nl": {"description": "At first, there was a legend related to the name of the problem, but now it's just a formal statement.You are given $$$n$$$ points $$$a_1, a_2, \\dots, a_n$$$ on the $$$OX$$$ axis. Now you are asked to find such an integer point $$$x$$$ on $$$OX$$$ axis that $$$f_k(x)$$$ is minimal possible.The function $$$f_k(x)$$$ can be described in the following way: form a list of distances $$$d_1, d_2, \\dots, d_n$$$ where $$$d_i = |a_i - x|$$$ (distance between $$$a_i$$$ and $$$x$$$); sort list $$$d$$$ in non-descending order; take $$$d_{k + 1}$$$ as a result. If there are multiple optimal answers you can print any of them.", "input_spec": "The first line contains single integer $$$T$$$ ($$$ 1 \\le T \\le 2 \\cdot 10^5$$$) \u2014 number of queries. Next $$$2 \\cdot T$$$ lines contain descriptions of queries. All queries are independent. The first line of each query contains two integers $$$n$$$, $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le k < n$$$) \u2014 the number of points and constant $$$k$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_1 < a_2 < \\dots < a_n \\le 10^9$$$) \u2014 points in ascending order. It's guaranteed that $$$\\sum{n}$$$ doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print $$$T$$$ integers \u2014 corresponding points $$$x$$$ which have minimal possible value of $$$f_k(x)$$$. If there are multiple answers you can print any of them.", "sample_inputs": ["3\n3 2\n1 2 5\n2 1\n1 1000000000\n1 0\n4"], "sample_outputs": ["3\n500000000\n4"], "notes": null}, "positive_code": [{"source_code": "let () =\n let t = Scanf.scanf \"%d\\n\" (fun x -> x) in\n for i = 1 to t do\n let n, k = Scanf.scanf \"%d %d\\n\" (fun x y -> x, y) in\n let a = Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n let b = Array.init (n-k) (fun i -> a.(i+k) - a.(i)) in\n let min = ref b.(0) in\n let min_i = ref 0 in\n Array.iteri\n (fun i x ->\n if x < !min then begin min := x; min_i := i; end\n ) b;\n let res =\n if a.(!min_i) mod 2 = 0 then a.(!min_i) / 2 + a.(!min_i + k)/2\n else 1 + a.(!min_i) / 2 + a.(!min_i + k)/2\n in\n Printf.printf \"%d\\n\" res\n done\n;;\n"}], "negative_code": [{"source_code": "let () =\n let t = Scanf.scanf \"%d\\n\" (fun x -> x) in\n for i = 1 to t do\n let n, k = Scanf.scanf \"%d %d\\n\" (fun x y -> x, y) in\n let a = Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n let b = Array.init (n-k) (fun i -> a.(i+k) - a.(i)) in\n let min = ref b.(0) in\n let min_i = ref 0 in\n Array.iteri\n (fun i x ->\n if x < !min then begin min := x; min_i := i; end\n ) b;\n Printf.printf \"%d\\n\" ((a.(!min_i) + a.(!min_i + k))/2)\n done\n;;\n"}], "src_uid": "87e39e14d6e33427148c284b16a7fb13"} {"nl": {"description": "Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.The park is a rectangular table with $$$n$$$ rows and $$$m$$$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $$$1$$$. For example, park with $$$n=m=2$$$ has $$$12$$$ streets.You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park). The park sizes are: $$$n=4$$$, $$$m=5$$$. The lighted squares are marked yellow. Please note that all streets have length $$$1$$$. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit. Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$n$$$, $$$m$$$ ($$$1 \\le n, m \\le 10^4$$$) \u2014 park sizes.", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer must be a single integer \u2014 the minimum number of lanterns that are required to light all the squares.", "sample_inputs": ["5\n1 1\n1 3\n2 2\n3 3\n5 3"], "sample_outputs": ["1\n2\n2\n5\n8"], "notes": "NotePossible optimal arrangement of the lanterns for the $$$2$$$-nd test case of input data example: Possible optimal arrangement of the lanterns for the $$$3$$$-rd test case of input data example: "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let (n,m) = read_pair() in\n printf \"%d\\n\" ((n*m+1)/2)\n done\n"}], "negative_code": [], "src_uid": "19df5f3b8b31b763162c5331c1499529"} {"nl": {"description": "Gennady is one of the best child dentists in Berland. Today n children got an appointment with him, they lined up in front of his office.All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to n in the order they go in the line. Every child is associated with the value of his cofidence pi. The children take turns one after another to come into the office; each time the child that is the first in the line goes to the doctor.While Gennady treats the teeth of the i-th child, the child is crying with the volume of vi. At that the confidence of the first child in the line is reduced by the amount of vi, the second one \u2014 by value vi\u2009-\u20091, and so on. The children in the queue after the vi-th child almost do not hear the crying, so their confidence remains unchanged.If at any point in time the confidence of the j-th child is less than zero, he begins to cry with the volume of dj and leaves the line, running towards the exit, without going to the doctor's office. At this the confidence of all the children after the j-th one in the line is reduced by the amount of dj.All these events occur immediately one after the other in some order. Some cries may lead to other cries, causing a chain reaction. Once in the hallway it is quiet, the child, who is first in the line, goes into the doctor's office.Help Gennady the Dentist to determine the numbers of kids, whose teeth he will cure. Print their numbers in the chronological order.", "input_spec": "The first line of the input contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u20094000) \u2014 the number of kids in the line. Next n lines contain three integers each vi,\u2009di,\u2009pi (1\u2009\u2264\u2009vi,\u2009di,\u2009pi\u2009\u2264\u2009106) \u2014 the volume of the cry in the doctor's office, the volume of the cry in the hall and the confidence of the i-th child.", "output_spec": "In the first line print number k \u2014 the number of children whose teeth Gennady will cure. In the second line print k integers \u2014 the numbers of the children who will make it to the end of the line in the increasing order.", "sample_inputs": ["5\n4 2 2\n4 1 2\n5 2 4\n3 3 5\n5 1 2", "5\n4 5 1\n5 3 9\n4 1 2\n2 1 8\n4 1 9"], "sample_outputs": ["2\n1 3", "4\n1 2 4 5"], "notes": "NoteIn the first example, Gennady first treats the teeth of the first child who will cry with volume 4. The confidences of the remaining children will get equal to \u2009-\u20092,\u20091,\u20093,\u20091, respectively. Thus, the second child also cries at the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 0,\u20092,\u20090. Then the third child will go to the office, and cry with volume 5. The other children won't bear this, and with a loud cry they will run to the exit.In the second sample, first the first child goes into the office, he will cry with volume 4. The confidence of the remaining children will be equal to 5,\u2009\u2009-\u20091,\u20096,\u20098. Thus, the third child will cry with the volume of 1 and run to the exit. The confidence of the remaining children will be equal to 5,\u20095,\u20097. After that, the second child goes to the office and cry with the volume of 5. The confidences of the remaining children will be equal to 0,\u20093. Then the fourth child will go into the office and cry with the volume of 2. Because of this the confidence of the fifth child will be 1, and he will go into the office last."}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n (* read volume in office, volume in hall and confidence *)\n let read i = Scanf.scanf \"%Ld %Ld %Ld\\n\" (fun v d p -> (i + 1, v, d, p)) in\n (* build array of children *)\n let c = Array.to_list (Array.init n read) in\n\n let (+) = Int64.add\n and (-) = Int64.sub in\n\n let rec dentist l acc = match l with\n | [] -> acc\n | (i, v, _, _) :: rest ->\n (* calculate the new line by removing the office volume from elements\n * and summing the line volume as well *)\n let _, _, line = List.fold_left (fun (ov, lv, acc) (i, v, d, p) ->\n (* prevent underflow of the volume from the office *)\n let ov = max ov 0L in\n (* calculate new confidence level *)\n let p' = p - ov - lv in\n\n if p' < 0L\n (* this child leaves the queue, so add their line volume to lv\n * NB: prevent overflow here, since the max confidence is only 10^6 *)\n then (ov - 1L, lv + d, acc)\n (* otherwise, this child remains in the queue with a new confidence *)\n else (ov - 1L, lv, ((i, v, d, p') :: acc))) (v, 0L, []) rest in\n dentist (List.rev line) (i :: acc)\n in\n let res = List.rev (dentist c []) in\n Printf.printf \"%d\\n%s\\n\" (List.length res) (String.concat \" \" (List.map string_of_int res)))\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n (* read volume in office, volume in hall and confidence *)\n let read i = Scanf.scanf \"%Ld %Ld %Ld\\n\" (fun v d p -> (i + 1, v, d, p)) in\n (* build array of children *)\n let c = Array.to_list (Array.init n read) in\n\n let (+) = Int64.add\n and (-) = Int64.sub in\n\n let rec dentist l acc = match l with\n | [] -> acc\n | (i, v, _, _) :: rest ->\n (* calculate the new line by removing the office volume from elements\n * and summing the line volume as well *)\n let _, _, line = List.fold_left (fun (ov, lv, acc) (i, v, d, p) ->\n (* prevent underflow of the volume from the office *)\n let ov = max ov 0L in\n (* calculate new confidence level *)\n let p' = p - ov - lv in\n\n if p' < 0L\n (* this child leaves the queue, so add their line volume to lv\n * NB: prevent overflow here, since the max confidence is only 10^6 *)\n then (ov - 1L, lv + d, acc)\n (* otherwise, this child remains in the queue with a new confidence *)\n else (ov - 1L, lv, ((i, v, d, p') :: acc))) (v, 0L, []) rest in\n dentist (List.rev line) (i :: acc)\n in\n let res = List.rev (dentist c []) in\n Printf.printf \"%d\\n%s\\n\" (List.length res) (String.concat \" \" (List.map string_of_int res)))\n"}], "negative_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n (* read volume in office, volume in hall and confidence *)\n let read i = Scanf.scanf \"%d %d %d\\n\" (fun v d p -> (i + 1, v, d, p)) in\n (* build array of children *)\n let c = Array.to_list (Array.init n read) in\n\n let rec dentist l acc = match l with\n | [] -> acc\n | (i, v, d, p) :: rest ->\n (* calculate the new line by removing the office volume from elements\n * and summing the line volume as well *)\n let _, _, line = List.fold_left (fun (ov, lv, acc) (i, v, d, p) ->\n let ov = max ov 0 in\n let p' = p - ov - lv in\n if p' < 0\n then (ov - 1, min (lv + d) 1000000, acc)\n else (ov - 1, lv, ((i, v, d, p') :: acc))) (v, 0, []) rest in\n dentist (List.rev line) (i :: acc)\n in\n let res = List.rev (dentist c []) in\n Printf.printf \"%d\\n%s\\n\" (List.length res) (String.concat \" \" (List.map string_of_int res)))\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n (* read volume in office, volume in hall and confidence *)\n let read i = Scanf.scanf \"%d %d %d\\n\" (fun v d p -> (i + 1, v, d, p)) in\n (* build array of children *)\n let c = Array.to_list (Array.init n read) in\n\n let rec dentist l acc = match l with\n | [] -> acc\n | (i, v, d, p) :: rest ->\n (* calculate the new line by removing the office volume from elements\n * and summing the line volume as well *)\n let _, _, line = List.fold_left (fun (ov, lv, acc) (i, v, d, p) ->\n let ov = max ov 0 in\n let p' = p - ov - lv in\n if p' < 0\n then (ov - 1, lv + d, acc)\n else (ov - 1, lv, ((i, v, d, p') :: acc))) (v, 0, []) rest in\n dentist (List.rev line) (i :: acc)\n in\n let res = List.rev (dentist c []) in\n Printf.printf \"%d\\n%s\\n\" (List.length res) (String.concat \" \" (List.map string_of_int res)))\n"}], "src_uid": "8cf8590d1f3668b768702c7eb0ee8249"} {"nl": {"description": "Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character \"/\". Every other directory has a name \u2014 a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory \u2014 the one that contains the given directory. It is denoted as \"..\".The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be \"..\", which means a step up to the parent directory. \u00ab..\u00bb can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or \"..\"), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.The command pwd should display the absolute path to the current directory. This path must not contain \"..\".Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.", "input_spec": "The first line of the input data contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of commands. Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter. The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive. Directories in the file system can have the same names.", "output_spec": "For each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.", "sample_inputs": ["7\npwd\ncd /home/vasya\npwd\ncd ..\npwd\ncd vasya/../petya\npwd", "4\ncd /a/b\npwd\ncd ../a/b\npwd"], "sample_outputs": ["/\n/home/vasya/\n/home/\n/home/petya/", "/a/b/\n/a/a/b/"], "notes": null}, "positive_code": [{"source_code": "open Printf;;\nopen Scanf;;\n\nlet output_directory dir =\n let rec process_dir dir =\n match dir with\n | [] -> printf \"\\n\"\n | h::t -> printf \"%s/\" h;\n\t process_dir t\n in\n printf \"/\";\n process_dir (List.rev dir)\n;;\n\nlet rec change_directory act_dir s idx act_str =\n if idx < (String.length s) then\n match s.[idx] with\n | '/' -> if(act_str = \"..\") then\n\t\tchange_directory (List.tl act_dir) s (idx+1) \"\"\n\t else\n\t\tchange_directory (act_str::act_dir) s (idx+1) \"\"\n | c -> change_directory act_dir s (idx+1) (act_str ^ (Char.escaped c))\n else\n act_dir\n;;\n\nlet process_line dir =\n let s = scanf \"%s\" (fun x->x) in\n(* printf \"mam komende %s\\n\" s; *)\n if s = \"pwd\" then begin\n(* printf \"%s\\n\" s; *)\n let _ = scanf \"%s\\n\" (fun x->x) in\n output_directory dir;\n dir\n end else begin\n(* printf \"%s\\n\" s; *)\n let s2 = scanf \" %s\\n\" (fun x->x) in\n(* printf \"robie cd do %s\\n\" s2; *)\n if s2.[0] = '/' then\n change_directory [] (s2^\"/\") 1 \"\"\n else\n change_directory dir (s2^\"/\") 0 \"\"\n end\n \n;;\n\nlet rec solve n directory =\n if n <> 0 then\n solve (n-1) (process_line directory)\n;;\n\nlet n = scanf \"%d\\n\" (fun x->x) in\nsolve n []"}, {"source_code": "open Printf\nopen String\n\nlet n = Scanf.scanf \"%d \" (fun x -> x)\n\nlet rec msplit t i ll=\n if t=\"\" || i>=String.length t then\n List.rev ll\n else\n begin\n try\n let j = String.index_from t i '/' in\n let s1= String.sub t i (j-i) in\n match s1 with\n |\"\" -> msplit t (j+1) ll\n |_ -> msplit t (j+1) (s1::ll)\n with\n Not_found ->\n let s1 = String.sub t i ((String.length t) - i) in\n List.rev (s1::ll)\n end\n\nlet msplit2 s = msplit s 0 []\n\n (*\nlet a = msplit2 \"home/xyzt\" in\n let () =List.iter (printf \"%s \") a in\n print_endline \"\\n====\\n\"\n *)\n\nlet rec process_cd t cwd =\n if t=\"\" then\n cwd\n else\n begin\n match (String.get t 0) with\n | '/' -> (process_cd (String.sub t 1 ((String.length t)-1)) [])\n | _ ->\n begin\n let ll = msplit t 0 [] in\n process_dirs ll cwd\n end\n end\nand process_dirs l c =\n match l with\n | [] -> c\n | hd::lr ->\n begin\n match hd with\n |\".\" -> process_dirs lr c\n |\"..\"-> process_dirs lr (List.tl c)\n | _ -> process_dirs lr (hd::c)\n end\n\nlet rec process_command ls cwd =\n match ls with\n |[] -> ()\n |s::lr ->\n begin\n match s with\n | \"pwd\" ->\n List.iter (fun x -> printf \"/%s\" x) (List.rev cwd); print_endline \"/\";\n process_command lr cwd\n | \"cd\" ->\n let cwd1 = process_cd (List.hd lr) cwd in\n process_command (List.tl lr) cwd1\n end\n\nlet rec readl l =\n let s = Scanf.scanf \"%s \" (fun x -> x) in\n match s with\n | \"\" -> List.rev l\n | _ -> readl (s::l)\n\nlet commands = readl [];;\n\n (*\nlet _ = List.iter (fun x -> printf \"%s \" x) commands\nin print_endline \"\\n---\"\n *)\n\nlet _ = process_command commands []\n"}], "negative_code": [], "src_uid": "494ac937ba939db1dbc4081e518ab54c"} {"nl": {"description": "Momiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of nodes in the tree. The next n\u2009-\u20091 lines contain the tree edges. The i-th line contains integers ai, bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi) \u2014 the numbers of the nodes that are connected by the i-th edge. It is guaranteed that the given graph is a tree.", "output_spec": "Print a single real number \u2014 the expectation of the number of steps in the described game. The answer will be considered correct if the absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["2\n1 2", "3\n1 2\n1 3"], "sample_outputs": ["1.50000000000000000000", "2.00000000000000000000"], "notes": "NoteIn the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are: 1\u2009\u00d7\u2009(1\u2009/\u20092)\u2009+\u20092\u2009\u00d7\u2009(1\u2009/\u20092)\u2009=\u20091.5In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are: 1\u2009\u00d7\u2009(1\u2009/\u20093)\u2009+\u2009(1\u2009+\u20091.5)\u2009\u00d7\u2009(2\u2009/\u20093)\u2009=\u2009(1\u2009/\u20093)\u2009+\u2009(5\u2009/\u20093)\u2009=\u20092"}, "positive_code": [{"source_code": "let read_int() = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let edge = Array.make (n+1) [] in\n for i=1 to n-1 do\n let u = read_int() in\n let v = read_int() in\n\tedge.(u) <- v::edge.(u);\n\tedge.(v) <- u::edge.(v);\n done;\n \n let rec dfs d p v = \n (* p=parent, v=the node to search, d=the depth of v (the root is depth 1) *)\n List.fold_left (fun ac w -> if w = p then ac else\n\t\t\tac +. (dfs (d+1) v w)\n\t\t ) (1.0 /. (float d)) edge.(v)\n in\n Printf.printf \"%.7f\\n\" (dfs 1 0 1)\n"}], "negative_code": [], "src_uid": "85b78251160db9d7ca1786e90e5d6f21"} {"nl": {"description": "You are given a string $$$s$$$, consisting of $$$n$$$ letters, each letter is either 'a' or 'b'. The letters in the string are numbered from $$$1$$$ to $$$n$$$.$$$s[l; r]$$$ is a continuous substring of letters from index $$$l$$$ to $$$r$$$ of the string inclusive. A string is called balanced if the number of letters 'a' in it is equal to the number of letters 'b'. For example, strings \"baba\" and \"aabbab\" are balanced and strings \"aaab\" and \"b\" are not.Find any non-empty balanced substring $$$s[l; r]$$$ of string $$$s$$$. Print its $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le n$$$). If there is no such substring, then print $$$-1$$$ $$$-1$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of the testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 50$$$)\u00a0\u2014 the length of the string. The second line of the testcase contains a string $$$s$$$, consisting of $$$n$$$ letters, each letter is either 'a' or 'b'.", "output_spec": "For each testcase print two integers. If there exists a non-empty balanced substring $$$s[l; r]$$$, then print $$$l$$$ $$$r$$$ ($$$1 \\le l \\le r \\le n$$$). Otherwise, print $$$-1$$$ $$$-1$$$.", "sample_inputs": ["4\n1\na\n6\nabbaba\n6\nabbaba\n9\nbabbabbaa"], "sample_outputs": ["-1 -1\n1 6\n3 6\n2 5"], "notes": "NoteIn the first testcase there are no non-empty balanced subtrings.In the second and third testcases there are multiple balanced substrings, including the entire string \"abbaba\" and substring \"baba\"."}, "positive_code": [{"source_code": "\nlet scan s =\n let rec go i =\n if i < String.length s - 1 then\n if s.[i] <> s.[i + 1] then (i + 1, i + 2) else go (i + 1)\n else (-1, -1) in\n go 0\n\nlet input f =\n Scanf.scanf \"%d\\n\" @@ fun n ->\n for _ = 1 to n do\n Scanf.scanf \"%d\\n%s\\n\" @@ fun m s -> assert (String.length s = m); f s\n done\n\nlet _ = input @@ fun s ->\n let i, j = scan s in Format.printf \"%d %d@.\" i j\n"}], "negative_code": [], "src_uid": "127d7f23a0ac8fcecccd687565d6f35a"} {"nl": {"description": "For the first place at the competition, Alex won many arrays of integers and was assured that these arrays are very expensive. After the award ceremony Alex decided to sell them. There is a rule in arrays pawnshop: you can sell array only if it can be compressed to a generator.This generator takes four non-negative numbers $$$n$$$, $$$m$$$, $$$c$$$, $$$s$$$. $$$n$$$ and $$$m$$$ must be positive, $$$s$$$ non-negative and for $$$c$$$ it must be true that $$$0 \\leq c < m$$$. The array $$$a$$$ of length $$$n$$$ is created according to the following rules: $$$a_1 = s \\bmod m$$$, here $$$x \\bmod y$$$ denotes remainder of the division of $$$x$$$ by $$$y$$$; $$$a_i = (a_{i-1} + c) \\bmod m$$$ for all $$$i$$$ such that $$$1 < i \\le n$$$. For example, if $$$n = 5$$$, $$$m = 7$$$, $$$c = 4$$$, and $$$s = 10$$$, then $$$a = [3, 0, 4, 1, 5]$$$.Price of such an array is the value of $$$m$$$ in this generator.Alex has a question: how much money he can get for each of the arrays. Please, help him to understand for every array whether there exist four numbers $$$n$$$, $$$m$$$, $$$c$$$, $$$s$$$ that generate this array. If yes, then maximize $$$m$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^5$$$)\u00a0\u2014 the number of arrays. The first line of array description contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the size of this array. The second line of array description contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 10^9$$$ )\u00a0\u2014 elements of the array. It is guaranteed that the sum of array sizes does not exceed $$$10^5$$$.", "output_spec": "For every array print: $$$-1$$$, if there are no such four numbers that generate this array; $$$0$$$, if $$$m$$$ can be arbitrary large; the maximum value $$$m$$$ and any appropriate $$$c$$$ ($$$0 \\leq c < m$$$) in other cases. ", "sample_inputs": ["6\n6\n1 9 17 6 14 3\n3\n4 2 2\n3\n7 3 4\n3\n2 2 4\n5\n0 1000000000 0 1000000000 0\n2\n1 1"], "sample_outputs": ["19 8\n-1\n-1\n-1\n2000000000 1000000000\n0"], "notes": null}, "positive_code": [{"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet gcd a b =\n let rec g a b = if a=0L then b else g (b %% a) a in\n g (Int64.abs a) (Int64.abs b)\n\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet ( mod ) x n = let y = x %% n in if y<0L then y++n else y\n\nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n (fun i -> long (read_int())) in\n if n <= 2 then printf \"0\\n\" else (\n let d = Array.init (n-1) (fun i -> a.(i+1) -- a.(i)) in\n let e = Array.init (n-2) (fun i -> d.(i+1) -- d.(i)) in\n\n let rec loop ac i =\n\tif i = n-2 then ac else loop (gcd ac e.(i)) (i+1)\n in\n let m = loop 0L 0 in\n if m = 0L then printf \"0\\n\" else (\n\tlet c = d.(0) mod m in\n\tif a.(0) < m && (forall 1 (n-1) (fun i -> a.(i) = (a.(i-1) ++ c) mod m))\n\tthen printf \"%Ld %Ld\\n\" m c\n\telse printf \"-1\\n\"\n )\n )\n done\n"}], "negative_code": [{"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet gcd a b =\n let rec g a b = if a=0L then b else g (b %% a) a in\n g (Int64.abs a) (Int64.abs b)\n\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f) \n\nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n (fun i -> long (read_int())) in\n if n<=2 then printf \"0\\n\" else (\n let d = Array.init (n-1) (fun i -> a.(i+1) -- a.(i)) in\n let e = Array.init (n-2) (fun i -> d.(i+1) -- d.(i)) in\n\n let rec loop ac i =\n\tif i = n-2 then ac else loop (gcd ac e.(i)) (i+1)\n in\n let m = loop 0L 0 in\n if m = 0L then printf \"0\\n\" else (\n\tif exists 0 (n-1) (fun i -> a.(i) >= m) then printf \"-1\\n\" else\n\t printf \"%Ld %Ld\\n\" m (d.(0) %% m)\n )\n )\n done\n \n"}], "src_uid": "d6721fb3dd02535fc08fc69a4811d60c"} {"nl": {"description": "Let us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.", "input_spec": "The first line contains an integer n, which is the number of contestants in the room (1\u2009\u2264\u2009n\u2009\u2264\u200950). The next n lines contain the participants of a given room. The i-th line has the format of \"handlei plusi minusi ai bi ci di ei\" \u2014 it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0\u2009\u2264\u2009plusi,\u2009minusi\u2009\u2264\u200950; 150\u2009\u2264\u2009ai\u2009\u2264\u2009500 or ai\u2009=\u20090, if problem A is not solved; 300\u2009\u2264\u2009bi\u2009\u2264\u20091000 or bi\u2009=\u20090, if problem B is not solved; 450\u2009\u2264\u2009ci\u2009\u2264\u20091500 or ci\u2009=\u20090, if problem C is not solved; 600\u2009\u2264\u2009di\u2009\u2264\u20092000 or di\u2009=\u20090, if problem D is not solved; 750\u2009\u2264\u2009ei\u2009\u2264\u20092500 or ei\u2009=\u20090, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).", "output_spec": "Print on the single line the handle of the room leader.", "sample_inputs": ["5\nPetr 3 1 490 920 1000 1200 0\ntourist 2 0 490 950 1100 1400 0\nEgor 7 0 480 900 950 0 1000\nc00lH4x0R 0 10 150 0 0 0 0\nsome_participant 2 1 450 720 900 0 0"], "sample_outputs": ["tourist"], "notes": "NoteThe number of points that each participant from the example earns, are as follows: Petr \u2014 3860 tourist \u2014 4140 Egor \u2014 4030 c00lH4x0R \u2014 \u2009-\u2009350 some_participant \u2014 2220 Thus, the leader of the room is tourist."}, "positive_code": [{"source_code": "let () = \n\tlet n = read_int () in\n\tlet max_name = ref \"\" in\n\tlet max_i = ref min_int in (\n\t\tfor i = 1 to n do\n\t\t\tScanf.scanf \" %s %d %d %d %d %d %d %d\" (fun n p m a b c d e ->\n\t\t\t\tlet i = p*100-m*50+a+b+c+d+e in\n\t\t\t\tif i > !max_i then (max_i := i; max_name := n); \n\t\t\t)\n\t\tdone;\n\t\tprint_string !max_name\n\t)\n;;\n"}], "negative_code": [{"source_code": "let () = \n\tlet n = read_int () in\n\tlet max_name = ref \"\" in\n\tlet max_i = ref 0 in (\n\t\tfor i = 1 to n do\n\t\t\tScanf.scanf \" %s %d %d %d %d %d %d %d\" (fun n p m a b c d e ->\n\t\t\t\tlet i = p*100-m*50+a+b+c+d+e in\n\t\t\t\tif i > !max_i then (max_i := i; max_name := n); \n\t\t\t)\n\t\tdone;\n\t\tprint_string !max_name\n\t)\n;;\n"}], "src_uid": "b9dacff0cab78595296d697d22dce5d9"} {"nl": {"description": "The only difference between easy and hard versions is constraints.There are $$$n$$$ kids, each of them is reading a unique book. At the end of any day, the $$$i$$$-th kid will give his book to the $$$p_i$$$-th kid (in case of $$$i = p_i$$$ the kid will give his book to himself). It is guaranteed that all values of $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i.e. $$$p$$$ is a permutation). The sequence $$$p$$$ doesn't change from day to day, it is fixed.For example, if $$$n=6$$$ and $$$p=[4, 6, 1, 3, 5, 2]$$$ then at the end of the first day the book of the $$$1$$$-st kid will belong to the $$$4$$$-th kid, the $$$2$$$-nd kid will belong to the $$$6$$$-th kid and so on. At the end of the second day the book of the $$$1$$$-st kid will belong to the $$$3$$$-th kid, the $$$2$$$-nd kid will belong to the $$$2$$$-th kid and so on.Your task is to determine the number of the day the book of the $$$i$$$-th child is returned back to him for the first time for every $$$i$$$ from $$$1$$$ to $$$n$$$.Consider the following example: $$$p = [5, 1, 2, 4, 3]$$$. The book of the $$$1$$$-st kid will be passed to the following kids: after the $$$1$$$-st day it will belong to the $$$5$$$-th kid, after the $$$2$$$-nd day it will belong to the $$$3$$$-rd kid, after the $$$3$$$-rd day it will belong to the $$$2$$$-nd kid, after the $$$4$$$-th day it will belong to the $$$1$$$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 200$$$) \u2014 the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \\le n \\le 200$$$) \u2014 the number of kids in the query. The second line of the query contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$, all $$$p_i$$$ are distinct, i.e. $$$p$$$ is a permutation), where $$$p_i$$$ is the kid which will get the book of the $$$i$$$-th kid.", "output_spec": "For each query, print the answer on it: $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$, where $$$a_i$$$ is the number of the day the book of the $$$i$$$-th child is returned back to him for the first time in this query.", "sample_inputs": ["6\n5\n1 2 3 4 5\n3\n2 3 1\n6\n4 6 2 1 5 3\n1\n1\n4\n3 4 1 2\n5\n5 1 2 4 3"], "sample_outputs": ["1 1 1 1 1 \n3 3 3 \n2 3 3 2 1 3 \n1 \n2 2 2 2 \n4 4 4 1 4"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet solve n = \n\tlet t = Array.make (n + 1) 0 and\n\tcolor = Array.make (n + 1) 0 and\n\tcnt = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tlet a = read_int () in\n\t\tt.(i) <- a;\n\tdone;\n\tfor i = 1 to n do\n\t\tif color.(i) = 0 then\n\t\t\tlet cur = ref i in\n\t\t\twhile color.(!cur) = 0 do\n\t\t\t\tcnt.(i) <- (cnt.(i) + 1);\n\t\t\t\tcolor.(!cur) <- i;\n\t\t\t\tcur := t.(!cur);\n\t\t\tdone;\n\t\tprintf \"%d \" cnt.(color.(i));\n\t\telse printf \"%d \" cnt.(color.(i));\n\tdone;\n\tprintf \"\\n\";\n\t()\n\nlet () = \n\tlet q = read_int () in\n\tfor tests = 1 to q do\n\t\tlet n = read_int () in\n\t\tsolve n;\n\tdone;"}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet solve n = \n\tlet t = Array.make (n + 1) 0 and\n\tcolor = Array.make (n + 1) 0 and\n\tcnt = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tlet a = read_int () in\n\t\tt.(i) <- a;\n\tdone;\n\tfor i = 1 to n do\n\t\tif color.(i) = 0 then\n\t\t\tlet cur = ref i in\n\t\t\twhile color.(!cur) = 0 do\n\t\t\t\tcnt.(i) <- (cnt.(i) + 1);\n\t\t\t\tcolor.(!cur) <- i;\n\t\t\t\tcur := t.(!cur);\n\t\t\tdone;\n\t\tprintf \"%d \" cnt.(color.(i));\n\t\telse printf \"%d \" cnt.(color.(i));\n\tdone;\n\tprintf \"\\n\";\n\t()\n\nlet () = \n\tlet q = read_int () in\n\tfor tests = 1 to q do\n\t\tlet n = read_int () in\n\t\tsolve n;\n\tdone;"}], "negative_code": [], "src_uid": "345e76bf67ae4342e850ab248211eb0b"} {"nl": {"description": "For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer.The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows: A number contains the integer part and the fractional part. The two parts are separated with a character \".\" (decimal point). To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character \",\" (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678 In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests). When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets. Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency \u2014 snakes ($), that's why right before the number in the financial format we should put the sign \"$\". If the number should be written in the brackets, then the snake sign should also be inside the brackets. For example, by the above given rules number 2012 will be stored in the financial format as \"$2,012.00\" and number -12345678.9 will be stored as \"($12,345,678.90)\".The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?", "input_spec": "The input contains a number that needs to be converted into financial format. The number's notation length does not exceed 100 characters, including (possible) signs \"-\" (minus) and \".\" (decimal point). The number's notation is correct, that is: The number's notation only contains characters from the set {\"0\" \u2013 \"9\", \"-\", \".\"}. The decimal point (if it is present) is unique and is preceded and followed by a non-zero quantity on decimal digits A number cannot start with digit 0, except for a case when its whole integer part equals zero (in this case the integer parts is guaranteed to be a single zero: \"0\"). The minus sign (if it is present) is unique and stands in the very beginning of the number's notation If a number is identically equal to 0 (that is, if it is written as, for example, \"0\" or \"0.000\"), than it is not preceded by the minus sign. The input data contains no spaces. The number's notation contains at least one decimal digit. ", "output_spec": "Print the number given in the input in the financial format by the rules described in the problem statement.", "sample_inputs": ["2012", "0.000", "-0.00987654321", "-12345678.9"], "sample_outputs": ["$2,012.00", "$0.00", "($0.00)", "($12,345,678.90)"], "notes": "NotePay attention to the second and third sample tests. They show that the sign of a number in the financial format (and consequently, the presence or absence of brackets) is determined solely by the sign of the initial number. It does not depend on the sign of the number you got after translating the number to the financial format."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let s = read_string () in\n let n = String.length s in\n let isneg = s.[0] = '-' in\n let rec finddot i = if i=n then n else if s.[i] = '.' then i else finddot (i+1) in\n let dot = finddot 0 in\n let start = if isneg then 1 else 0 in\n\n if isneg then Printf.printf \"(\";\n Printf.printf \"$\";\n for i=start to dot-1 do\n if i>start && i=n then Printf.printf \"0\"\n else Printf.printf \"%c\" s.[i]\n done;\n\n if isneg then Printf.printf \")\";\n Printf.printf \"\\n\";\n"}], "negative_code": [], "src_uid": "c704c5fb9e054fab1caeab534849901d"} {"nl": {"description": "Vasya decided to go to the grocery store. He found in his wallet $$$a$$$ coins of $$$1$$$ burle and $$$b$$$ coins of $$$2$$$ burles. He does not yet know the total cost of all goods, so help him find out $$$s$$$ ($$$s > 0$$$): the minimum positive integer amount of money he cannot pay without change or pay at all using only his coins.For example, if $$$a=1$$$ and $$$b=1$$$ (he has one $$$1$$$-burle coin and one $$$2$$$-burle coin), then: he can pay $$$1$$$ burle without change, paying with one $$$1$$$-burle coin, he can pay $$$2$$$ burle without change, paying with one $$$2$$$-burle coin, he can pay $$$3$$$ burle without change by paying with one $$$1$$$-burle coin and one $$$2$$$-burle coin, he cannot pay $$$4$$$ burle without change (moreover, he cannot pay this amount at all). So for $$$a=1$$$ and $$$b=1$$$ the answer is $$$s=4$$$.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the test. The description of each test case consists of one line containing two integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \\le a_i, b_i \\le 10^8$$$)\u00a0\u2014 the number of $$$1$$$-burle coins and $$$2$$$-burles coins Vasya has respectively.", "output_spec": "For each test case, on a separate line print one integer $$$s$$$ ($$$s > 0$$$): the minimum positive integer amount of money that Vasya cannot pay without change or pay at all.", "sample_inputs": ["5\n\n1 1\n\n4 0\n\n0 2\n\n0 0\n\n2314 2374"], "sample_outputs": ["4\n5\n1\n1\n7063"], "notes": "Note The first test case of the example is clarified into the main part of the statement. In the second test case, Vasya has only $$$1$$$ burle coins, and he can collect either any amount from $$$1$$$ to $$$4$$$, but $$$5$$$ can't. In the second test case, Vasya has only $$$2$$$ burle coins, and he cannot pay $$$1$$$ burle without change. In the fourth test case you don't have any coins, and he can't even pay $$$1$$$ burle. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nmodule LL = Int64\nlet rd_ll () = bscanf Scanning.stdin \" %Ld \" (fun x -> x)\n\nlet (&) x = LL.of_int x\nlet ( + ) x y = LL.add x y\nlet ( - ) x y = LL.sub x y\nlet ( * ) x y = LL.mul x y\nlet ( / ) x y = LL.div x y\nlet ( % ) x y = x - ( y * (x / y) ) \n\nlet solve x y =\n if x = 0L then 1L\n else x+2L*y+1L\n\nlet () =\n let t = read_int () in\n for i=1 to t do\n let n = rd_ll () in\n let x = rd_ll () in\n printf \"%Ld\\n\" (solve n x)\n done;"}, {"source_code": "let n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let l , r = Scanf.sscanf (input_line stdin) \"%d %d\" (fun l r -> (l,r)) in\r\n if l = 0 then print_endline \"1\" \r\n else begin\r\n let b = Int64.add (Int64.of_int r) (Int64.of_int r) in\r\n let a = Int64.add b (Int64.of_int (l+1)) in\r\n print_endline (Int64.to_string a)\r\n end\r\ndone;;\r\n \r\n "}], "negative_code": [], "src_uid": "2b6e670b602a89b467975edf5226219a"} {"nl": {"description": "Someone gave Alyona an array containing n positive integers a1,\u2009a2,\u2009...,\u2009an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1,\u2009b2,\u2009...,\u2009bn such that 1\u2009\u2264\u2009bi\u2009\u2264\u2009ai for every 1\u2009\u2264\u2009i\u2009\u2264\u2009n. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of elements in the Alyona's array. The second line of the input contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the elements of the array.", "output_spec": "Print one positive integer\u00a0\u2014 the maximum possible value of mex of the array after Alyona applies some (possibly none) operations.", "sample_inputs": ["5\n1 3 3 3 6", "2\n2 1"], "sample_outputs": ["5", "3"], "notes": "NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a\n in\n let res = ref 1 in\n for i = 0 to n - 1 do\n if a.(i) >= !res\n then incr res\n done;\n Printf.printf \"%d\\n\" !res\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n Array.sort compare a;\n\n let rec scan i mval = if i=n then mval else\n if a.(i) >= mval\n then scan (i+1) (mval+1) \n else scan (i+1) mval\n in\n\n printf \"%d\\n\" (scan 0 1)\n"}], "negative_code": [], "src_uid": "482b3ebbbadd583301f047181c988114"} {"nl": {"description": "Real stupidity beats artificial intelligence every time.\u2014 Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 number of test cases. Next $$$2 \\cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 100$$$, $$$0 \\le k \\le 1000$$$)\u00a0\u2014 the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters.", "output_spec": "For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints.", "sample_inputs": ["4\n\n3 2\n\naab\n\n3 3\n\naab\n\n7 1\n\nabacaba\n\n2 0\n\nab"], "sample_outputs": ["2\n2\n1\n1"], "notes": "NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab."}, "positive_code": [{"source_code": "Scanf.scanf \"%d\" (fun t ->\n let isparin n s =\n let rec loop l r =\n if l >= r then true else\n if s.[l] = s.[r] then loop (l + 1) (r - 1) else false\n in\n loop 0 (n - 1)\n in\n for i = 1 to t do\n Scanf.scanf \" %d %d %s\" (fun n k s ->\n Printf.printf \"%d\\n\" @@\n if k = 0 then 1 else\n if isparin n s then 1 else 2\n )\n done\n)\n"}], "negative_code": [], "src_uid": "08cd22b8ee760a9d2dacb0d050dcf37a"} {"nl": {"description": "The Narrator has an integer array $$$a$$$ of length $$$n$$$, but he will only tell you the size $$$n$$$ and $$$q$$$ statements, each of them being three integers $$$i, j, x$$$, which means that $$$a_i \\mid a_j = x$$$, where $$$|$$$ denotes the bitwise OR operation.Find the lexicographically smallest array $$$a$$$ that satisfies all the statements.An array $$$a$$$ is lexicographically smaller than an array $$$b$$$ of the same length if and only if the following holds: in the first position where $$$a$$$ and $$$b$$$ differ, the array $$$a$$$ has a smaller element than the corresponding element in $$$b$$$. ", "input_spec": "In the first line you are given with two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n \\le 10^5$$$, $$$0 \\le q \\le 2 \\cdot 10^5$$$). In the next $$$q$$$ lines you are given with three integers $$$i$$$, $$$j$$$, and $$$x$$$ ($$$1 \\le i, j \\le n$$$, $$$0 \\le x < 2^{30}$$$)\u00a0\u2014 the statements. It is guaranteed that all $$$q$$$ statements hold for at least one array.", "output_spec": "On a single line print $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i < 2^{30}$$$)\u00a0\u2014 array $$$a$$$.", "sample_inputs": ["4 3\n1 2 3\n1 3 2\n4 1 2", "1 0", "2 1\n1 1 1073741823"], "sample_outputs": ["0 3 2 2", "0", "1073741823 0"], "notes": "NoteIn the first sample, these are all the arrays satisfying the statements: $$$[0, 3, 2, 2]$$$, $$$[2, 1, 0, 0]$$$, $$$[2, 1, 0, 2]$$$, $$$[2, 1, 2, 0]$$$, $$$[2, 1, 2, 2]$$$, $$$[2, 3, 0, 0]$$$, $$$[2, 3, 0, 2]$$$, $$$[2, 3, 2, 0]$$$, $$$[2, 3, 2, 2]$$$. "}, "positive_code": [{"source_code": "module A = Array\r\nmodule L = List\r\nmodule I = Int64\r\nmodule B = Big_int\r\n\r\nmodule Opt = struct\r\n let get = function\r\n | None -> assert false\r\n | Some v -> v\r\nend\r\n\r\nlet pf = Printf.printf\r\nlet sf = Scanf.scanf\r\nlet read_int () = sf \" %d\" (fun x -> x)\r\nlet read_array read n = A.init n (fun _ -> read ())\r\n\r\nlet i_bit x i = (x lsr i) land 1\r\n\r\nlet () =\r\n let n = read_int () in\r\n let q = read_int () in\r\n let ans = Array.make n 0 in\r\n let gr = Array.make n [] in\r\n let qrs = Array.init q (fun _ ->\r\n let x = read_int () - 1 in\r\n let y = read_int () - 1 in\r\n let v = read_int () in\r\n (x, y, v)\r\n ) in\r\n\r\n Array.iter (fun (x, y, v) ->\r\n if (x <> y) then begin\r\n gr.(x) <- (y, v) :: gr.(x);\r\n gr.(y) <- (x, v) :: gr.(y);\r\n end\r\n ) qrs;\r\n\r\n let bit_val = Array.make n (-1) in\r\n for b = 29 downto 0 do\r\n Array.fill bit_val 0 n (-1);\r\n for i = 0 to q - 1 do\r\n let (x, y, v) = qrs.(i) in\r\n (* pf \"q = %d %d %d %d\\n\" i x y v;\r\n pf \"q = %d %d %d %b\\n\" i (i_bit v x ) (i_bit v y ) (i_bit v x = 0 && i_bit v y = 0); *)\r\n if (x = y) then bit_val.(x) <- i_bit v x\r\n else if (i_bit v b = 0 && i_bit v b = 0) then begin\r\n bit_val.(x) <- 0;\r\n bit_val.(y) <- 0;\r\n end\r\n done;\r\n\r\n for i = 0 to n - 1 do\r\n if (bit_val.(i) = -1) then begin\r\n let is_one = List.exists (fun (y, v) -> bit_val.(y) = 0 && i_bit v b = 1) gr.(i) in\r\n (* pf \"%d %d %b\\n\" b i is_one; *)\r\n if (is_one) then bit_val.(i) <- 1\r\n else bit_val.(i) <- 0;\r\n end;\r\n ans.(i) <- ans.(i) lor (bit_val.(i) lsl b);\r\n done;\r\n done;\r\n\r\n Array.iter (fun x -> pf \"%d \" x) ans;"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,q) = read_pair () in\n let constr = Array.init q (fun _ ->\n let i = -1 + read_int() in\n let j = -1 + read_int() in\n let x = read_int() in\n (i,j,x)\n ) in\n\n let req0 = Array.make n 0 in\n let req1 = Array.make n 0 in\n\n let adj = Array.make n [] in\n\n let add_edge i j x =\n adj.(i) <- (j,x)::adj.(i);\n adj.(j) <- (i,x)::adj.(j)\n in\n\n for k = 0 to q-1 do\n let (i,j,x) = constr.(k) in\n if i=j then (\n req0.(i) <- req0.(i) lor (lnot x);\n req1.(i) <- req1.(i) lor x\n ) else (\n req0.(i) <- req0.(i) lor (lnot x);\n req0.(j) <- req0.(j) lor (lnot x);\n add_edge i j x\n )\n done;\n\n for i = 0 to n-1 do\n req1.(i) <- List.fold_left (fun ac (j,x) ->\n (req0.(j) land x) lor ac\n ) req1.(i) adj.(i);\n req0.(i) <- lnot req1.(i)\n done;\n\n for i=0 to n-1 do\n printf \"%d \" req1.(i)\n done;\n print_newline()\n"}], "negative_code": [], "src_uid": "891a7bd69187975f61b8c6ef6b6acac3"} {"nl": {"description": "Vlad, like everyone else, loves to sleep very much.Every day Vlad has to do $$$n$$$ things, each at a certain time. For each of these things, he has an alarm clock set, the $$$i$$$-th of them is triggered on $$$h_i$$$ hours $$$m_i$$$ minutes every day ($$$0 \\le h_i < 24, 0 \\le m_i < 60$$$). Vlad uses the $$$24$$$-hour time format, so after $$$h=12, m=59$$$ comes $$$h=13, m=0$$$ and after $$$h=23, m=59$$$ comes $$$h=0, m=0$$$.This time Vlad went to bed at $$$H$$$ hours $$$M$$$ minutes ($$$0 \\le H < 24, 0 \\le M < 60$$$) and asks you to answer: how much he will be able to sleep until the next alarm clock.If any alarm clock rings at the time when he went to bed, then he will sleep for a period of time of length $$$0$$$.", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the test. The first line of the case contains three integers $$$n$$$, $$$H$$$ and $$$M$$$ ($$$1 \\le n \\le 10, 0 \\le H < 24, 0 \\le M < 60$$$) \u2014 the number of alarms and the time Vlad went to bed. The following $$$n$$$ lines contain two numbers each $$$h_i$$$ and $$$m_i$$$ ($$$0 \\le h_i < 24, 0 \\le m_i < 60$$$) \u2014 the time of the $$$i$$$ alarm. It is acceptable that two or more alarms will trigger at the same time. Numbers describing time do not contain leading zeros.", "output_spec": "Output $$$t$$$ lines, each containing the answer to the corresponding test case. As an answer, output two numbers \u00a0\u2014 the number of hours and minutes that Vlad will sleep, respectively. If any alarm clock rings at the time when he went to bed, the answer will be 0 0.", "sample_inputs": ["3\n\n1 6 13\n\n8 0\n\n3 6 0\n\n12 30\n\n14 45\n\n6 0\n\n2 23 35\n\n20 15\n\n10 30"], "sample_outputs": ["1 47\n0 0\n10 55"], "notes": null}, "positive_code": [{"source_code": "\r\n(* \r\n start: 22 00\r\n stop: 02 15\r\n if start>stop then\r\n diff = stop + offset\r\n else\r\n diff = stop - start *)\r\nlet sleep_time = function\r\n| (start_h, start_m), stop_times ->\r\n let offset_h, offset_m = if (start_m=0) then ((24-start_h),0) else ((23-start_h), (60-start_m)) in\r\n let rec get_min_time_diff = function\r\n | [], _min_time_diff -> _min_time_diff\r\n | (_stop_h, _stop_m)::_stop_times, (_min_h, _min_m) ->\r\n if ((_stop_h=60) then ((_h+1),(_m-60)) else (_h, _m) in\r\n if ((_h<_min_h) || (_h=_min_h && _m<_min_m)) then get_min_time_diff (_stop_times, (_h, _m))\r\n else get_min_time_diff (_stop_times, (_min_h, _min_m))\r\n end\r\n else begin\r\n let _h = _stop_h-start_h in\r\n let _m = _stop_m-start_m in\r\n let _h, _m = if (_m<0) then ((_h-1), (_m+60)) else (_h, _m) in \r\n if ((_h<_min_h) || (_h=_min_h && _m<_min_m)) then get_min_time_diff (_stop_times, (_h, _m))\r\n else get_min_time_diff (_stop_times, (_min_h, _min_m))\r\n end\r\n in get_min_time_diff (stop_times, (24, 0))\r\n;;\r\n\r\nlet read_int ()= Scanf.scanf \" %d\" (fun x-> x);;\r\nlet read_time ()= Scanf.scanf \" %d %d\" (fun h m -> h,m);;\r\n\r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in \r\n let s_h = read_int () in \r\n let s_m =read_int () in\r\n let start_time = (s_h, s_m) in\r\n let rec read_stop_times = function\r\n | 0 -> []\r\n | x -> \r\n let h=read_int () in \r\n let m=read_int () in \r\n (h,m)::read_stop_times (x-1)\r\n in\r\n let stop_times= read_stop_times n in\r\n let min_h, min_m = sleep_time (start_time, stop_times) in\r\n Printf.printf \"%d %d\\n\" min_h min_m\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| n -> run_case (); iter_cases (n-1)\r\n;;\r\n\r\nlet t = read_int () in iter_cases t;;\r\n(* \r\nlet h, m = sleep_time ((6,0), [(12, 30); (14, 45)]) in\r\nPrintf.printf \"%d %d\" h m;; *)"}], "negative_code": [{"source_code": "\r\n(* \r\n start: 22 00\r\n stop: 02 15\r\n if start>stop then\r\n diff = stop + offset\r\n else\r\n diff = stop - start *)\r\nlet sleep_time = function\r\n| (start_h, start_m), stop_times ->\r\n let offset_h = 23-start_h in\r\n let offset_m = if (start_m=0) then 0 else 60-start_m in\r\n let rec get_min_time_diff = function\r\n | [], _min_time_diff -> _min_time_diff\r\n | (_stop_h, _stop_m)::_stop_times, (_min_h, _min_m) ->\r\n if ((_stop_h=60) then ((_h+1),(_m-60)) else (_h, _m) in\r\n if ((_h<_min_h) || (_h=_min_h && _m<_min_m)) then get_min_time_diff (_stop_times, (_h, _m))\r\n else get_min_time_diff (_stop_times, (_min_h, _min_m))\r\n end\r\n else begin\r\n let _h = _stop_h-start_h in\r\n let _m = _stop_m-start_m in\r\n let _h, _m = if (_m<0) then ((_h-1), (_m+60)) else (_h, _m) in \r\n if ((_h<_min_h) || (_h=_min_h && _m<_min_m)) then get_min_time_diff (_stop_times, (_h, _m))\r\n else get_min_time_diff (_stop_times, (_min_h, _min_m))\r\n end\r\n in get_min_time_diff (stop_times, (24, 0))\r\n;;\r\n\r\nlet read_int ()= Scanf.scanf \" %d\" (fun x-> x);;\r\nlet read_time ()= Scanf.scanf \" %d %d\" (fun h m -> h,m);;\r\n\r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in \r\n let s_h = read_int () in \r\n let s_m =read_int () in\r\n let start_time = (s_h, s_m) in\r\n let rec read_stop_times = function\r\n | 0 -> []\r\n | x -> \r\n let h=read_int () in \r\n let m=read_int () in \r\n (h,m)::read_stop_times (x-1)\r\n in\r\n let stop_times= read_stop_times n in\r\n let min_h, min_m = sleep_time (start_time, stop_times) in\r\n Printf.printf \"%d %d\\n\" min_h min_m\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| n -> run_case (); iter_cases (n-1)\r\n;;\r\n\r\nlet t = read_int () in iter_cases t;;\r\n(* \r\nlet h, m = sleep_time ((6,0), [(12, 30); (14, 45)]) in\r\nPrintf.printf \"%d %d\" h m;; *)"}], "src_uid": "ce0579e9c5b4c157bc89103c76ddd4c3"} {"nl": {"description": "Petya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of n\u2009\u00d7\u2009m cells and a robotic arm. Each cell of the field is a 1\u2009\u00d7\u20091 square. The robotic arm has two lasers pointed at the field perpendicularly to its surface. At any one time lasers are pointed at the centres of some two cells. Since the lasers are on the robotic hand, their movements are synchronized \u2014 if you move one of the lasers by a vector, another one moves by the same vector.The following facts about the experiment are known: initially the whole field is covered with a chocolate bar of the size n\u2009\u00d7\u2009m, both lasers are located above the field and are active; the chocolate melts within one cell of the field at which the laser is pointed; all moves of the robotic arm should be parallel to the sides of the field, after each move the lasers should be pointed at the centres of some two cells; at any one time both lasers should be pointed at the field. Petya doesn't want to become a second Gordon Freeman. You are given n, m and the cells (x1,\u2009y1) and (x2,\u2009y2), where the lasers are initially pointed at (xi is a column number, yi is a row number). Rows are numbered from 1 to m from top to bottom and columns are numbered from 1 to n from left to right. You are to find the amount of cells of the field on which the chocolate can't be melted in the given conditions.", "input_spec": "The first line contains one integer number t (1\u2009\u2264\u2009t\u2009\u2264\u200910000) \u2014 the number of test sets. Each of the following t lines describes one test set. Each line contains integer numbers n, m, x1, y1, x2, y2, separated by a space (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009109, 1\u2009\u2264\u2009x1,\u2009x2\u2009\u2264\u2009n, 1\u2009\u2264\u2009y1,\u2009y2\u2009\u2264\u2009m). Cells (x1,\u2009y1) and (x2,\u2009y2) are distinct.", "output_spec": "Each of the t lines of the output should contain the answer to the corresponding input test set.", "sample_inputs": ["2\n4 4 1 1 3 3\n4 3 1 1 2 2"], "sample_outputs": ["8\n2"], "notes": null}, "positive_code": [{"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\nlet (|>) x f = f x\n\nopen Int64\n\nlet (++) x y = add x y\nlet (--) x y = sub x y\nlet ( ** ) x y = mul x y\n\nlet () =\n for cc = 1 to read_int () do\n let n = read_int64 0 in\n let m = read_int64 0 in\n let x = read_int64 0 in\n let y = read_int64 0 in\n let xx = read_int64 0 in\n let yy = read_int64 0 in\n let nn = n -- abs (x--xx) in\n let mm = m -- abs (y--yy) in\n n**m--nn**mm**2L++max (nn**2L--n) 0L**max (mm**2L--m) 0L |> Printf.printf \"%Ld\\n\"\n done\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n for cc = 1 to read_int () do\n let n = read_int 0 in\n let m = read_int 0 in\n let x = read_int 0 in\n let y = read_int 0 in\n let xx = read_int 0 in\n let yy = read_int 0 in\n let nn = n - abs (x-xx) in\n let mm = m - abs (y-yy) in\n n*m-nn*mm*2+max (nn*2-n) 0*max (mm*2-m) 0 |> Printf.printf \"%d\\n\"\n done\n"}], "src_uid": "8e89fc6c3dfa30ac8c3495e2b1a1e106"} {"nl": {"description": "You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.For instance, if we are given an array $$$[10, 20, 30, 40]$$$, we can permute it so that it becomes $$$[20, 40, 10, 30]$$$. Then on the first and the second positions the integers became larger ($$$20>10$$$, $$$40>20$$$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $$$2$$$. Read the note for the first example, there is one more demonstrative test case.Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the elements of the array.", "output_spec": "Print a single integer\u00a0\u2014 the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.", "sample_inputs": ["7\n10 1 1 1 5 5 3", "5\n1 1 1 1 1"], "sample_outputs": ["4", "0"], "notes": "NoteIn the first sample, one of the best permutations is $$$[1, 5, 5, 3, 10, 1, 1]$$$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.In the second sample, there is no way to increase any element with a permutation, so the answer is 0."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt64 = struct \n\t(* include Int64 *)\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\nend open MyInt64\n\nmodule IMap = Map.Make (struct \n\ttype t = int64\n\tlet compare = compare\nend)\n\nexception Hoge\nexception Fuga\n\nlet () =\n\tlet n = get_i64 ()\n\tin let ar = input_i64_array n\n\tin Array.sort (fun u v -> compare u v) ar;\n\tlet lef,rig = ref 0, ref 0\n\tin\n\t(* print_endline @@ Array.fold_left (fun u v -> u ^ (sprintf \"%Ld \" v)) \"\" ar; *)\n\twhile (!lef < ~|n && !rig < ~|n) do\n\t\t(* printf \" %d -- %d : %Ld -- %Ld\\n\" !lef !rig ar.(!lef) ar.(!rig); *)\n\t\tif ar.(!rig) > ar.(!lef) then (\n\t\t\tlef := !lef +$ 1;\n\t\t\trig := !rig +$ 1;\n\t\t) else (\n\t\t\trig := !rig +$ 1;\n\t\t);\n\tdone;\n\t~|n -$ (!rig -$ !lef)\n\t|> printf \"%d\\n\""}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt64 = struct \n\t(* include Int64 *)\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\nend open MyInt64\n\nmodule IMap = Map.Make (struct \n\ttype t = int64\n\tlet compare = compare\nend)\n\nexception Hoge\nexception Fuga\n\nlet () =\n\tlet n = get_i64 ()\n\tin let ar = input_i64_array n\n\tin Array.sort (fun u v -> compare u v) ar;\n\tlet lef,rig = ref 0, ref 0\n\tin\n\tprint_endline @@ Array.fold_left (fun u v -> u ^ (sprintf \"%Ld \" v)) \"\" ar;\n\twhile (!lef < ~|n && !rig < ~|n) do\n\t\t(* printf \" %d -- %d : %Ld -- %Ld\\n\" !lef !rig ar.(!lef) ar.(!rig); *)\n\t\tif ar.(!rig) > ar.(!lef) then (\n\t\t\tlef := !lef +$ 1;\n\t\t\trig := !rig +$ 1;\n\t\t) else (\n\t\t\trig := !rig +$ 1;\n\t\t);\n\tdone;\n\t~|n -$ (!rig -$ !lef)\n\t|> printf \"%d\\n\""}], "src_uid": "eaa768dc1024df6449e89773234cc0c3"} {"nl": {"description": "There are $$$n$$$ bags with candies, initially the $$$i$$$-th bag contains $$$i$$$ candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: Choose $$$m$$$ such that $$$1 \\le m \\le 1000$$$Perform $$$m$$$ operations. In the $$$j$$$-th operation, you will pick one bag and add $$$j$$$ candies to all bags apart from the chosen one.Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies. It can be proved that for the given constraints such a sequence always exists.You don't have to minimize $$$m$$$.If there are several valid sequences, you can output any.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first and only line of each test case contains one integer $$$n$$$ ($$$2 \\le n\\le 100$$$). ", "output_spec": "For each testcase, print two lines with your answer. In the first line print $$$m$$$ ($$$1\\le m \\le 1000$$$)\u00a0\u2014 the number of operations you want to take. In the second line print $$$m$$$ positive integers $$$a_1, a_2, \\dots, a_m$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_j$$$ is the number of bag you chose on the $$$j$$$-th operation.", "sample_inputs": ["2\n2\n3"], "sample_outputs": ["1\n2\n5\n3 3 3 1 2"], "notes": "NoteIn the first case, adding $$$1$$$ candy to all bags except of the second one leads to the arrangement with $$$[2, 2]$$$ candies.In the second case, firstly you use first three operations to add $$$1+2+3=6$$$ candies in total to each bag except of the third one, which gives you $$$[7, 8, 3]$$$. Later, you add $$$4$$$ candies to second and third bag, so you have $$$[7, 12, 7]$$$, and $$$5$$$ candies to first and third bag \u00a0\u2014 and the result is $$$[12, 12, 12]$$$."}, "positive_code": [{"source_code": "let () =\n let t = () |> read_line |> int_of_string in\n for i = 1 to t do\n let n = () |> read_line |> int_of_string in\n n |> string_of_int |> print_endline;\n for j = 1 to n do\n j |> string_of_int |> print_string;\n print_char ' '\n done;\n print_endline \"\"\n done\n"}], "negative_code": [], "src_uid": "ac248c83c99d8a2262772816b5f4ac6e"} {"nl": {"description": "Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.Recently, she was presented with an array $$$a$$$ of the size of $$$10^9$$$ elements that is filled as follows: $$$a_1 = -1$$$ $$$a_2 = 2$$$ $$$a_3 = -3$$$ $$$a_4 = 4$$$ $$$a_5 = -5$$$ And so on ... That is, the value of the $$$i$$$-th element of the array $$$a$$$ is calculated using the formula $$$a_i = i \\cdot (-1)^i$$$.She immediately came up with $$$q$$$ queries on this array. Each query is described with two numbers: $$$l$$$ and $$$r$$$. The answer to a query is the sum of all the elements of the array at positions from $$$l$$$ to $$$r$$$ inclusive.Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you\u00a0\u2014 the best programmer.Help her find the answers!", "input_spec": "The first line contains a single integer $$$q$$$ ($$$1 \\le q \\le 10^3$$$)\u00a0\u2014 the number of the queries. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le 10^9$$$)\u00a0\u2014 the descriptions of the queries.", "output_spec": "Print $$$q$$$ lines, each containing one number\u00a0\u2014 the answer to the query. ", "sample_inputs": ["5\n1 3\n2 5\n5 5\n4 4\n2 3"], "sample_outputs": ["-2\n-2\n-5\n4\n-1"], "notes": "NoteIn the first query, you need to find the sum of the elements of the array from position $$$1$$$ to position $$$3$$$. The sum is equal to $$$a_1 + a_2 + a_3 = -1 + 2 -3 = -2$$$.In the second query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$5$$$. The sum is equal to $$$a_2 + a_3 + a_4 + a_5 = 2 -3 + 4 - 5 = -2$$$.In the third query, you need to find the sum of the elements of the array from position $$$5$$$ to position $$$5$$$. The sum is equal to $$$a_5 = -5$$$.In the fourth query, you need to find the sum of the elements of the array from position $$$4$$$ to position $$$4$$$. The sum is equal to $$$a_4 = 4$$$.In the fifth query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$3$$$. The sum is equal to $$$a_2 + a_3 = 2 - 3 = -1$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet (--) = Int64.sub\nlet (//) = Int64.div\nlet (%%) = Int64.rem\n\nlet sum = function\n r when r %% 2L = 0L -> r // 2L\n | r -> r // 2L -- r\n\nlet () =\n let q = scanf \" %d\" (fun x -> x) in\n for i = 0 to q-1 do\n let l, r = scanf \" %Ld %Ld\" (fun x y -> x,y) in\n printf \"%Ld\\n\" @@ sum r -- sum (l -- 1L)\n done"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\n(* let () =\n let hoge = init 100 (fun i -> let i = i+$1 in i*$(if i %$ 2=0 then 1 else -1))\n in\n print_array (sprintf \"%3d\") hoge;\n let cumul = make 100 0 in\n iteri (fun i v ->\n if i<>0 then cumul.(i) <- cumul.(i-$1)+$hoge.(i-$1)\n ) cumul;\n print_array (sprintf \"%3d\") cumul *)\nlet f l = l*(if l mod 2L=0L then 1L else -1L)\nlet g l = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L)\nlet () =\n let q = get_i64 0 in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n printf \"%Ld\\n\" @@\n if l=r then f l\n (* else if r=l+1L then f l + f (l+1L)\n else if r=l+2L then f l + f (l+1L) + f (l+2L)\n (*let vl = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L) in\n let vr = ceildiv (r) 2L*(if r mod 2L=0L then 1L else -1L) in\n (* printf \"%Ld\\n\" @@ vl + vr *)\n printf \"%Ld\\n\" @@ vl + vr; *)\n else if l = 1L then g r\n else\n (* if l mod 2L=0L && (r-l) mod 2L=0L then g l + g r\n else if l mod 2L=1L && (r-l) mod 2L=0L then 0L\n else if l mod 2L=0L && (r-l) mod 2L=1L then g l + g r\n else 0L *)\n g l + g r *)\n else\n (* if l=1L then g r\n else g (l-1L) + g r *)\n g r - g (l-1L)\n )\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\n(* let () =\n let hoge = init 100 (fun i -> let i = i+$1 in i*$(if i %$ 2=0 then 1 else -1))\n in\n print_array (sprintf \"%3d\") hoge;\n let cumul = make 100 0 in\n iteri (fun i v ->\n if i<>0 then cumul.(i) <- cumul.(i-$1)+$hoge.(i-$1)\n ) cumul;\n print_array (sprintf \"%3d\") cumul *)\nlet f l = l*(if l mod 2L=0L then 1L else -1L)\nlet g l = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L)\nlet () =\n let q = get_i64 0 in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n printf \"%Ld\\n\" @@\n if l=r then f l\n else if r=l+1L then f l + f (l+1L)\n else if r=l+2L then f l + f (l+1L) + f (l+2L)\n (*let vl = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L) in\n let vr = ceildiv (r) 2L*(if r mod 2L=0L then 1L else -1L) in\n (* printf \"%Ld\\n\" @@ vl + vr *)\n printf \"%Ld\\n\" @@ vl + vr; *)\n else\n (* if l mod 2L=0L && (r-l) mod 2L=0L then g l + g r\n else if l mod 2L=1L && (r-l) mod 2L=0L then 0L\n else if l mod 2L=0L && (r-l) mod 2L=1L then g l + g r\n else 0L *)\n g l + g r\n )\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\n(* let () =\n let hoge = init 100 (fun i -> let i = i+$1 in i*$(if i %$ 2=0 then 1 else -1))\n in\n print_array (sprintf \"%3d\") hoge;\n let cumul = make 100 0 in\n iteri (fun i v ->\n if i<>0 then cumul.(i) <- cumul.(i-$1)+$hoge.(i-$1)\n ) cumul;\n print_array (sprintf \"%3d\") cumul; *)\nlet f l = l*(if l mod 2L=0L then 1L else -1L)\nlet g l = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L)\nlet () =\n let q = get_i64 0 in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n printf \"%Ld\\n\" @@\n if l=r then f l\n else if r=l+1L then f l + f (l+1L)\n else if r=l+2L then f l + f (l+1L) + f (l+2L)\n (*let vl = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L) in\n let vr = ceildiv (r) 2L*(if r mod 2L=0L then 1L else -1L) in\n (* printf \"%Ld\\n\" @@ vl + vr *)\n printf \"%Ld\\n\" @@ vl + vr; *)\n else if l mod 2L=0L && (r-l) mod 2L=0L then g l + g r\n else if l mod 2L=1L && (r-l) mod 2L=0L then 0L\n else if l mod 2L=0L && (r-l) mod 2L=1L then g r\n else 0L\n )\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\n(* let () =\n let hoge = init 100 (fun i -> let i = i+$1 in i*$(if i %$ 2=0 then 1 else -1))\n in\n print_array (sprintf \"%3d\") hoge;\n let cumul = make 100 0 in\n iteri (fun i v ->\n if i<>0 then cumul.(i) <- cumul.(i-$1)+$hoge.(i-$1)\n ) cumul;\n print_array (sprintf \"%3d\") cumul *)\nlet f l = l*(if l mod 2L=0L then 1L else -1L)\nlet g l = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L)\nlet () =\n let q = get_i64 0 in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n printf \"%Ld\\n\" @@\n if l=r then f l\n else if r=l+1L then f l + f (l+1L)\n else if r=l+2L then f l + f (l+1L) + f (l+2L)\n (*let vl = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L) in\n let vr = ceildiv (r) 2L*(if r mod 2L=0L then 1L else -1L) in\n (* printf \"%Ld\\n\" @@ vl + vr *)\n printf \"%Ld\\n\" @@ vl + vr; *)\n else if l mod 2L=0L && (r-l) mod 2L=0L then g l + g r\n else if l mod 2L=1L && (r-l) mod 2L=0L then 0L\n else if l mod 2L=0L && (r-l) mod 2L=1L then g l + g r\n else 0L\n )\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\n(* let () =\n let hoge = init 100 (fun i -> let i = i+$1 in i*$(if i %$ 2=0 then 1 else -1))\n in\n print_array (sprintf \"%3d\") hoge;\n let cumul = make 100 0 in\n iteri (fun i v ->\n if i<>0 then cumul.(i) <- cumul.(i-$1)+$hoge.(i-$1)\n ) cumul;\n print_array (sprintf \"%3d\") cumul *)\nlet f l = l*(if l mod 2L=0L then 1L else -1L)\nlet g l = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L)\nlet () =\n let q = get_i64 0 in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n printf \"%Ld\\n\" @@\n if l=r then f l\n else if r=l+1L then f l + f (l+1L)\n else if r=l+2L then f l + f (l+1L) + f (l+2L)\n (*let vl = ceildiv (l) 2L*(if l mod 2L=0L then 1L else -1L) in\n let vr = ceildiv (r) 2L*(if r mod 2L=0L then 1L else -1L) in\n (* printf \"%Ld\\n\" @@ vl + vr *)\n printf \"%Ld\\n\" @@ vl + vr; *)\n else if l = 1L then g r\n else\n (* if l mod 2L=0L && (r-l) mod 2L=0L then g l + g r\n else if l mod 2L=1L && (r-l) mod 2L=0L then 0L\n else if l mod 2L=0L && (r-l) mod 2L=1L then g l + g r\n else 0L *)\n g l + g r\n )\n\n\n\n\n\n\n\n"}], "src_uid": "7eae40835f6e9580b985d636d5730e2d"} {"nl": {"description": "You are given a program that consists of $$$n$$$ instructions. Initially a single variable $$$x$$$ is assigned to $$$0$$$. Afterwards, the instructions are of two types: increase $$$x$$$ by $$$1$$$; decrease $$$x$$$ by $$$1$$$. You are given $$$m$$$ queries of the following format: query $$$l$$$ $$$r$$$\u00a0\u2014 how many distinct values is $$$x$$$ assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order? ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Then the description of $$$t$$$ testcases follows. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of instructions in the program and the number of queries. The second line of each testcase contains a program\u00a0\u2014 a string of $$$n$$$ characters: each character is either '+' or '-'\u00a0\u2014 increment and decrement instruction, respectively. Each of the next $$$m$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le n$$$)\u00a0\u2014 the description of the query. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$. ", "output_spec": "For each testcase print $$$m$$$ integers\u00a0\u2014 for each query $$$l$$$, $$$r$$$ print the number of distinct values variable $$$x$$$ is assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order.", "sample_inputs": ["2\n8 4\n-+--+--+\n1 8\n2 8\n2 5\n1 1\n4 10\n+-++\n1 1\n1 2\n2 2\n1 3\n2 3\n3 3\n1 4\n2 4\n3 4\n4 4"], "sample_outputs": ["1\n2\n4\n4\n3\n3\n4\n2\n3\n2\n1\n2\n2\n2"], "notes": "NoteThe instructions that remain for each query of the first testcase are: empty program\u00a0\u2014 $$$x$$$ was only equal to $$$0$$$; \"-\"\u00a0\u2014 $$$x$$$ had values $$$0$$$ and $$$-1$$$; \"---+\"\u00a0\u2014 $$$x$$$ had values $$$0$$$, $$$-1$$$, $$$-2$$$, $$$-3$$$, $$$-2$$$\u00a0\u2014 there are $$$4$$$ distinct values among them; \"+--+--+\"\u00a0\u2014 the distinct values are $$$1$$$, $$$0$$$, $$$-1$$$, $$$-2$$$. "}, "positive_code": [{"source_code": "open Str\nopen Big_int\nopen Num\n\nlet multitest = true\n\n\nmodule Int = struct\n type t = int\n let compare = compare\n end\n\nmodule Ints = Set.Make(Int)\n\nmodule Shortcuts = struct\n let loop ?(from = 0) n f = for i = from to n - 1 do f i; done\n let rep ?(too = 0) n f = for i = n-1 downto too do f i; done\n\nend\n\nmodule Helper = struct\n open Shortcuts\n\n let read_int ~endl () =\n if endl then Scanf.scanf \"%d\\n\" (fun x -> x)\n else Scanf.scanf \"%d \" (fun x -> x)\n\n let read_s () = Scanf.scanf \"%s\\n\" (fun x -> x)\n\n type _ t =\n | I : int t\n | S : string t\n | II : (int * int) t\n | A : int -> int array t\n\n let read x =\n let rec aux : type a. bool -> a t -> a = fun endl -> function\n | I -> read_int ~endl ()\n | S -> read_s ()\n | II ->\n let l = aux false I in\n let r = aux true I in\n l, r\n | A n ->\n let a = Array.make n 0 in\n loop (n-1) (fun i -> a.(i) <- aux false I);\n a.(n-1) <- aux true I;\n a\n in\n aux true x\n\nend\n\nmodule Ext = struct\n module List = struct\n let rec make n x =\n if (n <= 0) then []\n else x :: make (n-1) x\n\n end\n\nend\n\nmodule Alg = struct\n let rec gcd x y =\n if y <> 0 then (gcd y (x mod y))\n else (abs x)\n\n let lcm x y =\n if x = 0 || y = 0 then 0\n else abs (x * y) / (gcd x y)\n\nend\n\nlet solve _ =\n let open Shortcuts in\n let open Helper in\n let open Printf in\n let open Ext in\n let open Alg in\n (* ***** Solution code here ***** *)\n let n, d = read II in\n let s = read S in\n let pref = Array.make (n + 1) (0,0,0) in\n let x = ref 0 in\n let pmin = ref 0 in\n let pmax = ref 0 in\n loop n (fun i ->\n if String.get s i = '-' then begin\n decr x;\n if !x < !pmin then pmin := !x\n end else begin\n incr x;\n if !pmax < !x then pmax := !x\n end;\n pref.(i+1) <- (!pmin, !x, !pmax)\n );\n let suf = Array.make (n+1) (0,0,0) in\n let x = ref 0 in\n let smin = ref 0 in\n let smax = ref 0 in\n loop (n - 1) (fun i ->\n if String.get s (n-i-1) = '+' then begin\n decr x;\n if !x < !smin then smin := !x\n end else begin\n incr x;\n if !smax < !x then smax := !x\n end;\n suf.(n-1-i) <- (!smin, !x, !smax)\n );\n loop d (fun i ->\n let l,r = read II in\n let p_min, p_last, p_max = pref.(l-1) in\n let s_min, s_first, s_max = suf.(r) in\n printf \"%d\\n\" (max p_max (p_last + s_max - s_first) - min p_min (p_last + s_min - s_first) + 1);\n );\n (* ***** ******************* ***** *)\n;;\n\nlet () =\n let open Helper in\n let open Shortcuts in\n let t = if multitest then read I else 1 in\n loop t solve;;\n"}], "negative_code": [], "src_uid": "85769fb020b0d7f8e447a84a09cdddda"} {"nl": {"description": "Sherlock Holmes and Dr. Watson played some game on a checkered board n\u2009\u00d7\u2009n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8\u2009+\u20093\u2009+\u20096\u2009+\u20097\u2009=\u200924, sum of its row numbers equals 9\u2009+\u20095\u2009+\u20093\u2009+\u20092\u2009=\u200919, and 24\u2009>\u200919.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u200930). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.", "output_spec": "Print the single number \u2014 the number of the winning squares.", "sample_inputs": ["1\n1", "2\n1 2\n3 4", "4\n5 7 8 4\n9 5 3 2\n1 6 6 4\n9 5 7 3"], "sample_outputs": ["0", "2", "6"], "notes": "NoteIn the first example two upper squares are winning.In the third example three left squares in the both middle rows are winning:5 7 8 49 5 3 21 6 6 49 5 7 3"}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet read_int () = bscanf Scanning.stdib \" %d\" (fun x -> x)\n\n\nlet main () =\n let n : int = read_int () in\n let cols = Array.make n 0 in\n let rows = Array.make n 0 in\n let rec compute i j =\n let num = read_int () in\n Array.set cols j ((Array.get cols j)+num);\n Array.set rows i ((Array.get rows i)+num);\n match i, j with\n | 0, 0 -> ()\n | _, 0 -> compute (i-1) (n-1)\n | _, _ -> compute i (j-1)\n in\n\n compute (n-1) (n-1);\n\n let total =\n Array.fold_left (fun total i ->\n Array.fold_left (fun total j -> if (i > j) then total+1 else total)\n total\n rows)\n 0\n cols\n in\n print_int total\n\n\nlet () = main ()\n\n\n(*\n let rec compute i =\n let line = read_line () in\n let nums = Str.split (Str.regexp \"\\b\") line in\n ignore (List.fold_left (fun j s ->\n let num = int_of_string s in\n Array.set cols j ((Array.get cols j)+num);\n Array.set rows i ((Array.get rows i)+num);\n j-1\n ) (n-1) nums);\n if i == 0\n then ()\n else compute (i-1)\n in\n*)\n"}], "negative_code": [], "src_uid": "6e7c2c0d7d4ce952c53285eb827da21d"} {"nl": {"description": "There are $$$n$$$ candies in a row, they are numbered from left to right from $$$1$$$ to $$$n$$$. The size of the $$$i$$$-th candy is $$$a_i$$$.Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob \u2014 from right to left. The game ends if all the candies are eaten.The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob \u2014 from the right).Alice makes the first move. During the first move, she will eat $$$1$$$ candy (its size is $$$a_1$$$). Then, each successive move the players alternate \u2014 that is, Bob makes the second move, then Alice, then again Bob and so on.On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.For example, if $$$n=11$$$ and $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, then: move 1: Alice eats one candy of size $$$3$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3,5]$$$. move 2: Alice ate $$$3$$$ on the previous move, which means Bob must eat $$$4$$$ or more. Bob eats one candy of size $$$5$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3]$$$. move 3: Bob ate $$$5$$$ on the previous move, which means Alice must eat $$$6$$$ or more. Alice eats three candies with the total size of $$$1+4+1=6$$$ and the sequence of candies becomes $$$[5,9,2,6,5,3]$$$. move 4: Alice ate $$$6$$$ on the previous move, which means Bob must eat $$$7$$$ or more. Bob eats two candies with the total size of $$$3+5=8$$$ and the sequence of candies becomes $$$[5,9,2,6]$$$. move 5: Bob ate $$$8$$$ on the previous move, which means Alice must eat $$$9$$$ or more. Alice eats two candies with the total size of $$$5+9=14$$$ and the sequence of candies becomes $$$[2,6]$$$. move 6 (the last): Alice ate $$$14$$$ on the previous move, which means Bob must eat $$$15$$$ or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers: $$$a$$$ \u2014 the total size of all sweets eaten by Alice during the game; $$$b$$$ \u2014 the total size of all sweets eaten by Bob during the game. ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) \u2014 the number of test cases in the input. The following are descriptions of the $$$t$$$ test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the number of candies. The second line contains a sequence of integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 1000$$$) \u2014 the sizes of candies in the order they are arranged from left to right. It is guaranteed that the sum of the values of $$$n$$$ for all sets of input data in a test does not exceed $$$2\\cdot10^5$$$.", "output_spec": "For each set of input data print three integers \u2014 the number of moves in the game and the required values $$$a$$$ and $$$b$$$.", "sample_inputs": ["7\n11\n3 1 4 1 5 9 2 6 5 3 5\n1\n1000\n3\n1 1 1\n13\n1 2 3 4 5 6 7 8 9 10 11 12 13\n2\n2 1\n6\n1 1 1 1 1 1\n7\n1 1 1 1 1 1 1"], "sample_outputs": ["6 23 21\n1 1000 0\n2 1 2\n6 45 46\n2 2 1\n3 4 2\n4 4 3"], "notes": null}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n \nopen Printf\n\nlet init (x : int) (f : int -> 'a) : 'a list =\n let rec build k =\n if k = x then []\n else (f k) :: build (k + 1) in\n build 0\n;;\n \nlet run () = \n let n = scan_int () in\n let a = Array.init n (fun _x -> scan_int ()) in\n let posA = ref 0 and posB = ref (n-1) in\n let totA = ref 0 and totB = ref 0 in\n let prv = ref 0 and now = ref 0 in\n let turn = ref 0 and totturn = ref 0 in\n while !posA <= !posB do\n if !turn = 0 then begin\n now := !now + a.(!posA);\n totA := !totA + a.(!posA);\n posA := !posA + 1\n end\n else begin\n now := !now + a.(!posB);\n totB := !totB + a.(!posB);\n posB := !posB - 1\n end;\n if !now > !prv then begin\n prv := !now;\n now := 0;\n turn := 1 - !turn;\n totturn := !totturn + 1\n end\n done;\n if !now > 0 then incr totturn;\n let lst = [!totturn; !totA; !totB] in\n List.iter (printf \"%d \") lst;\n print_endline \"\"\n;;\n \nlet () =\n let t = scan_int () in\n for i = 1 to t do\n run ()\n done\n;;\n"}, {"source_code": "(* Codeforces 1352 D Alice, Bob and Candies comp *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\n(* ============= above library below custom ========== *)\n\nlet rec alice ia sma ib smb lastbob nmov v =\n\tlet rec eat i eaten = \n\t\t(* let _ = Printf.printf \"al eat i eaten = %d %d\\n\" i eaten in *)\n\t\tif eaten > lastbob then (i, eaten) \n\t\telse if i > ib then (i, eaten)\n\t\telse \n\t\t\tlet eaten = eaten + v.(i) in\n\t\t\tlet i = i + 1 in\n\t\t\teat i eaten in\n\tlet idx,aeat = eat ia 0 in\n\tlet sma = sma + aeat in\n let nmov = nmov + 1 in\n\tif idx > ib then (nmov, sma, smb)\n\telse\n\tbob idx sma ib smb aeat nmov v\n\t\nand\n\nbob ia sma ib smb lastalice nmov v =\n let rec eat i eaten = \n (* let _ = Printf.printf \"bo eat i eaten = %d %d\\n\" i eaten in *)\n if eaten > lastalice then (i, eaten) \n else if i < ia then (i, eaten)\n else \n let eaten = eaten + v.(i) in\n let i = i - 1 in\n eat i eaten in\n let idx,beat = eat ib 0 in\n let smb = smb + beat in\n let nmov = nmov + 1 in\n if idx < ia then (nmov, sma, smb)\n else\n alice ia sma idx smb beat nmov v;;\n\t \n \nlet do_one () = \n let n = gr () in\n let a = readlist n [] in\n\t\tlet a = (List.rev a) in\n\t\tlet va = Array.of_list a in\n\t\tlet nm,ca,cb = alice 0 0 (n-1) 0 0 0 va in\n \tPrintf.printf \"%d %d %d\\n\" nm ca cb;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [], "src_uid": "d70ee6d3574e0f2cac3c683729e2979d"} {"nl": {"description": "Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0,\u20090) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0,\u20090) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a,\u20090). We also know that the length of the marathon race equals nd\u2009+\u20090.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d,\u20092\u00b7d,\u2009...,\u2009n\u00b7d meters.", "input_spec": "The first line contains two space-separated real numbers a and d (1\u2009\u2264\u2009a,\u2009d\u2009\u2264\u2009105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) showing that Valera needs an extra drink n times.", "output_spec": "Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi,\u2009yi) after he covers i\u00b7d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10\u2009-\u20094. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.", "sample_inputs": ["2 5\n2", "4.147 2.8819\n6"], "sample_outputs": ["1.0000000000 2.0000000000\n2.0000000000 0.0000000000", "2.8819000000 0.0000000000\n4.1470000000 1.6168000000\n3.7953000000 4.1470000000\n0.9134000000 4.1470000000\n0.0000000000 2.1785000000\n0.7034000000 0.0000000000"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet s=read_line();;\n\nlet rec ind i t=if t.[i]=' ' then i else ind (i+1) t;;\nlet i=ind 0 s;;\n\nlet s1=String.sub s 0 i;;\nlet s2=String.sub s (i+1) (String.length(s)-i-1);;\n\nlet a=float_of_string(s1);;\nlet d=float_of_string(s2);;\n\nlet n=read_int();;\n\nlet frac b=b-.float_of_int(int_of_float(b));;\n\nlet bop b c=\nprint_float b;\nprint_string \" \";\nprint_float c;\nprint_newline();;\n\nlet m=ref 0.;;\n\nfor i=1 to n do\n m:= !m+.d;\n let p=frac( !m/.(4.0*.a)) in\n if p<0.25 then bop (p*.4.0*.a) 0.0\n else if p<0.5 then bop a ((p-.0.25)*.4.0*.a)\n else if p<0.75 then bop (a-.(p-.0.5)*.4.0*.a) a\n else bop 0.0 (a-.(p-.0.75)*.4.0*.a);\n m:=(p*.4.0*.a)\ndone;;"}, {"source_code": "let read_int () = Scanf.scanf \"%d\" (fun x -> x);;\n\nlet a = Scanf.scanf \"%f \" (fun x -> x);;\nlet d = Scanf.scanf \"%f\\n\" (fun x -> x);;\nlet n = Scanf.scanf \"%d\" (fun x -> x);;\n\nlet distance = ref 0.;;\n\nlet modulo a b = a -. b *. floor (a /. b);;\n\nfor i=1 to n do\n distance := modulo (!distance +. d) (4.*.a);\n match int_of_float (!distance /. a) with\n | 0 -> print_float !distance;\n print_string \" \";\n print_float 0.;\n print_string \"\\n\"\n | 1 -> print_float a;\n print_string \" \";\n print_float (!distance -. a);\n print_string \"\\n\"\n | 2 -> print_float (3.*.a -. !distance);\n print_string \" \";\n print_float a;\n print_string \"\\n\"\n | 3 -> print_float 0.;\n print_string \" \";\n print_float (4.*.a -. !distance);\n print_string \"\\n\"\n | _ -> failwith \"Erreur !!\"\ndone;"}], "negative_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet s=read_line();;\n\nlet rec ind i t=if t.[i]=' ' then i else ind (i+1) t;;\nlet i=ind 0 s;;\n\nlet s1=String.sub s 0 i;;\nlet s2=String.sub s (i+1) (String.length(s)-i-1);;\n\nlet a=float_of_string(s1);;\nlet d=float_of_string(s2);;\n\nlet n=read_int();;\n\nlet frac b=b-.float_of_int(int_of_float(b));;\n\nlet bop b c=\nprint_float b;\nprint_string \" \";\nprint_float c;\nprint_newline();;\n\nfor i=1 to n do\n let m=float_of_int(i)*.d in\n let p=frac(m/.(4.0*.a)) in\n if p<0.25 then bop (p*.4.0*.a) 0.0\n else if p<0.5 then bop a ((p-.0.25)*.4.0*.a)\n else if p<0.75 then bop (a-.(p-.0.5)*.4.0*.a) a\n else bop 0.0 (a-.(p-.0.75)*.4.0*.a)\ndone;;"}], "src_uid": "d00b8423c3c52b19fec25bc63e4d4c1c"} {"nl": {"description": "In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.Lesha knows that today he can study for at most $$$a$$$ hours, and he will have $$$b$$$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $$$k$$$ in $$$k$$$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.Thus, the student has to fully read several lecture notes today, spending at most $$$a$$$ hours in total, and fully read several lecture notes tomorrow, spending at most $$$b$$$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which\u00a0\u2014 in the second?", "input_spec": "The only line of input contains two integers $$$a$$$ and $$$b$$$ ($$$0 \\leq a, b \\leq 10^{9}$$$)\u00a0\u2014 the number of hours Lesha has today and the number of hours Lesha has tomorrow.", "output_spec": "In the first line print a single integer $$$n$$$ ($$$0 \\leq n \\leq a$$$)\u00a0\u2014 the number of lecture notes Lesha has to read in the first day. In the second line print $$$n$$$ distinct integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\leq p_i \\leq a$$$), the sum of all $$$p_i$$$ should not exceed $$$a$$$. In the third line print a single integer $$$m$$$ ($$$0 \\leq m \\leq b$$$)\u00a0\u2014 the number of lecture notes Lesha has to read in the second day. In the fourth line print $$$m$$$ distinct integers $$$q_1, q_2, \\ldots, q_m$$$ ($$$1 \\leq q_i \\leq b$$$), the sum of all $$$q_i$$$ should not exceed $$$b$$$. All integers $$$p_i$$$ and $$$q_i$$$ should be distinct. The sum $$$n + m$$$ should be largest possible.", "sample_inputs": ["3 3", "9 12"], "sample_outputs": ["1\n3 \n2\n2 1", "2\n3 6\n4\n1 2 4 5"], "notes": "NoteIn the first example Lesha can read the third note in $$$3$$$ hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending $$$3$$$ hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.In the second example Lesha should read the third and the sixth notes in the first day, spending $$$9$$$ hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending $$$12$$$ hours in total."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64,ist = Int64.(to_int,of_int,to_string)\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* io *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls =\n\t\tls |> List.map f |> String.concat separator\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\t(* imperative *)\n\tlet rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done\n\tlet repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done\n\tlet repm f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m\n\tlet repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done\n\tlet repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done\n\tlet repim f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m\n\t(* debug *)\n\t(* let dump_list f ls = ls |> List.map f |> String.concat \" \" |> print_endline\n\tlet dump_array f a = a |> Array.to_list |> dump_list f *)\n\tlet dump_list f ls = string_of_list f ls |> print_endline\nend open Lib\n\nlet binary_search ng ok f =\n\tlet rec f0 ng ok =\n\t\tif labs (ok - ng) <= 1L then ok\n\t\telse let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n\tin let d = if ng < ok then 1L else -1L\n\tin f0 (ng-1L*d) (ok+1L*d)\n\n(* let a,b = get_2_i64 0\nlet sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)\nlet rec f0 ra rb la lb = function\n\t| 0L -> (la,lb)\n\t| v ->\n\t\tif ra > rb then f0 (ra-v) rb (v::la) lb (v-1L)\n\t\telse f0 ra (rb-v) la (v::lb) (v-1L)\nlet (la,lb) = f0 a b [] [] sum\nlet () =\n\tprintf \"%d\\n\" @@ List.length la;\n\tdump_list Int64.to_string la;\n\tprintf \"%d\\n\" @@ List.length lb;\n\tdump_list Int64.to_string lb; *)\n\nlet ist = Int64.to_string\nlet () =\n\tlet a,b = get_2_i64 0 in\n\tlet sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)\n\tin\n\t(* printf \"%Ld\\n\" sum; *)\n\tlet d1,d2 = ref [],ref [] in\n\tlet r1,r2 = ref a,ref b in \n\t(* rep 1L sum (fun i -> \n\t\tlet i = sum - i + 1L in\n\t\tif !ra > !rb then (\n\t\t\tla := i::!la; ra -= i;\n\t\t) else (\n\t\t\tlb := i::!lb; rb -= i;\n\t\t)\n\t); *)\n\tlet i = ref sum in\n\twhile !i >= 1L do\n\t\tif !r2 <= !r1 then (\n\t\t\tr1 := !r1 - !i;\n\t\t\td1 := !i :: !d1\n\t\t) else (\n\t\t\tr2 := !r2 - !i;\n\t\t\td2 := !i :: !d2\n\t\t);\n\t\ti := !i - 1L\n\tdone;\n\tprintf \"%d\\n\" @@ List.length !d1;\n\tdump_list ist !d1;\n\tprintf \"%d\\n\" @@ List.length !d2;\n\tdump_list ist !d2;\n\n\n\n\n"}, {"source_code": "let (++),(--),labs,(//),( ** ),i64,ist = Int64.(add,sub,abs,div,mul,of_int,to_string)\nlet binary_search ng ok f =\n\tlet rec f0 ng ok =\n\t\tif labs (ok -- ng) <= 1L then ok\n\t\telse let mid = ng ++ (ok -- ng) // 2L in if f mid then f0 ng mid else f0 mid ok\n\tin let d = if ng < ok then 1L else -1L\n\tin f0 (ng--d) (ok++d)\nlet dump_list ls = ls\n\t|> List.map ist\n\t|> String.concat \" \"\n\t|> print_endline\nlet () = Scanf.scanf \" %Ld %Ld\" @@ fun a b ->\n\tlet sum = binary_search 2000000018L 0L (fun v -> v**(v++1L)//2L <= a++b)\n\tin\n\tlet d1,d2 = ref [], ref [] in\n\tlet a = ref a in\n\tlet i = ref sum in\n\twhile !i >= 1L do\n\t\tif !i <= !a then (\n\t\t\ta := !a -- !i;\n\t\t\td1 := !i :: !d1\n\t\t) else d2 := !i :: !d2;\n\t\ti := !i -- 1L\n\tdone;\n\tPrintf.printf \"%d\\n\" @@ List.length !d1;\n\tdump_list !d1;\n\tPrintf.printf \"%d\\n\" @@ List.length !d2;\n\tdump_list !d2;\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64 = Int64.to_int,Int64.of_int\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.add,Int64.sub,Int64.mul,Int64.div,Int64.rem,Int64.rem\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* io *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls =\n\t\tlet rec f0 a s = match a with\n\t\t| [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator)\n\t\tin f0 ls \"\"\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\t(* imperative *)\n\tlet rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done\n\tlet repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done\n\tlet repm f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m\n\tlet repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done\n\tlet repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done\n\tlet repim f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m\n\t(* debug *)\n\tlet dump_list f ls = string_of_list f ls |> print_endline\n\tlet dump_array f a = string_of_array f a |> print_endline\nend open Lib\n\nlet binary_search ng ok f =\n\tlet rec f0 ng ok =\n\t\tif labs (ok - ng) <= 1L then ok\n\t\telse let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n\tin let d = if ng < ok then 1L else -1L\n\tin f0 (ng-1L*d) (ok+1L*d)\n\n(* let a,b = get_2_i64 0\nlet sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)\nlet rec f0 ra rb la lb = function\n\t| 0L -> (la,lb)\n\t| v ->\n\t\tif ra > rb then f0 (ra-v) rb (v::la) lb (v-1L)\n\t\telse f0 ra (rb-v) la (v::lb) (v-1L)\nlet (la,lb) = f0 a b [] [] sum\nlet () =\n\tprintf \"%d\\n\" @@ List.length la;\n\tdump_list Int64.to_string la;\n\tprintf \"%d\\n\" @@ List.length lb;\n\tdump_list Int64.to_string lb; *)\n\nlet ist = Int64.to_string\nlet dump_list ls = ls\n\t|> List.map ist\n\t|> String.concat \" \"\n\t|> print_endline\nlet () =\n\tlet a,b = get_2_i64 0 in\n\tlet sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)\n\tin\n\t(* printf \"%Ld\\n\" sum; *)\n\tlet d1,d2 = ref [],ref [] in\n\tlet r1,r2 = ref a,ref b in \n\t(* rep 1L sum (fun i -> \n\t\tlet i = sum - i + 1L in\n\t\tif !ra > !rb then (\n\t\t\tla := i::!la; ra -= i;\n\t\t) else (\n\t\t\tlb := i::!lb; rb -= i;\n\t\t)\n\t); *)\n\tlet i = ref sum in\n\twhile !i >= 1L do\n\t\tif !r2 <= !r1 then (\n\t\t\tr1 := !r1 - !i;\n\t\t\td1 := !i :: !d1\n\t\t) else (\n\t\t\tr2 := !r2 - !i;\n\t\t\td2 := !i :: !d2\n\t\t);\n\t\ti := !i - 1L\n\tdone;\n\tprintf \"%d\\n\" @@ List.length !d1;\n\tdump_list !d1;\n\tprintf \"%d\\n\" @@ List.length !d2;\n\tdump_list !d2;\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64,ist = Int64.(to_int,of_int,to_string)\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* io *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\t(* imperative *)\n\tlet rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done\n\tlet repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done\n\tlet repm f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m\n\tlet repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done\n\tlet repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done\n\tlet repim f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m\n\t(* debug *)\n\tlet dump_list f ls = string_of_list f ls |> print_endline\n\tlet dump_array f a = string_of_array f a |> print_endline\n\tlet dump_list_test f ls = List.iter (fun v -> printf \"%s \" @@ f v) ls; print_newline ()\nend open Lib\n\nlet binary_search ng ok f =\n\tlet rec f0 ng ok =\n\t\tif labs (ok - ng) <= 1L then ok\n\t\telse let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n\tin let d = if ng < ok then 1L else -1L\n\tin f0 (ng-1L*d) (ok+1L*d)\n\n(* let a,b = get_2_i64 0\nlet sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)\nlet rec f0 ra rb la lb = function\n\t| 0L -> (la,lb)\n\t| v ->\n\t\tif ra > rb then f0 (ra-v) rb (v::la) lb (v-1L)\n\t\telse f0 ra (rb-v) la (v::lb) (v-1L)\nlet (la,lb) = f0 a b [] [] sum\nlet () =\n\tprintf \"%d\\n\" @@ List.length la;\n\tdump_list Int64.to_string la;\n\tprintf \"%d\\n\" @@ List.length lb;\n\tdump_list Int64.to_string lb; *)\n\nlet ist = Int64.to_string\nlet () =\n\tlet a,b = get_2_i64 0 in\n\tlet sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)\n\tin\n\t(* printf \"%Ld\\n\" sum; *)\n\tlet d1,d2 = ref [],ref [] in\n\tlet r1,r2 = ref a,ref b in \n\t(* rep 1L sum (fun i -> \n\t\tlet i = sum - i + 1L in\n\t\tif !ra > !rb then (\n\t\t\tla := i::!la; ra -= i;\n\t\t) else (\n\t\t\tlb := i::!lb; rb -= i;\n\t\t)\n\t); *)\n\tlet i = ref sum in\n\twhile !i >= 1L do\n\t\tif !r2 <= !r1 then (\n\t\t\tr1 := !r1 - !i;\n\t\t\td1 := !i :: !d1\n\t\t) else (\n\t\t\tr2 := !r2 - !i;\n\t\t\td2 := !i :: !d2\n\t\t);\n\t\ti := !i - 1L\n\tdone;\n\tprintf \"%d\\n\" @@ List.length !d1;\n\tdump_list_test ist !d1;\n\tprintf \"%d\\n\" @@ List.length !d2;\n\tdump_list_test ist !d2;\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64,ist = Int64.(to_int,of_int,to_string)\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* io *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls =\n\t\tlet rec f0 a s = match a with\n\t\t| [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator)\n\t\tin f0 ls \"\"\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\t(* imperative *)\n\tlet rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done\n\tlet repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done\n\tlet repm f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m\n\tlet repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done\n\tlet repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done\n\tlet repim f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m\n\t(* debug *)\n\tlet dump_list_slow f ls = string_of_list f ls |> print_endline\n\tlet dump_array_slow f a = string_of_array f a |> print_endline\n\tlet dump_i64_list ls = ls\n\t\t|> List.map ist\nend open Lib\n\nlet binary_search ng ok f =\n\tlet rec f0 ng ok =\n\t\tif labs (ok - ng) <= 1L then ok\n\t\telse let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n\tin let d = if ng < ok then 1L else -1L\n\tin f0 (ng-1L*d) (ok+1L*d)\n\n(* let a,b = get_2_i64 0\nlet sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)\nlet rec f0 ra rb la lb = function\n\t| 0L -> (la,lb)\n\t| v ->\n\t\tif ra > rb then f0 (ra-v) rb (v::la) lb (v-1L)\n\t\telse f0 ra (rb-v) la (v::lb) (v-1L)\nlet (la,lb) = f0 a b [] [] sum\nlet () =\n\tprintf \"%d\\n\" @@ List.length la;\n\tdump_list Int64.to_string la;\n\tprintf \"%d\\n\" @@ List.length lb;\n\tdump_list Int64.to_string lb; *)\n\nlet ist = Int64.to_string\nlet dump_list f ls = ls\n\t|> List.map f\n\t|> String.concat \" \"\n\t|> print_endline\nlet () =\n\tlet a,b = get_2_i64 0 in\n\tlet sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)\n\tin\n\t(* printf \"%Ld\\n\" sum; *)\n\tlet d1,d2 = ref [],ref [] in\n\tlet r1,r2 = ref a,ref b in \n\t(* rep 1L sum (fun i -> \n\t\tlet i = sum - i + 1L in\n\t\tif !ra > !rb then (\n\t\t\tla := i::!la; ra -= i;\n\t\t) else (\n\t\t\tlb := i::!lb; rb -= i;\n\t\t)\n\t); *)\n\tlet i = ref sum in\n\twhile !i >= 1L do\n\t\tif !r2 <= !r1 then (\n\t\t\tr1 := !r1 - !i;\n\t\t\td1 := !i :: !d1\n\t\t) else (\n\t\t\tr2 := !r2 - !i;\n\t\t\td2 := !i :: !d2\n\t\t);\n\t\ti := !i - 1L\n\tdone;\n\tprintf \"%d\\n\" @@ List.length !d1;\n\tdump_list ist !d1;\n\tprintf \"%d\\n\" @@ List.length !d2;\n\tdump_list ist !d2;\n\n\n\n\n"}, {"source_code": "let (++),(--),labs,(//),( ** ),i64,ist = Int64.(add,sub,abs,div,mul,of_int,to_string)\nlet binary_search ng ok f =\n\tlet rec f0 ng ok =\n\t\tif labs (ok -- ng) <= 1L then ok\n\t\telse let mid = ng ++ (ok -- ng) // 2L in if f mid then f0 ng mid else f0 mid ok\n\tin let d = if ng < ok then 1L else -1L\n\tin f0 (ng--d) (ok++d)\nlet dump_list ls = ls\n\t|> List.map ist\n\t|> String.concat \" \"\n\t|> print_endline\nlet () = Scanf.scanf \" %Ld %Ld\" @@ fun a b ->\n\tlet sum = binary_search 2000000018L 0L (fun v -> v**(v++1L)//2L <= a++b)\n\tin\n\tlet d1,d2 = ref [], ref [] in\n\tlet r1,r2 = ref a, ref b in\n\tlet i = ref sum in\n\twhile !i >= 1L do\n\t\tif !r2 <= !r1 then (\n\t\t\tr1 := !r1 -- !i;\n\t\t\td1 := !i :: !d1\n\t\t) else (\n\t\t\tr2 := !r2 -- !i;\n\t\t\td2 := !i :: !d2\n\t\t);\n\t\ti := !i -- 1L\n\tdone;\n\tPrintf.printf \"%d\\n\" @@ List.length !d1;\n\tdump_list !d1;\n\tPrintf.printf \"%d\\n\" @@ List.length !d2;\n\tdump_list !d2;"}], "negative_code": [], "src_uid": "fab438cef9eb5e9e4a4a2e3f9e4f9cec"} {"nl": {"description": "Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of throws of the first team. Then follow n integer numbers \u2014 the distances of throws ai (1\u2009\u2264\u2009ai\u2009\u2264\u20092\u00b7109). Then follows number m (1\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the number of the throws of the second team. Then follow m integer numbers \u2014 the distances of throws of bi (1\u2009\u2264\u2009bi\u2009\u2264\u20092\u00b7109).", "output_spec": "Print two numbers in the format a:b \u2014 the score that is possible considering the problem conditions where the result of subtraction a\u2009-\u2009b is maximum. If there are several such scores, find the one in which number a is maximum.", "sample_inputs": ["3\n1 2 3\n2\n5 6", "5\n6 7 8 9 10\n5\n1 2 3 4 5"], "sample_outputs": ["9:6", "15:10"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 493C VasiaBasketball *)\n\nopen List;;\nopen String;;\nopen Array;;\nopen Int64;;\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet printarri64 ai = Array.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) ai;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n - 1) (gr() :: acc);;\n\nlet mcomp a b = a-b;;\n\n(* count elements less than d using binary search *)\nlet rec countd a i0 i1 d = \n\tif i1 = i0+1 then \n\t\tbegin\n\t\t\t(*printarri a;\n\t\t\tprint_string \" d = \"; print_int d; \n\t\t\tprint_string \" i0 = \"; print_int i0; \n\t\t\tprint_string \" i1 = \"; print_int i1; \n\t\t\tprint_string \" cnt = \";*)\n\t\t\tlet cnt = 2*i1 + 3*((length a)-i1) + (if a.(i0)>d then 1 else 0) in\n\t\t\t cnt\n\t\tend\n\telse\n\t\tlet i = (i0 + i1)/2 in\n\t\tif a.(i)>d then countd a i0 i d\n\t\telse countd a i i1 d;; \n\nlet diff aa bb d = \n\tlet da = countd aa 0 (length aa) d in\n\tlet db = countd bb 0 (length bb) d in\n\t(da, db,d);;\n\nlet mprcomp pra prb = \n\tlet (a0,a1,d) = pra in\n\tlet (b0,b1,d) = prb in\n\tlet da = a0-a1 in\n\tlet db = b0-b1 in\n\tif da-db != 0 then db - da\n\telse b0 - a0;;\n\nlet main () = \n\tlet n = gr () in\n\tlet a = readlist n [] in\n\tlet aa = Array.of_list (List.sort mcomp a) in\n\tlet m = gr() in\n\tlet b = readlist m [] in\n\tlet bb = Array.of_list (List.sort mcomp b) in\n\tlet ab = (0 :: (a @ b)) in \n\tlet abpr = List.map (fun d -> diff aa bb d) ab in\n\tlet abprso = List.sort mprcomp abpr in\n\tlet (x,y,d) = List.hd abprso in\n\tbegin\n\t print_int x;\n\t\tprint_string \":\";\n\t\tprint_int y;\n\t\t(*print_string \" d= \"; print_int d*)\n\tend;;\n\nmain();;\n"}], "negative_code": [], "src_uid": "a30b5ff6855dcbad142f6bcc282601a0"} {"nl": {"description": "Omkar has received a message from Anton saying \"Your story for problem A is confusing. Just make a formal statement.\" Because of this, Omkar gives you an array $$$a = [a_1, a_2, \\ldots, a_n]$$$ of $$$n$$$ distinct integers. An array $$$b = [b_1, b_2, \\ldots, b_k]$$$ is called nice if for any two distinct elements $$$b_i, b_j$$$ of $$$b$$$, $$$|b_i-b_j|$$$ appears in $$$b$$$ at least once. In addition, all elements in $$$b$$$ must be distinct. Can you add several (maybe, $$$0$$$) integers to $$$a$$$ to create a nice array $$$b$$$ of size at most $$$300$$$? If $$$a$$$ is already nice, you don't have to add any elements.For example, array $$$[3, 6, 9]$$$ is nice, as $$$|6-3|=|9-6| = 3$$$, which appears in the array, and $$$|9-3| = 6$$$, which appears in the array, while array $$$[4, 2, 0, 6, 9]$$$ is not nice, as $$$|9-4| = 5$$$ is not present in the array.For integers $$$x$$$ and $$$y$$$, $$$|x-y| = x-y$$$ if $$$x > y$$$ and $$$|x-y| = y-x$$$ otherwise.", "input_spec": "Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \\leq t \\leq 50$$$), the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$) \u2014 the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \\cdots, a_n$$$ ($$$-100 \\leq a_i \\leq 100$$$) \u2014 the elements of the array $$$a$$$.", "output_spec": "For each test case, output one line containing YES if Omkar can create a nice array $$$b$$$ by adding elements to $$$a$$$ and NO otherwise. The case of each letter does not matter, so yEs and nO will also be accepted. If the first line is YES, output a second line containing a single integer $$$k$$$ ($$$n \\leq k \\leq 300$$$). Then output one line containing $$$k$$$ distinct integers $$$b_1, b_2, \\cdots, b_k$$$ ($$$-10^9 \\leq b_i \\leq 10^9$$$), the elements of the nice array $$$b$$$. $$$b_1, b_2, \\cdots, b_k$$$ can be in any order. For each $$$a_i$$$ in $$$a$$$, $$$a_i$$$ must appear at least once in $$$b$$$. It can be proved that if Omkar can create such an array $$$b$$$, then he can also do so in a way that satisfies the above constraints. If multiple solutions exist, you can print any. ", "sample_inputs": ["4\n3\n3 0 9\n2\n3 4\n5\n-7 3 13 -2 8\n4\n4 8 12 6"], "sample_outputs": ["yes\n4\n6 0 3 9\nyEs\n5\n5 3 1 2 4\nNO\nYes\n6\n8 12 6 2 4 10"], "notes": "NoteFor the first case, you can add integers to $$$a$$$ to receive the array $$$b = [6, 0, 3, 9]$$$. Note that $$$|6-3| = |9-6| = |3-0| = 3$$$ and $$$3$$$ is in $$$b$$$, $$$|6-0| = |9-3| = 6$$$ and $$$6$$$ is in $$$b$$$, and $$$|9-0| = 9$$$ is in $$$b$$$, so $$$b$$$ is nice.For the second case, you can add integers to $$$a$$$ to receive the array $$$b = [5, 3, 1, 2, 4]$$$. We have that $$$|2-1| = |3-2| = |4-3| = |5-4| = 1$$$ is in $$$b$$$, $$$|3-1| = |4-2| = |5-3| = 2$$$ is in $$$b$$$, $$$|4-1| = |5-2| = 3$$$ is in $$$b$$$, and $$$|5-1| = 4$$$ is in $$$b$$$, so $$$b$$$ is nice.For the fourth case, you can add integers to $$$a$$$ to receive the array $$$b = [8, 12, 6, 2, 4, 10]$$$. We have that $$$|4-2| = |6-4| = |8-6| = |10-8| = |12-10| = 2$$$ is in $$$b$$$, $$$|6-2| = |8-4| = |10-6| = |12-8| = 4$$$ is in $$$b$$$, $$$|8-2| = |10-4| = |12-6| = 6$$$ is in $$$b$$$, $$$|10-2| = |12-4| = 8$$$ is in $$$b$$$, and $$$|12-2| = 10$$$ is in $$$b$$$, so $$$b$$$ is nice.It can be proven that for all other test cases it is impossible to create a nice array $$$b$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let a = Array.init n read_int in\n Array.sort compare a;\n if a.(0) < 0 then printf \"NO\\n\" else (\n let g = fold 0 (n-1) (fun i ac -> gcd ac a.(i)) 0 in\n let allg = fold 1 (a.(n-1)/g) (fun i ac -> (i*g)::ac) (Array.to_list a) in\n let ans = List.sort_uniq compare allg in\n printf \"YES\\n\";\n printf \"%d\\n\" (List.length ans);\n List.iter (printf \"%d \") ans;\n print_newline()\n )\n done\n"}], "negative_code": [], "src_uid": "5698e6fd934b9f6b847d7e30a3d06f2b"} {"nl": {"description": "You are given a digital clock with $$$n$$$ digits. Each digit shows an integer from $$$0$$$ to $$$9$$$, so the whole clock shows an integer from $$$0$$$ to $$$10^n-1$$$. The clock will show leading zeroes if the number is smaller than $$$10^{n-1}$$$.You want the clock to show $$$0$$$ with as few operations as possible. In an operation, you can do one of the following: decrease the number on the clock by $$$1$$$, or swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show $$$0$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^3$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 number of digits on the clock. The second line of each test case contains a string of $$$n$$$ digits $$$s_1, s_2, \\ldots, s_n$$$ ($$$0 \\le s_1, s_2, \\ldots, s_n \\le 9$$$) \u2014 the number on the clock. Note: If the number is smaller than $$$10^{n-1}$$$ the clock will show leading zeroes.", "output_spec": "For each test case, print one integer: the minimum number of operations needed to make the clock show $$$0$$$.", "sample_inputs": ["7\n3\n007\n4\n1000\n5\n00000\n3\n103\n4\n2020\n9\n123456789\n30\n001678294039710047203946100020"], "sample_outputs": ["7\n2\n0\n5\n6\n53\n115"], "notes": "NoteIn the first example, it's optimal to just decrease the number $$$7$$$ times.In the second example, we can first swap the first and last position and then decrease the number by $$$1$$$.In the third example, the clock already shows $$$0$$$, so we don't have to perform any operations."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet l2n c = (int_of_char c) - (int_of_char '0')\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let d = read_int() in\n let s = read_string() in\n let answer = sum 0 (d-1) (fun i ->\n let x = l2n s.[i] in\n (if i = (d-1) || x=0 then 0 else 1) + x\n ) in\n printf \"%d\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "6571fdd506a858d7620c2faa0fe46cc1"} {"nl": {"description": "Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.", "input_spec": "The first line contains one integer n\u00a0\u2014 the number of vertices in the tree (3\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000). Each of the next n\u2009-\u20091 lines contains one integer pi (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091)\u00a0\u2014 the index of the parent of the i\u2009+\u20091-th vertex (1\u2009\u2264\u2009pi\u2009\u2264\u2009i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children.", "output_spec": "Print \"Yes\" if the tree is a spruce and \"No\" otherwise.", "sample_inputs": ["4\n1\n1\n1", "7\n1\n1\n1\n2\n2\n2", "8\n1\n1\n1\n1\n3\n3\n3"], "sample_outputs": ["Yes", "No", "Yes"], "notes": "NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:"}, "positive_code": [{"source_code": "type spruce = Leaf of int\n | Node of spruce list\n\nlet rec split num str = \n match str with\n | \"\" -> []\n | s ->\n let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnIntList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (int_of_string one) ::(returnIntList t \"\")\n else returnIntList t (one^h)\n | _ -> (int_of_string one) :: []\n\nlet splitToList line =\n let lineList = split 1 line in\n returnIntList lineList \"\"\n\n\nlet rec makePairList numList num =\n match numList with\n | h :: t -> (h, num) :: (makePairList t (num+1))\n | _ -> []\n\nlet rec makeNode pairList num =\n match pairList with\n | (a,b) :: t -> \n if (num == a) then \n Node (Leaf(b) :: (makeNode t b)) :: (makeNode t num)\n else makeNode t num\n | _ -> []\n\nlet rec countLeaf node =\n match node with\n | Node(Leaf(a) :: []) ::t -> 1 + countLeaf t\n | Node(Leaf(a) :: t) :: tail -> countLeaf tail\n | _ -> 0\n\nlet rec checkNotAllNode node =\n match node with\n | Node (Leaf(b) :: []) :: tail -> true\n | Node (Leaf(a) :: t) :: [] -> false\n | Node (Leaf(a) :: t) :: tail -> checkNotAllNode tail\n | _ -> true\n\nlet rec countSpruce spruce =\n match spruce with\n | Node (Leaf(a) :: t) :: tail ->\n let num = countLeaf t in\n if (num >= 3 || num == 0) && (checkNotAllNode t) == true then \n countSpruce t && countSpruce tail\n else false\n | _ -> true\n\nlet printLeaf leaf = \n match leaf with\n | Leaf(a) -> print_string \"[Leaf : \";print_int a; print_string \"]\"\n | _ -> print_string \" \"\n\nlet rec printNode node = \n match node with\n | Node (h :: t) :: tail -> \n print_string \"[Node : \";printLeaf h; printNode t;print_string\"]\";\n printNode tail\n | _ -> print_string \" \"\n\nlet n = read_int()\nlet rec numList k =\n if (k < n) then \n let m = read_int() in\n m :: (numList (k+1))\n else []\n\nlet pairList = makePairList (numList 1) 2\n\nlet newSpruce =\n Node (Leaf(1) :: (makeNode pairList 1)) :: []\n\n\nlet _ = \n if (countSpruce newSpruce) then print_string \"Yes\"\n else print_string \"No\"\n"}, {"source_code": "(* Codeforces 913 B Christmas Spruce *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet rec revert l acc = match l with\n\t| [] -> acc\n\t| h :: t ->\n\t\t\tlet aa = h :: acc in\n\t\t\trevert t aa;;\n\nlet rec setna na li idx =\n\tif idx = 0 then \n\t\tbegin\n\t\t\tna.(0) <- [];\n\t\t\tsetna na li (idx + 1)\n\t\tend\n\telse\n\t\tmatch li with\n\t\t| [] -> ()\n\t\t| h :: t ->\n\t\t\t\tbegin\n\t\t\t\t\tna.(h - 1) <- idx :: na.(h - 1);\n\t\t\t\t\tsetna na t (idx + 1)\n\t\t\t\tend;;\n\n(* count elements of numa array with idndexes in li *)\nlet rec arr_count numa li = match li with\n\t| [] -> 0\n\t| h :: t -> numa.(h) + arr_count numa t;;\n\nlet is_leaf li = match li with\n\t| [] -> 1\n\t| _ -> 0;;\n\n(* count lefes for current root, returns (isLeaf, good) *)\nlet check_node na is_leafa idx =\n\t(* let _ = begin \n\t\tprint_string \"\\n check_node \"; \n\t\tprint_int idx;\n\t print_string \" na_idx \";\n\t\t\tprintlisti na.(idx)\n\t end in *)\n\tlet lcnt = arr_count is_leafa na.(idx) in\n\tif is_leafa.(idx) = 0 then lcnt >= 3\n\telse true;;\n\nlet rec all_true idx f nmax =\n\tif idx < nmax then (f idx) && all_true (idx + 1) f nmax\n\telse true;;\n\nlet main() =\n\tlet n = gr() in\n\tlet a = readlist (n - 1) [] in\n\tlet ar = revert a [] in\n (* let _ = printlisti ar in *) \n\tlet na = Array.make n [] in\n\tlet _ = setna na ar 0 in\n\tlet is_leafa = Array.map is_leaf na in\n\tbegin\n\t\t(*print_string \"\\n is_leafa: \";\n\t\tprintarri is_leafa;*) \n\t\tlet simp_check i = check_node na is_leafa i in\n\t\tlet ok = all_true 0 simp_check n in\n\t\tif ok then print_string \"Yes\"\n\t\telse print_string \"No\"\n\tend;;\n\nmain();;"}], "negative_code": [{"source_code": "type spruce = Leaf of int\n | Node of spruce list\n\nlet rec split num str = \n match str with\n | \"\" -> []\n | s ->\n let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnIntList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (int_of_string one) ::(returnIntList t \"\")\n else returnIntList t (one^h)\n | _ -> (int_of_string one) :: []\n\nlet splitToList line =\n let lineList = split 1 line in\n returnIntList lineList \"\"\n\n\nlet rec makePairList numList num =\n match numList with\n | h :: t -> (h, num) :: (makePairList t (num+1))\n | _ -> []\n\nlet rec makeNode pairList num =\n match pairList with\n | (a,b) :: t -> \n if (num == a) then \n Node (Leaf(b) :: (makeNode t b)) :: (makeNode t num)\n else makeNode t num\n | _ -> []\n\nlet rec countLeaf node =\n match node with\n | Node(Leaf(a) :: []) ::t -> 1 + countLeaf t\n | Node(Leaf(a) :: t) :: tail -> countLeaf tail\n | _ -> 0\n\nlet rec checkNotAllNode node =\n match node with\n | Node (Leaf(b) :: []) :: tail -> true\n | Node (Leaf(a) :: t) :: [] -> false\n | Node (Leaf(a) :: t) :: tail -> checkNotAllNode tail\n | _ -> true\n\nlet rec countSpruce spruce =\n match spruce with\n | Node (Leaf(a) :: t) :: tail ->\n let num = countLeaf t in\n if (num == 3 || num == 0) && (checkNotAllNode t == true) then \n countSpruce t && countSpruce tail\n else false\n | _ -> true\n\nlet printLeaf leaf = \n match leaf with\n | Leaf(a) -> print_string \"[Leaf : \";print_int a; print_string \"]\"\n | _ -> print_string \" \"\n\nlet rec printNode node = \n match node with\n | Node (h :: t) :: tail -> \n print_string \"[Node : \";printLeaf h; printNode t;print_string\"]\";\n printNode tail\n | _ -> print_string \" \"\n\nlet n = read_int()\nlet rec numList k =\n if (k < n) then \n let m = read_int() in\n m :: (numList (k+1))\n else []\n\nlet pairList = makePairList (numList 1) 2\n\nlet newSpruce =\n Node (Leaf(1) :: (makeNode pairList 1)) :: []\n\n\nlet _ = \n if (countSpruce newSpruce) then print_string \"Yes\"\n else print_string \"No\"\n"}, {"source_code": "type spruce = Leaf of int\n | Node of spruce list\n\nlet rec split num str = \n match str with\n | \"\" -> []\n | s ->\n let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnIntList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (int_of_string one) ::(returnIntList t \"\")\n else returnIntList t (one^h)\n | _ -> (int_of_string one) :: []\n\nlet splitToList line =\n let lineList = split 1 line in\n returnIntList lineList \"\"\n\n\nlet rec makePairList numList num =\n match numList with\n | h :: t -> (h, num) :: (makePairList t (num+1))\n | _ -> []\n\nlet rec makeNode pairList num =\n match pairList with\n | (a,b) :: t -> \n if (num == a) then \n Node (Leaf(b) :: (makeNode t b)) :: (makeNode t num)\n else makeNode t num\n | _ -> []\n\nlet rec countLeaf node =\n match node with\n | Node(Leaf(a) :: []) ::t -> 1 + countLeaf t\n | Node(Leaf(a) :: t) :: tail -> countLeaf tail\n | _ -> 0\n\nlet rec countSpruce spruce =\n match spruce with\n | Node (Leaf(a) :: t) :: tail ->\n let num = countLeaf t in\n if (num == 3 || num == 0) then \n countSpruce t && countSpruce tail\n else false\n | _ -> true\n\nlet printLeaf leaf = \n match leaf with\n | Leaf(a) -> print_string \"[Leaf : \";print_int a; print_string \"]\"\n | _ -> print_string \" \"\n\nlet rec printNode node = \n match node with\n | Node (h :: t) :: tail -> \n print_string \"[Node : \";printLeaf h; printNode t;print_string\"]\";\n printNode tail\n | _ -> print_string \" \"\n\nlet n = read_int()\nlet rec numList k =\n if (k < n) then \n let m = read_int() in\n m :: (numList (k+1))\n else []\n\nlet pairList = makePairList (numList 1) 2\n\nlet newSpruce =\n Node (Leaf(1) :: (makeNode pairList 1)) :: []\n\n\nlet _ = \n if (countSpruce newSpruce) then print_string \"Yes\"\n else print_string \"No\"\n"}, {"source_code": "type spruce = Leaf of int\n | Node of spruce list\n\nlet rec split num str = \n match str with\n | \"\" -> []\n | s ->\n let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnIntList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (int_of_string one) ::(returnIntList t \"\")\n else returnIntList t (one^h)\n | _ -> (int_of_string one) :: []\n\nlet splitToList line =\n let lineList = split 1 line in\n returnIntList lineList \"\"\n\n\nlet rec makePairList numList num =\n match numList with\n | h :: t -> (h, num) :: (makePairList t (num+1))\n | _ -> []\n\nlet rec makeNode pairList num =\n match pairList with\n | (a,b) :: t -> \n if (num == a) then \n Node (Leaf(b) :: (makeNode t b)) :: (makeNode t num)\n else makeNode t num\n | _ -> []\n\nlet rec countLeaf node =\n match node with\n | Node(Leaf(a) :: []) ::t -> 1 + countLeaf t\n | Node(Leaf(a) :: t) :: tail -> countLeaf tail\n | _ -> 0\n\nlet rec checkNotAllNode node =\n match node with\n | Node (Leaf(b) :: []) :: tail -> true\n | Node (Leaf(a) :: t) :: [] -> false\n | Node (Leaf(a) :: t) :: tail -> checkNotAllNode tail\n | _ -> true\n\nlet rec countSpruce spruce =\n match spruce with\n | Node (Leaf(a) :: t) :: tail ->\n let num = countLeaf t in\n if (num == 3 || num == 0) && (checkNotAllNode t == true) then \n countSpruce t && countSpruce tail\n else false\n | _ -> true\n\nlet printLeaf leaf = \n match leaf with\n | Leaf(a) -> print_string \"[Leaf : \";print_int a; print_string \"]\"\n | _ -> print_string \" \"\n\nlet rec printNode node = \n match node with\n | Node (h :: t) :: tail -> \n print_string \"[Node : \";printLeaf h; printNode t;print_string\"]\";\n printNode tail\n | _ -> print_string \" \"\n\nlet n = read_int()\nlet rec numList k =\n if (k < n) then \n let m = read_int() in\n m :: (numList (k+1))\n else []\n\nlet pairList = makePairList (numList 1) 2\n\nlet newSpruce =\n Node (Leaf(1) :: (makeNode pairList 1)) :: []\n\nlet _ = \n if (countSpruce newSpruce) then print_string \"Yes\"\n else print_string \"No\""}], "src_uid": "69edc72ec29d4dd56751b281085c3591"} {"nl": {"description": "There are some beautiful girls in Arpa\u2019s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i,\u2009j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n) such that , where is bitwise xor operation (see notes for explanation). Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.", "input_spec": "First line contains two integers n and x (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009x\u2009\u2264\u2009105)\u00a0\u2014 the number of elements in the array and the integer x. Second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105)\u00a0\u2014 the elements of the array.", "output_spec": "Print a single integer: the answer to the problem.", "sample_inputs": ["2 3\n1 2", "6 1\n5 1 2 3 4 1"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first sample there is only one pair of i\u2009=\u20091 and j\u2009=\u20092. so the answer is 1.In the second sample the only two pairs are i\u2009=\u20093, j\u2009=\u20094 (since ) and i\u2009=\u20091, j\u2009=\u20095 (since ).A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n \nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = read_int () in \n let a = Array.init n (fun _ -> read_int()) in\n\n let h = Hashtbl.create 10 in\n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n let get k = try Hashtbl.find h k with Not_found -> 0 in \n\n for i=0 to n-1 do increment a.(i) done;\n\n let answer = if x = 0 then (\n Hashtbl.fold (fun _ c ac -> let c = long c in ac ++ c**(c--1L)//2L) h 0L\n ) else (\n (sum 0 (n-1) (fun i -> long (get (x lxor a.(i))))) // 2L\n )\n in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "daabf732540e0f66d009dc211c2d7b0b"} {"nl": {"description": "Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009k\u2009<\u2009n\u2009\u2264\u2009105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph. The second line contains space-separated integers d[1],\u2009d[2],\u2009...,\u2009d[n] (0\u2009\u2264\u2009d[i]\u2009<\u2009n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.", "output_spec": "If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0\u2009\u2264\u2009m\u2009\u2264\u2009106) \u2014 the number of edges in the found graph. In each of the next m lines print two space-separated integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.", "sample_inputs": ["3 2\n0 1 1", "4 2\n2 0 1 3", "3 1\n0 0 0"], "sample_outputs": ["3\n1 2\n1 3\n3 2", "3\n1 3\n1 4\n2 3", "-1"], "notes": null}, "positive_code": [{"source_code": "let n = Scanf.scanf \"%d \" (fun x -> x);;\nlet k = Scanf.scanf \"%d\\n\" (fun x -> x);;\n\nlet tab = Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x));;\n\nlet liste = ref [];;\n\nfor i=0 to n-1 do\n liste := (tab.(i), i)::!liste;\ndone;\n\nliste := List.sort (fun (x,_) -> fun (y,_) -> x - y) !liste;\n\nlet _,debut = List.hd !liste in\nliste := List.tl !liste;\n\nlet en_cours = Queue.create () in\nlet arete = Array.make n [] in\nlet nb_arete = Array.make n 0 in\nlet res = ref 0 in\n\nQueue.push debut en_cours;\n\nwhile not (Queue.is_empty en_cours) do\n let actuel = Queue.pop en_cours in\n while (nb_arete.(actuel) < k)\n & (!liste <> [])\n & (tab.(snd (List.hd !liste)) = tab.(actuel) + 1) do\n let suivant = snd (List.hd !liste) in\n arete.(actuel) <- suivant::arete.(actuel);\n nb_arete.(actuel) <- 1 + nb_arete.(actuel);\n nb_arete.(suivant) <- 1 + nb_arete.(suivant);\n res := !res + 1;\n Queue.push suivant en_cours;\n liste := List.tl !liste;\n done;\ndone;\n\nlet tab2 = Array.make n 1000000000 in\ntab2.(debut) <- 0;\nQueue.push debut en_cours;\n\nwhile not (Queue.is_empty en_cours) do\n let actuel = Queue.pop en_cours in\n List.iter (fun x -> if tab2.(x) = 1000000000 then begin\n Queue.push x en_cours;\n tab2.(x) <- tab2.(actuel) + 1\n end) arete.(actuel);\ndone;\n\nlet valide = ref true in\nfor i=0 to n-1 do\n if tab.(i) <> tab2.(i)\n then valide := false;\ndone;\n\nif !valide then begin\n print_int !res;\n print_newline ();\n for i=0 to n-1 do\n List.iter (fun x -> print_int (i+1);\n print_string \" \";\n print_int (x+1);\n print_newline()) arete.(i);\n done;\nend else print_string \"-1\\n\";"}], "negative_code": [{"source_code": "let n = Scanf.scanf \"%d \" (fun x -> x);;\nlet k = Scanf.scanf \"%d\\n\" (fun x -> x);;\n\nlet tab = Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x));;\n\nlet liste = ref [];;\n\nfor i=0 to n-1 do\n liste := (tab.(i), i)::!liste;\ndone;\n\nliste := List.sort (fun (x,_) -> fun (y,_) -> x - y) !liste;\n\nlet _,debut = List.hd !liste in\nliste := List.tl !liste;\n\nlet en_cours = Queue.create () in\nlet arete = Array.make n [] in\nlet nb_arete = Array.make n 0 in\nlet res = ref 0 in\n\nQueue.push debut en_cours;\n\nwhile not (Queue.is_empty en_cours) do\n let actuel = Queue.pop en_cours in\n while (nb_arete.(actuel) < k)\n & (!liste <> [])\n & (tab.(snd (List.hd !liste)) = tab.(actuel) + 1) do\n let suivant = snd (List.hd !liste) in\n arete.(actuel) <- suivant::arete.(actuel);\n nb_arete.(actuel) <- 1 + nb_arete.(actuel);\n nb_arete.(suivant) <- 1 + nb_arete.(suivant);\n res := !res + 1;\n Queue.push suivant en_cours;\n liste := List.tl !liste;\n done;\ndone;\n\nlet tab2 = Array.make n 1000000000 in\ntab2.(debut) <- 0;\nQueue.push debut en_cours;\n\nwhile not (Queue.is_empty en_cours) do\n let actuel = Queue.pop en_cours in\n List.iter (fun x -> if tab2.(x) = 1000000000 then begin\n Queue.push x en_cours;\n tab2.(x) <- tab2.(actuel) + 1\n end) arete.(actuel);\ndone;\n\nlet valide = ref true in\nfor i=0 to n-1 do\n if tab.(i) <> tab2.(i)\n then valide := false;\ndone;\n\nif !valide then begin\n print_int !res;\n print_newline ();\nend else print_string \"-1\\n\";\nfor i=0 to n-1 do\n List.iter (fun x -> print_int (i+1);\n print_string \" \";\n print_int (x+1);\n print_newline()) arete.(i);\ndone"}, {"source_code": "let n = Scanf.scanf \"%d \" (fun x -> x);;\nlet k = Scanf.scanf \"%d\\n\" (fun x -> x);;\n\nlet tab = Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x));;\n\nlet liste = ref [];;\n\nfor i=0 to n-1 do\n liste := (tab.(i), i)::!liste;\ndone;\n\nliste := List.sort (fun (x,_) -> fun (y,_) -> x - y) !liste;\n\nlet _,debut = List.hd !liste in\nliste := List.tl !liste;\n\nlet en_cours = Queue.create () in\nlet arete = Array.make n [] in\nlet nb_arete = Array.make n 0 in\nlet res = ref 0 in\n\nQueue.push debut en_cours;\n\nwhile not (Queue.is_empty en_cours) do\n let actuel = Queue.pop en_cours in\n while (nb_arete.(actuel) < k)\n & (!liste <> [])\n & (tab.(snd (List.hd !liste)) = tab.(actuel) + 1) do\n let suivant = snd (List.hd !liste) in\n arete.(actuel) <- suivant::arete.(actuel);\n nb_arete.(actuel) <- 1+ nb_arete.(actuel);\n res := !res + 1;\n Queue.push suivant en_cours;\n liste := List.tl !liste;\n done;\ndone;\n\nlet tab2 = Array.make n 1000000000 in\ntab2.(debut) <- 0;\nQueue.push debut en_cours;\n\nwhile not (Queue.is_empty en_cours) do\n let actuel = Queue.pop en_cours in\n List.iter (fun x -> if tab2.(x) = 1000000000 then begin\n Queue.push x en_cours;\n tab2.(x) <- tab2.(actuel) + 1\n end) arete.(actuel);\ndone;\n\nlet valide = ref true in\nfor i=0 to n-1 do\n if tab.(i) <> tab2.(i)\n then valide := false;\ndone;\n\nif !valide then begin\n print_int !res;\n print_newline ();\nend else print_string \"-1\\n\";\nfor i=0 to n-1 do\n List.iter (fun x -> print_int (i+1);\n print_string \" \";\n print_int (x+1);\n print_newline()) arete.(i);\ndone"}], "src_uid": "73668a75036dce819ff27c316de378af"} {"nl": {"description": "The new \"Die Hard\" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A \"Die Hard\" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 \u2014 the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.", "output_spec": "Print \"YES\" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print \"NO\".", "sample_inputs": ["4\n25 25 50 50", "2\n25 100", "4\n50 50 25 25"], "sample_outputs": ["YES", "NO", "NO"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\nlet print str = Printf.printf \"%s\\n\" str\n\nlet check int n =\n if int >= n\n then\n true\n else\n false\n\nlet () = \n let n = read () in\n let rec loop i quart half = \n if i < n\n then\n let cash = read () in\n match cash with\n | 25 -> loop (i + 1) (quart + 1) half\n | 50 -> \n if check quart 1\n then \n loop (i + 1) (quart - 1) (half + 1)\n else\n print \"NO\"\n | 100 -> \n if check half 1 && check quart 1\n then \n loop (i + 1) (quart - 1) (half - 1)\n else\n if check quart 3\n then\n loop (i + 1) (quart - 3) half\n else\n print \"NO\"\n else\n print \"YES\"\n in loop 0 0 0"}, {"source_code": "(* Codeforces 349 A Cinema Line *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet rec can_change l n50 n25 = match l with\n\t| [] -> \"YES\"\n\t| h :: t -> match h with\n\t\t\t| 25 -> can_change t n50 (n25 + 1)\n\t\t\t| 50 -> if n25 ==0 then \"NO\" else can_change t (n50 +1) (n25 -1)\n\t\t\t| 100 -> if (2 * n50 + n25 < 3) || (n25 == 0)then \"NO\"\n\t\t\t\t\telse if n50 >0 then can_change t (n50 -1) (n25 -1)\n\t\t\t\t\telse can_change t n50 (n25 -3)\n\t\t\t| _ -> \"Error, wrong n\";;\n\nlet main() =\n\tlet n = gr() in\n\tlet l = readlist (n) [] in\n\tlet li = List.rev l in\n\tlet ans = can_change li 0 0 in\n\tbegin\n\t\tprint_string (ans ^ \"\\n\")\n\tend;;\n\nmain();;"}], "negative_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\nlet print str = Printf.printf \"%s\\n\" str\n\nlet check int n =\n if int >= n\n then\n true\n else\n false\n\nlet () = \n let n = read () in\n let rec loop i quart half = \n if i < n\n then\n let cash = read () in\n match cash with\n | 25 -> loop (i + 1) (quart + 1) half\n | 50 -> \n if check quart 1\n then \n loop (i + 1) (quart - 1) (half + 1)\n else\n print \"NO\"\n | 100 -> \n if check half 1 && check quart 1 || check quart 3\n then \n loop (i + 1) (quart - 1) (half - 1)\n else\n if check quart 3\n then\n loop (i + 1) (quart - 3) half\n else\n print \"NO\"\n else\n print \"YES\"\n in loop 0 0 0"}, {"source_code": "(* Codeforces 349 A Cinema Line *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet rec can_change l n50 n25 = match l with\n\t| [] -> \"YES\"\n\t| h :: t -> match h with\n\t\t\t| 25 -> can_change t n50 (n25 + 1)\n\t\t\t| 50 -> if n25 ==0 then \"NO\" else can_change t (n50 +1) (n25 -1)\n\t\t\t| 100 -> if (2 * n50 + n25 < 3) || (n50 == 0)then \"NO\"\n\t\t\t\t\telse if n50 >0 then can_change t (n50 -1) (n25 -1)\n\t\t\t\t\telse can_change t n50 (n25 -3)\n\t\t\t| _ -> \"Error, wrong n\";;\n\nlet main() =\n\tlet n = gr() in\n\tlet l = readlist (n) [] in\n\tlet li = List.rev l in\n\tlet ans = can_change li 0 0 in\n\tbegin\n\t\tprint_string (ans ^ \"\\n\")\n\tend;;\n\nmain();;"}], "src_uid": "63b20ab2993fddf2cc469c4c4e8027df"} {"nl": {"description": "Qwerty the Ranger arrived to the Diatar system with a very important task. He should deliver a special carcinogen for scientific research to planet Persephone. This is urgent, so Qwerty has to get to the planet as soon as possible. A lost day may fail negotiations as nobody is going to pay for an overdue carcinogen.You can consider Qwerty's ship, the planet Persephone and the star Diatar points on a plane. Diatar is located in the origin of coordinate axes \u2014 at point (0,\u20090). Persephone goes round Diatar along a circular orbit with radius R in the counter-clockwise direction at constant linear speed vp (thus, for instance, a full circle around the star takes of time). At the initial moment of time Persephone is located at point (xp,\u2009yp).At the initial moment of time Qwerty's ship is at point (x,\u2009y). Qwerty can move in any direction at speed of at most v (v\u2009>\u2009vp). The star Diatar is hot (as all stars), so Qwerty can't get too close to it. The ship's metal sheathing melts at distance r (r\u2009<\u2009R) from the star.Find the minimum time Qwerty needs to get the carcinogen to planet Persephone.", "input_spec": "The first line contains space-separated integers xp, yp and vp (\u2009-\u2009104\u2009\u2264\u2009xp,\u2009yp\u2009\u2264\u2009104, 1\u2009\u2264\u2009vp\u2009<\u2009104) \u2014 Persephone's initial position and the speed at which it goes round Diatar. The second line contains space-separated integers x, y, v and r (\u2009-\u2009104\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009104, 1\u2009<\u2009v\u2009\u2264\u2009104, 1\u2009\u2264\u2009r\u2009\u2264\u2009104) \u2014 The intial position of Qwerty's ship, its maximum speed and the minimum safe distance to star Diatar. It is guaranteed that r2\u2009<\u2009x2\u2009+\u2009y2, r2\u2009<\u2009xp2\u2009+\u2009yp2 and vp\u2009<\u2009v.", "output_spec": "Print a single real number \u2014 the minimum possible delivery time. The answer will be considered valid if its absolute or relative error does not exceed 10\u2009-\u20096.", "sample_inputs": ["10 0 1\n-10 0 2 8", "50 60 10\n50 60 20 40"], "sample_outputs": ["9.584544103", "0.000000000"], "notes": null}, "positive_code": [{"source_code": "let pi = 4.0 *. atan 1.0\nlet pi2 = 2.0 *. pi\nlet sqr x = x *. x\n\nlet circle_zero_tangent x y r =\n let sxy = sqr x +. sqr y in\n let d = sxy -. sqr r in\n if d > 0.0 then (\n let sd = sqrt d in\n let c1 = (-. r *. x +. y *. sd) /. sxy in\n let c2 = (-. r *. x -. y *. sd) /. sxy in\n let check t =\n\t(x +. r *. cos t) *. (r *. cos t) +.\n\t (y +. r *. sin t) *. (r *. sin t)\n in\n let t1 = acos c1\n and t2 = -. acos c1\n and t3 = acos c2\n and t4 = -. acos c2 in\n let t11 =\n\tif abs_float (check t1) < abs_float (check t2)\n\tthen t1\n\telse t2\n in\n let t21 =\n\tif abs_float (check t3) <= abs_float (check t4)\n\tthen t3\n\telse t4\n in\n\tSome (t11, t21)\n\t(*Some (acos c1, -. acos c1, acos c2, -. acos c2,\n\t\tcheck (acos c1), check (-. acos c1),\n\t\tcheck (acos c2), check (-. acos c2))*)\n(*\tif abs_float c1 <= 1.0 then\n\t Some (acos c1, -. acos c1)\n\telse if abs_float c2 <= 1.0 then\n\t Some (acos c2, -. acos c2)\n\telse\n\t None*)\n ) else\n None\n\nlet point_circle_tangent x1 y1 x2 y2 r2 =\n match circle_zero_tangent (x2 -. x1) (y2 -. y1) r2 with\n | Some (t1, t2) ->\n\tlet t1 = t1 +. pi /. 2.0\n\tand t2 = t2 +. pi /. 2.0 in\n\t Some ((-. sin t1, cos t1, x1 *. sin t1 -. y1 *. cos t1),\n\t\t(-. sin t2, cos t2, x1 *. sin t2 -. y1 *. cos t2))\n | None -> None\n\n\nlet norm x y =\n sqrt (sqr x +. sqr y)\n\nlet dist x1 y1 x2 y2 =\n norm (x1 -. x2) (y1 -. y2)\n\nlet point_line_distance x y a b c =\n let sab = sqr a +. sqr b in\n abs_float (a *. x +. b *. y +. c) /. sqrt sab\n\nlet point_line_projection x y a b c =\n let sab = sqr a +. sqr b in\n let ab = sqrt sab in\n let d = -. (a *. x +. b *. y +. c) /. ab in\n let dx = d *. a /. ab\n and dy = d *. b /. ab in\n (x +. dx, y +. dy)\n\nlet point_line_projection_vec x y a b c =\n let sab = sqr a +. sqr b in\n let ab = sqrt sab in\n let r =\n if (a *. x +. b *. y +. c) >= 0.\n then -1.0\n else 1.0\n in\n let dx = r *. a /. ab\n and dy = r *. b /. ab in\n (dx, dy)\n\nlet point_line_projection_dist x y a b c r =\n let (dx, dy) = point_line_projection_vec x y a b c in\n (x +. r *. dx, y +. r *. dy)\n\nlet point_segment_dist x y x1 y1 x2 y2 =\n let vx = x2 -. x1\n and vy = y2 -. y1\n and wx = x -. x1\n and wy = y -. y1 in\n let c1 = wx *. vx +. wy *. vy in\n if c1 <= 0.0 then\n dist x y x1 y1\n else\n let c2 = sqr vx +. sqr vy in\n\tif c2 <= c1 then\n\t dist x y x2 y2\n\telse\n\t let b = c1 /. c2 in\n\t let px = x1 +. b *. vx\n\t and py = y1 +. b *. vy in\n\t dist x y px py\n\n\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let xp = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let yp = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let vp = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let x = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let v = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let omega = 2.0 *. pi *. sqrt (sqr xp +. sqr yp) /. vp in\n let ppos t =\n let alpha = 2.0 *. pi *. t /. omega in\n let x = xp *. cos alpha -. yp *. sin alpha in\n let y = xp *. sin alpha +. yp *. cos alpha in\n (x, y)\n in\n let tr = 2.0 *. (sqrt (sqr (xp -. x) +. sqr (yp -. y)) +. r) /. (v -. vp) in\n let tl = 0.0 in\n let tr = ref tr in\n let tl = ref tl in\n for i = 1 to 100 do\n let tm = (!tl +. !tr) /. 2.0 in\n let (xp, yp) = ppos tm in\n let t =\n\tif point_segment_dist 0.0 0.0 x y xp yp < r then (\n\t let (x11, y11, x12, y12) =\n\t match point_circle_tangent x y 0.0 0.0 r with\n\t | Some ((a1, b1, c1), (a2, b2, c2)) ->\n\t\t let (x1, y1) = point_line_projection_vec 0.0 0.0 a1 b1 c1 in\n\t\t let (x2, y2) = point_line_projection_vec 0.0 0.0 a2 b2 c2 in\n\t\t (x1 *.r , y1 *. r, x2 *.r , y2 *. r)\n\t | None -> assert false\n\t in\n\t let (x21, y21, x22, y22) =\n\t match point_circle_tangent xp yp 0.0 0.0 r with\n\t | Some ((a1, b1, c1), (a2, b2, c2)) ->\n\t\t let (x1, y1) = point_line_projection_vec 0.0 0.0 a1 b1 c1 in\n\t\t let (x2, y2) = point_line_projection_vec 0.0 0.0 a2 b2 c2 in\n\t\t (x1 *.r , y1 *. r, x2 *.r , y2 *. r)\n\t | None -> assert false\n\t in\n\t let t = ref infinity in\n\t List.iter\n\t (fun (x1, y1, x2, y2) ->\n\t\t let c = dist x1 y1 x2 y2 in\n\t\t let beta = acos ((2.0 *. sqr r -. sqr c) /. (2.0 *. sqr r)) in\n(*Printf.printf \"qwe %f %f %f %f %f\\n\" x1 y1 x2 y2 beta;*)\n\t\t let d =\n\t\t dist x y x1 y1 +. beta *. r +. dist x2 y2 xp yp\n\t\t in\n\t\t let t' = d /. v in\n\t\t t := min !t t'\n\t ) [ (x11, y11, x21, y21);\n\t\t (x11, y11, x22, y22);\n\t\t (x12, y12, x21, y21);\n\t\t (x12, y12, x22, y22);\n\t\t];\n\t !t\n\t) else (\n\t dist x y xp yp /. v\n\t)\n in\n(*Printf.printf \"asd %f %f %f %f\\n\" tm t xp yp;*)\n\tif t < tm\n\tthen tr := tm\n\telse tl := tm\n done;\n let res = (!tl +. !tr) /. 2.0 in\n Printf.printf \"%.6f\\n\" res\n"}], "negative_code": [{"source_code": "let pi = 4.0 *. atan 1.0\nlet pi2 = 2.0 *. pi\nlet sqr x = x *. x\n\nlet circle_zero_tangent x y r =\n let sxy = sqr x +. sqr y in\n let d = sxy -. sqr r in\n if d > 0.0 then (\n let sd = sqrt d in\n let c1 = (-. r *. x +. y *. sd) /. sxy in\n let c2 = (-. r *. x -. y *. sd) /. sxy in\n let check t =\n\t(x +. r *. cos t) *. (r *. cos t) +.\n\t (y +. r *. sin t) *. (r *. sin t)\n in\n let t1 = acos c1\n and t2 = -. acos c1\n and t3 = acos c2\n and t4 = -. acos c2 in\n let t11 =\n\tif abs_float (check t1) < abs_float (check t2)\n\tthen t1\n\telse t2\n in\n let t21 =\n\tif abs_float (check t3) <= abs_float (check t4)\n\tthen t3\n\telse t4\n in\n\tSome (t11, t21)\n\t(*Some (acos c1, -. acos c1, acos c2, -. acos c2,\n\t\tcheck (acos c1), check (-. acos c1),\n\t\tcheck (acos c2), check (-. acos c2))*)\n(*\tif abs_float c1 <= 1.0 then\n\t Some (acos c1, -. acos c1)\n\telse if abs_float c2 <= 1.0 then\n\t Some (acos c2, -. acos c2)\n\telse\n\t None*)\n ) else\n None\n\nlet point_circle_tangent x1 y1 x2 y2 r2 =\n match circle_zero_tangent (x2 -. x1) (y2 -. y1) r2 with\n | Some (t1, t2) ->\n\tlet t1 = t1 +. pi /. 2.0\n\tand t2 = t2 +. pi /. 2.0 in\n\t Some ((-. sin t1, cos t1, x1 *. sin t1 -. y1 *. cos t1),\n\t\t(-. sin t2, cos t2, x1 *. sin t2 -. y1 *. cos t2))\n | None -> None\n\n\nlet norm x y =\n sqrt (sqr x +. sqr y)\n\nlet dist x1 y1 x2 y2 =\n norm (x1 -. x2) (y1 -. y2)\n\nlet point_line_distance x y a b c =\n let sab = sqr a +. sqr b in\n abs_float (a *. x +. b *. y +. c) /. sqrt sab\n\nlet point_line_projection x y a b c =\n let sab = sqr a +. sqr b in\n let ab = sqrt sab in\n let d = -. (a *. x +. b *. y +. c) /. ab in\n let dx = d *. a /. ab\n and dy = d *. b /. ab in\n (x +. dx, y +. dy)\n\nlet point_line_projection_vec x y a b c =\n let sab = sqr a +. sqr b in\n let ab = sqrt sab in\n let r =\n if (a *. x +. b *. y +. c) >= 0.\n then -1.0\n else 1.0\n in\n let dx = r *. a /. ab\n and dy = r *. b /. ab in\n (dx, dy)\n\nlet point_line_projection_dist x y a b c r =\n let (dx, dy) = point_line_projection_vec x y a b c in\n (x +. r *. dx, y +. r *. dy)\n\nlet point_segment_dist x y x1 y1 x2 y2 =\n let vx = x2 -. x1\n and vy = y2 -. y1\n and wx = x -. x1\n and wy = y -. y1 in\n let c1 = wx *. vx +. wy *. vy in\n if c1 <= 0.0 then\n dist x y x1 y1\n else\n let c2 = sqr vx +. sqr vy in\n\tif c2 <= c1 then\n\t dist x y x2 y2\n\telse\n\t let b = c1 /. c2 in\n\t let px = x1 +. b *. vx\n\t and py = y1 +. b *. vy in\n\t dist x y px py\n\n\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let xp = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let yp = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let vp = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let x = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let v = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let omega = 2.0 *. pi *. sqrt (sqr xp +. sqr yp) /. vp in\n let ppos t =\n let alpha = 2.0 *. pi *. t /. omega in\n let x = xp *. cos alpha -. yp *. sin alpha in\n let y = xp *. sin alpha +. yp *. cos alpha in\n (x, y)\n in\n let tr = 2.0 *. (sqrt (sqr (xp -. x) +. sqr (yp -. y)) +. r) /. v in\n let tl = 0.0 in\n let tr = ref tr in\n let tl = ref tl in\n for i = 1 to 100 do\n let tm = (!tl +. !tr) /. 2.0 in\n let (xp, yp) = ppos tm in\n let t =\n\tif point_segment_dist 0.0 0.0 x y xp yp < r then (\n\t let (x11, y11, x12, y12) =\n\t match point_circle_tangent x y 0.0 0.0 r with\n\t | Some ((a1, b1, c1), (a2, b2, c2)) ->\n\t\t let (x1, y1) = point_line_projection_vec 0.0 0.0 a1 b1 c1 in\n\t\t let (x2, y2) = point_line_projection_vec 0.0 0.0 a2 b2 c2 in\n\t\t (x1 *.r , y1 *. r, x2 *.r , y2 *. r)\n\t | None -> assert false\n\t in\n\t let (x21, y21, x22, y22) =\n\t match point_circle_tangent xp yp 0.0 0.0 r with\n\t | Some ((a1, b1, c1), (a2, b2, c2)) ->\n\t\t let (x1, y1) = point_line_projection_vec 0.0 0.0 a1 b1 c1 in\n\t\t let (x2, y2) = point_line_projection_vec 0.0 0.0 a2 b2 c2 in\n\t\t (x1 *.r , y1 *. r, x2 *.r , y2 *. r)\n\t | None -> assert false\n\t in\n\t let t = ref infinity in\n\t List.iter\n\t (fun (x1, y1, x2, y2) ->\n\t\t let c = dist x1 y1 x2 y2 in\n\t\t let beta = acos ((2.0 *. sqr r -. sqr c) /. (2.0 *. sqr r)) in\n(*Printf.printf \"qwe %f %f %f %f %f\\n\" x1 y1 x2 y2 beta;*)\n\t\t let d =\n\t\t dist x y x1 y1 +. beta *. r +. dist x2 y2 xp yp\n\t\t in\n\t\t let t' = d /. v in\n\t\t t := min !t t'\n\t ) [ (x11, y11, x21, y21);\n\t\t (x11, y11, x22, y22);\n\t\t (x12, y12, x21, y21);\n\t\t (x12, y12, x22, y22);\n\t\t];\n\t !t\n\t) else (\n\t dist x y xp yp /. v\n\t)\n in\n(*Printf.printf \"asd %f %f %f %f\\n\" tm t xp yp;*)\n\tif t < tm\n\tthen tr := tm\n\telse tl := tm\n done;\n let res = (!tl +. !tr) /. 2.0 in\n Printf.printf \"%.6f\\n\" res\n"}], "src_uid": "e8471556906e5fa3a701842570fa4ee2"} {"nl": {"description": "George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi\u2009\u2264\u2009qi). Your task is to count how many rooms has free place for both George and Alex.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of rooms. The i-th of the next n lines contains two integers pi and qi (0\u2009\u2264\u2009pi\u2009\u2264\u2009qi\u2009\u2264\u2009100) \u2014 the number of people who already live in the i-th room and the room's capacity.", "output_spec": "Print a single integer \u2014 the number of rooms where George and Alex can move in.", "sample_inputs": ["3\n1 1\n2 2\n3 3", "3\n1 10\n0 10\n10 10"], "sample_outputs": ["0", "2"], "notes": null}, "positive_code": [{"source_code": "let list_init n f =\n let rec read_input n new_list = \n if n > 0\n then\n let new_element = f() in\n read_input (n - 1) (new_element :: new_list)\n else\n List.rev new_list\n in read_input n []\n\nlet room_data n = list_init n (fun i -> Scanf.scanf \"%d %d \" (fun s0 s1 -> (s0, s1)))\n\nlet input () = \n let number_of_rooms = Scanf.scanf \"%d \" (fun n -> n) in\n room_data number_of_rooms\n\nlet solve list = List.length(List.filter(fun (a, b) -> b - a >= 2) list)\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input()))"}, {"source_code": "let read_int () =\n Scanf.scanf \" %d\" (fun x -> x)\n\nlet rec solve n ak =\n if n = 0 then\n ak\n else\n let p = read_int () in\n let q = read_int () in\n if q - p < 2 then\n solve (n - 1) ak\n else\n solve (n - 1) (ak + 1)\n\nlet () =\n let n = read_int () in\n Printf.printf \"%d\" (solve n 0)\n\n"}, {"source_code": "let list_init n f =\n let rec read_input n new_list =\n if n > 0\n then\n let new_element = f() in\n read_input (n - 1) (new_element :: new_list)\n else\n List.rev new_list\n in read_input n []\n\nlet room_data n = list_init n (fun i -> Scanf.scanf \"%d %d \" (fun s0 s1 -> (s0, s1)))\n\nlet input () =\n let number_of_rooms = Scanf.scanf \"%d \" (fun n -> n) in\n room_data number_of_rooms\n\nlet solve list = List.length(List.filter(fun (a, b) -> b - a >= 2) list)\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input ()));;\n"}, {"source_code": "open Printf\ntype room = R of int*int\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x) in\nlet read_int () = Scanf.scanf \"%d %d \" ( fun x y -> R(x,y)) in\nlet a = Array.init n (fun i -> read_int ()) in\nlet f = function\n | R (p,q) -> if q-p >=2 then true else false\nin Array.to_list a |>List.filter (fun x -> f x) |> List.length |> printf \"%d\\n\"\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = \n let x = read_int () and y = read_int () in\n (x, y)\n\n\nlet () =\n let n = read_int () in\n let a = Array.init n (fun _ -> read_pair ()) in\n\n print_int (Array.fold_left (fun acc pair -> if (fst(pair) + 2 <= snd(pair)) then acc + 1 else acc) 0 a);\n print_newline ();\n"}], "negative_code": [], "src_uid": "2a6c457012f7ceb589b3dea6b889f7cb"} {"nl": {"description": "Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?", "input_spec": "The first line contains the only integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of cookie bags Anna and Maria have. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) \u2014 the number of cookies in the i-th bag.", "output_spec": "Print in the only line the only number \u2014 the sought number of ways. If there are no such ways print 0.", "sample_inputs": ["1\n1", "10\n1 2 2 3 4 4 4 2 2 2", "11\n2 2 2 2 2 2 2 2 2 2 99"], "sample_outputs": ["1", "8", "1"], "notes": "NoteIn the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies \u2014 5\u2009+\u20093\u2009=\u20098 ways in total.In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2\u2009*\u20099\u2009+\u200999\u2009=\u2009117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies."}, "positive_code": [{"source_code": "(* Read first line input and return numbers *)\nlet read_nums str =\n let nstrings = Str.split (Str.regexp \" \") str in\n List.map (fun x -> int_of_string x) nstrings\nin\nignore (read_line ());\nlet p = read_line () in\nlet pck = read_nums p in\nlet methods_count packs =\n let count = ref 0 in\n let list_sum list =\n let sum = ref 0 in\n List.iter (fun x -> sum := !sum + x) list;\n !sum\n in\n let lsum = list_sum packs in\n let even = lsum mod 2 = 0 in\n let comparefun' e =\n match e with\n\ttrue -> fun x -> x mod 2 = 0\n | false -> fun x -> x mod 2 <> 0\n in\n let compare = comparefun' even in\n List.iter (fun x -> if compare x then\n count := !count + 1\n ) packs;\n !count\nin\nprint_int (methods_count pck)\n"}], "negative_code": [], "src_uid": "4c59b4d43b59c8659bf274f3e29d01fe"} {"nl": {"description": "Find the number of k-divisible numbers on the segment [a,\u2009b]. In other words you need to find the number of such integer values x that a\u2009\u2264\u2009x\u2009\u2264\u2009b and x is divisible by k.", "input_spec": "The only line contains three space-separated integers k, a and b (1\u2009\u2264\u2009k\u2009\u2264\u20091018;\u2009-\u20091018\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009\u2264\u20091018).", "output_spec": "Print the required number.", "sample_inputs": ["1 1 10", "2 -4 4"], "sample_outputs": ["10", "5"], "notes": null}, "positive_code": [{"source_code": "let [x; a; b] = List.map (Int64.of_string) (Str.split (Str.regexp \" \") (read_line ()));; \nlet k = ref (Int64.div a x);;\nif ((Int64.mul !k x) < a) then k := Int64.add !k 1L;;\nlet t = Int64.sub b (Int64.mul x !k) and ans = ref 0L;;\nif t >= 0L then\tans := Int64.add (Int64.div t x) 1L;;\nprint_string (Int64.to_string !ans);; \n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let c = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let quot x y =\n let d = x /| y in\n let x' = d *| y in\n if x' <= x\n then d\n else d -| 1L\n in\n let res = quot b c -| quot (a -| 1L) c in\n Printf.printf \"%Ld\\n\" res\n"}], "negative_code": [], "src_uid": "98de093d78f74273e0ac5c7886fb7a41"} {"nl": {"description": "You are the gym teacher in the school.There are $$$n$$$ students in the row. And there are two rivalling students among them. The first one is in position $$$a$$$, the second in position $$$b$$$. Positions are numbered from $$$1$$$ to $$$n$$$ from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions $$$p$$$ and $$$s$$$ respectively, then distance between them is $$$|p - s|$$$. You can do the following operation at most $$$x$$$ times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most $$$x$$$ swaps.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The only line of each test case contains four integers $$$n$$$, $$$x$$$, $$$a$$$ and $$$b$$$ ($$$2 \\le n \\le 100$$$, $$$0 \\le x \\le 100$$$, $$$1 \\le a, b \\le n$$$, $$$a \\neq b$$$) \u2014 the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.", "output_spec": "For each test case print one integer \u2014 the maximum distance between two rivaling students which you can obtain.", "sample_inputs": ["3\n5 1 3 2\n100 33 100 1\n6 0 2 3"], "sample_outputs": ["2\n99\n1"], "notes": "NoteIn the first test case you can swap students in positions $$$3$$$ and $$$4$$$. And then the distance between the rivals is equal to $$$|4 - 2| = 2$$$.In the second test case you don't have to swap students. In the third test case you can't swap students."}, "positive_code": [{"source_code": "let wczytaj () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet _ =\n let (t : int ref) = ref (wczytaj ()) in\n while !t > 0 do\n let n = wczytaj () and\n x = wczytaj () and\n a = wczytaj () and\n b = wczytaj () in\n let a = min a b and\n b = max a b in\n let odl = (b - a) in\n let delta = min (a - 1 + (n - b)) x in\n Printf.printf \"%d\\n\" (odl + delta);\n t := !t - 1;\n done\n;;\n\n\n\n"}], "negative_code": [], "src_uid": "1fd2619aabf4557093a59da804fd0e7b"} {"nl": {"description": "Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,\u2009o,\u2009i} and Igor has the set of letters {i,\u2009m,\u2009o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,\u2009o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,\u2009m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s\u2009=\u2009s1s2...sm is called lexicographically smaller than a string t\u2009=\u2009t1t2...tm (where s\u2009\u2260\u2009t) if si\u2009<\u2009ti where i is the smallest index such that si\u2009\u2260\u2009ti. (so sj\u2009=\u2009tj for all j\u2009<\u2009i)", "input_spec": "The first line of input contains a string s of length n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.", "output_spec": "The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.", "sample_inputs": ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"], "sample_outputs": ["fzfsirk", "xxxxxx", "ioi"], "notes": "NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx."}, "positive_code": [{"source_code": "module Letters =\nstruct\n type t = char * int\n let compare = Pervasives.compare\nend\n\nmodule Heap = Set.Make(Letters)\n\nlet rec oleg deb fin igr olg =\n if Heap.is_empty olg\n then (deb, fin)\n else if Heap.is_empty igr || fst (Heap.min_elt olg) >= fst (Heap.max_elt igr)\n then let x = Heap.max_elt olg in\n let olg_rmv = Heap.remove x olg in\n igor deb (x::fin) igr olg_rmv\n else let y = Heap.min_elt olg in\n let olg_rmv = Heap.remove y olg in\n igor (y::deb) fin igr olg_rmv\nand igor deb fin igr olg =\n if Heap.is_empty igr\n then (deb, fin)\n else if Heap.is_empty olg || fst (Heap.max_elt igr) <= fst (Heap.min_elt olg)\n then let x = Heap.min_elt igr in\n let igr_rmv = Heap.remove x igr in\n oleg deb (x::fin) igr_rmv olg\n else let y = Heap.max_elt igr in\n let igr_rmv = Heap.remove y igr in\n oleg (y::deb) fin igr_rmv olg\n\nlet rec first_aux acc k = function\n | x::l when k > 0 -> first_aux (x::acc) (k-1) l\n | _ -> acc\n\nlet first = first_aux []\n\nlet not_cmp x y = - (compare x y)\n\nlet _ =\n let igr = ref [] and olg = ref [] in\n let (s,t) = Scanf.scanf \"%s %s\" (fun s t -> s,t) in\n let n = String.length s in\n String.iteri (fun i x -> olg := (x,i)::!olg) s;\n String.iteri (fun i x -> igr := (x,i)::!igr) t;\n olg := List.sort compare !olg;\n igr := List.sort not_cmp !igr;\n olg := first ((n + 1) / 2) !olg;\n igr := first (n / 2) !igr;\n let (deb, fin) = oleg [] [] (Heap.of_list !igr) (Heap.of_list !olg)\n in\n List.iter (fun (x,_) -> print_char x) (List.rev deb);\n List.iter (fun (x,_) -> print_char x) fin\n"}], "negative_code": [], "src_uid": "bc3d0d902ef457560e444ec0128f0688"} {"nl": {"description": "During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up. Imagine a Martian who has exactly n eyes located in a row and numbered from the left to the right from 1 to n. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string s consisting of uppercase Latin letters. The string's length is n. \"Ding dong!\" \u2014 the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only m Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. More formally, the Martian chooses four numbers a, b, c, d, (1\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009<\u2009c\u2009\u2264\u2009d\u2009\u2264\u2009n) and opens all eyes with numbers i such that a\u2009\u2264\u2009i\u2009\u2264\u2009b or c\u2009\u2264\u2009i\u2009\u2264\u2009d. After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word.Let's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.", "input_spec": "The first line contains a non-empty string s consisting of uppercase Latin letters. The strings' length is n (2\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains an integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009100) \u2014 the number of beautiful words. Next m lines contain the beautiful words pi, consisting of uppercase Latin letters. Their length is from 1 to 1000. All beautiful strings are pairwise different.", "output_spec": "Print the single integer \u2014 the number of different beautiful strings the Martian can see this morning.", "sample_inputs": ["ABCBABA\n2\nBAAB\nABBA"], "sample_outputs": ["1"], "notes": "NoteLet's consider the sample test. There the Martian can get only the second beautiful string if he opens segments of eyes a\u2009=\u20091,\u2009b\u2009=\u20092 and c\u2009=\u20094,\u2009d\u2009=\u20095 or of he opens segments of eyes a\u2009=\u20091,\u2009b\u2009=\u20092 and c\u2009=\u20096,\u2009d\u2009=\u20097. "}, "positive_code": [{"source_code": "(* codeforces 106. Danny Sleator *)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\n(* kmp algorithm. *)\n(* memo.(i) will store the length of the longest prefix of s\n that matches the tail of s1...si *)\nlet kmptable s n = \n let memo = Array.make n 0 in\n for i=1 to (n-1) do\n let rec loop j = \n\tif s.[i] = s.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)\n in memo.(i) <- loop memo.(i-1)\n done;\n memo\n\n(* returns table.\n table.(i) will store the length of the longest prefix of ms\n that matches the tail of ts0...tsi *)\nlet tailtable ts n ms m = \n let memo = kmptable ms m in\n let table = Array.make n 0 in\n table.(0) <- if ts.[0] = ms.[0] then 1 else 0;\n for i=1 to (n-1) do\n let rec loop j = \n\tif ts.[i] = ms.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)\n in\n\ttable.(i) <- loop (if table.(i-1) < m then table.(i-1) else memo.(m-1))\n done;\n table\n\nlet reverse s n = \n let r = String.create n in\n let rec loop i = if i=n then r else (r.[n-1-i] <- s.[i]; loop (i+1)) in\n loop 0\n\nlet can_make s r n mag rmag m = \n if m>n || m=1 then false else\n let rec maxize t i = if i=n-1 then t else (t.(i) <- max t.(i) t.(i-1); maxize t (i+1)) in\n let table = maxize (tailtable s n mag m) 1 in\n let rtable = maxize (tailtable r n rmag m) 1 in\n let rec loop i = i= m || loop (i+1)) in\n loop 0\n\nlet () =\n let s = read_string() in\n let n = String.length s in\n let r = reverse s n in\n let mcount = read_int() in\n\n let rec read_magic i ac = if i=mcount then ac else \n let magic = read_string() in\n let m = String.length magic in\n let rmagic = reverse magic m in\n read_magic (i+1) ((magic,rmagic,m)::ac)\n in\n\n let answer = List.fold_left \n (fun ac (mag,rmag,m) -> if can_make s r n mag rmag m then ac+1 else ac)\n 0 (read_magic 0 [])\n in\n Printf.printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "(* codeforces 106. Danny Sleator *)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\n(* kmp algorithm. *)\n(* memo.(i) will store the length of the longest prefix of s\n that matches the tail of s1...si *)\n(*\nlet kmptable s n = \n let memo = Array.make n 0 in\n for i=1 to (n-1) do\n let rec loop j = \n\tif j <= 0 then 0 else\n\t if s.[i] = s.[memo.(j-1)] then memo.(j-1)+1 else loop memo.(j-1)\n in memo.(i) <- loop i\n done;\n memo\n\n*)\nlet kmptable s n = \n let memo = Array.make n 0 in\n for i=1 to (n-1) do\n let rec loop j = \n\tif s.[i] = s.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)\n in memo.(i) <- loop memo.(i-1)\n done;\n memo\n\n(* returns table.\n table.(i) will store the length of the longest prefix of ms\n that matches the tail of ts0...tsi *)\nlet tailtable ts n ms m = \n let memo = kmptable ms m in\n let table = Array.make n 0 in\n table.(0) <- if ts.[0] = ms.[0] then 1 else 0;\n for i=1 to (n-1) do\n let rec loop j = \n\tif ts.[i] = ms.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)\n in\n\ttable.(i) <- loop (if table.(i-1) < m then table.(i-1) else memo.(m-1))\n done;\n table\n\nlet reverse s n = \n let r = String.create n in\n let rec loop i = if i=n then r else (r.[n-1-i] <- s.[i]; loop (i+1)) in\n loop 0\n\n(*\nlet can_make s r n mag rmag m = m <= n && (\n Printf.printf \"s=%s r=%s mag=%s rmag=%s\\n\" s r mag rmag;\n let table = tailtable s n mag m in\n for i=0 to n-2 do Printf.printf \"%d \" table.(i) done;\n print_newline();\n let rtable = tailtable r n rmag m in\n for i=0 to n-2 do Printf.printf \"%d \" rtable.(i) done;\n print_newline();\n\n let rec maxize t i = if i=n-1 then () else (t.(i) <- max t.(i) t.(i-1); maxize t (i+1)) in\n maxize table 1;\n maxize rtable 1;\n\n let rec loop i = i= m || loop (i+1)) in\n loop 0\n)\n*)\n\nlet can_make s r n mag rmag m = m <= n &&\n let table = tailtable s n mag m in\n let rtable = tailtable r n rmag m in\n let rec maxize t i = if i=n-1 then () else (t.(i) <- max t.(i) t.(i-1); maxize t (i+1)) in\n maxize table 1;\n maxize rtable 1;\n let rec loop i = i= m || loop (i+1)) in\n loop 0\n\nlet () =\n let s = read_string() in\n let n = String.length s in\n let r = reverse s n in\n let mcount = read_int() in\n\n let rec read_magic i ac = if i=mcount then ac else \n let magic = read_string() in\n let m = String.length magic in\n let rmagic = reverse magic m in\n read_magic (i+1) ((magic,rmagic,m)::ac)\n in\n\n let answer = List.fold_left \n (fun ac (mag,rmag,m) -> if can_make s r n mag rmag m then ac+1 else ac)\n 0 (read_magic 0 [])\n in\n Printf.printf \"%d\\n\" answer\n"}], "src_uid": "bfc2f482bdd0b138dfc25016682d86d7"} {"nl": {"description": "Aleksey has $$$n$$$ friends. He is also on a vacation right now, so he has $$$m$$$ days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these $$$m$$$ days.On each of these days some friends will be available for playing, and all others will not. On each day Aleksey must choose one of his available friends to offer him playing the game (and they, of course, always agree). However, if any of them happens to be chosen strictly more than $$$\\left\\lceil\\dfrac{m}{2}\\right\\rceil$$$ times, then all other friends are offended. Of course, Aleksey doesn't want to offend anyone.Help him to choose teammates so that nobody is chosen strictly more than $$$\\left\\lceil\\dfrac{m}{2}\\right\\rceil$$$ times.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\\leq n, m\\leq 100\\,000$$$) standing for the number of friends and the number of days to play, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains an integer $$$k_i$$$ ($$$1\\leq k_i\\leq n$$$), followed by $$$k_i$$$ distinct integers $$$f_{i1}$$$, ..., $$$f_{ik_i}$$$ ($$$1\\leq f_{ij}\\leq n$$$), separated by spaces\u00a0\u2014 indices of available friends on the day $$$i$$$. It is guaranteed that the sums of $$$n$$$ and $$$m$$$ over all test cases do not exceed $$$100\\,000$$$. It's guaranteed that the sum of all $$$k_i$$$ over all days of all test cases doesn't exceed $$$200\\,000$$$.", "output_spec": "Print an answer for each test case. If there is no way to achieve the goal, print \"NO\". Otherwise, in the first line print \"YES\", and in the second line print $$$m$$$ space separated integers $$$c_1$$$, ..., $$$c_m$$$. Each $$$c_i$$$ must denote the chosen friend on day $$$i$$$ (and therefore must be one of $$$f_{ij}$$$). No value must occur more than $$$\\left\\lceil\\dfrac{m}{2}\\right\\rceil$$$ times. If there is more than one possible answer, print any of them.", "sample_inputs": ["2\n4 6\n1 1\n2 1 2\n3 1 2 3\n4 1 2 3 4\n2 2 3\n1 3\n2 2\n1 1\n1 1"], "sample_outputs": ["YES\n1 2 1 1 2 3 \nNO"], "notes": null}, "positive_code": [{"source_code": "\n\nlet infinite_c = 1_000_000 (* \"infinite\" capacity *)\n\nlet maxflow s t adj cap =\n (* s and t are nodes (numbers). g is a graph (represented via an\n array of adjacency lists). c is a 1-d array of capacities. The\n adjacency list on node v stores pairs like (w,i) where w is the\n other node, and i is the index into the capacity array for where\n this capacity is stored. It's set up so that i lxor 1 is where the\n capacity of edge (w,v) is stored. We compute the maximum flow in\n the same representation as the capacities. It returns (f,resid)\n where f is the maximum flow, and resid is the residual capacities\n that result from that flow.\n *)\n\n let c = Array.copy cap in\n let n = Array.length adj in\n let alive = Array.make n [] in\n let level = Array.make n 0 in\n let queue = Array.make n 0 in\n let front = ref 0 in\n let back = ref 0 in\n\n let push w = queue.(!back) <- w; back := !back+1 in\n let eject() = let x = queue.(!front) in front := !front + 1; x; in\n\n let rec bfs () = \n let rec loop () = \n if !front = !back then false else\n\tlet v = eject() in\n\tif level.(v) = level.(t) then true else (\n\t List.iter ( \n\t fun (w,i) -> if level.(w) < 0 && c.(i) > 0 then (\n\t level.(w) <- level.(v) + 1;\n\t push w\n\t )\n\t ) adj.(v);\n\t loop ()\n\t)\n in\n level.(s) <- 0;\n back := 0; front := 0;\n push s;\n loop ();\n in\n \n let rec dfs v cap = \n (* Does a DFS from v looking for a path to t. It tries to push cap units\n of flow to t. It returns the amount of flow actually pushed *)\n if v=t then cap else\n let rec loop total remaining li = \n\tmatch li with \n\t | [] -> \n\t alive.(v) <- [];\n\t total\n\t | (w,i)::tail -> \n\t if level.(w) = level.(v)+1 && c.(i) > 0 then (\n\t let p = dfs w (min c.(i) remaining) in\n\t c.(i) <- c.(i) - p;\n\t c.(i lxor 1) <- c.(i lxor 1) + p;\n\t if remaining-p = 0 then (\n\t\talive.(v) <- li;\n\t\ttotal+p\n\t ) else loop (total+p) (remaining-p) tail\n\t ) else loop total remaining tail\n in loop 0 cap alive.(v)\n in\n \n let rec main_loop flow_so_far = \n Array.fill level 0 n (-1);\n Array.blit adj 0 alive 0 n;\n if bfs () then main_loop (flow_so_far + (dfs s infinite_c)) else (flow_so_far, c)\n in\n main_loop 0\n\n(* end flow *)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nopen Printf\nopen Scanf\n \nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y)) \n\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n\n let (n,m) = read_pair () in\n\n let nn = n + m + 2 in\n \n let graph = Array.make nn [] in\n\n let index = ref 0 in\n let add_edge u v =\n let i = !index in\n graph.(u) <- (v,i)::graph.(u);\n graph.(v) <- (u,i+1)::graph.(v);\n index := i+2\n in\n\n let (s,t) = (nn-2, nn-1) in\n\n for day=0 to m-1 do\n let k = read_int() in\n for j = 0 to k-1 do\n\tlet f = -1 + read_int() in\n\tadd_edge day (m+f)\n done;\n done;\n \n for day=0 to m-1 do\n add_edge s day;\n done;\n\n for friend=m to n+m-1 do\n add_edge friend t;\n done;\n\n let mm = !index in\n\n let cap = Array.init mm (fun i -> (i+1) land 1) in\n\n for friend = m to n+m-1 do\n List.iter (fun (v,i) -> if v = t then cap.(i) <- (m+1)/2) graph.(friend)\n done;\n let (f,final_cap) = maxflow s t graph cap in\n if f < m then printf \"NO\\n\" else (\n printf \"YES\\n\";\n for day = 0 to m-1 do\n\tList.iter (fun (v,j) ->\n\t if v <> s && final_cap.(j) = 0 then \n\t printf \"%d \" (v-m+1)) graph.(day)\n done;\n print_newline()\n )\n done\n"}], "negative_code": [], "src_uid": "1f6be4f0f7d3f9858b498aae1357c2c3"} {"nl": {"description": "There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the initial number of beacons. The i-th of next n lines contains two integers ai and bi (0\u2009\u2264\u2009ai\u2009\u2264\u20091\u2009000\u2009000, 1\u2009\u2264\u2009bi\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the position and power level of the i-th beacon respectively. No two beacons will have the same position, so ai\u2009\u2260\u2009aj if i\u2009\u2260\u2009j.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of beacons that could be destroyed if exactly one beacon is added.", "sample_inputs": ["4\n1 9\n3 1\n6 1\n7 4", "7\n1 1\n2 1\n3 1\n4 1\n5 1\n6 1\n7 1"], "sample_outputs": ["1", "3"], "notes": "NoteFor the first sample case, the minimum number of beacons destroyed is 1. One way to achieve this is to place a beacon at position 9 with power level 2.For the second sample case, the minimum number of beacons destroyed is 3. One way to achieve this is to place a beacon at position 1337 with power level 42."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\t\t\t\t \nlet () = \n let n = read_int () in\n let beacon = Array.init n (fun _ -> read_pair()) in\n\n Array.sort compare beacon;\n\n let fp = Array.init (2*n) (fun i ->\n let j = i mod n in\n let (a,b) = beacon.(j) in\n if i < n then (a, 1, j) else (a - b, 0, j)\n ) in\n\n Array.sort compare fp;\n\n let preserve = Array.make n 0 in\n (* preserve.(i) = rightmost index preserved when i is activated *)\n\n let rec loop i prevj = if i=2*n then () else\n let (_, t, index) = fp.(i) in\n match t with\n\t| 1 -> loop (i+1) index\n\t| 0 ->\n\t preserve.(index) <- prevj;\n\t loop (i+1) prevj\n\t| _ -> failwith \"bad type\"\n in\n\n loop 0 (-1);\n\n let score = Array.make n 1 in\n\n for i=1 to n-1 do\n if preserve.(i) < 0\n then score.(i) <- 1\n else score.(i) <- 1 + score.(preserve.(i))\n done;\n\n let max_preserved = maxf 0 (n-1) (fun i -> score.(i)) in\n\n let answer = n - max_preserved in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "bcd689387c9167c7d0d45d4ca3b0c4c7"} {"nl": {"description": "Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns \u2013 starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x,\u2009y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1,\u2009y1), (x2,\u2009y2), ..., (xr,\u2009yr), that: r\u2009\u2265\u20092; for any integer i (1\u2009\u2264\u2009i\u2009\u2264\u2009r\u2009-\u20091) the following equation |xi\u2009-\u2009xi\u2009+\u20091|\u2009+\u2009|yi\u2009-\u2009yi\u2009+\u20091|\u2009=\u20091 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.", "input_spec": "The first line contains three space-separated integers n,\u2009m,\u2009k (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009300; 2\u2009\u2264\u20092k\u2009\u2264\u2009n\u00b7m) \u2014 the number of rows, the number of columns and the number of tubes, correspondingly. ", "output_spec": "Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1,\u2009yi1,\u2009xi2,\u2009yi2,\u2009...,\u2009xiri,\u2009yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists. ", "sample_inputs": ["3 3 3", "2 3 1"], "sample_outputs": ["3 1 1 1 2 1 3\n3 2 1 2 2 2 3\n3 3 1 3 2 3 3", "6 1 1 1 2 1 3 2 3 2 2 2 1"], "notes": "NotePicture for the first sample: Picture for the second sample: "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n\n let cells = Array.make (n*m) (0,0) in\n\n let next (x,y) = \n if x land 1 = 1 (* left to right *) then\n if y1 then (x,y-1) else (x+1,1)\n in\n\n let rec loop i p = if fst p = n+1 then () else (\n cells.(i) <- p;\n loop (i+1) (next p)\n )\n in\n\n loop 0 (1,1);\n \n let small_size = (n*m)/k in\n let big_size = small_size+1 in\n\n(* \n let rec find_mult remain sc = if remain=0 then sc else\n if remain mod big_size = 0 then sc else\n\tfind_mult (remain-small_size) (sc+1)\n in\n*)\n\n let rec find_count c = \n if c*small_size + (k-c)*big_size = n*m then c else find_count (c+1)\n in\n\n let scount = find_count 1 in\n\n let bcount = (n*m - scount * small_size)/big_size in\n\n if scount+bcount <> k then failwith \"count wrong\";\n\n let rec loop i p = if i=k then () else\n if ix);;\nlet n=read_int();;\nlet m=read_int();;\nlet k=read_int();;\n\nlet tab=Array.make (k+1) [];;\nlet a=(n*m)/k;;\n\nlet suivant i j s=\n if (s=\"droite\")&&(j1) then (i,j-1,s)\n else (i+1,j,\"droite\");;\n \nlet i=ref 1;;\nlet j=ref 0;;\nlet s=ref \"droite\";;\n\nfor l=1 to k-1 do\n for o=1 to a do\n let (x,y,z)=suivant (!i) (!j) (!s) in\n i:=x;\n j:=y;\n s:=z;\n tab.(l)<-(!i,!j)::tab.(l)\n done\ndone;;\nfor o=1 to a+((n*m) mod k) do\n let (x,y,z)=suivant (!i) (!j) (!s) in\n i:=x;\n j:=y;\n s:=z;\n tab.(k)<-(!i, !j)::tab.(k)\ndone;;\nlet rec taille=function\n|[]->0\n|(_,_)::t->1+taille t;;\nlet rec print_list=function\n|[]->print_newline()\n|(h,g)::t->Printf.printf \"%d %d \" h g;print_list t;;\nfor i=1 to k do\n Printf.printf \"%d \" (taille tab.(i));\n print_list tab.(i)\ndone;;"}], "negative_code": [], "src_uid": "779e73c2f5eba950a20e6af9b53a643a"} {"nl": {"description": "You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.You are playing the game on the new generation console so your gamepad have $$$26$$$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.You are given a sequence of hits, the $$$i$$$-th hit deals $$$a_i$$$ units of damage to the opponent's character. To perform the $$$i$$$-th hit you have to press the button $$$s_i$$$ on your gamepad. Hits are numbered from $$$1$$$ to $$$n$$$.You know that if you press some button more than $$$k$$$ times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of $$$a_i$$$ over all $$$i$$$ for the hits which weren't skipped.Note that if you skip the hit then the counter of consecutive presses the button won't reset.Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of hits and the maximum number of times you can push the same button in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the damage of the $$$i$$$-th hit. The third line of the input contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters \u2014 the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).", "output_spec": "Print one integer $$$dmg$$$ \u2014 the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.", "sample_inputs": ["7 3\n1 5 16 18 7 2 10\nbaaaaca", "5 5\n2 4 1 3 1000\naaaaa", "5 4\n2 4 1 3 1000\naaaaa", "8 1\n10 15 2 1 4 8 15 16\nqqwweerr", "6 3\n14 18 9 19 2 15\ncccccc", "2 1\n10 10\nqq"], "sample_outputs": ["54", "1010", "1009", "41", "52", "10"], "notes": "NoteIn the first example you can choose hits with numbers $$$[1, 3, 4, 5, 6, 7]$$$ with the total damage $$$1 + 16 + 18 + 7 + 2 + 10 = 54$$$.In the second example you can choose all hits so the total damage is $$$2 + 4 + 1 + 3 + 1000 = 1010$$$.In the third example you can choose all hits expect the third one so the total damage is $$$2 + 4 + 3 + 1000 = 1009$$$.In the fourth example you can choose hits with numbers $$$[2, 3, 6, 8]$$$. Only this way you can reach the maximum total damage $$$15 + 2 + 8 + 16 = 41$$$.In the fifth example you can choose only hits with numbers $$$[2, 4, 6]$$$ with the total damage $$$18 + 19 + 15 = 52$$$.In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage $$$10$$$."}, "positive_code": [{"source_code": "let rv f p q = f q p\nlet rec fix f x = f (fix f) x\nlet (++),( ** ),(--) = Int64.(add,mul,sub)\n;;\nScanf.(Array.(scanf \" %d %d\" @@ fun n k ->\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v) in\n let s = scanf \" %s\" @@ fun v -> v in\n let sects = fix (fun f i ls all ->\n if i=0 then\n f (i+1) (a.(i)::ls) all\n else if i=n then\n if List.length ls <> 0 then (List.sort (rv compare) ls)::all\n else all\n else\n if s.[i] = s.[i-1] then\n f (i+1) (a.(i)::ls) all\n else\n f (i+1) [a.(i)] ((List.sort (rv compare) ls)::all)\n ) 0 [] []\n in\n Printf.printf \"%Ld\" @@\n List.fold_left (fun sum ls ->\n if List.length ls <= k then\n sum ++ List.fold_left (++) 0L ls\n else\n sum ++ snd (List.fold_left (fun (i,sum) v ->\n if i m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,k = g2 0 in\n let a = iia n in\n let s = scanf \" %s\" @@ id in\n let r =\n let r = ref [] in\n let now = ref s.[0] in\n let cnt = ref 1L in\n let dmgs = ref [a.(0)] in\n String.iteri (fun i c ->\n if i=0 then ()\n else (\n if !now = c then (\n cnt += 1L;\n dmgs := a.(i) :: !dmgs;\n ) else (\n r := (List.sort (rv compare) !dmgs) :: !r;\n dmgs := a.(i) :: [];\n cnt := 1L;\n );\n now := c\n )\n ) s;\n if !cnt <> 0L then r := (List.sort (rv compare) !dmgs) :: !r;\n List.rev @@ !r\n in\n (* print_list (fun s -> string_of_list ist s ^ \"\\n\") r; *)\n List.fold_left (fun sum ls ->\n if llen ls <= k then (\n sum + List.fold_left (+) 0L ls\n ) else (\n let s = ref 0L in\n List.iteri (fun i v -> if i64 i < k then s += v) ls;\n sum + !s\n )\n ) 0L r |> printf \"%Ld\"\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "let rv f p q = f q p\nlet (++),( ** ),(--) = Int64.(add,mul,sub);;\nScanf.(Array.(scanf \" %d %d\" @@ fun n k ->\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v) in\n let b =\n let s = scanf \" %s\" @@ fun v -> v in\n init n (fun i -> s.[i])\n in\n let sects =\n let _,_,ls,all = fold_left (fun (i,prev,ls,all) c ->\n if i=0 then\n (i+1,c,a.(i)::ls,all)\n else\n if prev=c then\n (i+1,c,a.(i)::ls,all)\n else\n (i+1,c,[a.(i)],(List.sort (rv compare) ls)::all)\n ) (0,'_',[],[]) b\n in\n if List.length ls <> 0 then (List.sort (rv compare) ls)::all\n else all\n in\n Printf.printf \"%Ld\" @@\n List.fold_left (fun sum ls ->\n if List.length ls <= k then\n sum ++ List.fold_left (++) 0L ls\n else\n sum ++ snd (List.fold_left (fun (i,sum) v ->\n if i\n let a = init n (fun _ -> scanf \" %d\" @@ fun v -> v) in\n let s = scanf \" %s\" @@ fun v -> v in\n let sects = fix (fun f i ls all ->\n if i=0 then\n f (i+1) (a.(i)::ls) all\n else if i=n then\n if List.length ls <> 0 then (List.sort (rv compare) ls)::all\n else all\n else\n if s.[i] = s.[i-1] then\n f (i+1) (a.(i)::ls) all\n else\n f (i+1) [a.(i)] ((List.sort (rv compare) ls)::all)\n ) 0 [] []\n in\n print_int @@\n List.fold_left (fun sum ls ->\n if List.length ls <= k then\n sum + List.fold_left (+) 0 ls\n else\n sum + snd (List.fold_left (fun (i,sum) v ->\n if i m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,k = g2 0 in\n let a = iia n in\n let s = scanf \" %s\" @@ id in\n let r =\n let r = ref [] in\n let now = ref s.[0] in\n let cnt = ref 1L in\n let dmgs = ref [a.(0)] in\n String.iteri (fun i c ->\n if i=0 then ()\n else (\n if !now = c then (\n cnt += 1L;\n dmgs := a.(i) :: !dmgs;\n ) else (\n r := (List.sort (rv compare) !dmgs) :: !r;\n dmgs := a.(i) :: [];\n cnt := 1L;\n );\n now := c\n )\n ) s;\n if !cnt <> 0L then r := (List.sort (rv compare) !dmgs) :: !r;\n List.rev @@ !r\n in\n print_list (fun s -> string_of_list ist s ^ \"\\n\") r;\n List.fold_left (fun sum ls ->\n if llen ls <= k then (\n sum + List.fold_left (+) 0L ls\n ) else (\n let s = ref 0L in\n List.iteri (fun i v -> if i64 i < k then s += v) ls;\n sum + !s\n )\n ) 0L r |> printf \"%Ld\"\n\n\n\n\n\n\n\n\n\n"}], "src_uid": "aa3b5895046ed34e89d5fcc3264b3944"} {"nl": {"description": "You are given the string s of length n and the numbers p,\u2009q. Split the string s to pieces of length p and q.For example, the string \"Hello\" for p\u2009=\u20092, q\u2009=\u20093 can be split to the two strings \"Hel\" and \"lo\" or to the two strings \"He\" and \"llo\".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).", "input_spec": "The first line contains three positive integers n,\u2009p,\u2009q (1\u2009\u2264\u2009p,\u2009q\u2009\u2264\u2009n\u2009\u2264\u2009100). The second line contains the string s consists of lowercase and uppercase latin letters and digits.", "output_spec": "If it's impossible to split the string s to the strings of length p and q print the only number \"-1\". Otherwise in the first line print integer k \u2014 the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s \u2014 from left to right. If there are several solutions print any of them.", "sample_inputs": ["5 2 3\nHello", "10 9 5\nCodeforces", "6 4 5\nPrivet", "8 1 1\nabacabac"], "sample_outputs": ["2\nHe\nllo", "2\nCodef\norces", "-1", "8\na\nb\na\nc\na\nb\na\nc"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let q = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n for i = 0 to n / p do\n if (n - i * p) mod q = 0 then (\n\tlet a = i\n\tand b = (n - i * p) / q in\n\tlet pos = ref 0 in\n\t Printf.printf \"%d\\n\" (a + b);\n\t for i = 1 to a do\n\t Printf.printf \"%s\\n\" (String.sub s !pos p);\n\t pos := !pos + p;\n\t done;\n\t for i = 1 to b do\n\t Printf.printf \"%s\\n\" (String.sub s !pos q);\n\t pos := !pos + q;\n\t done;\n\t exit 0;\n )\n done;\n Printf.printf \"-1\\n\"\n"}], "negative_code": [], "src_uid": "c4da69789d875853beb4f92147825ebf"} {"nl": {"description": "You are given a set of points $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ on the number line.Two points $$$i$$$ and $$$j$$$ can be matched with each other if the following conditions hold: neither $$$i$$$ nor $$$j$$$ is matched with any other point; $$$|x_i - x_j| \\ge z$$$. What is the maximum number of pairs of points you can match with each other?", "input_spec": "The first line contains two integers $$$n$$$ and $$$z$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le z \\le 10^9$$$) \u2014 the number of points and the constraint on the distance between matched points, respectively. The second line contains $$$n$$$ integers $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ ($$$1 \\le x_i \\le 10^9$$$).", "output_spec": "Print one integer \u2014 the maximum number of pairs of points you can match with each other.", "sample_inputs": ["4 2\n1 3 3 7", "5 5\n10 9 5 8 7"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first example, you may match point $$$1$$$ with point $$$2$$$ ($$$|3 - 1| \\ge 2$$$), and point $$$3$$$ with point $$$4$$$ ($$$|7 - 3| \\ge 2$$$).In the second example, you may match point $$$1$$$ with point $$$3$$$ ($$$|5 - 10| \\ge 5$$$)."}, "positive_code": [{"source_code": "let ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( ** ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet read_int _ = Scanf.scanf \" %d \" (fun n -> n)\nlet read_int64 _ = read_int () |> Int64.of_int\n\nlet () =\n let n = read_int () in\n let z = read_int64 () in\n let xs = Array.init n read_int64 in\n Array.fast_sort Int64.compare xs;\n let k = (n + 1) / 2 in\n let rec iter l r res =\n if r >= n || l >= k then\n res\n else if xs.(r) -- xs.(l) >= z then\n iter (l+1) (r+1) (res+1)\n else\n iter l (r+1) res in\n print_int (iter 0 k 0);\n print_newline ()\n\n\n"}, {"source_code": "let ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( ** ) = Int64.mul\nlet ( // ) = Int64.div\n\n\nlet () =\n let (n, z) = read_line ()\n |> Str.split (Str.regexp \" \")\n |> (fun [a; b] -> (int_of_string a, Int64.of_string b)) in\n let xs = read_line ()\n |> Str.split (Str.regexp \" \")\n |> Array.of_list\n |> Array.map Int64.of_string in\n Array.fast_sort Int64.compare xs;\n let k = (n + 1) / 2 in\n let l = ref 0 in\n let r = ref k in\n let res = ref 0 in\n while !l < k && !r < n do\n if xs.(!r) -- xs.(!l) >= z then\n (l := !l + 1;\n res := !res + 1;\n );\n r := !r + 1\n done;\n print_int !res;\n print_newline ()\n\n\n"}], "negative_code": [], "src_uid": "b063660572a78f25525656332a1782a8"} {"nl": {"description": "You are given two $$$n \\times m$$$ matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly increasing. A matrix is increasing if all rows are strictly increasing and all columns are strictly increasing. For example, the matrix $$$\\begin{bmatrix} 9&10&11\\\\ 11&12&14\\\\ \\end{bmatrix}$$$ is increasing because each individual row and column is strictly increasing. On the other hand, the matrix $$$\\begin{bmatrix} 1&1\\\\ 2&3\\\\ \\end{bmatrix}$$$ is not increasing because the first row is not strictly increasing.Let a position in the $$$i$$$-th row (from top) and $$$j$$$-th column (from left) in a matrix be denoted as $$$(i, j)$$$. In one operation, you can choose any two numbers $$$i$$$ and $$$j$$$ and swap the number located in $$$(i, j)$$$ in the first matrix with the number in $$$(i, j)$$$ in the second matrix. In other words, you can swap two numbers in different matrices if they are located in the corresponding positions.You would like to make both matrices increasing by performing some number of operations (possibly none). Determine if it is possible to do this. If it is, print \"Possible\", otherwise, print \"Impossible\".", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n,m \\leq 50$$$)\u00a0\u2014 the dimensions of each matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \\ldots, a_{im}$$$ ($$$1 \\leq a_{ij} \\leq 10^9$$$)\u00a0\u2014 the number located in position $$$(i, j)$$$ in the first matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$b_{i1}, b_{i2}, \\ldots, b_{im}$$$ ($$$1 \\leq b_{ij} \\leq 10^9$$$)\u00a0\u2014 the number located in position $$$(i, j)$$$ in the second matrix.", "output_spec": "Print a string \"Impossible\" or \"Possible\".", "sample_inputs": ["2 2\n2 10\n11 5\n9 4\n3 12", "2 3\n2 4 5\n4 5 6\n3 6 7\n8 10 11", "3 2\n1 3\n2 4\n5 10\n3 1\n3 6\n4 8"], "sample_outputs": ["Possible", "Possible", "Impossible"], "notes": "NoteThe first example, we can do an operation on the top left and bottom right cells of the matrices. The resulting matrices will be $$$\\begin{bmatrix} 9&10\\\\ 11&12\\\\ \\end{bmatrix}$$$ and $$$\\begin{bmatrix} 2&4\\\\ 3&5\\\\ \\end{bmatrix}$$$.In the second example, we don't need to do any operations.In the third example, no matter what we swap, we can't fix the first row to be strictly increasing in both matrices. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let (n,m) = read_pair () in\n\n let a = Array.make_matrix n m 0 in\n let b = Array.make_matrix n m 0 in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n a.(i).(j) <- read_int()\n done\n done;\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n b.(i).(j) <- read_int()\n done\n done;\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n let (x,y) = (a.(i).(j), b.(i).(j)) in\n a.(i).(j) <- min x y;\n b.(i).(j) <- max x y\n done\n done;\n \n let check1 =\n forall 0 (n-1) (fun i ->\n forall 1 (m-1) (fun j ->\n\ta.(i).(j-1) < a.(i).(j) && b.(i).(j-1) < b.(i).(j)\n )\n )\n in\n\n let check2 =\n forall 1 (n-1) (fun i ->\n forall 0 (m-1) (fun j ->\n\ta.(i-1).(j) < a.(i).(j) && b.(i-1).(j) < b.(i).(j)\n )\n )\n in\n\n if check1 && check2 then printf \"Possible\\n\" else printf \"Impossible\\n\"\n\n \n\n"}], "negative_code": [], "src_uid": "53e061fe3fbe3695d69854c621ab6037"} {"nl": {"description": "Lunar New Year is approaching, and you bought a matrix with lots of \"crosses\".This matrix $$$M$$$ of size $$$n \\times n$$$ contains only 'X' and '.' (without quotes). The element in the $$$i$$$-th row and the $$$j$$$-th column $$$(i, j)$$$ is defined as $$$M(i, j)$$$, where $$$1 \\leq i, j \\leq n$$$. We define a cross appearing in the $$$i$$$-th row and the $$$j$$$-th column ($$$1 < i, j < n$$$) if and only if $$$M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $$$ 'X'.The following figure illustrates a cross appearing at position $$$(2, 2)$$$ in a $$$3 \\times 3$$$ matrix. X.X.X.X.X Your task is to find out the number of crosses in the given matrix $$$M$$$. Two crosses are different if and only if they appear in different rows or columns.", "input_spec": "The first line contains only one positive integer $$$n$$$ ($$$1 \\leq n \\leq 500$$$), denoting the size of the matrix $$$M$$$. The following $$$n$$$ lines illustrate the matrix $$$M$$$. Each line contains exactly $$$n$$$ characters, each of them is 'X' or '.'. The $$$j$$$-th element in the $$$i$$$-th line represents $$$M(i, j)$$$, where $$$1 \\leq i, j \\leq n$$$.", "output_spec": "Output a single line containing only one integer number $$$k$$$ \u2014 the number of crosses in the given matrix $$$M$$$.", "sample_inputs": ["5\n.....\n.XXX.\n.XXX.\n.XXX.\n.....", "2\nXX\nXX", "6\n......\nX.X.X.\n.X.X.X\nX.X.X.\n.X.X.X\n......"], "sample_outputs": ["1", "0", "4"], "notes": "NoteIn the first sample, a cross appears at $$$(3, 3)$$$, so the answer is $$$1$$$.In the second sample, no crosses appear since $$$n < 3$$$, so the answer is $$$0$$$.In the third sample, crosses appear at $$$(3, 2)$$$, $$$(3, 4)$$$, $$$(4, 3)$$$, $$$(4, 5)$$$, so the answer is $$$4$$$."}, "positive_code": [{"source_code": "let rec read_m n m = if n > 0 then let line = read_line() in List.append [line] (read_m (n - 1) m) else m in\nlet get m i j = String.get (List.nth m i) j in\nlet is_x m n i j = i >= 0 && j >= 0 && i < n && j < n && (get m i j) == 'X' in\nlet is_cross m n i j = (is_x m n (i - 1) (j + 1)) && (is_x m n (i + 1) (j + 1)) && (is_x m n (i - 1) (j - 1)) && (is_x m n (i + 1) (j - 1)) && (is_x m n i j) in\nlet rec number_of_crosses m n number i j = if i == n then number else number_of_crosses m n (number + (if is_cross m n i j then 1 else 0)) (if j == n - 1 then (i + 1) else i) (if j == n - 1 then 0 else (j + 1)) in\nlet n = int_of_string (read_line()) in\nlet m = read_m n [] in\nprint_string (string_of_int (number_of_crosses m n 0 0 0))\n"}], "negative_code": [], "src_uid": "3270260030fc56dda3e375af4dad9330"} {"nl": {"description": "The Squareland national forest is divided into equal $$$1 \\times 1$$$ square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates $$$(x, y)$$$ of its south-west corner.Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land $$$A, B, C$$$ in the forest. Initially, all plots in the forest (including the plots $$$A, B, C$$$) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots $$$A, B, C$$$ from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side. For example, $$$A=(0,0)$$$, $$$B=(1,1)$$$, $$$C=(2,2)$$$. The minimal number of plots to be cleared is $$$5$$$. One of the ways to do it is shown with the gray color. Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.", "input_spec": "The first line contains two integers $$$x_A$$$ and $$$y_A$$$\u00a0\u2014 coordinates of the plot $$$A$$$ ($$$0 \\leq x_A, y_A \\leq 1000$$$). The following two lines describe coordinates $$$(x_B, y_B)$$$ and $$$(x_C, y_C)$$$ of plots $$$B$$$ and $$$C$$$ respectively in the same format ($$$0 \\leq x_B, y_B, x_C, y_C \\leq 1000$$$). It is guaranteed that all three plots are distinct.", "output_spec": "On the first line print a single integer $$$k$$$\u00a0\u2014 the smallest number of plots needed to be cleaned from trees. The following $$$k$$$ lines should contain coordinates of all plots needed to be cleaned. All $$$k$$$ plots should be distinct. You can output the plots in any order. If there are multiple solutions, print any of them.", "sample_inputs": ["0 0\n1 1\n2 2", "0 0\n2 0\n1 1"], "sample_outputs": ["5\n0 0\n1 0\n1 1\n1 2\n2 2", "4\n0 0\n1 0\n1 1\n2 0"], "notes": "NoteThe first example is shown on the picture in the legend.The second example is illustrated with the following image: "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let ps = make 3 (0L,0L) in\n repi 0 2 (fun i -> ps.(i) <- g2 0);\n let px = init 3 (fun i -> ps.(i)) in\n sort compare px;\n let py = init 3 (fun i -> ps.(i)) in\n sort (fun (p,q) (r,s) -> compare q s) py;\n let r = ref [] in\n let xx i = fst px.(i) in\n let yx i = snd px.(i) in\n rep (xx 0) (xx 1) (fun x ->\n r := (x, yx 0) :: !r\n );\n rep (xx 1) (xx 2) (fun x ->\n r := (x, yx 2) :: !r\n );\n rep (min (yx 0) (yx 1)) (max (yx 0) (yx 1)) (fun y ->\n r := (xx 1, y) :: !r\n );\n rep (min (yx 2) (yx 1)) (max (yx 2) (yx 1)) (fun y ->\n r := (xx 1, y) :: !r\n );\n r := List.sort_uniq compare !r;\n printf \"%Ld\\n\" @@ llen !r;\n List.iter (fun (p,q) -> printf \"%Ld %Ld\\n\" p q) !r\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Array\nlet p = init 3 (fun _ ->\n Scanf.scanf \" %d %d\" @@ fun u v -> u,v)\nlet () =\n let dmin = ref max_int in\n let dp,dq = ref 0,ref 0 in\n let _ =\n init 1001 (fun y ->\n init 1001 (fun x ->\n let w = fold_left (fun s (p,q) -> s + abs (x-p) + abs (y-q)) 0 p\n in if w < !dmin then (dmin := w; dp := x; dq := y)))\n in\n let res = ref [] in\n let line (p,q) (r,s) =\n let [|p,q;r,s|] = [p,q;r,s] |> List.sort compare |> of_list in\n for x=p to r do\n res := (x,q) :: !res\n done;\n for y=min q s to max q s do\n res := (r,y) :: !res\n done\n in\n let d = !dp,!dq in\n iter (fun t -> line t d) p;\n let res = List.sort_uniq compare !res in\n Printf.(\n printf \"%d\\n\" @@ List.length res;\n List.iter (fun (p,q) ->\n printf \"%d %d\\n\" p q\n ) res\n )\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "1a358e492dfd7e226138ea64e432c180"} {"nl": {"description": "The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $$$n$$$ haybale piles on the farm. The $$$i$$$-th pile contains $$$a_i$$$ haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$) such that $$$|i-j|=1$$$ and $$$a_i>0$$$ and apply $$$a_i = a_i - 1$$$, $$$a_j = a_j + 1$$$. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile $$$1$$$ (i.e. to maximize $$$a_1$$$), and she only has $$$d$$$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $$$1$$$ if she acts optimally!", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u00a0\u2014 the number of test cases. Next $$$2t$$$ lines contain a description of test cases \u00a0\u2014 two lines per test case. The first line of each test case contains integers $$$n$$$ and $$$d$$$ ($$$1 \\le n,d \\le 100$$$) \u2014 the number of haybale piles and the number of days, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 100$$$) \u00a0\u2014 the number of haybales in each pile.", "output_spec": "For each test case, output one integer: the maximum number of haybales that may be in pile $$$1$$$ after $$$d$$$ days if Bessie acts optimally.", "sample_inputs": ["3\n4 5\n1 0 3 2\n2 2\n100 1\n1 8\n0"], "sample_outputs": ["3\n101\n0"], "notes": "NoteIn the first test case of the sample, this is one possible way Bessie can end up with $$$3$$$ haybales in pile $$$1$$$: On day one, move a haybale from pile $$$3$$$ to pile $$$2$$$ On day two, move a haybale from pile $$$3$$$ to pile $$$2$$$ On day three, move a haybale from pile $$$2$$$ to pile $$$1$$$ On day four, move a haybale from pile $$$2$$$ to pile $$$1$$$ On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile $$$2$$$ to pile $$$1$$$ on the second day."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\nlet read_int() = scanf \" %d\" (fun x -> x);;\n\nlet t = read_int() in\nfor z = 1 to t do\n(\n let n = read_int() in\n let d = ref (read_int()) in\n let a = Array.make n 0 in\n for i = 0 to (n-1) do\n a.(i) <- read_int()\n done;\n for i = 1 to n-1 do (\n \t let c = min !d (i*a.(i)) in\n \t a.(0) <- a.(0) + c/i;\n\t d := !d - c;\n )\n done;\n print_int a.(0);\n print_string \"\\n\";\n)\ndone\n"}], "negative_code": [], "src_uid": "7bbb4b9f5eccfe13741445c815a4b1ca"} {"nl": {"description": "Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?", "input_spec": "The only line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910100\u2009000).", "output_spec": "Print the n-th even-length palindrome number.", "sample_inputs": ["1", "10"], "sample_outputs": ["11", "1001"], "notes": "NoteThe first 10 even-length palindrome numbers are 11,\u200922,\u200933,\u2009... ,\u200988,\u200999 and 1001."}, "positive_code": [{"source_code": "\nlet rec reverse s i j =\n if i < j then\n begin\n let c = s.[i] in\n s.[i] <- s.[j];\n s.[j] <- c;\n reverse s (i+1) (j-1);\n end\n;;\n\nlet get_ans () = \n let s = read_line () in\n let () = print_string s in\n let () = reverse s 0 ((String.length s) - 1) in\n let () = print_string s in\n let () = print_string \"\\n\" in\n ()\n;;\n\nlet () = get_ans ()\n"}, {"source_code": "let s = Scanf.scanf \"%s\" (fun x->x) in\n print_string s;\n for i = String.length s - 1 downto 0 do print_char s.[i] done\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () =\n let n = read_string () in\n\n let l = String.length n in\n\n printf \"%s\" n;\n \n for i=l-1 downto 0 do\n printf \"%c\" n.[i]\n done;\n\n print_newline()\n"}], "negative_code": [], "src_uid": "bcf75978c9ef6202293773cf533afadf"} {"nl": {"description": "A ticket is a string consisting of six digits. A ticket is considered lucky if the sum of the first three digits is equal to the sum of the last three digits. Given a ticket, output if it is lucky or not. Note that a ticket can have leading zeroes.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$)\u00a0\u2014 the number of testcases. The description of each test consists of one line containing one string consisting of six digits.", "output_spec": "Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. Output \"YES\" if the given ticket is lucky, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["5\n213132\n973894\n045207\n000000\n055776"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO"], "notes": "NoteIn the first test case, the sum of the first three digits is $$$2 + 1 + 3 = 6$$$ and the sum of the last three digits is $$$1 + 3 + 2 = 6$$$, they are equal so the answer is \"YES\".In the second test case, the sum of the first three digits is $$$9 + 7 + 3 = 19$$$ and the sum of the last three digits is $$$8 + 9 + 4 = 21$$$, they are not equal so the answer is \"NO\".In the third test case, the sum of the first three digits is $$$0 + 4 + 5 = 9$$$ and the sum of the last three digits is $$$2 + 0 + 7 = 9$$$, they are equal so the answer is \"YES\"."}, "positive_code": [{"source_code": "(** https://codeforces.com/problemset/problem/1676/A *)\n\nlet lucky l =\n let rec sums li i sum_a sum_b =\n match li with\n | h::t -> \n if i > 2\n then sums t (i+1) sum_a (sum_b+h)\n else sums t (i+1) (sum_a+h) sum_b\n | [] -> sum_a, sum_b in\n let sum_a, sum_b = sums l 0 0 0 in\n sum_a = sum_b\n\nlet init_list i f =\n let rec helper i l =\n if i < 0\n then l\n else helper (i-1) ((f i)::l) in\n helper (i-1) []\n\nlet solve_n nb_cases =\n let rec helper i =\n if i > 0\n then (\n let ticket = read_line () in\n let ticket_list = \n init_list\n 6\n (fun i -> (int_of_char ticket.[i]) - (int_of_char '0')) in\n print_endline (if lucky ticket_list then \"YES\" else \"NO\");\n helper (i-1)\n ) in\n helper nb_cases\n \n\nlet () =\n let nb_tickets = read_int () in\n solve_n nb_tickets\n"}], "negative_code": [], "src_uid": "c7a5b4a015e28dd3759569bbdc130e93"} {"nl": {"description": "Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous).If it is possible to partition the array, also give any possible way of valid partitioning.", "input_spec": "The first line will contain three space separated integers n, k, p (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a00\u2009\u2264\u2009p\u2009\u2264\u2009k). The next line will contain n space-separated distinct integers representing the content of array a: a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "In the first line print \"YES\" (without the quotes) if it is possible to partition the array in the required way. Otherwise print \"NO\" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition.", "sample_inputs": ["5 5 3\n2 6 10 5 9", "5 5 3\n7 14 2 9 5", "5 3 1\n1 2 3 7 5"], "sample_outputs": ["YES\n1 9\n1 5\n1 10\n1 6\n1 2", "NO", "YES\n3 5 1 3\n1 7\n1 2"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let k = read_int () in\n let p = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let rec loop evens odds i = if i=n then (evens, odds) else\n if a.(i) land 1 = 0 then loop (a.(i)::evens) odds (i+1) else loop evens (a.(i)::odds) (i+1)\n in\n\n let (evens,odds) = loop [] [] 0 in\n\n let evens = Array.of_list evens in\n let odds = Array.of_list odds in\n let nevens = Array.length evens in\n let nodds = Array.length odds in\n\n if (k-p) > nodds || p > nevens + (nodds-(k-p))/2 || (nodds-(k-p)) mod 2 = 1 then printf \"NO\\n\" else (\n\n printf \"YES\\n\";\n \n let oddsets = Array.make (k-p) [] in\n let evensets = Array.make p [] in\n \n for i=0 to k-p-1 do\n oddsets.(i) <- [odds.(i)]\n done;\n\n let oddsused = ref (k-p) in\n\n for i=0 to p-1 do\n if i 0 then (\n oddsets.(0) <- !remains @ oddsets.(0)\n )else ( \n evensets.(0) <- !remains @ evensets.(0)\n );\n \n let pset set sz =\n for i=0 to sz-1 do\n\tprintf \"%d \" (List.length set.(i));\n\tList.iter (printf \" %d\") set.(i);\n\tprint_newline ()\n done\n in\n \n pset oddsets (k-p);\n pset evensets p;\n )\n"}], "negative_code": [], "src_uid": "5185f842c7c24d4118ae3661f4418a1d"} {"nl": {"description": "Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied: The picture is connected, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side). Each gray cell has an even number of gray neighbours. There are exactly $$$n$$$ gray cells with all gray neighbours. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).Leo Jr. is now struggling to draw a beautiful picture with a particular choice of $$$n$$$. Help him, and provide any example of a beautiful picture.To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin $$$(0, 0)$$$, axes $$$0x$$$ and $$$0y$$$ are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.", "input_spec": "The only line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 500$$$)\u00a0\u2014 the number of gray cells with all gray neighbours in a beautiful picture.", "output_spec": "In the first line, print a single integer $$$k$$$\u00a0\u2014 the number of gray cells in your picture. For technical reasons, $$$k$$$ should not exceed $$$5 \\cdot 10^5$$$. Each of the following $$$k$$$ lines should contain two integers\u00a0\u2014 coordinates of a gray cell in your picture. All listed cells should be distinct, and the picture should satisdfy all the properties listed above. All coordinates should not exceed $$$10^9$$$ by absolute value. One can show that there exists an answer satisfying all requirements with a small enough $$$k$$$.", "sample_inputs": ["4"], "sample_outputs": ["12\n1 0\n2 0\n0 1\n1 1\n2 1\n3 1\n0 2\n1 2\n2 2\n3 2\n1 3\n2 3"], "notes": "NoteThe answer for the sample is pictured below: "}, "positive_code": [{"source_code": "let rec solve (k : int) =\n if k < 0 then\n ()\n else\n (print_endline ((string_of_int k) ^ \" \" ^ (string_of_int k));\n print_endline ((string_of_int k) ^ \" \" ^ (string_of_int (k+1)));\n print_endline ((string_of_int (k+1)) ^ \" \" ^ (string_of_int k));\n solve (k - 1))\n;;\n\nlet k = read_int() in\nlet () = print_endline (string_of_int (3 * (k + 1) + 1)) in\nlet () = solve k in\nprint_endline ((string_of_int (k+1)) ^ \" \" ^ (string_of_int (k+1)))\n"}], "negative_code": [{"source_code": "let rec solve (k : int) =\n if k < 0 then\n ()\n else\n (print_endline ((string_of_int k) ^ \" \" ^ (string_of_int k));\n print_endline ((string_of_int k) ^ \" \" ^ (string_of_int (k+1)));\n print_endline ((string_of_int (k+1)) ^ \" \" ^ (string_of_int k));\n solve (k - 1))\n;;\n\nlet k = read_int() in\nlet () = solve k in\nprint_endline ((string_of_int (k+1)) ^ \" \" ^ (string_of_int (k+1)))\n"}], "src_uid": "d87c40ae942f3c378bde372f3320a09f"} {"nl": {"description": "The Department of economic development of IT City created a model of city development till year 2100.To prepare report about growth perspectives it is required to get growth estimates from the model.To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.", "input_spec": "The only line of the input contains three integers a,\u2009b,\u2009c (\u2009-\u20091000\u2009\u2264\u2009a,\u2009b,\u2009c\u2009\u2264\u20091000) \u2014 the coefficients of ax2\u2009+\u2009bx\u2009+\u2009c\u2009=\u20090 equation.", "output_spec": "In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10\u2009-\u20096.", "sample_inputs": ["1 30 200"], "sample_outputs": ["-10.000000000000000\n-20.000000000000000"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let a = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let d = b *. b -. 4.0 *. a *. c in\n let x1 = (-.b +. sqrt d) /. (2.0 *. a) in\n let x2 = (-.b -. sqrt d) /. (2.0 *. a) in\n let x1 = max x1 x2\n and x2 = min x1 x2 in\n Printf.printf \"%.9f\\n\" x1;\n Printf.printf \"%.9f\\n\" x2;\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let a = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let d = b *. b -. 4.0 *. a *. c in\n let x1 = (-.b +. sqrt d) /. 2.0 in\n let x2 = (-.b -. sqrt d) /. 2.0 in\n let x1 = max x1 x2\n and x2 = min x1 x2 in\n Printf.printf \"%.6f\\n\" x1;\n Printf.printf \"%.6f\\n\" x2;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let a = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let d = b *. b -. 4.0 *. a *. c in\n let x1 = (-.b +. sqrt d) /. 2.0 in\n let x2 = (-.b -. sqrt d) /. 2.0 in\n let x1 = max x1 x2\n and x2 = min x1 x2 in\n Printf.printf \"%.9f\\n\" x1;\n Printf.printf \"%.9f\\n\" x2;\n"}], "src_uid": "2d4ad39d42b349765435b351897403da"} {"nl": {"description": "Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$=\"abac\", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: \"ab\", \"ba\", \"ac\". Therefore, the string $$$b$$$=\"abbaac\".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.", "input_spec": "The first line contains a single positive integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case consists of one line in which the string $$$b$$$ is written, consisting of lowercase English letters ($$$2 \\le |b| \\le 100$$$)\u00a0\u2014 the string Bob came up with, where $$$|b|$$$ is the length of the string $$$b$$$. It is guaranteed that $$$b$$$ was built according to the algorithm given above.", "output_spec": "Output $$$t$$$ answers to test cases. Each answer is the secret string $$$a$$$, consisting of lowercase English letters, that Bob came up with.", "sample_inputs": ["4\nabbaac\nac\nbccddaaf\nzzzzzzzzzz"], "sample_outputs": ["abac\nac\nbcdaf\nzzzzzz"], "notes": "NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string $$$a$$$=\"ac\", the string $$$a$$$ has a length $$$2$$$, so the string $$$b$$$ is equal to the string $$$a$$$.In the third test case, Bob came up with the string $$$a$$$=\"bcdaf\", substrings of length $$$2$$$ of string $$$a$$$ are: \"bc\", \"cd\", \"da\", \"af\", so the string $$$b$$$=\"bccddaaf\"."}, "positive_code": [{"source_code": "let rec loop (str : string) (pos : int) =\n if pos >= String.length str then\n ()\n else\n (print_char str.[pos];\n loop str (pos + 2))\n;;\n\nlet rec main (t : int) =\n if t = 0 then\n ()\n else\n let st = read_line () in\n (print_char st.[0];\n loop st 1;\n print_endline \"\";\n main (t-1)\n )\n;;\n\nlet t = read_int() in\nmain t\n"}], "negative_code": [], "src_uid": "ac77e2e6c86b5528b401debe9f68fc8e"} {"nl": {"description": "You have a sequence $$$a$$$ with $$$n$$$ elements $$$1, 2, 3, \\dots, k - 1, k, k - 1, k - 2, \\dots, k - (n - k)$$$ ($$$k \\le n < 2k$$$).Let's call as inversion in $$$a$$$ a pair of indices $$$i < j$$$ such that $$$a[i] > a[j]$$$.Suppose, you have some permutation $$$p$$$ of size $$$k$$$ and you build a sequence $$$b$$$ of size $$$n$$$ in the following manner: $$$b[i] = p[a[i]]$$$.Your goal is to find such permutation $$$p$$$ that the total number of inversions in $$$b$$$ doesn't exceed the total number of inversions in $$$a$$$, and $$$b$$$ is lexicographically maximum.Small reminder: the sequence of $$$k$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$k$$$ exactly once.Another small reminder: a sequence $$$s$$$ is lexicographically smaller than another sequence $$$t$$$, if either $$$s$$$ is a prefix of $$$t$$$, or for the first $$$i$$$ such that $$$s_i \\ne t_i$$$, $$$s_i < t_i$$$ holds (in the first position that these sequences are different, $$$s$$$ has smaller number than $$$t$$$).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$k \\le n < 2k$$$; $$$1 \\le k \\le 10^5$$$)\u00a0\u2014 the length of the sequence $$$a$$$ and its maximum. It's guaranteed that the total sum of $$$k$$$ over test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print $$$k$$$ integers\u00a0\u2014 the permutation $$$p$$$ which maximizes $$$b$$$ lexicographically without increasing the total number of inversions. It can be proven that $$$p$$$ exists and is unique.", "sample_inputs": ["4\n1 1\n2 2\n3 2\n4 3"], "sample_outputs": ["1 \n1 2 \n2 1 \n1 3 2"], "notes": "NoteIn the first test case, the sequence $$$a = [1]$$$, there is only one permutation $$$p = [1]$$$.In the second test case, the sequence $$$a = [1, 2]$$$. There is no inversion in $$$a$$$, so there is only one permutation $$$p = [1, 2]$$$ which doesn't increase the number of inversions.In the third test case, $$$a = [1, 2, 1]$$$ and has $$$1$$$ inversion. If we use $$$p = [2, 1]$$$, then $$$b = [p[a[1]], p[a[2]], p[a[3]]] = [2, 1, 2]$$$ and also has $$$1$$$ inversion.In the fourth test case, $$$a = [1, 2, 3, 2]$$$, and since $$$p = [1, 3, 2]$$$ then $$$b = [1, 3, 2, 3]$$$. Both $$$a$$$ and $$$b$$$ have $$$1$$$ inversion and $$$b$$$ is the lexicographically maximum."}, "positive_code": [{"source_code": "open Str\nopen Big_int\nopen Num\n\nlet multitest = true\n\nmodule Shortcuts = struct\n let loop n f = for i = 0 to n - 1 do f i; done\n\nend\n\nmodule Helper = struct\n open Shortcuts\n\n let read_s () = Scanf.scanf \"%s\\n\" (fun x -> x)\n\n let read_int ?endl () =\n match endl with\n | None -> Scanf.scanf \"%d \" (fun x -> x)\n | Some () -> Scanf.scanf \"%d\\n\" (fun x -> x)\n\n let read_array n =\n let a = Array.make n 0 in\n loop (n-1) (fun i -> a.(i) <- read_int ());\n a.(n-1) <- read_int ~endl:() ();\n a\n\nend\n\nmodule Ext = struct\n module List = struct\n let rec make n x =\n if (n <= 0) then []\n else x :: make (n-1) x\n\n end\n\nend\n\nmodule Alg = struct\n let rec gcd x y =\n if y <> 0 then (gcd y (x mod y))\n else (abs x)\n\n let lcm x y =\n if x = 0 || y = 0 then 0\n else abs (x * y) / (gcd x y)\n\nend\n\nlet solve _ =\n let open Shortcuts in\n let open Helper in\n let open Printf in\n let open Ext in\n let open Alg in\n (* ***** Solution code here ***** *)\n let n = read_int () in\n let k = read_int ~endl:() () in\n loop (2*k - n-1) (fun i -> printf \"%d \" (i+1));\n loop (n - k+1) (fun i -> printf \"%d \" (k - i));\n printf \"\\n\";\n (* ***** ******************* ***** *)\n;;\n\nlet () =\n let open Helper in\n let open Shortcuts in\n let t = if multitest then read_int ~endl:() () else 1 in\n loop t solve;;\n"}], "negative_code": [], "src_uid": "67de9506ac2458ee67346bae1a9e3926"} {"nl": {"description": "Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something. Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal k. In other words, , where aj is the taste of the j-th chosen fruit and bj is its calories.Inna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem \u2014 now the happiness of a young couple is in your hands!Inna loves Dima very much so she wants to make the salad from at least one fruit.", "input_spec": "The first line of the input contains two integers n, k (1\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009k\u2009\u2264\u200910). The second line of the input contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) \u2014 the fruits' tastes. The third line of the input contains n integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009100) \u2014 the fruits' calories. Fruit number i has taste ai and calories bi.", "output_spec": "If there is no way Inna can choose the fruits for the salad, print in the single line number -1. Otherwise, print a single integer \u2014 the maximum possible sum of the taste values of the chosen fruits.", "sample_inputs": ["3 2\n10 8 1\n2 7 1", "5 3\n4 4 4 4 4\n2 2 2 2 2"], "sample_outputs": ["18", "-1"], "notes": "NoteIn the first test sample we can get the total taste of the fruits equal to 18 if we choose fruit number 1 and fruit number 2, then the total calories will equal 9. The condition fulfills, that's exactly what Inna wants.In the second test sample we cannot choose the fruits so as to follow Inna's principle."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\n\nlet n = scan_int() and k = scan_int();;\nlet a = Array.init (n + 1) (fun i -> if i = 0 then 0 else scan_int());;\nlet b = Array.init (n + 1) (fun i -> if i = 0 then 0 else scan_int());;\n\nlet mx = 20007 and shift = 10003 and duzo = -1000000;;\nlet dp = Array.make_matrix (n + 1) mx duzo;;\ndp.(0).(shift) <- 0;;\n\nfor i = 1 to n do\n let odejm = k * b.(i) in\n for j = 0 to mx - 1 do\n dp.(i).(j) <- (dp.(i - 1).(j));\n let wtedy = j - a.(i) + odejm in\n if wtedy >= 0 && wtedy < mx then dp.(i).(j) <- max dp.(i).(j) (dp.(i - 1).(wtedy) + b.(i)); \n done;\ndone;;\n\nif dp.(n).(shift) <= 0 then print_string(\"-1\") else print_int(dp.(n).(shift) * k);;"}], "negative_code": [], "src_uid": "91f0341e7f55bb03d87e4cfc63973295"} {"nl": {"description": "In an English class Nick had nothing to do at all, and remembered about wonderful strings called palindromes. We should remind you that a string is called a palindrome if it can be read the same way both from left to right and from right to left. Here are examples of such strings: \u00abeye\u00bb, \u00abpop\u00bb, \u00ablevel\u00bb, \u00ababa\u00bb, \u00abdeed\u00bb, \u00abracecar\u00bb, \u00abrotor\u00bb, \u00abmadam\u00bb. Nick started to look carefully for all palindromes in the text that they were reading in the class. For each occurrence of each palindrome in the text he wrote a pair \u2014 the position of the beginning and the position of the ending of this occurrence in the text. Nick called each occurrence of each palindrome he found in the text subpalindrome. When he found all the subpalindromes, he decided to find out how many different pairs among these subpalindromes cross. Two subpalindromes cross if they cover common positions in the text. No palindrome can cross itself.Let's look at the actions, performed by Nick, by the example of text \u00abbabb\u00bb. At first he wrote out all subpalindromes:\u2022 \u00abb\u00bb \u2014 1..1 \u2022 \u00abbab\u00bb \u2014 1..3 \u2022 \u00aba\u00bb \u2014 2..2 \u2022 \u00abb\u00bb \u2014 3..3 \u2022 \u00abbb\u00bb \u2014 3..4 \u2022 \u00abb\u00bb \u2014 4..4 Then Nick counted the amount of different pairs among these subpalindromes that cross. These pairs were six: 1. 1..1 cross with 1..3 2. 1..3 cross with 2..2 3. 1..3 cross with 3..3 4. 1..3 cross with 3..4 5. 3..3 cross with 3..4 6. 3..4 cross with 4..4 Since it's very exhausting to perform all the described actions manually, Nick asked you to help him and write a program that can find out the amount of different subpalindrome pairs that cross. Two subpalindrome pairs are regarded as different if one of the pairs contains a subpalindrome that the other does not.", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7106) \u2014 length of the text. The following line contains n lower-case Latin letters (from a to z).", "output_spec": "In the only line output the amount of different pairs of two subpalindromes that cross each other. Output the answer modulo 51123987.", "sample_inputs": ["4\nbabb", "2\naa"], "sample_outputs": ["6", "2"], "notes": null}, "positive_code": [{"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\n\nopen Int64\n\nlet modulo = 51123987L\nlet ( ++ ) = add\nlet ( ** ) = mul\nlet ( -- ) = sub\nlet ( // ) = div\nlet ( %% ) = rem\n\nlet manacher a n =\n let z = Array.make n 0 in\n let rec go f g i =\n if i < n then\n if i < g && g-i <> z.(2*f-i) then (\n z.(i) <- min (g-i) z.(2*f-i);\n go f g (i+1)\n ) else (\n let rec go2 j =\n if j < n && 2*i-j >= 0 && a.[j] = a.[2*i-j] then\n go2 (j+1)\n else\n j\n in\n let g' = go2 (max g i) in\n z.(i) <- g'-i;\n go i g' (i+1)\n )\n in\n go 0 0 0;\n z\n\nlet () =\n let n = read_int () in\n let m = 2*n+1 in\n let a = read_str () in\n\n let b = String.make m '.' in\n for i = 0 to n-1 do\n b.[i*2+1] <- a.[i]\n done;\n let z = manacher b m in\n\n let l = Array.make (m+1) 0 in\n let r = Array.make (m+1) 0 in\n let ans = ref 0L in\n let rr = ref 0L in\n let add a x y = a.(x) <- a.(x) + y in\n for i = 0 to m-1 do\n add l (i-z.(i)+1) 1;\n add l (i+1) (-1);\n add r i 1;\n add r (i+z.(i)) (-1);\n ans := (!ans ++ of_int (z.(i)/2)) %% modulo\n done;\n ans := !ans ** (!ans -- 1L) // 2L %% modulo;\n for i = 0 to m-1 do\n if i > 0 then (\n add l i l.(i-1);\n add r i r.(i-1)\n );\n if i mod 2 = 1 then (\n ans := (!ans -- !rr ** of_int l.(i)) %% modulo;\n rr := !rr ++ of_int r.(i)\n )\n done;\n Printf.printf \"%Ld\\n\" ((!ans ++ modulo) %% modulo)\n"}], "negative_code": [{"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\n\nopen Int64\n\nlet modulo = 51123987L\nlet ( ++ ) = add\nlet ( ** ) = mul\nlet ( -- ) = sub\nlet ( // ) = div\nlet ( %% ) = rem\n\nlet manacher a n =\n let z = Array.make n 0 in\n let rec go f g i =\n if i < n then\n if i < g && g-i <> z.(2*f-i) then (\n z.(i) <- min (g-i) z.(2*f-i);\n go f g (i+1)\n ) else (\n let rec go2 j =\n if j < n && 2*i-j >= 0 && a.[j] = a.[2*i-j] then\n go2 (j+1)\n else\n j\n in\n let g' = go2 (max g i) in\n z.(i) <- g'-i;\n go i g' (i+1)\n )\n in\n go 0 0 0;\n z\n\nlet () =\n let n = read_int () in\n let m = 2*n+1 in\n let a = read_str () in\n\n let b = String.make m '.' in\n for i = 0 to n-1 do\n b.[i*2+1] <- a.[i]\n done;\n let z = manacher b m in\n\n let l = Array.make (m+1) 0 in\n let r = Array.make (m+1) 0 in\n let ans = ref 0L in\n let rr = ref 0L in\n let add a x y = a.(x) <- a.(x) + y in\n for i = 0 to m-1 do\n add l (i-z.(i)+1) 1;\n add l (i+1) (-1);\n add r i 1;\n add r (i+z.(i)) (-1);\n ans := !ans ++ of_int (z.(i)/2)\n done;\n ans := !ans ** (!ans -- 1L) // 2L %% modulo;\n for i = 0 to m-1 do\n if i > 0 then (\n add l i l.(i-1);\n add r i r.(i-1)\n );\n if i mod 2 = 1 then (\n ans := (!ans -- !rr ** of_int l.(i)) %% modulo;\n rr := !rr ++ of_int r.(i)\n )\n done;\n Printf.printf \"%Ld\\n\" ((!ans ++ modulo) %% modulo)\n"}, {"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\n\nopen Int64\n\nlet modulo = 51123987L\nlet ( ++ ) = add\nlet ( ** ) = mul\nlet ( -- ) = sub\nlet ( // ) = div\nlet ( %% ) = rem\n\nlet manacher a n =\n let z = Array.make n 0 in\n let rec go f g i =\n if i < n then\n if i < g && g-i <> z.(2*f-i) then (\n z.(i) <- min (g-i) z.(2*f-i);\n go f g (i+1)\n ) else (\n let rec go2 j =\n if j < n && 2*i-j >= 0 && a.[j] = a.[2*i-j] then\n go2 (j+1)\n else\n j\n in\n let j = go2 i in\n z.(i) <- j-i;\n go i j (i+1)\n )\n in\n go 0 0 0;\n z\n\nlet () =\n let n = read_int () in\n let m = 2*n+1 in\n let a = read_str () in\n\n let b = String.make m '.' in\n for i = 0 to n-1 do\n b.[i*2+1] <- a.[i]\n done;\n let z = manacher b m in\n\n let l = Array.make (m+1) 0 in\n let r = Array.make (m+1) 0 in\n let ans = ref 0L in\n let rr = ref 0L in\n let add a x y = a.(x) <- a.(x) + y in\n for i = 0 to m-1 do\n add l (i-z.(i)+1) 1;\n add l (i+1) (-1);\n add r i 1;\n add r (i+z.(i)) (-1);\n ans := !ans ++ of_int (z.(i)/2)\n done;\n ans := !ans ** (!ans -- 1L) // 2L %% modulo;\n for i = 0 to m-1 do\n if i > 0 then (\n add l i l.(i-1);\n add r i r.(i-1)\n );\n if i mod 2 = 1 then (\n ans := (!ans -- !rr ** of_int l.(i)) %% modulo;\n rr := !rr ++ of_int r.(i)\n )\n done;\n Printf.printf \"%Ld\\n\" !ans\n"}], "src_uid": "1322a0f1c38f8de56f840fc7e2f14a54"} {"nl": {"description": "You are given n points on the plane. You need to delete exactly k of them (k\u2009<\u2009n) so that the diameter of the set of the remaining n\u2009-\u2009k points were as small as possible. The diameter of a set of points is the maximum pairwise distance between the points of the set. The diameter of a one point set equals zero.", "input_spec": "The first input line contains a pair of integers n,\u2009k (2\u2009\u2264\u2009n\u2009\u2264\u20091000, 1\u2009\u2264\u2009k\u2009\u2264\u200930, k\u2009<\u2009n) \u2014 the numbers of points on the plane and the number of points to delete, correspondingly. Next n lines describe the points, one per line. Each description consists of a pair of integers xi,\u2009yi (0\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u200932000) \u2014 the coordinates of the i-th point. The given points can coincide.", "output_spec": "Print k different space-separated integers from 1 to n \u2014 the numbers of points to delete. The points are numbered in the order, in which they are given in the input from 1 to n. You can print the numbers in any order. If there are multiple solutions, print any of them.", "sample_inputs": ["5 2\n1 2\n0 0\n2 2\n1 1\n3 3", "4 1\n0 0\n0 0\n1 1\n1 1"], "sample_outputs": ["5 2", "3"], "notes": null}, "positive_code": [{"source_code": "exception Found\n\nlet debug = false\n\nlet _ =\n let sqr x = x * x in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n (0, 0) in\n let es = Array.make (n * n) (0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tp.(i) <- (x, y)\n done;\n for i = 0 to n - 1 do\n let (x1, y1) = p.(i) in\n\tfor j = i + 1 to n - 1 do\n\t let (x2, y2) = p.(j) in\n\t let d =\n\t Int32.add\n\t (Int32.of_int (sqr (x2 - x1)))\n\t (Int32.of_int (sqr (y2 - y1)))\n\t in\n\t es.(i * n + j) <- (d, i, j)\n\tdone\n done;\n let cmp (x, _, _) (y, _, _) = Int32.compare y x in\n Array.sort cmp es\n in\n let res = Array.make n 0 in\n let solve d =\n if debug then Printf.printf \"solve %ld\\n\" d;\n let m =\n let m = ref 0 in\n\twhile !m < n * n &&\n\t (let (d', _, _) = es.(!m) in d' > d )\n\tdo\n\t incr m\n\tdone;\n\t!m\n in\n let es' = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n\tres.(i) <- 0\n done;\n for i = 0 to m - 1 do\n\tlet (_d, u, v) = es.(i) in\nif debug then Printf.printf \"edge %d %d %ld\\n\" u v _d;\n\t es'.(u) <- v :: es'.(u);\n\t es'.(v) <- u :: es'.(v)\n done\n in\n let es = Array.map Array.of_list es' in\n let vs = ref [] in\n let k = ref k in\n let m = ref m in\n let () =\n for i = 0 to n - 1 do\n\tif Array.length es.(i) = 0\n\tthen ()\n\telse if Array.length es.(i) = 1 && Array.length es.(es.(i).(0)) = 1\n\tthen (\n\t if i < es.(i).(0) then (\n (*Printf.printf \"remove %d-%d\\n\" i es.(i).(0);*)\n\t res.(i) <- 1;\n\t decr k;\n\t decr m;\n\t )\n\t) else if Array.length es.(i) = 1\n\tthen ()\n\telse vs := i :: !vs\n done\n in\n let vs = Array.of_list !vs in\n(*Printf.printf \"asd2 %ld %d\\n\" d (Array.length vs);*)\n let rec bf p k m =\n if debug then Printf.printf \"bf %d %d %d\\n\" p k m;\n assert (m >= 0);\n if k >= 0 then (\n\tif m = 0 then (\n\t let k = ref k in\n\t if !k = 0\n\t then raise Found;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 then (\n\t\tres.(i) <- 1;\n\t\tdecr k;\n\t\tif !k = 0\n\t\tthen raise Found\n\t )\n\t done;\n\t assert false\n\t) else if p < Array.length vs then (\n\t let v = vs.(p) in\nif debug then Printf.printf \"asd4 %d\\n\" v;\n\t if res.(v) = 0 then (\n\t (let m' = ref m in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\nif debug then Printf.printf \"rem %d %d\\n\" v u;\n\t\t m' := !m' - 1\n\t\t );\n\t\t done;\n\t\t res.(v) <- 1;\n\t\t if !m' < m - 1\n\t\t then bf (p + 1) (k - 1) !m';\n\t\t res.(v) <- 0\n\t );\n(*Printf.printf \"asd45\\n\";*)\n\t (let m' = ref m in\n\t let k' = ref k in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\n\t\t decr k';\n\t\t for i = 0 to Array.length es.(u) - 1 do\n\t\t\t let w = es.(u).(i) in\n\t\t\t if res.(w) = 0 then (\nif debug then Printf.printf \"rem2 %d %d %d\\n\" v u w;\n\t\t\t m' := !m' - 1\n\t\t\t );\n\t\t done;\n\t\t );\n\t\t res.(u) <- res.(u) + 1\n\t\t done;\n\t\t bf (p + 1) !k' !m';\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t res.(u) <- res.(u) - 1\n\t\t done;\n\t )\n\t ) else bf (p + 1) k m\n\t)\n )\n(*;Printf.printf \"asd5\\n\";*)\n in\n try\n\tbf 0 !k !m;\n\tfalse\n with\n\t| Found ->\n\t true\n in\n let l = ref 0l in\n let r = ref Int32.max_int in\n while !l < Int32.sub !r 1l do\n let m = Int32.div (Int32.add !l !r) 2l in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n if debug then Printf.printf \"QWE %ld\\n\" !r;\n ignore (solve !r);\n for i = 0 to n - 1 do\n if res.(i) > 0\n then Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n\n"}], "negative_code": [{"source_code": "exception Found\n\nlet debug = false\n\nlet _ =\n let sqr x = x * x in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n (0, 0) in\n let es = Array.make (n * n) (0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tp.(i) <- (x, y)\n done;\n for i = 0 to n - 1 do\n let (x1, y1) = p.(i) in\n\tfor j = i + 1 to n - 1 do\n\t let (x2, y2) = p.(j) in\n\t let d =\n\t Int32.add\n\t (Int32.of_int (sqr (x2 - x1)))\n\t (Int32.of_int (sqr (y2 - y1)))\n\t in\n\t es.(i * n + j) <- (d, i, j)\n\tdone\n done;\n let cmp (x, _, _) (y, _, _) = Int32.compare y x in\n Array.sort cmp es\n in\n let res = Array.make n 0 in\n let solve d =\n if debug then Printf.printf \"solve %ld\\n\" d;\n let m =\n let m = ref 0 in\n\twhile !m < n * n &&\n\t (let (d', _, _) = es.(!m) in d' > d )\n\tdo\n\t incr m\n\tdone;\n\t!m\n in\n let es' = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n\tres.(i) <- 0\n done;\n for i = 0 to m - 1 do\n\tlet (_d, u, v) = es.(i) in\nif debug then Printf.printf \"edge %d %d %ld\\n\" u v _d;\n\t es'.(u) <- v :: es'.(u);\n\t es'.(v) <- u :: es'.(v)\n done\n in\n let es = Array.map Array.of_list es' in\n let vs = ref [] in\n let k = ref k in\n let m = ref m in\n let () =\n for i = 0 to n - 1 do\n\tif Array.length es.(i) = 0\n\tthen ()\n\telse if Array.length es.(i) = 1 && Array.length es.(es.(i).(0)) = 1\n\tthen (\n\t if i < es.(i).(0) then (\n (*Printf.printf \"remove %d-%d\\n\" i es.(i).(0);*)\n\t res.(i) <- 1;\n\t decr k;\n\t decr m;\n\t )\n\t) else if Array.length es.(i) = 1\n\tthen ()\n\telse vs := i :: !vs\n done\n in\n let vs = Array.of_list !vs in\n(*Printf.printf \"asd2 %ld %d\\n\" d (Array.length vs);*)\n let rec bf p k m =\n if debug then Printf.printf \"bf %d %d %d\\n\" p k m;\n assert (m >= 0);\n if k >= 0 then (\n\tif m = 0 then (\n\t let k = ref k in\n\t if !k = 0\n\t then raise Found;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 then (\n\t\tres.(i) <- 1;\n\t\tdecr k;\n\t\tif !k = 0\n\t\tthen raise Found\n\t )\n\t done;\n\t assert false\n\t) else if p < Array.length vs then (\n\t let v = vs.(p) in\nif debug then Printf.printf \"asd4 %d\\n\" v;\n\t if res.(v) = 0 then (\n\t (let m' = ref m in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t m' := !m' - 1;\n\t\t if res.(u) = 0 then (\nif debug then Printf.printf \"rem %d %d\\n\" v u;\n\t\t );\n\t\t done;\n\t\t res.(v) <- 1;\n\t\t bf (p + 1) (k - 1) !m';\n\t\t res.(v) <- 0\n\t );\n(*Printf.printf \"asd45\\n\";*)\n\t (let m' = ref m in\n\t let k' = ref k in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\n\t\t decr k';\n\t\t for i = 0 to Array.length es.(u) - 1 do\n\t\t\t let w = es.(u).(i) in\n\t\t\t m' := !m' - 1;\n\t\t\t if res.(w) = 0 then (\nif debug then Printf.printf \"rem2 %d %d %d\\n\" v u w;\n\t\t\t );\n\t\t done;\n\t\t );\n\t\t res.(u) <- res.(u) + 1\n\t\t done;\n\t\t bf (p + 1) !k' !m';\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t res.(u) <- res.(u) - 1\n\t\t done;\n\t )\n\t ) else bf (p + 1) k m\n\t)\n )\n(*;Printf.printf \"asd5\\n\";*)\n in\n try\n\tbf 0 !k (2 * !m);\n\tfalse\n with\n\t| Found ->\n\t true\n in\n let l = ref 0l in\n let r = ref Int32.max_int in\n while !l < Int32.sub !r 1l do\n let m = Int32.div (Int32.add !l !r) 2l in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n if debug then Printf.printf \"QWE %ld\\n\" !r;\n ignore (solve !r);\n for i = 0 to n - 1 do\n if res.(i) > 0\n then Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n\n"}, {"source_code": "exception Found\n\nlet debug = false\n\nlet _ =\n let sqr x = x * x in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n (0, 0) in\n let es = Array.make (n * n) (0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tp.(i) <- (x, y)\n done;\n for i = 0 to n - 1 do\n let (x1, y1) = p.(i) in\n\tfor j = i + 1 to n - 1 do\n\t let (x2, y2) = p.(j) in\n\t let d =\n\t Int32.add\n\t (Int32.of_int (sqr (x2 - x1)))\n\t (Int32.of_int (sqr (y2 - y1)))\n\t in\n\t es.(i * n + j) <- (d, i, j)\n\tdone\n done;\n let cmp (x, _, _) (y, _, _) = Int32.compare y x in\n Array.sort cmp es\n in\n let res = Array.make n 0 in\n let solve d =\n if debug then Printf.printf \"solve %ld\\n\" d;\n let m =\n let m = ref 0 in\n\twhile !m < n * n &&\n\t (let (d', _, _) = es.(!m) in d' > d )\n\tdo\n\t incr m\n\tdone;\n\t!m\n in\n let es' = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n\tres.(i) <- 0\n done;\n for i = 0 to m - 1 do\n\tlet (_d, u, v) = es.(i) in\nif debug then Printf.printf \"edge %d %d %ld\\n\" u v _d;\n\t es'.(u) <- v :: es'.(u);\n\t es'.(v) <- u :: es'.(v)\n done\n in\n let es = Array.map Array.of_list es' in\n let vs = ref [] in\n let k = ref k in\n let m = ref m in\n let () =\n for i = 0 to n - 1 do\n\tif Array.length es.(i) = 0\n\tthen ()\n\telse if Array.length es.(i) = 1 && Array.length es.(es.(i).(0)) = 1\n\tthen (\n\t if i < es.(i).(0) then (\n (*Printf.printf \"remove %d-%d\\n\" i es.(i).(0);*)\n\t res.(i) <- 1;\n\t decr k;\n\t decr m;\n\t )\n\t) else if Array.length es.(i) = 1\n\tthen ()\n\telse vs := i :: !vs\n done\n in\n let vs = Array.of_list !vs in\n(*Printf.printf \"asd2 %ld %d\\n\" d (Array.length vs);*)\n let rec bf p k m =\n if debug then Printf.printf \"bf %d %d %d\\n\" p k m;\n assert (m >= 0);\n if k >= 0 then (\n\tif m = 0 then (\n\t let k = ref k in\n\t if !k = 0\n\t then raise Found;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 then (\n\t\tres.(i) <- 1;\n\t\tdecr k;\n\t\tif !k = 0\n\t\tthen raise Found\n\t )\n\t done;\n\t assert false\n\t) else if p < Array.length vs then (\n\t let v = vs.(p) in\nif debug then Printf.printf \"asd4 %d\\n\" v;\n\t if res.(v) = 0 then (\n\t (let m' = ref m in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\nif debug then Printf.printf \"rem %d %d\\n\" v u;\n\t\t m' := !m' - 1\n\t\t );\n\t\t done;\n\t\t res.(v) <- 1;\n\t\t bf (p + 1) (k - 1) !m';\n\t\t res.(v) <- 0\n\t );\n(*Printf.printf \"asd45\\n\";*)\n\t (let m' = ref m in\n\t let k' = ref k in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\n\t\t decr k';\n\t\t for i = 0 to Array.length es.(u) - 1 do\n\t\t\t let w = es.(u).(i) in\n\t\t\t if res.(w) = 0 then (\nif debug then Printf.printf \"rem2 %d %d %d\\n\" v u w;\n\t\t\t m' := !m' - 1\n\t\t\t );\n\t\t done;\n\t\t );\n\t\t res.(u) <- res.(u) + 1\n\t\t done;\n\t\t if !k' <= k - 1\n\t\t then bf (p + 1) !k' !m';\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t res.(u) <- res.(u) - 1\n\t\t done;\n\t )\n\t ) else bf (p + 1) k m\n\t)\n )\n(*;Printf.printf \"asd5\\n\";*)\n in\n try\n\tbf 0 !k !m;\n\tfalse\n with\n\t| Found ->\n\t true\n in\n let l = ref 0l in\n let r = ref Int32.max_int in\n while !l < Int32.sub !r 1l do\n let m = Int32.div (Int32.add !l !r) 2l in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n if debug then Printf.printf \"QWE %ld\\n\" !r;\n ignore (solve !r);\n for i = 0 to n - 1 do\n if res.(i) > 0\n then Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n\n"}, {"source_code": "exception Found\n\nlet debug = false\n\nlet _ =\n let sqr x = x * x in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n (0, 0) in\n let es = Array.make (n * n) (0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tp.(i) <- (x, y)\n done;\n for i = 0 to n - 1 do\n let (x1, y1) = p.(i) in\n\tfor j = i + 1 to n - 1 do\n\t let (x2, y2) = p.(j) in\n\t let d =\n\t Int32.add\n\t (Int32.of_int (sqr (x2 - x1)))\n\t (Int32.of_int (sqr (y2 - y1)))\n\t in\n\t es.(i * n + j) <- (d, i, j)\n\tdone\n done;\n let cmp (x, _, _) (y, _, _) = Int32.compare y x in\n Array.sort cmp es\n in\n let res = Array.make n 0 in\n let solve d =\n if debug then Printf.printf \"solve %ld\\n\" d;\n let m =\n let m = ref 0 in\n\twhile !m < n * n &&\n\t (let (d', _, _) = es.(!m) in d' > d )\n\tdo\n\t incr m\n\tdone;\n\t!m\n in\n let es' = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n\tres.(i) <- 0\n done;\n for i = 0 to m - 1 do\n\tlet (_d, u, v) = es.(i) in\nif debug then Printf.printf \"edge %d %d %ld\\n\" u v _d;\n\t es'.(u) <- v :: es'.(u);\n\t es'.(v) <- u :: es'.(v)\n done\n in\n let es = Array.map Array.of_list es' in\n let vs = ref [] in\n let k = ref k in\n let m = ref m in\n let () =\n for i = 0 to n - 1 do\n\tif Array.length es.(i) = 0\n\tthen ()\n\telse if Array.length es.(i) = 1 && Array.length es.(es.(i).(0)) = 1\n\tthen (\n\t if i < es.(i).(0) then (\n (*Printf.printf \"remove %d-%d\\n\" i es.(i).(0);*)\n\t res.(i) <- 1;\n\t decr k;\n\t decr m;\n\t )\n\t) else if Array.length es.(i) = 1\n\tthen ()\n\telse vs := i :: !vs\n done\n in\n let vs = Array.of_list !vs in\n(*Printf.printf \"asd2 %ld %d\\n\" d (Array.length vs);*)\n let rec bf p k m =\n if debug then Printf.printf \"bf %d %d %d\\n\" p k m;\n if k >= 0 then (\n\tif m = 0 then (\n\t let k = ref k in\n\t if !k = 0\n\t then raise Found;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 then (\n\t\tres.(i) <- 1;\n\t\tdecr k;\n\t\tif !k = 0\n\t\tthen raise Found\n\t )\n\t done;\n\t assert false\n\t) else if p < Array.length vs then (\n\t let v = vs.(p) in\nif debug then Printf.printf \"asd4 %d\\n\" v;\n\t if res.(v) = 0 then (\n\t (let m' = ref m in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\nif debug then Printf.printf \"rem %d %d\\n\" v u;\n\t\t m' := !m' - 1\n\t\t );\n\t\t done;\n\t\t res.(v) <- 1;\n\t\t bf (p + 1) (k - 1) !m';\n\t\t res.(v) <- 0\n\t );\n(*Printf.printf \"asd45\\n\";*)\n\t (let m' = ref m in\n\t let k' = ref k in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\n\t\t decr k';\n\t\t for i = 0 to Array.length es.(u) - 1 do\n\t\t\t let w = es.(u).(i) in\n\t\t\t if res.(w) = 0 then (\nif debug then Printf.printf \"rem2 %d %d %d\\n\" v u w;\n\t\t\t m' := !m' - 1\n\t\t\t );\n\t\t done;\n\t\t );\n\t\t res.(u) <- res.(u) + 1\n\t\t done;\n\t\t bf (p + 1) !k' !m';\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t res.(u) <- res.(u) - 1\n\t\t done;\n\t )\n\t )\n\t)\n )\n(*;Printf.printf \"asd5\\n\";*)\n in\n try\n\tbf 0 !k !m;\n\tfalse\n with\n\t| Found ->\n\t true\n in\n let l = ref 0l in\n let r = ref Int32.max_int in\n while !l < Int32.sub !r 1l do\n let m = Int32.div (Int32.add !l !r) 2l in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n if debug then Printf.printf \"QWE %ld\\n\" !r;\n ignore (solve !r);\n for i = 0 to n - 1 do\n if res.(i) > 0\n then Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n\n"}, {"source_code": "exception Found\n\nlet debug = false\n\nlet _ =\n let sqr x = x * x in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n (0, 0) in\n let es = Array.make (n * n) (0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tp.(i) <- (x, y)\n done;\n for i = 0 to n - 1 do\n let (x1, y1) = p.(i) in\n\tfor j = i + 1 to n - 1 do\n\t let (x2, y2) = p.(j) in\n\t let d =\n\t Int32.add\n\t (Int32.of_int (sqr (x2 - x1)))\n\t (Int32.of_int (sqr (y2 - y1)))\n\t in\n\t es.(i * n + j) <- (d, i, j)\n\tdone\n done;\n let cmp (x, _, _) (y, _, _) = Int32.compare y x in\n Array.sort cmp es\n in\n let res = Array.make n 0 in\n let solve d =\n if debug then Printf.printf \"solve %ld\\n\" d;\n let m =\n let m = ref 0 in\n\twhile !m < n * n &&\n\t (let (d', _, _) = es.(!m) in d' > d )\n\tdo\n\t incr m\n\tdone;\n\t!m\n in\n let es' = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n\tres.(i) <- 0\n done;\n for i = 0 to m - 1 do\n\tlet (_d, u, v) = es.(i) in\nif debug then Printf.printf \"edge %d %d %ld\\n\" u v _d;\n\t es'.(u) <- v :: es'.(u);\n\t es'.(v) <- u :: es'.(v)\n done\n in\n let es = Array.map Array.of_list es' in\n let vs = ref [] in\n let k = ref k in\n let m = ref m in\n let () =\n for i = 0 to n - 1 do\n\tif Array.length es.(i) = 0\n\tthen ()\n\telse if Array.length es.(i) = 1 && Array.length es.(es.(i).(0)) = 1\n\tthen (\n\t if i < es.(i).(0) then (\n (*Printf.printf \"remove %d-%d\\n\" i es.(i).(0);*)\n\t res.(i) <- 1;\n\t decr k;\n\t decr m;\n\t )\n\t) else if Array.length es.(i) = 1\n\tthen ()\n\telse vs := i :: !vs\n done\n in\n let vs = Array.of_list !vs in\n(*Printf.printf \"asd2 %ld %d\\n\" d (Array.length vs);*)\n let rec bf p k m =\n if debug then Printf.printf \"bf %d %d %d\\n\" p k m;\n assert (m >= 0);\n if k >= 0 then (\n\tif m = 0 then (\n\t let k = ref k in\n\t if !k = 0\n\t then raise Found;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 then (\n\t\tres.(i) <- 1;\n\t\tdecr k;\n\t\tif !k = 0\n\t\tthen raise Found\n\t )\n\t done;\n\t assert false\n\t) else if p < Array.length vs then (\n\t let v = vs.(p) in\nif debug then Printf.printf \"asd4 %d\\n\" v;\n\t if res.(v) = 0 then (\n\t (let m' = ref m in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\nif debug then Printf.printf \"rem %d %d\\n\" v u;\n\t\t m' := !m' - 1\n\t\t );\n\t\t done;\n\t\t res.(v) <- 1;\n\t\t bf (p + 1) (k - 1) !m';\n\t\t res.(v) <- 0\n\t );\n(*Printf.printf \"asd45\\n\";*)\n\t (let m' = ref m in\n\t let k' = ref k in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\n\t\t decr k';\n\t\t for i = 0 to Array.length es.(u) - 1 do\n\t\t\t let w = es.(u).(i) in\n\t\t\t if res.(w) = 0 then (\nif debug then Printf.printf \"rem2 %d %d %d\\n\" v u w;\n\t\t\t m' := !m' - 1\n\t\t\t );\n\t\t done;\n\t\t );\n\t\t res.(u) <- res.(u) + 1\n\t\t done;\n\t\t if !k' <= k - 2\n\t\t then bf (p + 1) !k' !m';\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t res.(u) <- res.(u) - 1\n\t\t done;\n\t )\n\t ) else bf (p + 1) k m\n\t)\n )\n(*;Printf.printf \"asd5\\n\";*)\n in\n try\n\tbf 0 !k !m;\n\tfalse\n with\n\t| Found ->\n\t true\n in\n let l = ref 0l in\n let r = ref Int32.max_int in\n while !l < Int32.sub !r 1l do\n let m = Int32.div (Int32.add !l !r) 2l in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n if debug then Printf.printf \"QWE %ld\\n\" !r;\n ignore (solve !r);\n for i = 0 to n - 1 do\n if res.(i) > 0\n then Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n\n"}, {"source_code": "exception Found\n\nlet debug = false\n\nlet _ =\n let sqr x = x * x in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n (0, 0) in\n let es = Array.make (n * n) (0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tp.(i) <- (x, y)\n done;\n for i = 0 to n - 1 do\n let (x1, y1) = p.(i) in\n\tfor j = i + 1 to n - 1 do\n\t let (x2, y2) = p.(j) in\n\t let d =\n\t Int32.add\n\t (Int32.of_int (sqr (x2 - x1)))\n\t (Int32.of_int (sqr (y2 - y1)))\n\t in\n\t es.(i * n + j) <- (d, i, j)\n\tdone\n done;\n let cmp (x, _, _) (y, _, _) = Int32.compare y x in\n Array.sort cmp es\n in\n let res = Array.make n 0 in\n let solve d =\n if debug then Printf.printf \"solve %ld\\n\" d;\n let m =\n let m = ref 0 in\n\twhile !m < n * n &&\n\t (let (d', _, _) = es.(!m) in d' > d )\n\tdo\n\t incr m\n\tdone;\n\t!m\n in\n let es' = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n\tres.(i) <- 0\n done;\n for i = 0 to m - 1 do\n\tlet (_d, u, v) = es.(i) in\nif debug then Printf.printf \"edge %d %d %ld\\n\" u v _d;\n\t es'.(u) <- v :: es'.(u);\n\t es'.(v) <- u :: es'.(v)\n done\n in\n let es = Array.map Array.of_list es' in\n let vs = ref [] in\n let k = ref k in\n let m = ref m in\n let () =\n for i = 0 to n - 1 do\n\tif Array.length es.(i) = 0\n\tthen ()\n\telse if Array.length es.(i) = 1 && Array.length es.(es.(i).(0)) = 1\n\tthen (\n\t if i < es.(i).(0) then (\n (*Printf.printf \"remove %d-%d\\n\" i es.(i).(0);*)\n\t res.(i) <- 1;\n\t decr k;\n\t decr m;\n\t )\n\t) else if Array.length es.(i) = 1\n\tthen ()\n\telse vs := i :: !vs\n done\n in\n let vs = Array.of_list !vs in\n(*Printf.printf \"asd2 %ld %d\\n\" d (Array.length vs);*)\n let rec bf p k m =\n if debug then Printf.printf \"bf %d %d %d\\n\" p k m;\n assert (m >= 0);\n if k >= 0 then (\n\tif m = 0 then (\n\t let k = ref k in\n\t if !k = 0\n\t then raise Found;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 then (\n\t\tres.(i) <- 1;\n\t\tdecr k;\n\t\tif !k = 0\n\t\tthen raise Found\n\t )\n\t done;\n\t assert false\n\t) else if p < Array.length vs then (\n\t let v = vs.(p) in\nif debug then Printf.printf \"asd4 %d\\n\" v;\n\t if res.(v) = 0 then (\n\t (let m' = ref m in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\nif debug then Printf.printf \"rem %d %d\\n\" v u;\n\t\t m' := !m' - 1\n\t\t );\n\t\t done;\n\t\t res.(v) <- 1;\n\t\t bf (p + 1) (k - 1) !m';\n\t\t res.(v) <- 0\n\t );\n(*Printf.printf \"asd45\\n\";*)\n\t (let m' = ref m in\n\t let k' = ref k in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\n\t\t decr k';\n\t\t for i = 0 to Array.length es.(u) - 1 do\n\t\t\t let w = es.(u).(i) in\n\t\t\t if res.(w) = 0 then (\nif debug then Printf.printf \"rem2 %d %d %d\\n\" v u w;\n\t\t\t m' := !m' - 1\n\t\t\t );\n\t\t done;\n\t\t );\n\t\t res.(u) <- res.(u) + 1\n\t\t done;\n\t\t bf (p + 1) !k' !m';\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t res.(u) <- res.(u) - 1\n\t\t done;\n\t )\n\t )\n\t)\n )\n(*;Printf.printf \"asd5\\n\";*)\n in\n try\n\tbf 0 !k !m;\n\tfalse\n with\n\t| Found ->\n\t true\n in\n let l = ref 0l in\n let r = ref Int32.max_int in\n while !l < Int32.sub !r 1l do\n let m = Int32.div (Int32.add !l !r) 2l in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n if debug then Printf.printf \"QWE %ld\\n\" !r;\n ignore (solve !r);\n for i = 0 to n - 1 do\n if res.(i) > 0\n then Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n\n"}, {"source_code": "exception Found\n\nlet _ =\n let sqr x = x * x in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n (0, 0) in\n let es = Array.make (n * n) (0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tp.(i) <- (x, y)\n done;\n for i = 0 to n - 1 do\n let (x1, y1) = p.(i) in\n\tfor j = i + 1 to n - 1 do\n\t let (x2, y2) = p.(j) in\n\t let d =\n\t Int32.add\n\t (Int32.of_int (sqr (x2 - x1)))\n\t (Int32.of_int (sqr (y2 - y1)))\n\t in\n\t es.(i * n + j) <- (d, i, j)\n\tdone\n done;\n let cmp (x, _, _) (y, _, _) = Int32.compare y x in\n Array.sort cmp es\n in\n let res = Array.make n 0 in\n let solve d =\n (*Printf.printf \"solve %ld\\n\" d;*)\n let m =\n let m = ref 0 in\n\twhile !m < n &&\n\t (let (d', _, _) = es.(!m) in d' > d )\n\tdo\n\t incr m\n\tdone;\n\t!m\n in\n let es' = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n\tres.(i) <- 0\n done;\n for i = 0 to m - 1 do\n\tlet (_, u, v) = es.(i) in\n (*Printf.printf \"edge %d %d\\n\" u v;*)\n\t es'.(u) <- v :: es'.(u);\n\t es'.(v) <- u :: es'.(v)\n done\n in\n let es = Array.map Array.of_list es' in\n let vs = ref [] in\n let k = ref k in\n let m = ref m in\n let () =\n for i = 0 to n - 1 do\n\tif Array.length es.(i) = 0\n\tthen ()\n\telse if Array.length es.(i) = 1 && Array.length es.(es.(i).(0)) = 1\n\tthen (\n\t if i < es.(i).(0) then (\n (*Printf.printf \"remove %d-%d\\n\" i es.(i).(0);*)\n\t res.(i) <- 1;\n\t decr k;\n\t decr m;\n\t )\n\t) else if Array.length es.(i) = 1\n\tthen ()\n\telse vs := i :: !vs\n done\n in\n let vs = Array.of_list !vs in\n(*Printf.printf \"asd2 %ld %d\\n\" d (Array.length vs);*)\n let rec bf p k m =\n(*Printf.printf \"bf %d %d %d\\n\" p k m;*)\n if k >= 0 then (\n\tif m = 0 then (\n\t let k = ref k in\n\t if !k = 0\n\t then raise Found;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 then (\n\t\tres.(i) <- 1;\n\t\tdecr k;\n\t\tif !k = 0\n\t\tthen raise Found\n\t )\n\t done;\n\t assert false\n\t) else if p < Array.length vs then (\n\t let v = vs.(p) in\n(*Printf.printf \"asd4 %d\\n\" v;*)\n\t if res.(v) = 0 then (\n\t (let m' = ref m in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\n(*Printf.printf \"rem %d %d\\n\" v u;*)\n\t\t m' := !m' - 1\n\t\t );\n\t\t done;\n\t\t res.(v) <- 1;\n\t\t bf (p + 1) (k - 1) !m';\n\t\t res.(v) <- 0\n\t );\n(*Printf.printf \"asd45\\n\";*)\n\t (let m' = ref m in\n\t\tfor i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\n\t\t for i = 0 to Array.length es.(u) - 1 do\n\t\t\tlet w = es.(u).(i) in\n\t\t\t if res.(w) = 0 then (\n(*Printf.printf \"rem2 %d %d %d\\n\" v u w;*)\n\t\t\t m' := !m' - 1\n\t\t\t );\n\t\t done;\n\t\t );\n\t\t res.(u) <- res.(u) + 1\n\t\tdone;\n\t\tbf (p + 1) (k - Array.length es.(v)) !m';\n\t\tfor i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t res.(u) <- res.(u) - 1\n\t\tdone;\n\t )\n\t )\n\t)\n )\n(*;Printf.printf \"asd5\\n\";*)\n in\n try\n\tbf 0 !k !m;\n\tfalse\n with\n\t| Found ->\n\t true\n in\n let l = ref 0l in\n let r = ref Int32.max_int in\n while !l < Int32.sub !r 1l do\n let m = Int32.div (Int32.add !l !r) 2l in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n(*Printf.printf \"QWE %ld\\n\" !r;*)\n ignore (solve !r);\n for i = 0 to n - 1 do\n if res.(i) > 0\n then Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n\n"}, {"source_code": "exception Found\n\nlet debug = false\n\nlet _ =\n let sqr x = x * x in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n (0, 0) in\n let es = Array.make (n * n) (0l, 0, 0) in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tp.(i) <- (x, y)\n done;\n for i = 0 to n - 1 do\n let (x1, y1) = p.(i) in\n\tfor j = i + 1 to n - 1 do\n\t let (x2, y2) = p.(j) in\n\t let d =\n\t Int32.add\n\t (Int32.of_int (sqr (x2 - x1)))\n\t (Int32.of_int (sqr (y2 - y1)))\n\t in\n\t es.(i * n + j) <- (d, i, j)\n\tdone\n done;\n let cmp (x, _, _) (y, _, _) = Int32.compare y x in\n Array.sort cmp es\n in\n let res = Array.make n 0 in\n let solve d =\n if debug then Printf.printf \"solve %ld\\n\" d;\n let m =\n let m = ref 0 in\n\twhile !m < n * n &&\n\t (let (d', _, _) = es.(!m) in d' > d )\n\tdo\n\t incr m\n\tdone;\n\t!m\n in\n let es' = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n\tres.(i) <- 0\n done;\n for i = 0 to m - 1 do\n\tlet (_d, u, v) = es.(i) in\nif debug then Printf.printf \"edge %d %d %ld\\n\" u v _d;\n\t es'.(u) <- v :: es'.(u);\n\t es'.(v) <- u :: es'.(v)\n done\n in\n let es = Array.map Array.of_list es' in\n let vs = ref [] in\n let k = ref k in\n let m = ref m in\n let () =\n for i = 0 to n - 1 do\n\tif Array.length es.(i) = 0\n\tthen ()\n\telse if Array.length es.(i) = 1 && Array.length es.(es.(i).(0)) = 1\n\tthen (\n\t if i < es.(i).(0) then (\n (*Printf.printf \"remove %d-%d\\n\" i es.(i).(0);*)\n\t res.(i) <- 1;\n\t decr k;\n\t decr m;\n\t )\n\t) else if Array.length es.(i) = 1\n\tthen ()\n\telse vs := i :: !vs\n done\n in\n let vs = Array.of_list !vs in\n(*Printf.printf \"asd2 %ld %d\\n\" d (Array.length vs);*)\n let rec bf p k m =\n if debug then Printf.printf \"bf %d %d %d\\n\" p k m;\n assert (m >= 0);\n if k >= 0 then (\n\tif m = 0 then (\n\t let k = ref k in\n\t if !k = 0\n\t then raise Found;\n\t for i = 0 to n - 1 do\n\t if res.(i) = 0 then (\n\t\tres.(i) <- 1;\n\t\tdecr k;\n\t\tif !k = 0\n\t\tthen raise Found\n\t )\n\t done;\n\t assert false\n\t) else if p < Array.length vs then (\n\t let v = vs.(p) in\nif debug then Printf.printf \"asd4 %d\\n\" v;\n\t if res.(v) = 0 then (\n\t (let m' = ref m in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\nif debug then Printf.printf \"rem %d %d\\n\" v u;\n\t\t m' := !m' - 1\n\t\t );\n\t\t done;\n\t\t res.(v) <- 1;\n\t\t bf (p + 1) (k - 1) !m';\n\t\t res.(v) <- 0\n\t );\n(*Printf.printf \"asd45\\n\";*)\n\t (let m' = ref m in\n\t let k' = ref k in\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t if res.(u) = 0 then (\n\t\t decr k';\n\t\t for i = 0 to Array.length es.(u) - 1 do\n\t\t\t let w = es.(u).(i) in\n\t\t\t if res.(w) = 0 then (\nif debug then Printf.printf \"rem2 %d %d %d\\n\" v u w;\n\t\t\t m' := !m' - 1\n\t\t\t );\n\t\t done;\n\t\t );\n\t\t res.(u) <- res.(u) + 1\n\t\t done;\n\t\t if !m' <= m - 2\n\t\t then bf (p + 1) !k' !m';\n\t\t for i = 0 to Array.length es.(v) - 1 do\n\t\t let u = es.(v).(i) in\n\t\t res.(u) <- res.(u) - 1\n\t\t done;\n\t )\n\t ) else bf (p + 1) k m\n\t)\n )\n(*;Printf.printf \"asd5\\n\";*)\n in\n try\n\tbf 0 !k !m;\n\tfalse\n with\n\t| Found ->\n\t true\n in\n let l = ref 0l in\n let r = ref Int32.max_int in\n while !l < Int32.sub !r 1l do\n let m = Int32.div (Int32.add !l !r) 2l in\n\tif solve m\n\tthen r := m\n\telse l := m\n done;\n if debug then Printf.printf \"QWE %ld\\n\" !r;\n ignore (solve !r);\n for i = 0 to n - 1 do\n if res.(i) > 0\n then Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n\n"}], "src_uid": "e88654aa9eefa73bd40cff74826d2e37"} {"nl": {"description": "You are given a bracket sequence consisting of $$$n$$$ characters '(' and/or )'. You perform several operations with it.During one operation, you choose the shortest prefix of this string (some amount of first characters of the string) that is good and remove it from the string.The prefix is considered good if one of the following two conditions is satisfied: this prefix is a regular bracket sequence; this prefix is a palindrome of length at least two. A bracket sequence is called regular if it is possible to obtain a correct arithmetic expression by inserting characters '+' and '1' into this sequence. For example, sequences (())(), () and (()(())) are regular, while )(, (() and (()))( are not.The bracket sequence is called palindrome if it reads the same back and forth. For example, the bracket sequences )), (( and )(() are palindromes, while bracket sequences (), )( and ))( are not palindromes.You stop performing the operations when it's not possible to find a good prefix. Your task is to find the number of operations you will perform on the given string and the number of remaining characters in the string.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 5 \\cdot 10^5$$$) \u2014 the length of the bracket sequence. The second line of the test case contains $$$n$$$ characters '(' and/or ')' \u2014 the bracket sequence itself. It is guaranteed that the sum of $$$n$$$ over all test cases do not exceed $$$5 \\cdot 10^5$$$ ($$$\\sum n \\le 5 \\cdot 10^5$$$).", "output_spec": "For each test case, print two integers $$$c$$$ and $$$r$$$ \u2014 the number of operations you will perform on the given bracket sequence and the number of characters that remain in the string after performing all operations.", "sample_inputs": ["5\n2\n()\n3\n())\n4\n((((\n5\n)((()\n6\n)((()("], "sample_outputs": ["1 0\n1 1\n2 0\n1 0\n1 1"], "notes": null}, "positive_code": [{"source_code": "exception Breakloop ;;\r\n\r\nlet isPalin tab i j = \r\n try \r\n for k = 0 to (j-i)/2 do \r\n if tab.(i+k) <> tab.(j-k) then (raise Breakloop)\r\n done; \r\n true\r\n with Breakloop -> false\r\n \r\n;;\r\nlet isReg tab k count =\r\n if tab.(k) = '(' then\r\n incr count ;\r\n if tab.(k) = ')' then \r\n decr count ;\r\n !count\r\n;;\r\n\r\nlet findShor tab i =\r\n let pretoto = (isReg tab i (ref 0)) in\r\n let rec aux tab i j count canReg= match j with \r\n |x when x >= (Array.length tab) -> prerr_endline \"tooHigh\" ; -1 \r\n |_ when canReg && (isReg tab j (ref count)) = 0 -> prerr_endline \"isReg\" ; j\r\n |_ when isPalin tab i j -> prerr_endline \"isPalin\" ; j\r\n |_ -> let toto = isReg tab j (ref count) in let temp = if toto<0 then false else true in\r\n aux tab i (j+1) toto temp\r\n in aux tab i (i+1) (if pretoto = -1 then -5 else 1) true\r\n;;\r\n\r\nlet finish tab = \r\n let rec aux tab ind count = match (findShor tab ind) with\r\n | -1 -> (count,Array.length tab - ind)\r\n |x when x = Array.length tab -1 -> (count+1,0)\r\n |x -> aux tab (x+1) (count+1)\r\n in aux tab 0 0\r\n;;\r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str = input_line stdin in\r\n let tab = Array.make len '(' in\r\n for j = 0 to len -1 do\r\n tab.(j)<- str.[j]\r\n done;\r\n let a,b = finish tab in\r\n print_endline ((string_of_int a)^\" \"^(string_of_int b))\r\ndone;\r\n;;"}], "negative_code": [{"source_code": "let isPalin tab i j = \r\n let toto = ref true in\r\n for k = 0 to j-i do \r\n if tab.(i+k) <> tab.(j-k) then toto := false \r\n done;\r\n !toto\r\n;;\r\nlet isReg tab i j = \r\n let toto = ref true in \r\n let count = ref 0 in\r\n for k = i to j do\r\n if !toto && tab.(k) = '(' then\r\n incr count ;\r\n if !toto && tab.(k) = ')' then \r\n decr count ;\r\n if !count < 0 then toto := false\r\n done ;\r\n if !count = 0 then !toto else false \r\n;;\r\n\r\nlet findShor tab i =\r\n let rec aux tab i j = match j with \r\n |x when x >= (Array.length tab) -> -1\r\n |_-> if isPalin tab i j || (tab.(i) = '(' && j-i mod 2 =1 && isReg tab i j) then j else aux tab i (j+1) \r\n in aux tab i (i+1)\r\n;;\r\n\r\nlet finish tab = \r\n let rec aux tab ind count = match (findShor tab ind) with\r\n | -1 -> (count,Array.length tab - ind)\r\n |x when x = Array.length tab -1 -> (count+1,0)\r\n |x -> aux tab (x+1) (count+1)\r\n in aux tab 0 0\r\n;;\r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str = input_line stdin in\r\n let tab = Array.make len '(' in\r\n for j = 0 to len -1 do\r\n tab.(j)<- str.[j]\r\n done;\r\n let a,b = finish tab in\r\n print_endline ((string_of_int a)^\" \"^(string_of_int b))\r\ndone;\r\n;;"}, {"source_code": "let isPalin tab i j = \r\n let toto = ref true in\r\n for k = 0 to j-i do \r\n if tab.(i+k) <> tab.(j-k) then toto := false \r\n done;\r\n !toto\r\n;;\r\nlet isReg tab i j = \r\n let toto = ref true in \r\n let count = ref 0 in\r\n for k = i to j do\r\n if !toto && tab.(k) = '(' then\r\n incr count ;\r\n if !toto && tab.(k) = ')' then \r\n decr count ;\r\n if !count < 0 then toto := false\r\n done ;\r\n if !count = 0 then !toto else false \r\n;;\r\n\r\nlet findShor tab i =\r\n let rec aux tab i j = match j with \r\n |x when x >= (Array.length tab) -> -1\r\n |_-> if isPalin tab i j || (tab.(i) = '(' && isReg tab i j) then j else aux tab i (j+2) \r\n in aux tab i (i+2)\r\n;;\r\n\r\nlet finish tab = \r\n let rec aux tab ind count = match (findShor tab ind) with\r\n | -1 -> (count,Array.length tab - ind)\r\n |x when x = Array.length tab -1 -> (count+1,0)\r\n |x -> aux tab (x+1) (count+1)\r\n in aux tab 0 0\r\n;;\r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str = input_line stdin in\r\n let tab = Array.make len '(' in\r\n for j = 0 to len -1 do\r\n tab.(j)<- str.[j]\r\n done;\r\n let a,b = finish tab in\r\n print_endline ((string_of_int a)^\" \"^(string_of_int b))\r\ndone;\r\n;;"}], "src_uid": "af3f3329e249c0a4fa14476626e9c97c"} {"nl": {"description": "A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle\u00a0\u2014 a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.Determine if it is possible for the islanders to arrange the statues in the desired order.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the total number of islands. The second line contains n space-separated integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009n\u2009-\u20091)\u00a0\u2014 the statue currently placed on the i-th island. If ai\u2009=\u20090, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0\u2009\u2264\u2009bi\u2009\u2264\u2009n\u2009-\u20091) \u2014 the desired statues of the ith island. Once again, bi\u2009=\u20090 indicates the island desires no statue. It is guaranteed that the bi are distinct.", "output_spec": "Print \"YES\" (without quotes) if the rearrangement can be done in the existing network, and \"NO\" otherwise.", "sample_inputs": ["3\n1 0 2\n2 0 1", "2\n1 0\n0 1", "4\n1 2 3 0\n0 3 2 1"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.In the second sample, the islanders can simply move statue 1 from island 1 to island 2.In the third sample, no sequence of movements results in the desired position."}, "positive_code": [{"source_code": "let print_tab tab w =\n print_endline w\n\nlet main () =\n let n = Scanf.scanf \"%d\" (fun i -> i) in\n let tab = Array.make (n-1) 0 in\n let tab' = Array.make (n-1) 0 in\n let j = ref 0 in\n for i = 1 to n do\n let a = Scanf.scanf \" %d\" (fun i -> i) in\n if a <> 0 then (tab.(!j) <- a;incr j);\n done;\n let j = ref 0 in\n for i = 1 to n do\n let a = Scanf.scanf \" %d\" (fun i -> i) in\n if a <> 0 then (tab'.(!j) <- a;incr j);\n done;\n let i = ref (-1) and y = tab.(0) in\n let flag = ref true in\n Array.iteri (fun j x -> if x = y then i := j) tab';\n for j = 0 to n-2 do\n flag := !flag && (tab'.((!i + j) mod (n-1)) = tab.(j));\n done;\n print_string (if !flag then \"YES\" else \"NO\");;\n\nmain ()\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let b = Array.init n (fun _ -> read_int()) in \n\n let fill_x a =\n let x = Array.make (n-1) 0 in\n let rec loop i j = if i=n then () else\n\tif a.(i) = 0 then loop (i+1) j\n\telse (\n\t x.(j) <- a.(i);\n\t loop (i+1) (j+1)\n\t)\n in\n loop 0 0;\n let rec find1 i = if x.(i) = 1 then i else find1 (i+1) in\n (x, find1 0)\n in\n\n let (ax,ai) = fill_x a in\n let (bx,bi) = fill_x b in\n\n let ans = forall 0 (n-2) (fun i -> ax.((ai+i) mod (n-1)) = bx.((bi+i) mod (n-1))) in\n\n if ans then printf \"YES\\n\" else printf \"NO\\n\"\n"}], "negative_code": [], "src_uid": "846681af4b4b6b29d2c9c450a945de90"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$, both consisting only of lowercase Latin letters.The substring $$$s[l..r]$$$ is the string which is obtained by taking characters $$$s_l, s_{l + 1}, \\dots, s_r$$$ without changing the order.Each of the occurrences of string $$$a$$$ in a string $$$b$$$ is a position $$$i$$$ ($$$1 \\le i \\le |b| - |a| + 1$$$) such that $$$b[i..i + |a| - 1] = a$$$ ($$$|a|$$$ is the length of string $$$a$$$).You are asked $$$q$$$ queries: for the $$$i$$$-th query you are required to calculate the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.", "input_spec": "The first line contains three integer numbers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \\le n, m \\le 10^3$$$, $$$1 \\le q \\le 10^5$$$) \u2014 the length of string $$$s$$$, the length of string $$$t$$$ and the number of queries, respectively. The second line is a string $$$s$$$ ($$$|s| = n$$$), consisting only of lowercase Latin letters. The third line is a string $$$t$$$ ($$$|t| = m$$$), consisting only of lowercase Latin letters. Each of the next $$$q$$$ lines contains two integer numbers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$) \u2014 the arguments for the $$$i$$$-th query.", "output_spec": "Print $$$q$$$ lines \u2014 the $$$i$$$-th line should contain the answer to the $$$i$$$-th query, that is the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.", "sample_inputs": ["10 3 4\ncodeforces\nfor\n1 3\n3 10\n5 6\n5 7", "15 2 3\nabacabadabacaba\nba\n1 15\n3 4\n2 14", "3 5 2\naaa\nbaaab\n1 3\n1 1"], "sample_outputs": ["0\n1\n0\n1", "4\n0\n3", "0\n0"], "notes": "NoteIn the first example the queries are substrings: \"cod\", \"deforces\", \"fo\" and \"for\", respectively."}, "positive_code": [{"source_code": "\nmodule type StringView = sig\n type t\n val length: t -> int\n val get: t -> int -> char\nend\n \nmodule MakeStringViewUtil(S: StringView) = struct\n let iteri (f: int -> char -> unit) (src: S.t): unit =\n for i = 0 to (S.length src - 1) do f i (S.get src i) done\nend\n \nmodule MakeStringViewEqual(A: StringView)(B: StringView) = struct\n let equal (a: A.t) (b: B.t) =\n if A.length a != B.length b then false\n else\n let rec f i =\n if i = A.length a then true\n else if A.get a i != B.get b i then false\n else f (i + 1)\n in f 0\nend\n\nmodule MakeStringTruncated(S: StringView) = struct\n type t = S.t * int * int\n let create src l r = (src, l, r)\n let length (_, l, r) = r - l\n let get (src, l, _) i = S.get src (l + i)\nend\n\nmodule StringTruncated = MakeStringTruncated(String)\n\nmodule Match = struct\n type t = int\n let compare = compare\nend\n\nmodule MatchSet = Set.Make(Match)\n\nmodule MakeStringFindMultiple(S: StringView) = struct\n \n let do_find (callback: int -> unit) (term: string) (src: S.t): unit =\n let tlen = String.length term in\n\n let module STruncated = MakeStringTruncated(S) in\n let module EqStrSTrunc = MakeStringViewEqual(String)(STruncated) in\n let module SUtil = MakeStringViewUtil(S) in\n\n SUtil.iteri (fun i c ->\n if i <= S.length src - tlen &&\n c = String.get term 0 then\n if EqStrSTrunc.equal term (STruncated.create src i (i + tlen))\n then callback i\n ) src\n\n let count (term: string) (src: S.t): int =\n let ret = ref 0 in\n do_find (fun _ -> ret := !ret + 1) term src;\n !ret\n \n let all_matches (term: string) (src: S.t): MatchSet.t =\n let ret = ref MatchSet.empty in\n do_find (fun i -> ret := MatchSet.add i !ret) term src;\n !ret\nend\n\nmodule StringFindMultiple = MakeStringFindMultiple(String)\nmodule StringTruncatedFindMultiple = MakeStringFindMultiple(StringTruncated)\n\nlet find_opt (tbl: ('k, 'v) Hashtbl.t) (key: 'k): 'v option =\n let ret = Hashtbl.find_all tbl key in\n match ret with\n | [a] -> Some a\n | _ -> None\n \nmodule MakeSetBipart(S: Set.S) = struct\n let bipart ((l, r): S.elt * S.elt) (src: S.t): S.t =\n let (_, present, ge) = S.split l src in\n let ge = if present then S.add l ge else ge in\n let (le, _, _) = S.split r ge in\n le\nend\n\nmodule type OrderedContainer = sig\n type t\n type elt\n val length: t -> int\n val get: int -> t -> elt\nend\n\nmodule MakeBisearch(C: OrderedContainer) = struct\n let find_first_index_satisfying (callback: C.elt -> bool) (cont: C.t): int option =\n let rec f l r =\n if l >= r\n then if l = r && C.get l cont |> callback then Some l else None\n else\n let m = (l + r) / 2 in\n if C.get m cont |> callback then f l m else f (m + 1) r\n in f 0 (C.length cont - 1)\nend\n\nmodule MakeSetToOrderedArray(S: Set.S)(E: Set.OrderedType with type t = S.elt) = struct\n let convert (src: S.t): E.t array =\n let l = S.elements src in\n let ret = Array.of_list l in\n Array.sort E.compare ret;\n ret\nend\n\nmodule MatchArray = struct\n type elt = Match.t\n type t = elt array\n let length = Array.length\n let get i a = Array.get a i\nend\n\nmodule MatchSetBipart = MakeSetBipart(MatchSet)\nmodule MatchSetToOrderedArray = MakeSetToOrderedArray(MatchSet)(Match)\nmodule MatchArrayBisearch = MakeBisearch(MatchArray)\n \nlet option_get ~(default: 'a) (x: 'a option): 'a =\n match x with | Some x -> x | None -> default\n \nlet _ =\n let n, m, q = Scanf.scanf \" %d %d %d\" (fun x y z -> x, y, z) in\n let s, t = Scanf.scanf \" %s %s\" (fun x y -> x, y) in\n let matches_set = StringFindMultiple.all_matches t s in\n let matches = MatchSetToOrderedArray.convert matches_set in\n (* let cache = Hashtbl.create 102539 in *)\n for i = 1 to q do\n let entry = Scanf.scanf \" %d %d\" (fun x y -> x, y) in\n let l, r = entry in\n let lb = matches |>\n MatchArrayBisearch.find_first_index_satisfying (fun x -> x >= l - 1) |>\n option_get ~default:(Array.length matches) in\n let rb = matches |>\n MatchArrayBisearch.find_first_index_satisfying (fun x -> x > r - String.length t) |>\n option_get ~default:(Array.length matches) in\n (* Printf.printf \"-:%d ::%d\\n\" lb rb; *)\n rb - lb |> max 0 |> string_of_int |> print_endline\n \n (* matches |>\n * MatchSetBipart.bipart (l - 1, r - String.length t + 1) |>\n * MatchSet.cardinal |>\n * string_of_int |> print_endline *)\n (* let strunc = StringTruncated.create s (l - 1) r in\n * StringTruncatedFindMultiple.count t strunc\n * |> string_of_int |> print_endline *)\n done\n"}, {"source_code": "\nmodule type StringView = sig\n type t\n val length: t -> int\n val get: t -> int -> char\nend\n \nmodule MakeStringViewUtil(S: StringView) = struct\n let iteri (f: int -> char -> unit) (src: S.t): unit =\n for i = 0 to (S.length src - 1) do f i (S.get src i) done\nend\n \nmodule MakeStringViewEqual(A: StringView)(B: StringView) = struct\n let equal (a: A.t) (b: B.t) =\n if A.length a != B.length b then false\n else\n let rec f i =\n if i = A.length a then true\n else if A.get a i != B.get b i then false\n else f (i + 1)\n in f 0\nend\n\nmodule MakeStringTruncated(S: StringView) = struct\n type t = S.t * int * int\n let create src l r = (src, l, r)\n let length (_, l, r) = r - l\n let get (src, l, _) i = S.get src (l + i)\nend\n\nmodule StringTruncated = MakeStringTruncated(String)\n\nmodule Match = struct\n type t = int\n let compare = compare\nend\n\nmodule MatchSet = Set.Make(Match)\n\nmodule MakeStringFindMultiple(S: StringView) = struct\n \n let do_find (callback: int -> unit) (term: string) (src: S.t): unit =\n let tlen = String.length term in\n\n let module STruncated = MakeStringTruncated(S) in\n let module EqStrSTrunc = MakeStringViewEqual(String)(STruncated) in\n let module SUtil = MakeStringViewUtil(S) in\n\n SUtil.iteri (fun i c ->\n if i <= S.length src - tlen &&\n c = String.get term 0 then\n if EqStrSTrunc.equal term (STruncated.create src i (i + tlen))\n then callback i\n ) src\n\n let count (term: string) (src: S.t): int =\n let ret = ref 0 in\n do_find (fun _ -> ret := !ret + 1) term src;\n !ret\n \n let all_matches (term: string) (src: S.t): MatchSet.t =\n let ret = ref MatchSet.empty in\n do_find (fun i -> ret := MatchSet.add i !ret) term src;\n !ret\nend\n\nmodule StringFindMultiple = MakeStringFindMultiple(String)\nmodule StringTruncatedFindMultiple = MakeStringFindMultiple(StringTruncated)\n\nlet find_opt (tbl: ('k, 'v) Hashtbl.t) (key: 'k): 'v option =\n let ret = Hashtbl.find_all tbl key in\n match ret with\n | [a] -> Some a\n | _ -> None\n \nmodule MakeSetBipart(S: Set.S) = struct\n let bipart ((l, r): S.elt * S.elt) (src: S.t): S.t =\n let (_, present, ge) = S.split l src in\n let ge = if present then S.add l ge else ge in\n let (le, _, _) = S.split r ge in\n le\nend\n\nmodule MatchSetBipart = MakeSetBipart(MatchSet)\n \nlet _ =\n let n, m, q = Scanf.scanf \" %d %d %d\" (fun x y z -> x, y, z) in\n let s, t = Scanf.scanf \" %s %s\" (fun x y -> x, y) in\n let matches = StringFindMultiple.all_matches t s in\n (* let cache = Hashtbl.create 102539 in *)\n for i = 1 to q do\n let entry = Scanf.scanf \" %d %d\" (fun x y -> x, y) in\n let l, r = entry in\n matches |>\n MatchSetBipart.bipart (l - 1, r - String.length t + 1) |>\n MatchSet.cardinal |>\n string_of_int |> print_endline\n (* let strunc = StringTruncated.create s (l - 1) r in\n * StringTruncatedFindMultiple.count t strunc\n * |> string_of_int |> print_endline *)\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let q = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let a = Array.make (n + 1) 0 in\n for i = 0 to n - m do\n let b = ref true in\n\tfor j = 0 to m - 1 do\n\t if s.[i + j] <> t.[j]\n\t then b := false\n\tdone;\n\tif !b\n\tthen a.(i + 1) <- a.(i) + 1\n\telse a.(i + 1) <- a.(i)\n done;\n for i = 1 to q do\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let res =\n\tlet r = r - m + 1 in\n\t if l <= r\n\t then a.(r) - a.(l - 1)\n\t else 0\n in\n\tPrintf.printf \"%d\\n\" res\n done;\n"}], "negative_code": [{"source_code": "\nmodule type StringView = sig\n type t\n val length: t -> int\n val get: t -> int -> char\nend\n \nmodule MakeStringViewUtil(S: StringView) = struct\n let iteri (f: int -> char -> unit) (src: S.t): unit =\n for i = 0 to (S.length src - 1) do f i (S.get src i) done\nend\n \nmodule MakeStringViewEqual(A: StringView)(B: StringView) = struct\n let equal (a: A.t) (b: B.t) =\n if A.length a != B.length b then false\n else\n let rec f i =\n if i = A.length a then true\n else if A.get a i != B.get b i then false\n else f (i + 1)\n in f 0\nend\n\nmodule MakeStringTruncated(S: StringView) = struct\n type t = S.t * int * int\n let create src l r = (src, l, r)\n let length (_, l, r) = r - l\n let get (src, l, _) i = S.get src (l + i)\nend\n\nmodule StringTruncated = MakeStringTruncated(String)\n\nmodule Match = struct\n type t = int\n let compare = compare\nend\n\nmodule MatchSet = Set.Make(Match)\n\nmodule MakeStringFindMultiple(S: StringView) = struct\n \n let do_find (callback: int -> unit) (term: string) (src: S.t): unit =\n let tlen = String.length term in\n\n let module STruncated = MakeStringTruncated(S) in\n let module EqStrSTrunc = MakeStringViewEqual(String)(STruncated) in\n let module SUtil = MakeStringViewUtil(S) in\n\n SUtil.iteri (fun i c ->\n if i <= S.length src - tlen &&\n c = String.get term 0 then\n if EqStrSTrunc.equal term (STruncated.create src i (i + tlen))\n then callback i\n ) src\n\n let count (term: string) (src: S.t): int =\n let ret = ref 0 in\n do_find (fun _ -> ret := !ret + 1) term src;\n !ret\n \n let all_matches (term: string) (src: S.t): MatchSet.t =\n let ret = ref MatchSet.empty in\n do_find (fun i -> ret := MatchSet.add i !ret) term src;\n !ret\nend\n\nmodule StringFindMultiple = MakeStringFindMultiple(String)\nmodule StringTruncatedFindMultiple = MakeStringFindMultiple(StringTruncated)\n\nlet find_opt (tbl: ('k, 'v) Hashtbl.t) (key: 'k): 'v option =\n let ret = Hashtbl.find_all tbl key in\n match ret with\n | [a] -> Some a\n | _ -> None\n \nmodule MakeSetBipart(S: Set.S) = struct\n let bipart ((l, r): S.elt * S.elt) (src: S.t): S.t =\n let (_, present, ge) = S.split l src in\n let ge = if present then S.add l ge else ge in\n let (le, _, _) = S.split r ge in\n le\nend\n\nmodule type OrderedContainer = sig\n type t\n type elt\n val length: t -> int\n val get: int -> t -> elt\nend\n\nmodule MakeBisearch(C: OrderedContainer) = struct\n let find_first_index_satisfying (callback: C.elt -> bool) (cont: C.t): int option =\n let rec f l r =\n if l >= r\n then if l = r && C.get l cont |> callback then Some l else None\n else\n let m = (l + r) / 2 in\n if C.get m cont |> callback then f l m else f (m + 1) r\n in f 0 (C.length cont - 1)\nend\n\nmodule MakeSetToOrderedArray(S: Set.S)(E: Set.OrderedType with type t = S.elt) = struct\n let convert (src: S.t): E.t array =\n let l = S.elements src in\n let ret = Array.of_list l in\n Array.sort E.compare ret;\n ret\nend\n\nmodule MatchArray = struct\n type elt = Match.t\n type t = elt array\n let length = Array.length\n let get i a = Array.get a i\nend\n\nmodule MatchSetBipart = MakeSetBipart(MatchSet)\nmodule MatchSetToOrderedArray = MakeSetToOrderedArray(MatchSet)(Match)\nmodule MatchArrayBisearch = MakeBisearch(MatchArray)\n \nlet option_get ~(default: 'a) (x: 'a option): 'a =\n match x with | Some x -> x | None -> default\n \nlet _ =\n let n, m, q = Scanf.scanf \" %d %d %d\" (fun x y z -> x, y, z) in\n let s, t = Scanf.scanf \" %s %s\" (fun x y -> x, y) in\n let matches_set = StringFindMultiple.all_matches t s in\n let matches = MatchSetToOrderedArray.convert matches_set in\n (* let cache = Hashtbl.create 102539 in *)\n for i = 1 to q do\n let entry = Scanf.scanf \" %d %d\" (fun x y -> x, y) in\n let l, r = entry in\n let lb = matches |>\n MatchArrayBisearch.find_first_index_satisfying (fun x -> x >= l - 1) |>\n option_get ~default:0 in\n let rb = matches |>\n MatchArrayBisearch.find_first_index_satisfying (fun x -> x <= r - String.length t) |>\n option_get ~default:(-1) in\n (rb - lb + 1) |> max 0 |> string_of_int |> print_endline\n \n (* matches |>\n * MatchSetBipart.bipart (l - 1, r - String.length t + 1) |>\n * MatchSet.cardinal |>\n * string_of_int |> print_endline *)\n (* let strunc = StringTruncated.create s (l - 1) r in\n * StringTruncatedFindMultiple.count t strunc\n * |> string_of_int |> print_endline *)\n done\n"}], "src_uid": "4cc5a6975d33cee60e53e8f648ec30de"} {"nl": {"description": "You are given array a with n integers and m queries. The i-th query is given with three integers li,\u2009ri,\u2009xi.For the i-th query find any position pi (li\u2009\u2264\u2009pi\u2009\u2264\u2009ri) so that api\u2009\u2260\u2009xi.", "input_spec": "The first line contains two integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the number of elements in a and the number of queries. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the elements of the array a. Each of the next m lines contains three integers li,\u2009ri,\u2009xi (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009xi\u2009\u2264\u2009106) \u2014 the parameters of the i-th query.", "output_spec": "Print m lines. On the i-th line print integer pi \u2014 the position of any number not equal to xi in segment [li,\u2009ri] or the value \u2009-\u20091 if there is no such number.", "sample_inputs": ["6 4\n1 2 1 1 3 5\n1 4 1\n2 6 2\n3 4 1\n3 4 2"], "sample_outputs": ["2\n6\n-1\n4"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let b = Array.make n (-1) in\n let _ =\n for i = n - 2 downto 0 do\n if a.(i) = a.(i + 1) then (\n\tb.(i) <- b.(i + 1)\n ) else (\n\tb.(i) <- i + 1\n )\n done;\n in\n for t = 1 to m do\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let r = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let res =\n\tif a.(l) <> x\n\tthen l + 1\n\telse if b.(l) < 0 || b.(l) > r\n\tthen -1\n\telse b.(l) + 1\n in\n\tPrintf.printf \"%d\\n\" res\n done;\n"}], "negative_code": [], "src_uid": "dcf7988c35bb34973e7b60afa7a0e68c"} {"nl": {"description": "You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\\dots,a_n$$$ ($$$l\\le a_i\\le r$$$) such that $$$\\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 10^4$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \\le n \\le 10^5$$$, $$$1\\le l\\le r\\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, if there is no solution, print \"NO\" (without quotes). You can print letters in any case (upper or lower). Otherwise, print \"YES\" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$\u00a0\u2014 the array you construct. If there are multiple solutions, you may output any.", "sample_inputs": ["4\n5 1 5\n9 1000 2000\n10 30 35\n1 1000000000 1000000000"], "sample_outputs": ["YES\n1 2 3 4 5\nYES\n1145 1926 1440 1220 1230 1350 1001 1000 1233\nNO\nYES\n1000000000"], "notes": "NoteIn the first test case, $$$\\gcd(1,a_1),\\gcd(2,a_2),\\ldots,\\gcd(5,a_5)$$$ are equal to $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, respectively."}, "positive_code": [{"source_code": "(* From @Darooha's code (https://codeforces.com/profile/Darooha) *)\r\n\r\nopen Printf \r\nopen Scanf\r\n \r\nlet ( ** ) a b = Int64.mul a b\r\nlet ( ++ ) a b = Int64.add a b\r\nlet long x = Int64.of_int x\r\nlet short x = Int64.to_int x\r\n \r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\r\n \r\n(* Main Code file *)\r\n\r\nlet rec sum = function\r\n | [] -> 0\r\n | h::t -> h + sum(t)\r\n \r\nlet rec all = function\r\n | [] -> true\r\n | h::t -> if h then all(t) else false\r\n\r\nlet rec any = function\r\n | [] -> false\r\n | h::t -> if h then true else any(t)\r\n \r\nlet divis a b = b mod a = 0\r\n\r\nlet gen l r i = if r / (i + 1) = (l - 1) / (i + 1) then -1 else r / (i + 1) * (i + 1)\r\nlet output_with_space x = printf \"%d \" x\r\nlet eqm x = x = -1\r\n\r\nlet () = \r\n let t = read_int() in\r\n for i=1 to t do\r\n let n = read_int() in\r\n let l = read_int() in\r\n let r = read_int() in\r\n let arr = Array.init n (gen l r) in\r\n let no = any (Array.to_list (Array.map eqm arr)) in\r\n if no then printf \"NO\\n\"\r\n else (printf \"YES\\n\");\r\n \r\n if not no then Array.iter output_with_space arr;\r\n \r\n print_newline()\r\n done;"}], "negative_code": [], "src_uid": "d2cc6efe7173a64482659ba59efeec16"} {"nl": {"description": "Recently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).", "input_spec": "The first line contains one integer t \u2014 the number of test cases to solve (1\u2009\u2264\u2009t\u2009\u2264\u20091000). Then t test cases follow. The first line of each test case contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of students. Then n lines follow. Each line contains two integer li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u20095000) \u2014 the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea. It is guaranteed that for every condition li\u2009-\u20091\u2009\u2264\u2009li holds. The sum of n over all test cases doesn't exceed 1000. Note that in hacks you have to set t\u2009=\u20091.", "output_spec": "For each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.", "sample_inputs": ["2\n2\n1 3\n1 4\n3\n1 5\n1 1\n2 3"], "sample_outputs": ["1 2 \n1 0 2"], "notes": "NoteThe example contains 2 tests: During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second. During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea. "}, "positive_code": [{"source_code": "(* Codeforces 920 B Tea Queue - train *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\ntype student =\n\t{ l : int; r : int };;\n\nlet rec read_students n = match n with\n\t| 0 -> []\n\t| _ ->\n\t\t\tlet ll = gr () in\n\t\t\tlet rr = gr () in\n\t\t\tlet st = { l = ll; r = rr } in\n\t\t\tst :: read_students (n - 1);;\n\nlet rec tea_times tm stl = match stl with\n\t| [] -> []\n\t| st :: t ->\n\t\t\tif st.l > tm then\n\t\t\t\tst.l :: tea_times (st.l +1) t\n\t\t\telse\n\t\t\tif st.r < tm then\n\t\t\t\t0 :: tea_times tm t\n\t\t\telse\n\t\t\t\ttm :: tea_times (tm + 1) t;;\n\nlet main() =\n\tlet t = gr () in\n\tfor i = 1 to t do\n\t\tbegin\n\t\t\tlet n = gr () in\n\t\t\tlet stl = read_students n in\n\t\t\tlet tt = tea_times 0 stl in\n\t\t\tlet _ = printlisti tt in\n\t\t\tprint_string \"\\n\"\n\t\tend\n\tdone;;\n\nmain();;"}], "negative_code": [], "src_uid": "471f80e349e70339eedd20d45b16e253"} {"nl": {"description": "Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.", "input_spec": "The first line of the input contains n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of bishops. Each of next n lines contains two space separated integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u20091000)\u00a0\u2014 the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.", "output_spec": "Output one integer\u00a0\u2014 the number of pairs of bishops which attack each other. ", "sample_inputs": ["5\n1 1\n1 5\n3 3\n5 1\n5 5", "3\n1 1\n2 3\n3 5"], "sample_outputs": ["6", "0"], "notes": "NoteIn the first sample following pairs of bishops attack each other: (1,\u20093), (1,\u20095), (2,\u20093), (2,\u20094), (3,\u20094) and (3,\u20095). Pairs (1,\u20092), (1,\u20094), (2,\u20095) and (4,\u20095) do not attack each other because they do not share the same diagonal."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let n = read_int () in\n let k = 1000 in\n let diag1 = Array.make (2*k) 0 in\n let diag2 = Array.make (2*k) 0 in\n\n for i=1 to n do\n let (x,y) = read_pair() in\n let (x,y) = (x-1,y-1) in\n diag1.(x+y) <- diag1.(x+y) + 1;\n diag2.(x-y+k-1) <- diag2.(x-y+k-1) + 1;\n done;\n \n let count ar = sum 0 (2*k-1) (fun i -> ((long (ar.(i)) -- 1L) ** (long (ar.(i)))) // 2L) 0L in\n\n printf \"%Ld\\n\" ((count diag1) ++ (count diag2))\n \n"}], "negative_code": [], "src_uid": "eb7457fe1e1b571e5ee8dd9689c7d66a"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\ldots, a_n$$$ of positive integers. A good pair is a pair of indices $$$(i, j)$$$ with $$$1 \\leq i, j \\leq n$$$ such that, for all $$$1 \\leq k \\leq n$$$, the following equality holds:$$$$$$ |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, $$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Find a good pair. Note that $$$i$$$ can be equal to $$$j$$$.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$) \u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array. The sum of $$$n$$$ for all test cases is at most $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single line with two space-separated indices $$$i$$$ and $$$j$$$ which form a good pair of the array. The case $$$i=j$$$ is allowed. It can be shown that such a pair always exists. If there are multiple good pairs, print any of them.", "sample_inputs": ["3\n\n3\n\n5 2 7\n\n5\n\n1 4 2 2 3\n\n1\n\n2"], "sample_outputs": ["2 3\n1 2\n1 1"], "notes": "NoteIn the first case, for $$$i = 2$$$ and $$$j = 3$$$ the equality holds true for all $$$k$$$: $$$k = 1$$$: $$$|a_2 - a_1| + |a_1 - a_3| = |2 - 5| + |5 - 7| = 5 = |2 - 7| = |a_2-a_3|$$$, $$$k = 2$$$: $$$|a_2 - a_2| + |a_2 - a_3| = |2 - 2| + |2 - 7| = 5 = |2 - 7| = |a_2-a_3|$$$, $$$k = 3$$$: $$$|a_2 - a_3| + |a_3 - a_3| = |2 - 7| + |7 - 7| = 5 = |2 - 7| = |a_2-a_3|$$$. "}, "positive_code": [{"source_code": "let parse s len = let rep = Array.make len 0 in\r\n let temp = ref \"\" in\r\n let count = ref 0 in\r\n for j = 0 to String.length s -1 do\r\n if s.[j] = ' ' then (rep.(!count)<-(int_of_string !temp) ; incr count ; temp := \"\")\r\n else (temp := !temp ^ (String.make 1 s.[j]))\r\n done; rep.(!count)<-(int_of_string !temp) ; rep ;;\r\n\r\nlet findmm tab = let min = ref (-1,0) in let max = ref (-1,0) in\r\n for i = 0 to Array.length tab -1 do\r\n if fst (!min) = -1 then (min := (i,tab.(i)) ; max := (i,tab.(i)) )\r\n else ( if snd (!min) > tab.(i) then (min := (i,tab.(i))) ; if snd (!max) < tab.(i) then(max := (i,tab.(i))) )\r\n done ; (fst (!min)+1, fst (!max) +1)\r\n;;\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string(input_line stdin) in\r\n let str = (input_line stdin) in\r\n let tab = parse str len in\r\n let max,min = findmm tab in\r\n print_endline (string_of_int max ^\" \"^ string_of_int min)\r\ndone ;;"}], "negative_code": [], "src_uid": "7af4eee2e9f60283c4d99200769c77ec"} {"nl": {"description": "Let's define $$$S(x)$$$ to be the sum of digits of number $$$x$$$ written in decimal system. For example, $$$S(5) = 5$$$, $$$S(10) = 1$$$, $$$S(322) = 7$$$.We will call an integer $$$x$$$ interesting if $$$S(x + 1) < S(x)$$$. In each test you will be given one integer $$$n$$$. Your task is to calculate the number of integers $$$x$$$ such that $$$1 \\le x \\le n$$$ and $$$x$$$ is interesting.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u00a0\u2014 number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$) for the $$$i$$$-th test case.", "output_spec": "Print $$$t$$$ integers, the $$$i$$$-th should be the answer for the $$$i$$$-th test case.", "sample_inputs": ["5\n1\n9\n10\n34\n880055535"], "sample_outputs": ["0\n1\n1\n3\n88005553"], "notes": "NoteThe first interesting number is equal to $$$9$$$."}, "positive_code": [{"source_code": "for i=1 to read_int() do\r\nprint_string(let x = read_int() in string_of_int ((x + 1) / 10));\r\nprint_string(\"\\n\")\r\ndone"}], "negative_code": [{"source_code": "for i=1 to read_int() do\r\nprint_string(let x = read_int() in string_of_int ((x + 1) / 10));\r\ndone"}, {"source_code": "print_string(let x = read_int() in string_of_int ((x + 1) / 10))"}], "src_uid": "8e4194b356500cdaacca2b1d49c2affb"} {"nl": {"description": "Alice gave Bob two integers $$$a$$$ and $$$b$$$ ($$$a > 0$$$ and $$$b \\ge 0$$$). Being a curious boy, Bob wrote down an array of non-negative integers with $$$\\operatorname{MEX}$$$ value of all elements equal to $$$a$$$ and $$$\\operatorname{XOR}$$$ value of all elements equal to $$$b$$$.What is the shortest possible length of the array Bob wrote?Recall that the $$$\\operatorname{MEX}$$$ (Minimum EXcluded) of an array is the minimum non-negative integer that does not belong to the array and the $$$\\operatorname{XOR}$$$ of an array is the bitwise XOR of all the elements of the array.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 5 \\cdot 10^4$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\leq a \\leq 3 \\cdot 10^5$$$; $$$0 \\leq b \\leq 3 \\cdot 10^5$$$)\u00a0\u2014 the $$$\\operatorname{MEX}$$$ and $$$\\operatorname{XOR}$$$ of the array, respectively.", "output_spec": "For each test case, output one (positive) integer\u00a0\u2014 the length of the shortest array with $$$\\operatorname{MEX}$$$ $$$a$$$ and $$$\\operatorname{XOR}$$$ $$$b$$$. We can show that such an array always exists.", "sample_inputs": ["5\n1 1\n2 1\n2 0\n1 10000\n2 10000"], "sample_outputs": ["3\n2\n3\n2\n3"], "notes": "NoteIn the first test case, one of the shortest arrays with $$$\\operatorname{MEX}$$$ $$$1$$$ and $$$\\operatorname{XOR}$$$ $$$1$$$ is $$$[0, 2020, 2021]$$$.In the second test case, one of the shortest arrays with $$$\\operatorname{MEX}$$$ $$$2$$$ and $$$\\operatorname{XOR}$$$ $$$1$$$ is $$$[0, 1]$$$.It can be shown that these arrays are the shortest arrays possible."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () =\n let msize = 300001 in\n let xorsum = Array.make msize 0 in\n for i=1 to msize-1 do\n xorsum.(i) <- xorsum.(i-1) lxor i\n done;\n let cases = read_int () in\n for case = 1 to cases do\n let (mex,xor) = read_pair() in\n let natural_xor = xorsum.(mex-1) in\n let need_one = natural_xor lxor xor in\n let answer = if xor = natural_xor then mex\n else if need_one > mex then mex+1\n else if need_one = mex then mex+2\n else mex+1\n in\n printf \"%d\\n\" answer\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet xor_sum i j f = fold i j (fun i a -> (f i) lxor a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let (mex,xor) = read_pair() in\n\n let answer = if xor = xor_sum 0 (mex-1) (fun i -> i) then mex else mex+1 in\n printf \"%d\\n\" answer\n done\n"}], "src_uid": "d6790c9b4b2e488768fb4e746ee7ebe0"} {"nl": {"description": "You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of points. Each of the next n lines contains two integers (xi,\u2009yi) (0\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109) \u2014 the coordinates of the i-th point.", "output_spec": "Print the only integer c \u2014 the number of parallelograms with the vertices at the given points.", "sample_inputs": ["4\n0 1\n1 0\n1 1\n2 0"], "sample_outputs": ["1"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = Array.make n 0 in\n let y = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n x.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n y.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n done;\n in\n let ht = Hashtbl.create (n * n) in\n let add key =\n try\n let c = Hashtbl.find ht key in\n\tHashtbl.replace ht key (c + 1)\n with\n | Not_found ->\n\t Hashtbl.replace ht key 1\n in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif i <> j then (\n\t let dx = x.(i) - x.(j) in\n\t let dy = y.(i) - y.(j) in\n\t add (dx, dy)\n\t)\n done\n done;\n in\n let res = ref 0 in\n Hashtbl.iter\n (fun _key c ->\n\t res := !res + c * (c - 1) / 2\n ) ht;\n res := !res / 4;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = Array.make n 0 in\n let y = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n x.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n y.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n done;\n in\n let ht = Hashtbl.create 10 in\n let add key =\n try\n let c = Hashtbl.find ht key in\n\tHashtbl.replace ht key (c + 1)\n with\n | Not_found ->\n\t Hashtbl.replace ht key 1\n in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif i <> j then (\n\t let dx = x.(i) - x.(j) in\n\t let dy = y.(i) - y.(j) in\n\t add (dx, dy)\n\t)\n done\n done;\n in\n let res = ref 0 in\n res := !res / 4;\n Hashtbl.iter\n (fun _key c ->\n\t res := !res + c * (c - 1) / 2\n ) ht;\n Printf.printf \"%d\\n\" !res\n"}], "src_uid": "bd519efcfaf5b43bb737337004a1c2c0"} {"nl": {"description": "The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x0,\u2009y0) of a rectangular squared field of size x\u2009\u00d7\u2009y, after that a mine will be installed into one of the squares of the field. It is supposed to conduct exactly x\u00b7y tests, each time a mine is installed into a square that has never been used before. The starting cell of the robot always remains the same.After placing the objects on the field the robot will have to run a sequence of commands given by string s, consisting only of characters 'L', 'R', 'U', 'D'. These commands tell the robot to move one square to the left, to the right, up or down, or stay idle if moving in the given direction is impossible. As soon as the robot fulfills all the sequence of commands, it will blow up due to a bug in the code. But if at some moment of time the robot is at the same square with the mine, it will also blow up, but not due to a bug in the code.Moving to the left decreases coordinate y, and moving to the right increases it. Similarly, moving up decreases the x coordinate, and moving down increases it.The tests can go on for very long, so your task is to predict their results. For each k from 0 to length(s) your task is to find in how many tests the robot will run exactly k commands before it blows up.", "input_spec": "The first line of the input contains four integers x, y, x0, y0 (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009500,\u20091\u2009\u2264\u2009x0\u2009\u2264\u2009x,\u20091\u2009\u2264\u2009y0\u2009\u2264\u2009y)\u00a0\u2014 the sizes of the field and the starting coordinates of the robot. The coordinate axis X is directed downwards and axis Y is directed to the right. The second line contains a sequence of commands s, which should be fulfilled by the robot. It has length from 1 to 100\u2009000 characters and only consists of characters 'L', 'R', 'U', 'D'.", "output_spec": "Print the sequence consisting of (length(s)\u2009+\u20091) numbers. On the k-th position, starting with zero, print the number of tests where the robot will run exactly k commands before it blows up.", "sample_inputs": ["3 4 2 2\nUURDRDRL", "2 2 2 2\nULD"], "sample_outputs": ["1 1 0 1 1 1 1 0 6", "1 1 1 1"], "notes": "NoteIn the first sample, if we exclude the probable impact of the mines, the robot's route will look like that: ."}, "positive_code": [{"source_code": "let xs, ys, x0, y0, s = Scanf.scanf \"%d %d %d %d %s\" (fun a b c d e -> (a,b,c-1,d-1,e)) ;;\nlet next (x,y) ch = match ch with\n | 'L' -> (x, max 0 (y-1))\n | 'R' -> (x, min (ys-1) (y+1))\n | 'U' -> (max 0 (x-1), y)\n | 'D' -> (min (xs-1) (x+1), y)\nlet v = Array.make_matrix xs ys false ;;\nlet rec f i (x,y) =\n if i < String.length s then (\n let mine =\n if not v.(x).(y) then (\n v.(x).(y) <- true;\n 1\n ) else\n 0\n in\n Printf.printf \"%d \" mine ;\n mine + ( f (i+1) (next (x,y) s.[i]) )\n ) else 0\n;;\nprint_int( xs * ys - f 0 (x0, y0) )\n"}, {"source_code": "let new_place (x,y) (x0,y0) l =\n let new_xy = ref (x0,y0) in\n (match l with\n | 'R' -> if y0 < y then new_xy := (x0, y0+1)\n | 'L' -> if y0 > 1 then new_xy := (x0, y0-1)\n | 'U' -> if x0 > 1 then new_xy := (x0-1,y0)\n | 'D' -> if x0 < x then new_xy := (x0+1,y0));\n !new_xy\n\nlet main () =\n let (lim,pos,w) = Scanf.scanf \"%d %d %d %d %s\" (fun i j k l m -> ((i,j),(ref (k,l)),m)) and mat = Array.make_matrix 555 555 true and compt = ref 0 in\n for i = 0 to String.length w - 1 do\n let (a,b) = !pos in\n Printf.printf (if mat.(a).(b) = true\n then (mat.(a).(b) <- false; incr compt; \"1 \")\n else \"0 \");\n pos := new_place lim !pos (w.[i]);\n done;\n Printf.printf \"%d\" ((fst lim) * (snd lim) - !compt);;\n\nmain ();;\n"}, {"source_code": "(* start: 9:58 *)\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \n\nlet () = \n let xm = read_int () in\n let ym = read_int () in\n let x0 = read_int () in\n let y0 = read_int () in \n\n let s = read_string () in\n\n let ns = String.length s in\n\n let bomb = Array.make_matrix (xm+1) (ym+1) 1 in\n\n let rec loop x y i times_died =\n if i = ns then times_died else (\n let times_died = times_died + bomb.(x).(y) in\n\tprintf \"%d \" bomb.(x).(y);\n\tbomb.(x).(y) <- 0;\n\tlet (x,y) =\n\t match s.[i] with\n\t | 'U' -> (max 1 (x-1), y)\n\t | 'D' -> (min xm (x+1), y)\n\t | 'L' -> (x, max 1 (y-1))\n\t | 'R' -> (x, min ym (y+1))\n\t | _ -> failwith \"bad char\"\n\tin\n\tloop x y (i+1) times_died\n )\n in \n\n let times_died = loop x0 y0 0 0 in\n\n printf \"%d\\n\" (xm*ym - times_died)\n"}], "negative_code": [], "src_uid": "22bebd448f93c0ff07d2be91e873521c"} {"nl": {"description": "Fox Ciel just designed a puzzle game called \"Polygon\"! It is played using triangulations of a regular n-edge polygon. The goal is to transform one triangulation to another by some tricky rules.Triangulation of an n-edge poylgon is a set of n\u2009-\u20093 diagonals satisfying the condition that no two diagonals share a common internal point.For example, the initial state of the game may look like (a) in above figure. And your goal may look like (c). In each step you can choose a diagonal inside the polygon (but not the one of edges of the polygon) and flip this diagonal. Suppose you are going to flip a diagonal a\u2009\u2013\u2009b. There always exist two triangles sharing a\u2009\u2013\u2009b as a side, let's denote them as a\u2009\u2013\u2009b\u2009\u2013\u2009c and a\u2009\u2013\u2009b\u2009\u2013\u2009d. As a result of this operation, the diagonal a\u2009\u2013\u2009b is replaced by a diagonal c\u2009\u2013\u2009d. It can be easily proven that after flip operation resulting set of diagonals is still a triangulation of the polygon.So in order to solve above case, you may first flip diagonal 6\u2009\u2013\u20093, it will be replaced by diagonal 2\u2009\u2013\u20094. Then you flip diagonal 6\u2009\u2013\u20094 and get figure (c) as result.Ciel just proved that for any starting and destination triangulations this game has a solution. She wants you to solve it in no more than 20\u2009000 steps for any puzzle satisfying n\u2009\u2264\u20091000.", "input_spec": "The first line contain an integer n (4\u2009\u2264\u2009n\u2009\u2264\u20091000), number of edges of the regular polygon. Then follows two groups of (n\u2009-\u20093) lines describing the original triangulation and goal triangulation. Description of each triangulation consists of (n\u2009-\u20093) lines. Each line contains 2 integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n), describing a diagonal ai\u2009\u2013\u2009bi. It is guaranteed that both original and goal triangulations are correct (i. e. no two diagonals share a common internal point in both of these triangulations).", "output_spec": "First, output an integer k (0\u2009\u2264\u2009k\u2009\u2264\u200920,\u2009000): number of steps. Then output k lines, each containing 2 integers ai and bi: the endpoints of a diagonal you are going to flip at step i. You may output ai and bi in any order. If there are several possible solutions, output any of them.", "sample_inputs": ["4\n1 3\n2 4", "6\n2 6\n3 6\n4 6\n6 2\n5 2\n4 2", "8\n7 1\n2 7\n7 3\n6 3\n4 6\n6 1\n6 2\n6 3\n6 4\n6 8"], "sample_outputs": ["1\n1 3", "2\n6 3\n6 4", "3\n7 3\n7 2\n7 1"], "notes": "NoteSample test 2 is discussed above and shown on the picture."}, "positive_code": [{"source_code": "module IntSet = Set.Make(struct\n type t = int\n let compare = compare\nend)\n\ntype dir = Forward | Backward\n\n(* normalise a triangulation to have all\n * diagonals coming from node 1 *)\nlet normal t s dir =\n (* try updating edge a-b to point to c *)\n let update a b c d =\n (* normalise this diagonal *)\n let (a, b) = if a > b then (b, a) else (a, b) in\n\n if Hashtbl.mem t (a, b) then begin\n (* if this is a diagonal, get the other triangle\n * points *)\n let (x, y) = Hashtbl.find t (a, b) in\n let old = if x = d then y else x in\n let v = if old > c then (c, old) else (old, c) in\n Hashtbl.replace t (a, b) v;\n\n (* this edge now has a triangle containing node 0\n * we'll flip it next time around *)\n if c = 0 then Stack.push (a, b) s\n end\n in\n\n let rec aux a =\n if Stack.is_empty s then a\n else begin\n let cur = Stack.pop s in\n let (l, r) = Hashtbl.find t cur in\n (* flip edge *)\n Hashtbl.remove t cur;\n Hashtbl.add t (l, r) cur;\n (* update adjacent triangles *)\n let (x, y) = cur in\n update x l r y; update x r l y;\n update y l r x; update y r l x;\n match dir with\n | Forward -> aux (cur :: a)\n | Backward -> aux ((l, r) :: a)\n end\n in\n aux []\n\n(* for each diagonal, find the\n * two triangles to which it belongs *)\nlet triang n t a s =\n let e = Hashtbl.create (Array.length t) in\n Array.iter (fun (x, y) ->\n (* get the node by following the diagonal\n * (or edge) prior to x-y and the one\n * after x-y *)\n let lx, _, gx = IntSet.split x a.(y) in\n let l = if IntSet.is_empty lx\n then IntSet.max_elt gx\n else IntSet.max_elt lx\n and r = if IntSet.is_empty gx\n then IntSet.min_elt lx\n else IntSet.min_elt gx\n in\n if l = 0 || r = 0 then Stack.push (x, y) s;\n let v = if l > r then (r, l) else (l, r) in\n Hashtbl.add e (x,y) v\n ) t;\n e\n\nlet read_diags n a =\n Array.init (n - 3) (fun _ ->\n Scanf.scanf \"%d %d\\n\" (fun x y ->\n let x = x - 1 and y = y - 1 in\n (* increment the degree of the edges *)\n a.(x) <- IntSet.add y a.(x);\n a.(y) <- IntSet.add x a.(y);\n (* add the edge to the table with no triangles *)\n if x > y then (y, x) else (x, y)\n )\n )\n\nlet make_deg n =\n Array.init n (fun i ->\n IntSet.union\n (IntSet.singleton ((i + 1) mod n))\n (IntSet.singleton ((i - 1 + n) mod n))\n )\n\nlet () = Scanf.scanf \"%d\\n\" (fun n ->\n let print s =\n print_string (String.concat \"\" (List.map (fun (x, y) -> Printf.sprintf \"%d %d\\n\" (x+1) (y+1)) s))\n in\n (* degree of each node *)\n let odeg = make_deg n\n and tdeg = make_deg n\n in\n (* edge lists *)\n let orig = read_diags n odeg\n and targ = read_diags n tdeg in\n\n let s = Stack.create () in\n let otri = triang n orig odeg s in\n let fsteps = List.rev (normal otri s Forward) in\n\n let s = Stack.create () in\n let ttri = triang n targ tdeg s in\n let bsteps = normal ttri s Backward in\n Printf.printf \"%d\\n\" (List.length fsteps + List.length bsteps);\n print fsteps; print bsteps;\n)\n"}], "negative_code": [], "src_uid": "627642daf1f6e7dbe86345bc77e2a006"} {"nl": {"description": "Recently, Tokitsukaze found an interesting game. Tokitsukaze had $$$n$$$ items at the beginning of this game. However, she thought there were too many items, so now she wants to discard $$$m$$$ ($$$1 \\le m \\le n$$$) special items of them.These $$$n$$$ items are marked with indices from $$$1$$$ to $$$n$$$. In the beginning, the item with index $$$i$$$ is placed on the $$$i$$$-th position. Items are divided into several pages orderly, such that each page contains exactly $$$k$$$ positions and the last positions on the last page may be left empty.Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded. Consider the first example from the statement: $$$n=10$$$, $$$m=4$$$, $$$k=5$$$, $$$p=[3, 5, 7, 10]$$$. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices $$$3$$$ and $$$5$$$. After, the first page remains to be special. It contains $$$[1, 2, 4, 6, 7]$$$, Tokitsukaze discards the special item with index $$$7$$$. After, the second page is special (since it is the first page containing a special item). It contains $$$[9, 10]$$$, Tokitsukaze discards the special item with index $$$10$$$. Tokitsukaze wants to know the number of operations she would do in total.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \\le n \\le 10^{18}$$$, $$$1 \\le m \\le 10^5$$$, $$$1 \\le m, k \\le n$$$)\u00a0\u2014 the number of items, the number of special items to be discarded and the number of positions in each page. The second line contains $$$m$$$ distinct integers $$$p_1, p_2, \\ldots, p_m$$$ ($$$1 \\le p_1 < p_2 < \\ldots < p_m \\le n$$$)\u00a0\u2014 the indices of special items which should be discarded.", "output_spec": "Print a single integer\u00a0\u2014 the number of operations that Tokitsukaze would do in total.", "sample_inputs": ["10 4 5\n3 5 7 10", "13 4 5\n7 8 9 10"], "sample_outputs": ["3", "1"], "notes": "NoteFor the first example: In the first operation, Tokitsukaze would focus on the first page $$$[1, 2, 3, 4, 5]$$$ and discard items with indices $$$3$$$ and $$$5$$$; In the second operation, Tokitsukaze would focus on the first page $$$[1, 2, 4, 6, 7]$$$ and discard item with index $$$7$$$; In the third operation, Tokitsukaze would focus on the second page $$$[9, 10]$$$ and discard item with index $$$10$$$. For the second example, Tokitsukaze would focus on the second page $$$[6, 7, 8, 9, 10]$$$ and discard all special items at once."}, "positive_code": [{"source_code": "let () =\n let split s =\n let rec loop i cur flag acc =\n if i = String.length s then ( if flag then cur :: acc else acc) else (\n match flag, s.[i] with\n | true, ' ' -> loop (i + 1) \"\" false (cur :: acc)\n | false, ' ' -> loop (i + 1) \"\" false acc\n | true, v -> loop (i + 1) (Printf.sprintf \"%s%c\" cur v) true acc\n | false, v -> loop (i + 1) (Printf.sprintf \"%s%c\" cur v) true acc\n )\n in\n List.map Int64.of_string (List.rev (loop 0 \"\" false []))\n in\n let main () =\n let n, m, k = Scanf.sscanf (read_line ()) \"%Ld %d %Ld\" (fun n m k -> n, m, k) in\n let p = split (read_line ()) in\n let (+@) = Int64.add in\n let (-@) = Int64.sub in\n let ( *@) = Int64.mul in\n let (/@) = Int64.div in\n let page k f f2 = (f -@ f2 -@ Int64.one) /@ k *@ k +@ f2 +@ k in\n let rec shred f2 cnt p =\n match p with\n | [] -> cnt, []\n | hd :: tl -> if Int64.compare hd f2 > 0 then cnt, p else shred f2 (cnt + 1) tl\n in\n let imin a b = if Int64.compare a b > 0 then b else a in\n let rec loop n m f2 p count =\n if m = 0 then count else\n match p with\n | [] -> count\n | f :: _ ->\n let f2 = if Int64.compare f f2 > 0 then imin n (page k f f2) else f2 in\n let c, p = shred f2 0 p in\n loop n (m - c) (min n (f2 +@ Int64.of_int c)) p (count + 1)\n in\n Printf.printf \"%d\\n\" (loop n m k p 0)\n in\n main ()\n"}], "negative_code": [], "src_uid": "684273a4c6711295996e520739744b0f"} {"nl": {"description": "Suppose you have two points $$$p = (x_p, y_p)$$$ and $$$q = (x_q, y_q)$$$. Let's denote the Manhattan distance between them as $$$d(p, q) = |x_p - x_q| + |y_p - y_q|$$$.Let's say that three points $$$p$$$, $$$q$$$, $$$r$$$ form a bad triple if $$$d(p, r) = d(p, q) + d(q, r)$$$.Let's say that an array $$$b_1, b_2, \\dots, b_m$$$ is good if it is impossible to choose three distinct indices $$$i$$$, $$$j$$$, $$$k$$$ such that the points $$$(b_i, i)$$$, $$$(b_j, j)$$$ and $$$(b_k, k)$$$ form a bad triple.You are given an array $$$a_1, a_2, \\dots, a_n$$$. Calculate the number of good subarrays of $$$a$$$. A subarray of the array $$$a$$$ is the array $$$a_l, a_{l + 1}, \\dots, a_r$$$ for some $$$1 \\le l \\le r \\le n$$$.Note that, according to the definition, subarrays of length $$$1$$$ and $$$2$$$ are good.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print the number of good subarrays of array $$$a$$$.", "sample_inputs": ["3\n4\n2 4 1 3\n5\n6 9 1 9 6\n2\n13 37"], "sample_outputs": ["10\n12\n3"], "notes": "NoteIn the first test case, it can be proven that any subarray of $$$a$$$ is good. For example, subarray $$$[a_2, a_3, a_4]$$$ is good since it contains only three elements and: $$$d((a_2, 2), (a_4, 4)) = |4 - 3| + |2 - 4| = 3$$$ $$$<$$$ $$$d((a_2, 2), (a_3, 3)) + d((a_3, 3), (a_4, 4)) = 3 + 1 + 2 + 1 = 7$$$; $$$d((a_2, 2), (a_3, 3))$$$ $$$<$$$ $$$d((a_2, 2), (a_4, 4)) + d((a_4, 4), (a_3, 3))$$$; $$$d((a_3, 3), (a_4, 4))$$$ $$$<$$$ $$$d((a_3, 3), (a_2, 2)) + d((a_2, 2), (a_4, 4))$$$; In the second test case, for example, subarray $$$[a_1, a_2, a_3, a_4]$$$ is not good, since it contains a bad triple $$$(a_1, 1)$$$, $$$(a_2, 2)$$$, $$$(a_4, 4)$$$: $$$d((a_1, 1), (a_4, 4)) = |6 - 9| + |1 - 4| = 6$$$; $$$d((a_1, 1), (a_2, 2)) = |6 - 9| + |1 - 2| = 4$$$; $$$d((a_2, 2), (a_4, 4)) = |9 - 9| + |2 - 4| = 2$$$; So, $$$d((a_1, 1), (a_4, 4)) = d((a_1, 1), (a_2, 2)) + d((a_2, 2), (a_4, 4))$$$."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet scan_int _ = scanf \" %d\" (fun x -> x)\n\nlet mono [x; y; z] =\n (x <= y && y <= z) || (x >= y && y >= z)\n\nlet rec comb k xs = match k, xs with\n | 0, _ -> [[]]\n | _, [] -> []\n | k, (x :: xs) -> let cons x xs = x :: xs in\n List.map (cons x) (comb (k-1) xs) @ comb k xs\n\nlet () =\n for _ = 1 to read_int () do\n let n = scan_int () in\n let a = Array.init n scan_int in\n let bad l len =\n l + len > n || List.exists mono @@ comb 3 @@ Array.to_list @@ Array.sub a l len\n in\n let ans = ref 0 in\n for l = 0 to n-1 do\n let rec test len = if not (bad l len) then (incr ans; test (len+1)) in\n test 1\n done;\n printf \"%d\\n\" !ans\n done\n"}], "negative_code": [], "src_uid": "e87ff02ce425fc3e96c09a15679aa656"} {"nl": {"description": "A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $$$1$$$ to $$$9$$$ (inclusive) are round.For example, the following numbers are round: $$$4000$$$, $$$1$$$, $$$9$$$, $$$800$$$, $$$90$$$. The following numbers are not round: $$$110$$$, $$$707$$$, $$$222$$$, $$$1001$$$.You are given a positive integer $$$n$$$ ($$$1 \\le n \\le 10^4$$$). Represent the number $$$n$$$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $$$n$$$ as a sum of the least number of terms, each of which is a round number.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing an integer $$$n$$$ ($$$1 \\le n \\le 10^4$$$).", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer must begin with an integer $$$k$$$ \u2014 the minimum number of summands. Next, $$$k$$$ terms must follow, each of which is a round number, and their sum is $$$n$$$. The terms can be printed in any order. If there are several answers, print any of them.", "sample_inputs": ["5\n5009\n7\n9876\n10000\n10"], "sample_outputs": ["2\n5000 9\n1\n7 \n4\n800 70 6 9000 \n1\n10000 \n1\n10"], "notes": null}, "positive_code": [{"source_code": "let re () = Scanf.scanf \" %d\" (fun x -> x) ;;\n\nlet rec f x =\n if x = 0 then [], 0\n else if x < 10 then [x], 1\n else let y = int_of_float (10. ** (float_of_int(int_of_float(log10 (float_of_int x))))) in\n let z = f (x - (x / y) * y) in\n (x / y) * y :: fst z, 1 + snd z\n;;\n\nopen List\nopen Printf\n\nlet solve () =\n let n = re () in\n let m = f n in\n printf \"%d \\n\" (snd m);\n iter (printf \"%d \") (fst m);\n printf \"\\n\"\n;;\n\nlet _ =\n let t = re () in\n for i = 1 to t do\n solve ()\n done\n;;\n\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n \nopen Printf\nopen List\n \nlet run () = \n let n = scan_int () in\n let rec f x b =\n if x = 0 then []\n else begin\n let rest = f (x/10) (b * 10) in\n let tmp = (x mod 10) * b in\n if tmp > 0 then tmp :: rest\n else rest\n end in\n let lst = f n 1 in\n printf \"%d\\n\" (List.length lst);\n List.iter (printf \"%d \") lst;\n print_endline \"\"\n;;\n \nlet () =\n let t = scan_int () in\n for i = 1 to t do\n run ()\n done\n;;\n"}, {"source_code": "(* Codeforces 1352 0 Sum of Round Numbers comp *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec round_list acc p10 n = match n with\n | 0 -> acc\n | _ -> \n\t\t\tlet r = n mod 10 in\n\t\t\tlet n_acc = if r == 0 then acc else (r*p10) :: acc in\n\t\t\tlet p10 = p10 * 10 in\n\t\t\tlet n = n / 10 in\n\t\t\tround_list n_acc p10 n;;\t\t\t\n \nlet do_one () = \n\tlet n = gr () in\n\tlet lr = round_list [] 1 n in\n\tlet _ = Printf.printf \"%d\\n\" (List.length lr) in\n\tlet _ = printlisti lr in\n\tprint_string \"\\n\";;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [{"source_code": "let re () = Scanf.scanf \" %d\" (fun x -> x) ;;\n\nlet rec f x =\n if x = 0 then []\n else if x < 10 then [x]\n else let y = int_of_float (10. ** (float_of_int(int_of_float(log10 (float_of_int x))))) in\n (x / y) * y :: f (x - (x / y) * y)\n;;\n\nopen List\nopen Printf\n\nlet solve () =\n let n = re () in\n let m = int_of_float(log10 (float_of_int n)) + 1 in\n printf \"%d \\n\" m;\n iter (printf \"%d \") (f n);\n printf \"\\n\"\n;;\n\nlet _ =\n let t = re () in\n for i = 1 to t do\n solve ()\n done\n;;\n\n"}, {"source_code": "let re () = Scanf.scanf \" %d\" (fun x -> x) ;;\n\nlet rec f x =\n if x = 0 then []\n else if x < 10 then [x]\n else let y = int_of_float (10. ** (float_of_int(int_of_float(log10 (float_of_int x))))) in\n (x / y) * y :: f (x - (x / y) * y)\n;;\n\nopen List\nopen Printf\n\nlet solve () =\n let n = re () in\n let () = List.iter (printf \"%d \") (f n) in\n printf \"\\n\"\n;;\n"}, {"source_code": "let re () = Scanf.scanf \" %d\" (fun x -> x) ;;\n\nlet rec f x =\n if x = 0 then []\n else if x < 10 then [x]\n else let y = int_of_float (10. ** (float_of_int(int_of_float(log10 (float_of_int x))))) in\n (x / y) * y :: f (x - (x / y) * y)\n;;\n\nopen List\nopen Printf\n\nlet solve () =\n let n = 4 in\n iter (printf \"%d \") (f n);\n printf \"\\n\"\n;;\n"}, {"source_code": "let re () = Scanf.scanf \" %d\" (fun x -> x) ;;\n\nlet rec f x =\n if x = 0 then []\n else if x < 10 then [x]\n else let y = int_of_float (10. ** (float_of_int(int_of_float(log10 (float_of_int x))))) in\n (x / y) * y :: f (x - (x / y) * y)\n;;\n\nlet rec print_list = function\n[] -> print_string \"\\n\"\n| e::l -> print_int e ; print_string \" \" ; print_list l\n\nlet solve () =\n let n = re () in\n print_list (f n)\n;;\n"}, {"source_code": "let re () = Scanf.scanf \" %d\" (fun x -> x) ;;\n\nlet rec f x =\n if x = 0 then []\n else if x < 10 then [x]\n else let y = int_of_float (10. ** (float_of_int(int_of_float(log10 (float_of_int x))))) in\n (x / y) * y :: f (x - (x / y) * y)\n;;\n\nopen List\nopen Printf\n\nlet solve () =\n let n = 4 in\n let m = int_of_float(log10 (float_of_int n)) + 1 in\n printf \"%d \\n\" m;\n iter (printf \"%d \") (f n);\n printf \"\\n\"\n;;\n"}], "src_uid": "cd2519f4a7888b2c292f05c64a9db13a"} {"nl": {"description": "Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A\u2009=\u2009(a1,\u2009a2,\u2009...,\u2009am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B\u2009=\u2009(b1,\u2009b2,\u2009...,\u2009bk).Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7109) \u2014 the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1\u2009\u2264\u2009m,\u2009k\u2009\u2264\u20091000). The given lines only contain characters \"R\", \"S\" and \"P\". Character \"R\" stands for the rock, character \"S\" represents the scissors and \"P\" represents the paper.", "output_spec": "Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.", "sample_inputs": ["7\nRPS\nRSPP", "5\nRRRRRRRR\nR"], "sample_outputs": ["3 2", "0 0"], "notes": "NoteIn the first sample the game went like this: R - R. Draw. P - S. Nikephoros loses. S - P. Polycarpus loses. R - P. Nikephoros loses. P - R. Polycarpus loses. S - S. Draw. R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2."}, "positive_code": [{"source_code": "let rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let m = String.length a in\n let k = String.length b in\n let ares = ref 0 in\n let bres = ref 0 in\n for i = 0 to m * k - 1 do\n let ai = i mod m\n and bi = i mod k in\n\tmatch a.[ai], b.[bi] with\n\t | 'R', 'S'\n\t | 'S', 'P'\n\t | 'P', 'R' -> incr bres\n\t | 'S', 'R'\n\t | 'P', 'S'\n\t | 'R', 'P' -> incr ares\n\t | _, _ -> ()\n done;\n let ar = Int32.mul (Int32.of_int !ares)\n (Int32.div n (Int32.of_int (m * k)))\n in\n let br = Int32.mul (Int32.of_int !bres)\n (Int32.div n (Int32.of_int (m * k)))\n in\n let ares = ref 0 in\n let bres = ref 0 in\n for i = 0 to Int32.to_int (Int32.rem n (Int32.of_int (m * k))) - 1 do\n\tlet ai = i mod m\n\tand bi = i mod k in\n\t match a.[ai], b.[bi] with\n\t | 'R', 'S'\n\t | 'S', 'P'\n\t | 'P', 'R' -> incr bres\n\t | 'S', 'R'\n\t | 'P', 'S'\n\t | 'R', 'P' -> incr ares\n\t | _, _ -> ()\n done;\n let ar = Int32.add ar (Int32.of_int !ares) in\n let br = Int32.add br (Int32.of_int !bres) in\n\tPrintf.printf \"%ld %ld\\n\" ar br\n"}], "negative_code": [], "src_uid": "9a365e26f58ecb22a1e382fad3062387"} {"nl": {"description": "Team Red and Team Blue competed in a competitive FPS. Their match was streamed around the world. They played a series of $$$n$$$ matches.In the end, it turned out Team Red won $$$r$$$ times and Team Blue won $$$b$$$ times. Team Blue was less skilled than Team Red, so $$$b$$$ was strictly less than $$$r$$$.You missed the stream since you overslept, but you think that the match must have been neck and neck since so many people watched it. So you imagine a string of length $$$n$$$ where the $$$i$$$-th character denotes who won the $$$i$$$-th match \u00a0\u2014 it is R if Team Red won or B if Team Blue won. You imagine the string was such that the maximum number of times a team won in a row was as small as possible. For example, in the series of matches RBBRRRB, Team Red won $$$3$$$ times in a row, which is the maximum.You must find a string satisfying the above conditions. If there are multiple answers, print any.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u00a0\u2014 the number of test cases. Each test case has a single line containing three integers $$$n$$$, $$$r$$$, and $$$b$$$ ($$$3 \\leq n \\leq 100$$$; $$$1 \\leq b < r \\leq n$$$, $$$r+b=n$$$).", "output_spec": "For each test case, output a single line containing a string satisfying the given conditions. If there are multiple answers, print any.", "sample_inputs": ["3\n7 4 3\n6 5 1\n19 13 6", "6\n3 2 1\n10 6 4\n11 6 5\n10 9 1\n10 8 2\n11 9 2"], "sample_outputs": ["RBRBRBR\nRRRBRR\nRRBRRBRRBRRBRRBRRBR", "RBR\nRRBRBRBRBR\nRBRBRBRBRBR\nRRRRRBRRRR\nRRRBRRRBRR\nRRRBRRRBRRR"], "notes": "NoteThe first test case of the first example gives the optimal answer for the example in the statement. The maximum number of times a team wins in a row in RBRBRBR is $$$1$$$. We cannot minimize it any further.The answer for the second test case of the second example is RRBRBRBRBR. The maximum number of times a team wins in a row is $$$2$$$, given by RR at the beginning. We cannot minimize the answer any further."}, "positive_code": [{"source_code": "let n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let a,b,c = Scanf.sscanf (input_line stdin) \"%d %d %d\" (fun a b c -> (a,b,c)) in\r\n let toto = b/(c+1) in\r\n let titi = ref (b mod (c+1)) in\r\n let rep = ref \"\" in \r\n let tyty = ref (!titi > 0) in\r\n for i = 0 to c -1 do\r\n rep := !rep ^ (String.make (toto+(if !tyty then 1 else 0)) 'R');\r\n rep := !rep ^ (String.make 1 'B') ;\r\n if !tyty then titi := !titi -1 ; if !titi <= 0 then tyty := false ;\r\n done;\r\n rep := !rep ^ (String.make (toto) 'R');\r\n print_endline (!rep)\r\ndone;"}], "negative_code": [], "src_uid": "7cec27879b443ada552a6474c4e45c30"} {"nl": {"description": "A tree is a connected undirected graph with n\u2009-\u20091 edges, where n denotes the number of vertices. Vertices are numbered 1 through n.Limak is a little polar bear. His bear family prepares a New Year tree every year. One year ago their tree was more awesome than usually. Thus, they decided to prepare the same tree in the next year. Limak was responsible for remembering that tree.It would be hard to remember a whole tree. Limak decided to describe it in his notebook instead. He took a pen and wrote n\u2009-\u20091 lines, each with two integers\u00a0\u2014 indices of two vertices connected by an edge.Now, the New Year is just around the corner and Limak is asked to reconstruct that tree. Of course, there is a problem. He was a very little bear a year ago, and he didn't know digits and the alphabet, so he just replaced each digit with a question mark\u00a0\u2014 the only character he knew. That means, for any vertex index in his notes he knows only the number of digits in it. At least he knows there were no leading zeroes.Limak doesn't want to disappoint everyone. Please, take his notes and reconstruct a New Year tree. Find any tree matching Limak's records and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree\u00a0\u2013 in this case print \"-1\" (without the quotes).", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of vertices. Each of the next n\u2009-\u20091 lines contains two space-separated non-empty strings, both consisting of questions marks only. No string has more characters than the number of digits in n.", "output_spec": "If there is no tree matching Limak's records, print the only line with \"-1\" (without the quotes). Otherwise, describe any tree matching Limak's notes. Print n\u2009-\u20091 lines, each with two space-separated integers\u00a0\u2013 indices of vertices connected by an edge. You can print edges in any order.", "sample_inputs": ["12\n? ?\n? ?\n? ?\n? ??\n?? ?\n?? ??\n? ??\n? ?\n? ?\n? ?\n? ?", "12\n?? ??\n? ?\n? ?\n? ??\n?? ?\n?? ??\n? ??\n? ?\n? ?\n?? ??\n? ?"], "sample_outputs": ["3 1\n1 6\n9 1\n2 10\n1 7\n8 1\n1 4\n1 10\n5 1\n10 11\n12 1", "-1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\n(* -----------------------------Begin MaxFlow----------------------------------*)\n\n(* Implementation of Dinic's algorithm for max flow. See ../spoj/PROFIT/\n for additional algorithms. *)\n\nlet infinite_c = 10000 (* \"infinite\" capacity *)\n\nlet maxflow s t adj cap =\n (* s and t are nodes (numbers). g is a graph (represented via an\n array of adjacency lists). c is a 1-d array of capacities. The\n adjacency list on node v stores pairs like (w,i) where w is the\n other node, and i is the index into the capacity array for where\n this capacity is stored. It's set up so that i lxor 1 is where the\n capacity of edge (w,v) is stored. We compute the maximum flow in\n the same representation as the capacities. It returns (f,resid)\n where f is the maximum flow, and resid is the residual capacities\n that result from that flow.\n *)\n\n let c = Array.copy cap in\n let n = Array.length adj in\n let alive = Array.make n [] in\n let level = Array.make n 0 in\n let queue = Array.make n 0 in\n let front = ref 0 in\n let back = ref 0 in\n\n let push w = queue.(!back) <- w; back := !back+1 in\n let eject() = let x = queue.(!front) in front := !front + 1; x; in\n\n let rec bfs () = \n let rec loop () = \n if !front = !back then false else\n\tlet v = eject() in\n\tif level.(v) = level.(t) then true else (\n\t List.iter ( \n\t fun (w,i) -> if level.(w) < 0 && c.(i) > 0 then (\n\t level.(w) <- level.(v) + 1;\n\t push w\n\t )\n\t ) adj.(v);\n\t loop ()\n\t)\n in\n level.(s) <- 0;\n back := 0; front := 0;\n push s;\n loop ();\n in\n \n let rec dfs v cap = \n (* Does a DFS from v looking for a path to t. It tries to push cap units\n of flow to t. It returns the amount of flow actually pushed *)\n if v=t then cap else\n let rec loop total remaining li = \n\tmatch li with \n\t | [] -> \n\t alive.(v) <- [];\n\t total\n\t | (w,i)::tail -> \n\t if level.(w) = level.(v)+1 && c.(i) > 0 then (\n\t let p = dfs w (min c.(i) remaining) in\n\t c.(i) <- c.(i) - p;\n\t c.(i lxor 1) <- c.(i lxor 1) + p;\n\t if remaining-p = 0 then (\n\t\talive.(v) <- li;\n\t\ttotal+p\n\t ) else loop (total+p) (remaining-p) tail\n\t ) else loop total remaining tail\n in loop 0 cap alive.(v)\n in\n \n let rec main_loop flow_so_far = \n Array.fill level 0 n (-1);\n Array.blit adj 0 alive 0 n;\n if bfs () then main_loop (flow_so_far + (dfs s infinite_c)) else (flow_so_far, c)\n in\n main_loop 0\n\n(* ------------------------------End MaxFlow-----------------------------------*) \n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet list_contains li x = List.exists (fun e -> e=x) li\nlet sortp (a,b) = (min a b, max a b)\nlet rec digits n = if n=0 then 0 else 1 + digits (n/10)\n \nlet rec ( ^ ) e p = \n if p=0 then 1 else\n let a = e^(p/2) in\n if (p land 1)=0 then a*a else e*a*a\n\nlet all_spanning_trees n nedges edges =\n let connected elist =\n let mark = Array.make n false in\n let rec dfs u =\n if not mark.(u) then (\n\tmark.(u) <- true;\n\tfor v = 0 to n-1 do\n\t if list_contains elist (sortp (u,v)) then dfs v\n\tdone\n )\n in\n dfs 0;\n forall 0 (n-1) (fun i -> mark.(i));\n in\n\n let rec list_trees i elist ac =\n if List.length elist = n-1 then\n if connected elist then elist::ac else ac\n else if i = nedges then ac\n else\n let ac = list_trees (i+1) elist ac in\n list_trees (i+1) (edges.(i)::elist) ac\n in\n \n list_trees 0 [] []\n \nlet () = \n let n = read_int () in\n let input = Array.init (n-1) (\n fun _ ->\n let a = -1 + String.length (read_string()) in\n let b = -1 + String.length (read_string()) in\n (a,b)\n ) in\n\n try (\n let nb = 1 + maxf 0 (n-2) (fun i -> snd (sortp input.(i))) in\n (* number of bundles *)\n if nb <> digits n then raise Not_found;\n let graph = Array.make_matrix nb nb 0 in\n for i=0 to n-2 do\n let (a,b) = sortp input.(i) in\n graph.(a).(b) <- graph.(a).(b) + 1;\n done;\n\n let edges = Array.of_list (\n fold 0 (nb-2) (\n\tfun u ac -> fold (u+1) (nb-1) \n\t (fun v ac -> if graph.(u).(v) > 0 then (u,v)::ac else ac) ac\n ) []\n ) in \n\n let nedges = Array.length edges in\n let valence = Array.make nb 0 in\n let base = Array.make nb 0 in\n \n for i=0 to nb-1 do\n let (lo,hi) = (10 ^ i, min ((10 ^ (i+1)) - 1) n) in\n base.(i) <- lo;\n valence.(i) <- (hi - lo + 1) - graph.(i).(i) - 1;\n if valence.(i) < 0 then raise Not_found;\n done;\n\n let test_tree elist =\n let nv = nb + nedges + 2 in (* number of vertices in flow graph *)\n let (s,t) = (nv-2, nv-1) in\n let ne = nb + 3 * nedges in (* number of edges in flow graph*)\n let adj = Array.make nv [] in\n let cap = Array.make (2*ne) 0 in\n\n let edge_no = ref 0 in\n let add_edge u v c =\n\tlet en = !edge_no in\n\tadj.(u) <- (v,en)::adj.(u);\n\tadj.(v) <- (u,en+1)::adj.(v);\n\tcap.(en) <- c;\n\tcap.(en+1) <- 0;\n\tedge_no := 2 + en\n in\n\n for i = 0 to nedges-1 do\n\tlet (u,v) = edges.(i) in\n\tlet w = nb+i in\n\tlet c = graph.(u).(v) in\n\tif c > 0 then (\n\t let c = if list_contains elist (u,v) then c-1 else c in\n\t add_edge s w c;\n\t add_edge w u c;\n\t add_edge w v c\n\t)\n done;\n\n for i=0 to nb-1 do\n\tadd_edge i t valence.(i)\n done;\n\n let (f,res) = maxflow s t adj cap in\n let required_flow = sum 0 (nb-1) (fun i -> valence.(i)) in\n if f <> required_flow then None else (\n\tlet cur = Array.copy base in\n\tlet tree = List.map (fun (u,v) -> (base.(u), base.(v))) elist in\n\n\t(* generate the coning edges *)\n\tlet tree = fold nb (nb+nedges-1) (\n\t fun w ac ->\n\t (* the first two elements of adj.(w) are the two vertices\n\t we need to work with *)\n\t let x = List.hd adj.(w) in\n\t let y = List.hd (List.tl adj.(w)) in\n\n\t let proc (v,ind) (v',_) ac =\n\t (* cone the base of v' to the vertices of v *)\n\t fold 1 (cap.(ind) - res.(ind)) (\n\t\tfun _ ac ->\n\t\t cur.(v) <- cur.(v) + 1;\n\t\t (base.(v'), cur.(v))::ac\n\t ) ac\n\t in\n\t proc x y (proc y x ac);\n\t) tree in\n\n\t(* generate the edges internal to a bundle *)\n\tlet tree = fold 0 (nb-1) (\n\t fun v ac ->\n\t fold 1 graph.(v).(v) (\n\t fun _ ac -> \n\t\tcur.(v) <- cur.(v) + 1;\n\t\t(base.(v), cur.(v))::ac\t\t\n\t ) ac\n\t) tree in\n\n\tSome tree\n )\n in\n\n let rec try_trees tlist =\n match tlist with\n\t| [] -> raise Not_found\n\t| elist::tail ->\n\t match test_tree elist with\n\t | None -> try_trees tail\n\t | Some st ->\n\t (* let's output the tree in exactly the form of the input *)\n\t let h = Hashtbl.create 100 in\n\t let insert (i,j) =\n\t\tlet (i,j) = sortp (i,j) in\n\t\tlet (p,q) = (-1 + digits i, -1 + digits j) in\n\t\tlet c = try Hashtbl.find h (p,q) with Not_found -> [] in\n\t\tHashtbl.replace h (p,q) ((i,j)::c)\n\t in\n\t let remove_and_get x =\n\t\tlet (p,q) = sortp x in\n\t\tlet li = Hashtbl.find h (p,q) in\n\t\tlet (i,j) = List.hd li in\n\t\tHashtbl.replace h (p,q) (List.tl li);\n\t\tif (p,q) = x then (i,j) else (j,i)\n\t in\n\t List.iter insert st;\n\t for i=0 to n-2 do\n\t\tlet (a,b) = remove_and_get input.(i) in\n\t\tprintf \"%d %d\\n\" a b\n\t done\n in\n\n try_trees (all_spanning_trees nb nedges edges)\n\n ) with Not_found -> printf \"-1\\n\" \n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\n(* -----------------------------Begin MaxFlow----------------------------------*)\n\n(* Implementation of Dinic's algorithm for max flow. See ../spoj/PROFIT/\n for additional algorithms. *)\n\nlet infinite_c = 10000 (* \"infinite\" capacity *)\n\nlet maxflow s t adj cap =\n (* s and t are nodes (numbers). g is a graph (represented via an\n array of adjacency lists). c is a 1-d array of capacities. The\n adjacency list on node v stores pairs like (w,i) where w is the\n other node, and i is the index into the capacity array for where\n this capacity is stored. It's set up so that i lxor 1 is where the\n capacity of edge (w,v) is stored. We compute the maximum flow in\n the same representation as the capacities. It returns (f,resid)\n where f is the maximum flow, and resid is the residual capacities\n that result from that flow.\n *)\n\n let c = Array.copy cap in\n let n = Array.length adj in\n let alive = Array.make n [] in\n let level = Array.make n 0 in\n let queue = Array.make n 0 in\n let front = ref 0 in\n let back = ref 0 in\n\n let push w = queue.(!back) <- w; back := !back+1 in\n let eject() = let x = queue.(!front) in front := !front + 1; x; in\n\n let rec bfs () = \n let rec loop () = \n if !front = !back then false else\n\tlet v = eject() in\n\tif level.(v) = level.(t) then true else (\n\t List.iter ( \n\t fun (w,i) -> if level.(w) < 0 && c.(i) > 0 then (\n\t level.(w) <- level.(v) + 1;\n\t push w\n\t )\n\t ) adj.(v);\n\t loop ()\n\t)\n in\n level.(s) <- 0;\n back := 0; front := 0;\n push s;\n loop ();\n in\n \n let rec dfs v cap = \n (* Does a DFS from v looking for a path to t. It tries to push cap units\n of flow to t. It returns the amount of flow actually pushed *)\n if v=t then cap else\n let rec loop total remaining li = \n\tmatch li with \n\t | [] -> \n\t alive.(v) <- [];\n\t total\n\t | (w,i)::tail -> \n\t if level.(w) = level.(v)+1 && c.(i) > 0 then (\n\t let p = dfs w (min c.(i) remaining) in\n\t c.(i) <- c.(i) - p;\n\t c.(i lxor 1) <- c.(i lxor 1) + p;\n\t if remaining-p = 0 then (\n\t\talive.(v) <- li;\n\t\ttotal+p\n\t ) else loop (total+p) (remaining-p) tail\n\t ) else loop total remaining tail\n in loop 0 cap alive.(v)\n in\n \n let rec main_loop flow_so_far = \n Array.fill level 0 n (-1);\n Array.blit adj 0 alive 0 n;\n if bfs () then main_loop (flow_so_far + (dfs s infinite_c)) else (flow_so_far, c)\n in\n main_loop 0\n\n(* ------------------------------End MaxFlow-----------------------------------*) \n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet list_contains li x = List.exists (fun e -> e=x) li\nlet sortp (a,b) = (min a b, max a b)\nlet rec digits n = if n=0 then 0 else 1 + digits (n/10)\n \nlet rec ( ^ ) e p = \n if p=0 then 1 else\n let a = e^(p/2) in\n if (p land 1)=0 then a*a else e*a*a\n\nlet all_spanning_trees n nedges edges =\n let connected elist =\n let mark = Array.make n false in\n let rec dfs u =\n if not mark.(u) then (\n\tmark.(u) <- true;\n\tfor v = 0 to n-1 do\n\t if list_contains elist (sortp (u,v)) then dfs v\n\tdone\n )\n in\n dfs 0;\n forall 0 (n-1) (fun i -> mark.(i));\n in\n\n let rec list_trees i elist ac =\n if List.length elist = n-1 then\n if connected elist then elist::ac else ac\n else if i = nedges then ac\n else\n let ac = list_trees (i+1) elist ac in\n list_trees (i+1) (edges.(i)::elist) ac\n in\n \n list_trees 0 [] []\n \nlet () = \n let n = read_int () in\n let input = Array.init (n-1) (\n fun _ ->\n let a = -1 + String.length (read_string()) in\n let b = -1 + String.length (read_string()) in\n (a,b)\n ) in\n\n try (\n let nb = 1 + maxf 0 (n-2) (fun i -> snd input.(i)) in\n (* number of bundles *)\n if nb <> digits n then raise Not_found;\n let graph = Array.make_matrix nb nb 0 in\n for i=0 to n-2 do\n let (a,b) = sortp input.(i) in\n graph.(a).(b) <- graph.(a).(b) + 1;\n done;\n\n let edges = Array.of_list (\n fold 0 (nb-2) (\n\tfun u ac -> fold (u+1) (nb-1) \n\t (fun v ac -> if graph.(u).(v) > 0 then (u,v)::ac else ac) ac\n ) []\n ) in \n\n let nedges = Array.length edges in\n let valence = Array.make nb 0 in\n let base = Array.make nb 0 in\n \n for i=0 to nb-1 do\n let (lo,hi) = (10 ^ i, min ((10 ^ (i+1)) - 1) n) in\n base.(i) <- lo;\n valence.(i) <- (hi - lo + 1) - graph.(i).(i) - 1;\n if valence.(i) < 0 then raise Not_found;\n done;\n\n let test_tree elist =\n let nv = nb + nedges + 2 in (* number of vertices in flow graph *)\n let (s,t) = (nv-2, nv-1) in\n let ne = nb + 3 * nedges in (* number of edges in flow graph*)\n let adj = Array.make nv [] in\n let cap = Array.make (2*ne) 0 in\n\n let edge_no = ref 0 in\n let add_edge u v c =\n\tlet en = !edge_no in\n\tadj.(u) <- (v,en)::adj.(u);\n\tadj.(v) <- (u,en+1)::adj.(v);\n\tcap.(en) <- c;\n\tcap.(en+1) <- 0;\n\tedge_no := 2 + en\n in\n\n for i = 0 to nedges-1 do\n\tlet (u,v) = edges.(i) in\n\tlet w = nb+i in\n\tlet c = graph.(u).(v) in\n\tif c > 0 then (\n\t let c = if list_contains elist (u,v) then c-1 else c in\n\t add_edge s w c;\n\t add_edge w u c;\n\t add_edge w v c\n\t)\n done;\n\n for i=0 to nb-1 do\n\tadd_edge i t valence.(i)\n done;\n\n let (f,res) = maxflow s t adj cap in\n let required_flow = sum 0 (nb-1) (fun i -> valence.(i)) in\n if f <> required_flow then None else (\n\tlet cur = Array.copy base in\n\tlet tree = List.map (fun (u,v) -> (base.(u), base.(v))) elist in\n\n\t(* generate the coning edges *)\n\tlet tree = fold nb (nb+nedges-1) (\n\t fun w ac ->\n\t (* the first two elements of adj.(w) are the two vertices\n\t we need to work with *)\n\t let x = List.hd adj.(w) in\n\t let y = List.hd (List.tl adj.(w)) in\n\n\t let proc (v,ind) (v',_) ac =\n\t (* cone the base of v' to the vertices of v *)\n\t fold 1 (cap.(ind) - res.(ind)) (\n\t\tfun _ ac ->\n\t\t cur.(v) <- cur.(v) + 1;\n\t\t (base.(v'), cur.(v))::ac\n\t ) ac\n\t in\n\t proc x y (proc y x ac);\n\t) tree in\n\n\t(* generate the edges internal to a bundle *)\n\tlet tree = fold 0 (nb-1) (\n\t fun v ac ->\n\t fold 1 graph.(v).(v) (\n\t fun _ ac -> \n\t\tcur.(v) <- cur.(v) + 1;\n\t\t(base.(v), cur.(v))::ac\t\t\n\t ) ac\n\t) tree in\n\n\tSome tree\n )\n in\n\n let rec try_trees tlist =\n match tlist with\n\t| [] -> raise Not_found\n\t| elist::tail ->\n\t match test_tree elist with\n\t | None -> try_trees tail\n\t | Some st ->\n\t (* let's output the tree in exactly the form of the input *)\n\t let h = Hashtbl.create 100 in\n\t let insert (i,j) =\n\t\tlet (i,j) = sortp (i,j) in\n\t\tlet (p,q) = (-1 + digits i, -1 + digits j) in\n\t\tlet c = try Hashtbl.find h (p,q) with Not_found -> [] in\n\t\tHashtbl.replace h (p,q) ((i,j)::c)\n\t in\n\t let remove_and_get x =\n\t\tlet (p,q) = sortp x in\n\t\tlet li = Hashtbl.find h (p,q) in\n\t\tlet (i,j) = List.hd li in\n\t\tHashtbl.replace h (p,q) (List.tl li);\n\t\tif (p,q) = x then (i,j) else (j,i)\n\t in\n\t List.iter insert st;\n\t for i=0 to n-2 do\n\t\tlet (a,b) = remove_and_get input.(i) in\n\t\tprintf \"%d %d\\n\" a b\n\t done\n in\n\n try_trees (all_spanning_trees nb nedges edges)\n\n ) with Not_found -> printf \"-1\\n\" \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\n(* -----------------------------Begin MaxFlow----------------------------------*)\n\n(* Implementation of Dinic's algorithm for max flow. See ../spoj/PROFIT/\n for additional algorithms. *)\n\nlet infinite_c = 10000 (* \"infinite\" capacity *)\n\nlet maxflow s t adj cap =\n (* s and t are nodes (numbers). g is a graph (represented via an\n array of adjacency lists). c is a 1-d array of capacities. The\n adjacency list on node v stores pairs like (w,i) where w is the\n other node, and i is the index into the capacity array for where\n this capacity is stored. It's set up so that i lxor 1 is where the\n capacity of edge (w,v) is stored. We compute the maximum flow in\n the same representation as the capacities. It returns (f,resid)\n where f is the maximum flow, and resid is the residual capacities\n that result from that flow.\n *)\n\n let c = Array.copy cap in\n let n = Array.length adj in\n let alive = Array.make n [] in\n let level = Array.make n 0 in\n let queue = Array.make n 0 in\n let front = ref 0 in\n let back = ref 0 in\n\n let push w = queue.(!back) <- w; back := !back+1 in\n let eject() = let x = queue.(!front) in front := !front + 1; x; in\n\n let rec bfs () = \n let rec loop () = \n if !front = !back then false else\n\tlet v = eject() in\n\tif level.(v) = level.(t) then true else (\n\t List.iter ( \n\t fun (w,i) -> if level.(w) < 0 && c.(i) > 0 then (\n\t level.(w) <- level.(v) + 1;\n\t push w\n\t )\n\t ) adj.(v);\n\t loop ()\n\t)\n in\n level.(s) <- 0;\n back := 0; front := 0;\n push s;\n loop ();\n in\n \n let rec dfs v cap = \n (* Does a DFS from v looking for a path to t. It tries to push cap units\n of flow to t. It returns the amount of flow actually pushed *)\n if v=t then cap else\n let rec loop total remaining li = \n\tmatch li with \n\t | [] -> \n\t alive.(v) <- [];\n\t total\n\t | (w,i)::tail -> \n\t if level.(w) = level.(v)+1 && c.(i) > 0 then (\n\t let p = dfs w (min c.(i) remaining) in\n\t c.(i) <- c.(i) - p;\n\t c.(i lxor 1) <- c.(i lxor 1) + p;\n\t if remaining-p = 0 then (\n\t\talive.(v) <- li;\n\t\ttotal+p\n\t ) else loop (total+p) (remaining-p) tail\n\t ) else loop total remaining tail\n in loop 0 cap alive.(v)\n in\n \n let rec main_loop flow_so_far = \n Array.fill level 0 n (-1);\n Array.blit adj 0 alive 0 n;\n if bfs () then main_loop (flow_so_far + (dfs s infinite_c)) else (flow_so_far, c)\n in\n main_loop 0\n\n(* ------------------------------End MaxFlow-----------------------------------*) \n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet list_contains li x = List.exists (fun e -> e=x) li\nlet sortp (a,b) = (min a b, max a b)\nlet rec digits n = if n=0 then 0 else 1 + digits (n/10)\n \nlet rec ( ^ ) e p = \n if p=0 then 1 else\n let a = e^(p/2) in\n if (p land 1)=0 then a*a else e*a*a\n\nlet all_spanning_trees n nedges edges =\n let connected elist =\n let mark = Array.make n false in\n let rec dfs u =\n if not mark.(u) then (\n\tmark.(u) <- true;\n\tfor v = 0 to n-1 do\n\t if list_contains elist (sortp (u,v)) then dfs v\n\tdone\n )\n in\n dfs 0;\n forall 0 (n-1) (fun i -> mark.(i));\n in\n\n let rec list_trees i elist ac =\n if List.length elist = n-1 then\n if connected elist then elist::ac else ac\n else if i = nedges then ac\n else\n let ac = list_trees (i+1) elist ac in\n list_trees (i+1) (edges.(i)::elist) ac\n in\n \n list_trees 0 [] []\n \nlet () = \n let n = read_int () in\n let input = Array.init (n-1) (\n fun _ ->\n let a = -1 + String.length (read_string()) in\n let b = -1 + String.length (read_string()) in\n (a,b)\n ) in\n\n try (\n let nb = 1 + maxf 0 (n-2) (fun i -> snd input.(i)) in\n (* number of bundles *)\n if nb <> digits n then raise Not_found;\n let graph = Array.make_matrix nb nb 0 in\n for i=0 to n-2 do\n let (a,b) = sortp input.(i) in\n graph.(a).(b) <- graph.(a).(b) + 1;\n done;\n\n let edges = Array.of_list (\n fold 0 (nb-2) (\n\tfun u ac -> fold (u+1) (nb-1) \n\t (fun v ac -> if graph.(u).(v) > 0 then (u,v)::ac else ac) ac\n ) []\n ) in \n\n let nedges = Array.length edges in\n let valence = Array.make nb 0 in\n let base = Array.make nb 0 in\n \n for i=0 to nb-1 do\n let (lo,hi) = (10 ^ i, min ((10 ^ (i+1)) - 1) n) in\n base.(i) <- lo;\n valence.(i) <- (hi - lo + 1) - graph.(i).(i) - 1;\n if valence.(i) < 0 then raise Not_found;\n done;\n\n let test_tree elist =\n let nv = nb + nedges + 2 in (* number of vertices in flow graph *)\n let (s,t) = (nv-2, nv-1) in\n let ne = nb + 3 * nedges in (* number of edges in flow graph*)\n let adj = Array.make nv [] in\n let cap = Array.make (2*ne) 0 in\n\n let edge_no = ref 0 in\n let add_edge u v c =\n\tlet en = !edge_no in\n\tadj.(u) <- (v,en)::adj.(u);\n\tadj.(v) <- (u,en+1)::adj.(v);\n\tcap.(en) <- c;\n\tcap.(en+1) <- 0;\n\tedge_no := 2 + en\n in\n\n for i = 0 to nedges-1 do\n\tlet (u,v) = edges.(i) in\n\tlet w = nb+i in\n\tlet c = graph.(u).(v) in\n\tif c > 0 then (\n\t let c = if list_contains elist (u,v) then c-1 else c in\n\t add_edge s w c;\n\t add_edge w u c;\n\t add_edge w v c\n\t)\n done;\n\n for i=0 to nb-1 do\n\tadd_edge i t valence.(i)\n done;\n\n let (f,res) = maxflow s t adj cap in\n let required_flow = sum 0 (nb-1) (fun i -> valence.(i)) in\n if f <> required_flow then None else (\n\tlet cur = Array.init nb (fun i -> base.(i)) in\n\tlet tree = List.map (fun (u,v) -> (base.(u), base.(v))) elist in\n\n\t(* generate the coning edges *)\n\tlet tree = fold nb (2*nb-2) (\n\t fun w ac ->\n\t (* the first two elements of adj.(w) are the two vertices\n\t we need to work with *)\n\t let x = List.hd adj.(w) in\n\t let y = List.hd (List.tl adj.(w)) in\n\n\t let proc (v,ind) (v',_) ac =\n\t (* cone the base of v' to the vertices of v *)\n\t fold 1 (cap.(ind) - res.(ind)) (\n\t\tfun _ ac ->\n\t\t cur.(v) <- cur.(v) + 1;\n\t\t (base.(v'), cur.(v))::ac\n\t ) ac\n\t in\n\t proc x y (proc y x ac);\n\t) tree in\n\n\t(* generate the edges internal to a bundle *)\n\tlet tree = fold 0 (nb-1) (\n\t fun v ac ->\n\t fold 1 graph.(v).(v) (\n\t fun _ ac -> \n\t\tcur.(v) <- cur.(v) + 1;\n\t\t(base.(v), cur.(v))::ac\t\t\n\t ) ac\n\t) tree in\n\n\tSome tree\n )\n in\n \n let rec try_trees tlist =\n match tlist with\n\t| [] -> raise Not_found\n\t| elist::tail ->\n\t match test_tree elist with\n\t | None -> try_trees tail\n\t | Some st ->\n\t (* let's output the tree in exactly the form of the input *)\n\t let h = Hashtbl.create 100 in\n\t let insert (i,j) =\n\t\tlet (i,j) = sortp (i,j) in\n\t\tlet (p,q) = (-1 + digits i, -1 + digits j) in\n\t\tlet c = try Hashtbl.find h (p,q) with Not_found -> [] in\n\t\tHashtbl.replace h (p,q) ((i,j)::c)\n\t in\n\t let remove_and_get x =\n\t\tlet (p,q) = sortp x in\n\t\tlet li = Hashtbl.find h (p,q) in\n\t\tlet (i,j) = List.hd li in\n\t\tHashtbl.replace h (p,q) (List.tl li);\n\t\tif (p,q) = x then (i,j) else (j,i)\n\t in\n\t List.iter insert st;\n\t for i=0 to n-2 do\n\t\tlet (i,j) = remove_and_get input.(i) in\n\t\tprintf \"%d %d\\n\" i j\n\t done\n in\n\n try_trees (all_spanning_trees nb nedges edges)\n\n ) with Not_found -> printf \"-1\\n\" \n"}], "src_uid": "ad225a9d59e3c0350f929ee112c19fd8"} {"nl": {"description": "Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted \u2014 that is, one call connects exactly two people.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1,\u2009id2,\u2009...,\u2009idn (0\u2009\u2264\u2009idi\u2009\u2264\u2009109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise. Consider the secretaries indexed from 1 to n in some way.", "output_spec": "Print a single integer \u2014 the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.", "sample_inputs": ["6\n0 1 7 1 7 10", "3\n1 1 1", "1\n0"], "sample_outputs": ["2", "-1", "0"], "notes": "NoteIn the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.In the second test sample the described situation is impossible as conferences aren't allowed."}, "positive_code": [{"source_code": "(* CF Arguments 291B *)\nopen Filename;;\nopen Str;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string (s ^ \" \"))) ls;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet debug = false;;\n\nlet n = gr()\n\nlet rec countpairs ls cnt = match ls with\n\t| [] -> cnt\n\t| 0 :: tl -> countpairs tl cnt\n\t| a :: b :: c :: tl when a == b && b == c -> (-1)\n\t| a :: b :: tl when a == b -> countpairs tl (cnt +1)\n\t| hd :: tl -> countpairs tl cnt;;\n\nlet main() =\n\tlet ids = readlist n [] in\n\tlet sids = List.sort compare ids in\n\tlet cnt = countpairs sids 0 in\n\tprint_int cnt;;\n\nmain ();;"}], "negative_code": [], "src_uid": "45e51f3dee9a22cee86e1a98da519e2d"} {"nl": {"description": "One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters \"a\", \"b\" and \"c\" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i\u2009\u2260\u2009j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs \"a\"-\"b\" and \"b\"-\"c\" are neighbouring, while letters \"a\"-\"c\" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.", "input_spec": "The first line of the input contains two integers n and m \u00a0\u2014 the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n,\u2009ui\u2009\u2260\u2009vi)\u00a0\u2014 the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.", "output_spec": "In the first line print \"Yes\" (without the quotes), if the string s Petya is interested in really exists and \"No\" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters \"a\", \"b\" and \"c\" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.", "sample_inputs": ["2 1\n1 2", "4 3\n1 2\n1 3\n1 4"], "sample_outputs": ["Yes\naa", "No"], "notes": "NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings \"aa\", \"ab\", \"ba\", \"bb\", \"bc\", \"cb\", \"cc\" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n\n let mat = Array.make_matrix n n true in\n \n for i=0 to m-1 do\n let (u,v) = read_pair() in\n let (u,v) = (u-1, v-1) in\n mat.(u).(v) <- false;\n mat.(v).(u) <- false; \n done;\n\n for v=0 to n-1 do mat.(v).(v) <- false done;\n\n let find =\n let rec loop (r,c) = if r=n then None else (\n if mat.(r).(c) then Some (r,c) else \n loop (if c\n printf \"Yes\\n\";\n for i=0 to n-1 do printf \"b\" done;\n print_newline()\n | Some (start,_) ->\n\n let label = Array.make n (-1) in\n let hist = Array.make 2 0 in\n let bipartite = ref true in\n let rec dfs v lab =\n\tif label.(v) >= 0 then (\n\t if label.(v) <> lab then bipartite := false\n\t) else (\n\t label.(v) <- lab;\n\t hist.(lab) <- hist.(lab) + 1;\n\t for w = 0 to n-1 do\n\t if mat.(v).(w) then dfs w (1-lab)\n\t done\n\t)\n in\n\n dfs start 0;\n\n if !bipartite && m = (n * (n-1))/2 - hist.(0) * hist.(1) then (\n\tprintf \"Yes\\n\";\n\tfor v=0 to n-1 do\n\t let letter = match label.(v) with\n\t | -1 -> 'b'\n\t | 0 -> 'a'\n\t | 1 -> 'c'\n\t | _ -> failwith \"bad label\"\n\t in\n\t printf \"%c\" letter\n\tdone;\n\tprint_newline()\n ) else (\n\tprintf \"No\\n\"\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n\n let mat = Array.make_matrix n n true in\n \n for i=0 to m-1 do\n let (u,v) = read_pair() in\n let (u,v) = (u-1, v-1) in\n mat.(u).(v) <- false;\n mat.(v).(u) <- false; \n done;\n\n for v=0 to n-1 do mat.(v).(v) <- false done;\n\n let find =\n let rec loop (r,c) = if r=n then None else (\n if mat.(r).(c) then Some (r,c) else \n loop (if c\n printf \"Yes\\n\";\n for i=0 to n-1 do printf \"b\" done;\n print_newline()\n | Some (start,_) ->\n\n let label = Array.make n (-1) in\n let hist = Array.make 2 0 in\n let bipartite = ref true in\n let rec dfs v lab =\n\tif label.(v) >= 0 then (\n\t if label.(v) <> lab then bipartite := false\n\t) else (\n\t label.(v) <- lab;\n\t hist.(lab) <- hist.(lab) + 1;\n\t for w = 0 to n-1 do\n\t if mat.(v).(w) then dfs w (1-lab)\n\t done\n\t)\n in\n\n dfs start 0;\n\n if !bipartite && m = hist.(0) * hist.(1) then (\n\tprintf \"Yes\\n\";\n\tfor v=0 to n-1 do\n\t let letter = match label.(v) with\n\t | -1 -> 'b'\n\t | 0 -> 'a'\n\t | 1 -> 'c'\n\t | _ -> failwith \"bad label\"\n\t in\n\t printf \"%c\" letter\n\tdone;\n\tprint_newline()\n ) else (\n\tprintf \"No\\n\"\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n\n let mat = Array.make_matrix n n true in\n \n for i=0 to m-1 do\n let (u,v) = read_pair() in\n let (u,v) = (u-1, v-1) in\n mat.(u).(v) <- false;\n mat.(v).(u) <- false; \n done;\n\n for v=0 to n-1 do mat.(v).(v) <- false done;\n\n let find =\n let rec loop (r,c) = if r=n then None else (\n if mat.(r).(c) then Some (r,c) else \n loop (if c\n printf \"Yes\\n\";\n for i=0 to n-1 do printf \"b\" done;\n print_newline()\n | Some (start,_) ->\n\n let label = Array.make n (-1) in\n\n let bipartite = ref true in\n\n let rec dfs v lab =\n\tif label.(v) >= 0 then (\n\t if label.(v) <> lab then bipartite := false\n\t) else (\n\t label.(v) <- lab;\n\t for w = 0 to n-1 do\n\t if mat.(v).(w) then dfs w (1-lab)\n\t done\n\t)\n in\n\n dfs start 0;\n\n if !bipartite then (\n\tprintf \"Yes\\n\";\n\tfor v=0 to n-1 do\n\t let letter = match label.(v) with\n\t | -1 -> 'b'\n\t | 0 -> 'a'\n\t | 1 -> 'c'\n\t | _ -> failwith \"bad label\"\n\t in\n\t printf \"%c\" letter\n\tdone;\n\tprint_newline()\n ) else (\n\tprintf \"No\\n\"\n )\n"}], "src_uid": "e71640f715f353e49745eac5f72e682a"} {"nl": {"description": "Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes A\u2009=\u2009{a1,\u2009\u2009a2,\u2009\u2009...,\u2009\u2009an}, where the width and the height of the i-th envelope is strictly higher than the width and the height of the (i\u2009\u2009-\u2009\u20091)-th envelope respectively. Chain size is the number of envelopes in the chain. Peter wants to make the chain of the maximum size from the envelopes he has, the chain should be such, that he'll be able to put a card into it. The card fits into the chain if its width and height is lower than the width and the height of the smallest envelope in the chain respectively. It's forbidden to turn the card and the envelopes. Peter has very many envelopes and very little time, this hard task is entrusted to you.", "input_spec": "The first line contains integers n, w, h (1\u2009\u2009\u2264\u2009n\u2009\u2264\u20095000, 1\u2009\u2264\u2009w,\u2009\u2009h\u2009\u2009\u2264\u2009106) \u2014 amount of envelopes Peter has, the card width and height respectively. Then there follow n lines, each of them contains two integer numbers wi and hi \u2014 width and height of the i-th envelope (1\u2009\u2264\u2009wi,\u2009\u2009hi\u2009\u2264\u2009106).", "output_spec": "In the first line print the maximum chain size. In the second line print the numbers of the envelopes (separated by space), forming the required chain, starting with the number of the smallest envelope. Remember, please, that the card should fit into the smallest envelope. If the chain of maximum size is not unique, print any of the answers. If the card does not fit into any of the envelopes, print number 0 in the single line.", "sample_inputs": ["2 1 1\n2 2\n2 2", "3 3 3\n5 4\n12 11\n9 8"], "sample_outputs": ["1\n1", "3\n1 3 2"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\ntype envelope = { w: int; h: int; i: int }\n\nlet lbound a n x =\n let rec go l h =\n if l = h then\n l\n else\n let m = (l+h)/2 in\n if a.(m).h < x.h then\n go (m+1) h\n else\n go l m\n in go 0 n\n\nlet () =\n let n = read_int 0 in\n let a = Array.make (n+1) { w = 0; h = 0; i = 0 } in\n let pred = Array.make (n+1) (-1) in\n for i = 0 to n do\n let w = read_int 0 in\n let h = read_int 0 in\n a.(i) <- { w; h; i }\n done;\n Array.sort (fun x y -> if x.w <> y.w then x.w-y.w else y.h-x.h) a;\n\n let rec lis size i =\n if i > n then\n size\n else if a.(i).i = 0 then (\n a.(0) <- a.(i);\n lis 1 (i+1)\n ) else if size = 0 then\n lis 0 (i+1)\n else (\n let x = lbound a size a.(i) in\n if x > 0 then (\n a.(x) <- a.(i);\n pred.(a.(x).i) <- a.(x-1).i\n );\n lis (if x = size then size+1 else size) (i+1)\n )\n in\n let size = lis 0 0 in\n Printf.printf \"%d\\n\" (size-1);\n\n let rec plan i acc =\n if pred.(i) < 0 then\n acc\n else\n plan pred.(i) (i::acc)\n in\n if size > 0 then\n List.iter (Printf.printf \"%d \") (plan a.(size-1).i [])\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\ntype envelope = { w: int; h: int; i: int }\n\nlet cmp x y =\n if x.w <> y.w then x.w-y.w else y.h-x.h\n\nlet lbound a n x =\n let rec go l h =\n if l = h then\n l\n else\n let m = (l+h)/2 in\n if cmp a.(m) x < 0 then\n go (m+1) h\n else\n go l m\n in go 0 n\n\nlet () =\n let n = read_int 0 in\n let a = Array.make (n+1) { w = 0; h = 0; i = 0 } in\n let pred = Array.make (n+1) (-1) in\n for i = 0 to n do\n let w = read_int 0 in\n let h = read_int 0 in\n a.(i) <- { w; h; i }\n done;\n Array.sort cmp a;\n\n let rec lis size i =\n if i > n then\n size\n else if a.(i).i = 0 then (\n a.(0) <- a.(i);\n lis 1 (i+1)\n ) else (\n if size > 0 then (\n let x = lbound a size a.(i) in\n if x > 0 then (\n a.(x) <- a.(i);\n pred.(a.(x).i) <- a.(x-1).i\n );\n lis (if x = size then size+1 else size) (i+1)\n ) else\n lis size (i+1)\n )\n in\n let size = lis 0 0 in\n Printf.printf \"%d\\n\" (size-1);\n\n let rec plan i acc =\n if pred.(i) < 0 then\n acc\n else\n plan pred.(i) (i::acc)\n in\n if size > 0 then\n List.iter (Printf.printf \"%d \") (plan a.(size-1).i [])\n"}], "src_uid": "6f88e3f4c8a8a444d44e58505a750d3e"} {"nl": {"description": "Consider a sequence of digits of length $$$2^k$$$ $$$[a_1, a_2, \\ldots, a_{2^k}]$$$. We perform the following operation with it: replace pairs $$$(a_{2i+1}, a_{2i+2})$$$ with $$$(a_{2i+1} + a_{2i+2})\\bmod 10$$$ for $$$0\\le i<2^{k-1}$$$. For every $$$i$$$ where $$$a_{2i+1} + a_{2i+2}\\ge 10$$$ we get a candy! As a result, we will get a sequence of length $$$2^{k-1}$$$.Less formally, we partition sequence of length $$$2^k$$$ into $$$2^{k-1}$$$ pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth $$$\\ldots$$$, the last pair consists of the ($$$2^k-1$$$)-th and ($$$2^k$$$)-th numbers. For every pair such that sum of numbers in it is at least $$$10$$$, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by $$$10$$$ (and don't change the order of the numbers).Perform this operation with a resulting array until it becomes of length $$$1$$$. Let $$$f([a_1, a_2, \\ldots, a_{2^k}])$$$ denote the number of candies we get in this process. For example: if the starting sequence is $$$[8, 7, 3, 1, 7, 0, 9, 4]$$$ then:After the first operation the sequence becomes $$$[(8 + 7)\\bmod 10, (3 + 1)\\bmod 10, (7 + 0)\\bmod 10, (9 + 4)\\bmod 10]$$$ $$$=$$$ $$$[5, 4, 7, 3]$$$, and we get $$$2$$$ candies as $$$8 + 7 \\ge 10$$$ and $$$9 + 4 \\ge 10$$$.After the second operation the sequence becomes $$$[(5 + 4)\\bmod 10, (7 + 3)\\bmod 10]$$$ $$$=$$$ $$$[9, 0]$$$, and we get one more candy as $$$7 + 3 \\ge 10$$$. After the final operation sequence becomes $$$[(9 + 0) \\bmod 10]$$$ $$$=$$$ $$$[9]$$$. Therefore, $$$f([8, 7, 3, 1, 7, 0, 9, 4]) = 3$$$ as we got $$$3$$$ candies in total.You are given a sequence of digits of length $$$n$$$ $$$s_1, s_2, \\ldots s_n$$$. You have to answer $$$q$$$ queries of the form $$$(l_i, r_i)$$$, where for $$$i$$$-th query you have to output $$$f([s_{l_i}, s_{l_i+1}, \\ldots, s_{r_i}])$$$. It is guaranteed that $$$r_i-l_i+1$$$ is of form $$$2^k$$$ for some nonnegative integer $$$k$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the sequence. The second line contains $$$n$$$ digits $$$s_1, s_2, \\ldots, s_n$$$ ($$$0 \\le s_i \\le 9$$$). The third line contains a single integer $$$q$$$ ($$$1 \\le q \\le 10^5$$$)\u00a0\u2014 the number of queries. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$)\u00a0\u2014 $$$i$$$-th query. It is guaranteed that $$$r_i-l_i+1$$$ is a nonnegative integer power of $$$2$$$.", "output_spec": "Output $$$q$$$ lines, in $$$i$$$-th line output single integer\u00a0\u2014 $$$f([s_{l_i}, s_{l_i + 1}, \\ldots, s_{r_i}])$$$, answer to the $$$i$$$-th query.", "sample_inputs": ["8\n8 7 3 1 7 0 9 4\n3\n1 8\n2 5\n7 7", "6\n0 1 2 3 3 5\n3\n1 2\n1 4\n3 6"], "sample_outputs": ["3\n1\n0", "0\n0\n1"], "notes": "NoteThe first example illustrates an example from the statement.$$$f([7, 3, 1, 7]) = 1$$$: sequence of operations is $$$[7, 3, 1, 7] \\to [(7 + 3)\\bmod 10, (1 + 7)\\bmod 10]$$$ $$$=$$$ $$$[0, 8]$$$ and one candy as $$$7 + 3 \\ge 10$$$ $$$\\to$$$ $$$[(0 + 8) \\bmod 10]$$$ $$$=$$$ $$$[8]$$$, so we get only $$$1$$$ candy.$$$f([9]) = 0$$$ as we don't perform operations with it."}, "positive_code": [{"source_code": "module M = Map.Make (struct type t = int * int let compare = compare end)\n\nlet () =\n let split s =\n let rec loop i cur flag acc =\n if i = String.length s then (\n if flag then cur :: acc else acc\n ) else (\n match flag, s.[i] with\n | true, ' ' -> loop (i + 1) 0 false (cur :: acc)\n | false, ' ' -> loop (i + 1) 0 false acc\n | true, v -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc\n | false, v -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc\n )\n in\n List.rev (loop 0 0 false [])\n in\n let main () =\n let _ = int_of_string (read_line ()) in\n let s = Array.of_list (split (read_line ())) in\n let q = int_of_string (read_line ()) in\n let arr = Array.make_matrix 16 100001 (-1) in\n let lookup = Array.make 65537 (-1) in\n for i = 0 to 15 do\n lookup.((2 lsl i) - 1) <- i;\n done;\n let query () =\n let l, r = Scanf.sscanf (read_line ()) \"%d %d\" (fun l r -> l - 1, r - 1) in\n let rec subq l r =\n if l = r then 0 else\n let key = lookup.(r - l) in\n if arr.(key).(l) >= 0 then arr.(key).(l) else\n if r = l + 1 then (\n let sum = s.(l) + s.(r) in\n let c = if sum >= 10 then 1 else 0 in\n c * 10 + sum mod 10\n ) else\n let ab1 = subq l ((r + l) / 2) in\n let ab2 = subq ((r + l) / 2 + 1) r in\n let a1 = ab1 / 10 in\n let b1 = ab1 mod 10 in\n let a2 = ab2 / 10 in\n let b2 = ab2 mod 10 in\n let a = if b1 + b2 >= 10 then a1 + a2 + 1 else a1 + a2 in\n let b = (b1 + b2) mod 10 in\n let v = a * 10 + b in\n let () = arr.(key).(l) <- v in\n v\n in\n let candy10 = subq l r in\n Printf.printf \"%d\\n\" (candy10 / 10)\n in\n for i = 1 to q do\n query ()\n done\n in\n main ()\n"}], "negative_code": [], "src_uid": "2cd91be317328fec207da6773ead4541"} {"nl": {"description": "There are $$$n$$$ slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists). When a slime with a value $$$x$$$ eats a slime with a value $$$y$$$, the eaten slime disappears, and the value of the remaining slime changes to $$$x - y$$$.The slimes will eat each other until there is only one slime left. Find the maximum possible value of the last slime.", "input_spec": "The first line of the input contains an integer $$$n$$$ ($$$1 \\le n \\le 500\\,000$$$) denoting the number of slimes. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$-10^9 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the value of $$$i$$$-th slime.", "output_spec": "Print an only integer\u00a0\u2014 the maximum possible value of the last slime.", "sample_inputs": ["4\n2 1 2 1", "5\n0 -1 -1 -1 -1"], "sample_outputs": ["4", "4"], "notes": "NoteIn the first example, a possible way of getting the last slime with value $$$4$$$ is: Second slime eats the third slime, the row now contains slimes $$$2, -1, 1$$$ Second slime eats the third slime, the row now contains slimes $$$2, -2$$$ First slime eats the second slime, the row now contains $$$4$$$ In the second example, the first slime can keep eating slimes to its right to end up with a value of $$$4$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\nend open MyInt64\n\n\nlet foldi_left f v a = \n\tlet m = ref v in for i=0 to (Array.length a -$ 1) do\n\t\tm := f !m (~~|i) a.(i)\n\tdone; !m\nlet for_all f a =\n\tlet fc = ref true in\n\tfor i=0 to (Array.length a -$1 ) do\n\t\tif not (f a.(i)) then fc := false\n\tdone; !fc\n\nlet sum a = Array.fold_left (+) 0L a\n\nlet () =\n\tlet n = get_i64 0 in\n\tlet a = input_i64_array n in\n\tArray.sort compare a;\n\t(\n\t\tif n = 1L then a @ (0L) else\n\t\tif a @ (n-1L) < 0L then (\n\t\t\t(* (a @ (n-1L)) - sum a *)\n\t\t\tlabs (sum a) + (a @ (n-1L)) * 2L\n\t\t) else if a @ 0L > 0L then (\n\t\t\tlabs (sum a) - (a @ 0L) * 2L \n\t\t) else (\n\t\t\tfoldi_left (fun (sneg,f,spos,pmin) i v ->\n\t\t\t\tif v < 0L then (sneg - v,f,spos,pmin)\n\t\t\t\telse if not f && v >= 0L then (\n\t\t\t\t\t(sneg,true,v,v)\n\t\t\t\t)\n\t\t\t\telse (\n\t\t\t\t\t(sneg,f,spos+v,pmin)\n\t\t\t\t)\n\t\t\t) (0L,false,0L,0L) a\n\t\t\t|> (fun (sneg,_,spos,pmin) -> sneg + spos)\n\t\t)\n\t\t(*\n\t\t\tfoldi_left (fun (sneg,f,spos,pmin) i v ->\n\t\t\t\tif v < 0L then (sneg - v,f,spos,pmin)\n\t\t\t\telse if not f && v >= 0L then (\n\t\t\t\t\t(sneg,true,v,v)\n\t\t\t\t)\n\t\t\t\telse (\n\t\t\t\t\t(sneg,f,spos+v,pmin)\n\t\t\t\t)\n\t\t\t) (0L,false,0L,0L) a\n\t\t\t|> (fun (sneg,_,spos,pmin) -> sneg + spos - pmin * 2L)\n\t\t) *)\n\t)\n\t|> printf \"%Ld\\n\"\n(* \n\tfoldi_left (fun (sneg,f) i v ->\n\t\tif v < 0L then (sneg - v,f)\n\t\telse if i = n-1L then (\n\n\t\t) else (\n\n\t\t)\n\t) 0L a\n\t|> printf \"%Ld\\n\" *)\n\t\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\nend open MyInt64\n\n\nlet foldi_left f v a = \n\tlet m = ref v in for i=0 to (Array.length a -$ 1) do\n\t\tm := f !m (~~|i) a.(i)\n\tdone; !m\nlet for_all f a =\n\tlet fc = ref true in\n\tfor i=0 to (Array.length a -$1 ) do\n\t\tif not (f a.(i)) then fc := false\n\tdone; !fc\n\nlet sum a = Array.fold_left (+) 0L a\n\nlet () =\n\tlet n = get_i64 0 in\n\tlet a = input_i64_array n in\n\tArray.sort compare a;\n\t(\n\t\tif a @ (n-1L) < 0L then (\n\t\t\t(a @ (n-1L)) - sum a\n\t\t) else (\n\t\t\tfoldi_left (fun (sneg,f,spos,pmin) i v ->\n\t\t\t\tif v < 0L then (sneg - v,f,spos,pmin)\n\t\t\t\telse if not f && v >= 0L then (\n\t\t\t\t\t(sneg,true,v,v)\n\t\t\t\t)\n\t\t\t\telse (\n\t\t\t\t\t(sneg,f,spos+v,pmin)\n\t\t\t\t)\n\t\t\t) (0L,false,0L,0L) a\n\t\t\t|> (fun (sneg,_,spos,pmin) -> sneg + spos - pmin * 2L)\n\t\t)\n\t)\n\t|> printf \"%Ld\\n\""}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\nend open MyInt64\n\n\nlet foldi_left f v a = \n\tlet m = ref v in for i=0 to (Array.length a -$ 1) do\n\t\tm := f !m (~~|i) a.(i)\n\tdone; !m\nlet for_all f a =\n\tlet fc = ref true in\n\tfor i=0 to (Array.length a -$1 ) do\n\t\tif not (f a.(i)) then fc := false\n\tdone; !fc\n\nlet sum a = Array.fold_left (+) 0L a\n\nlet () =\n\tlet n = get_i64 0 in\n\tlet a = input_i64_array n in\n\tArray.sort compare a;\n\t(\n\t\tif n = 1L then a @ (0L) else\n\t\tif a @ (n-1L) < 0L then (\n\t\t\t(* (a @ (n-1L)) - sum a *)\n\t\t\tlabs (sum a) + (a @ (n-1L)) * 2L\n\t\t) else (\n\t\t\tfoldi_left (fun (sneg,f,spos,pmin) i v ->\n\t\t\t\tif v < 0L then (sneg - v,f,spos,pmin)\n\t\t\t\telse if not f && v >= 0L then (\n\t\t\t\t\t(sneg,true,v,v)\n\t\t\t\t)\n\t\t\t\telse (\n\t\t\t\t\t(sneg,f,spos+v,pmin)\n\t\t\t\t)\n\t\t\t) (0L,false,0L,0L) a\n\t\t\t|> (fun (sneg,_,spos,pmin) -> sneg + spos - pmin * 2L)\n\t\t)\n\t)\n\t|> printf \"%Ld\\n\""}], "src_uid": "090f57798ba45ba9e4c9d2d0514e478c"} {"nl": {"description": "The Fair Nut found a string $$$s$$$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $$$p_1, p_2, \\ldots, p_k$$$, such that: For each $$$i$$$ ($$$1 \\leq i \\leq k$$$), $$$s_{p_i} =$$$ 'a'. For each $$$i$$$ ($$$1 \\leq i < k$$$), there is such $$$j$$$ that $$$p_i < j < p_{i + 1}$$$ and $$$s_j =$$$ 'b'. The Nut is upset because he doesn't know how to find the number. Help him.This number should be calculated modulo $$$10^9 + 7$$$.", "input_spec": "The first line contains the string $$$s$$$ ($$$1 \\leq |s| \\leq 10^5$$$) consisting of lowercase Latin letters.", "output_spec": "In a single line print the answer to the problem\u00a0\u2014 the number of such sequences $$$p_1, p_2, \\ldots, p_k$$$ modulo $$$10^9 + 7$$$.", "sample_inputs": ["abbaa", "baaaa", "agaa"], "sample_outputs": ["5", "4", "3"], "notes": "NoteIn the first example, there are $$$5$$$ possible sequences. $$$[1]$$$, $$$[4]$$$, $$$[5]$$$, $$$[1, 4]$$$, $$$[1, 5]$$$.In the second example, there are $$$4$$$ possible sequences. $$$[2]$$$, $$$[3]$$$, $$$[4]$$$, $$$[5]$$$.In the third example, there are $$$3$$$ possible sequences. $$$[1]$$$, $$$[3]$$$, $$$[4]$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nmodule CumulSumArray = struct\n let make a =\n let ln = Array.length a\n in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n let sum l r a = (* 0-origin,closed *)\n if l>r then 0L else (a.(r+$1) - a.(l))\n let sum_1orig l r a = sum (l-$1) (r-$1) a\nend\nmodule Imos = struct\n let make n = Array.make (i32 n +$ 2) 0L\n let add_destructive_closed l r a =\n a.(l+$1) <- a.(l+$1) + 1L;\n a.(r+$2) <- a.(r+$2) - 1L\n let add_destructive_1orig_closed l r a =\n a.(l) <- a.(l) + 1L;\n a.(r+$1) <- a.(r+$1) - 1L\n let add_destructive_1orig_closed_safe l r a =\n let l = max l 0 in a.(l) <- a.(l) + 1L;\n let r = min (r+$1) (Array.length a-$1) in a.(r) <- a.(r) - 1L\n let cumulate_destructive a =\n for i=1 to Array.length a -$ 2 do a.(i) <- a.(i) + a.(i-$1) done\nend\nlet () =\n let s = scanf \" %s\" @@ id in\n let n = String.length s in\n (* let a = make (String.length s) 'z' in\n (* let b = make (String.length s) 0L in *)\n let b = Imos.make @@ i64 n in\n String.iteri (fun i v -> a.(i) <- v;\n (* if v='b' then b.(i) <- 1L; *)\n if v='b' then Imos.add_destructive_1orig_closed i i b;\n ) s;\n Imos.cumulate_destructive b;\n (* let b_query = Imos.make b in *)\n (* iteri (fun i v ->\n if v='a' then (\n\n )\n ) a; *)\n let dp = make (n+$1) 0L in\n let fprev = ref false in\n repi 1 n (fun i ->\n if s.[i] = 'a' then (\n dp.(i) <- dp.(i) + 1L;\n )\n ) *)\n (* let r = ref [] in\n let rr = ref [] in\n String.iter (fun v ->\n (* printf \"%c:\" v; *)\n if v='a' then r := v::!r\n else if v='b' then (\n if List.length !r > 0 then (\n rr := (List.rev !r) :: !rr;\n r := []\n )\n );\n (* List.iter (fun ls -> print_list (String.make 1) ls) (List.rev !rr); *)\n (* print_list (String.make 1) !r; *)\n ) s;\n if List.length !r > 0 then (\n rr := (List.rev !r) :: !rr;\n );\n rr := List.rev !rr;\n (* List.iter (fun ls -> print_list (String.make 1) ls) !rr; *)\n List.fold_left (fun u ls ->\n let k = llen ls in\n let r = u + u * k + k in\n (* printf \"%Ld\\n\" r; *)\n r\n ) 0L !rr\n |> printf \"%Ld\\n\"; *)\n let md = 1000000007L in\n let r = ref 0L in let rr = ref [] in\n String.iter (fun v ->\n if v='a' then r += 1L\n else if v='b' then (\n if !r>0L then (\n rr := !r :: !rr;\n r := 0L\n )\n )\n ) s;\n if !r>0L then rr := !r :: !rr;\n let rr = List.rev !rr in\n List.fold_left (fun u k ->\n let r = (u + ((u * k) mod md) + k) mod md in\n r\n ) 0L rr\n |> printf \"%Ld\\n\";\n\n\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "a765463559901e608035083be47aa245"} {"nl": {"description": "Polycarpus is a system administrator. There are two servers under his strict guidance \u2014 a and b. To stay informed about the servers' performance, Polycarpus executes commands \"ping a\" and \"ping b\". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x\u2009+\u2009y\u2009=\u200910;\u00a0x,\u2009y\u2009\u2265\u20090). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is \"alive\" or not. Polycarpus thinks that the server is \"alive\", if at least half of the packets that we send to this server reached it successfully along the network.Help Polycarpus, determine for each server, whether it is \"alive\" or not by the given commands and their results.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers \u2014 the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1\u2009\u2264\u2009ti\u2009\u2264\u20092;\u00a0xi,\u2009yi\u2009\u2265\u20090;\u00a0xi\u2009+\u2009yi\u2009=\u200910). If ti\u2009=\u20091, then the i-th command is \"ping a\", otherwise the i-th command is \"ping b\". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one \"ping a\" command and at least one \"ping b\" command.", "output_spec": "In the first line print string \"LIVE\" (without the quotes) if server a is \"alive\", otherwise print \"DEAD\" (without the quotes). In the second line print the state of server b in the similar format.", "sample_inputs": ["2\n1 5 5\n2 6 4", "3\n1 0 10\n2 0 10\n1 10 0"], "sample_outputs": ["LIVE\nLIVE", "LIVE\nDEAD"], "notes": "NoteConsider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network."}, "positive_code": [{"source_code": "let read_three () = Scanf.bscanf Scanf.Scanning.stdib \" %d %d %d \" (fun x y z -> (x,y,z))\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let ret = Array.make 2 0 in\n let tot = Array.make 2 0 in\n for i=0 to n-1 do \n let (t,x,y) = read_three() in\n let t = t-1 in\n ret.(t) <- ret.(t) + x;\n tot.(t) <- tot.(t) + 10;\n done;\n for j=0 to 1 do \n if 2*ret.(j) >= tot.(j) then print_string \"LIVE\\n\" else print_string \"DEAD\\n\"\n done\n"}, {"source_code": "let read_three () = Scanf.bscanf Scanf.Scanning.stdib \" %d %d %d \" (fun x y z -> (x,y,z))\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let ret = Array.make 2 0 in\n let tot = Array.make 2 0 in\n for i=0 to n-1 do \n let (t,x,y) = read_three() in\n let t = t-1 in\n\tret.(t) <- ret.(t) + x;\n\ttot.(t) <- tot.(t) + 10;\n done;\n for j=0 to 1 do \n if 2*ret.(j) >= tot.(j) then print_string \"LIVE\\n\" else print_string \"DEAD\\n\"\n done\n"}, {"source_code": "let n = read_int()\n\nlet goods = Array.make 2 0 ;;\nlet totals = Array.make 2 0 ;;\n\nlet handle i good bad =\n let total = good + bad in\n let idx = i - 1 in\n Array.set goods idx (Array.get goods idx + good) ;\n Array.set totals idx (Array.get totals idx + total);;\n\nfor i = 1 to n do\n Scanf.scanf \"%d %d %d\\n\" handle\ndone ;;\n\nfor i = 0 to 1 do\n Printf.printf \"%s\\n\" (if (Array.get goods i) >= (Array.get totals i) / 2 then \"LIVE\" else \"DEAD\" );\ndone ;;"}], "negative_code": [{"source_code": "let n = read_int()\n\nlet goods = Array.make 2 0 ;;\nlet totals = Array.make 2 0 ;;\n\nlet handle i good total =\n let idx = i - 1 in\n Array.set goods idx (Array.get goods idx + good) ;\n Array.set totals idx (Array.get totals idx + total);;\n\nfor i = 1 to n do\n Scanf.scanf \"%d %d %d\\n\" handle\ndone ;;\n\nfor i = 0 to 1 do\n Printf.printf \"%s\\n\" (if (Array.get goods i) >= (Array.get totals i) / 2 then \"LIVE\" else \"DEAD\" );\ndone ;;"}], "src_uid": "1d8870a705036b9820227309d74dd1e8"} {"nl": {"description": "Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form: You are given two positive integers $$$u$$$ and $$$v$$$, find any pair of integers (not necessarily positive) $$$x$$$, $$$y$$$, such that: $$$$$$\\frac{x}{u} + \\frac{y}{v} = \\frac{x + y}{u + v}.$$$$$$ The solution $$$x = 0$$$, $$$y = 0$$$ is forbidden, so you should find any solution with $$$(x, y) \\neq (0, 0)$$$. Please help Ivan to solve some equations of this form.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$)\u00a0\u2014 the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$u$$$ and $$$v$$$ ($$$1 \\leq u, v \\leq 10^9$$$) \u2014 the parameters of the equation.", "output_spec": "For each test case print two integers $$$x$$$, $$$y$$$ \u2014 a possible solution to the equation. It should be satisfied that $$$-10^{18} \\leq x, y \\leq 10^{18}$$$ and $$$(x, y) \\neq (0, 0)$$$. We can show that an answer always exists. If there are multiple possible solutions you can print any.", "sample_inputs": ["4\n1 1\n2 3\n3 5\n6 9"], "sample_outputs": ["-1 1\n-4 9\n-18 50\n-4 9"], "notes": "NoteIn the first test case: $$$\\frac{-1}{1} + \\frac{1}{1} = 0 = \\frac{-1 + 1}{1 + 1}$$$.In the second test case: $$$\\frac{-4}{2} + \\frac{9}{3} = 1 = \\frac{-4 + 9}{2 + 3}$$$.In the third test case: $$$\\frac{-18}{3} + \\frac{50}{5} = 4 = \\frac{-18 + 50}{3 + 5}$$$.In the fourth test case: $$$\\frac{-4}{6} + \\frac{9}{9} = \\frac{1}{3} = \\frac{-4 + 9}{6 + 9}$$$."}, "positive_code": [{"source_code": "(*\r\nx/u+y/v=(x+y)/(u+v)\r\n(x*(u+v)/u)+(y*(u+v)/v) = x+y\r\nx*v/u+y*u/v = 0\r\nx=-y*u/v**2\r\n*)\r\n\r\nlet read_long () = Scanf.scanf \" %Ld\" (fun l -> l);;\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\nlet run_case = function\r\n| () -> \r\n let u=read_long () in\r\n let v=read_long () in\r\n let y=Int64.mul (Int64.mul v v) (-1L) in\r\n let x=Int64.mul u u in\r\n Printf.printf \"%Ld %Ld\\n\" x y\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| t -> \r\n run_case ();\r\n iter_cases (t-1)\r\n;;\r\n\r\nlet t=read_int () in\r\niter_cases (t);;"}], "negative_code": [], "src_uid": "4dfa99acbe06b314f0f0b934237c66f3"} {"nl": {"description": "One day, Vogons wanted to build a new hyperspace highway through a distant system with $$$n$$$ planets. The $$$i$$$-th planet is on the orbit $$$a_i$$$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed.Vogons have two machines to do that. The first machine in one operation can destroy any planet at cost of $$$1$$$ Triganic Pu. The second machine in one operation can destroy all planets on a single orbit in this system at the cost of $$$c$$$ Triganic Pus. Vogons can use each machine as many times as they want.Vogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then the test cases follow. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$c$$$ ($$$1 \\le n, c \\le 100$$$) \u2014 the number of planets and the cost of the second machine usage. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 100$$$), where $$$a_i$$$ is the orbit of the $$$i$$$-th planet.", "output_spec": "For each test case print a single integer \u2014 the minimum cost of destroying all planets.", "sample_inputs": ["4\n\n10 1\n\n2 1 4 5 2 4 5 5 1 2\n\n5 2\n\n3 2 1 2 2\n\n2 2\n\n1 1\n\n2 2\n\n1 2", "1\n\n1 100\n\n1"], "sample_outputs": ["4\n4\n2\n2", "1"], "notes": "NoteIn the first test case, the cost of using both machines is the same, so you can always use the second one and destroy all planets in orbit $$$1$$$, all planets in orbit $$$2$$$, all planets in orbit $$$4$$$, all planets in orbit $$$5$$$.In the second test case, it is advantageous to use the second machine for $$$2$$$ Triganic Pus to destroy all the planets in orbit $$$2$$$, then destroy the remaining two planets using the first machine.In the third test case, you can use the first machine twice or the second machine once.In the fourth test case, it is advantageous to use the first machine twice."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let (n,c) = read_pair () in\n let a = Array.init n read_int in\n let hist = Array.make 101 0 in\n for i=0 to n-1 do\n hist.(a.(i)) <- hist.(a.(i)) + 1\n done;\n let answer = sum 0 100 (fun x -> min hist.(x) c) in\n printf \"%d\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "2805d460df1121c4410999a9f36e383a"} {"nl": {"description": "Monocarp has forgotten the password to his mobile phone. The password consists of $$$4$$$ digits from $$$0$$$ to $$$9$$$ (note that it can start with the digit $$$0$$$).Monocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers some digits which were definitely not used in the password.You have to calculate the number of different sequences of $$$4$$$ digits that could be the password for Monocarp's mobile phone (i.\u2009e. these sequences should meet all constraints on Monocarp's password).", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 200$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \\le n \\le 8$$$)\u00a0\u2014 the number of digits for which Monocarp remembers that they were not used in the password. The second line contains $$$n$$$ different integers $$$a_1, a_2, \\dots a_n$$$ ($$$0 \\le a_i \\le 9$$$) representing the digits that were not used in the password. Note that the digits $$$a_1, a_2, \\dots, a_n$$$ are given in ascending order.", "output_spec": "For each testcase, print one integer\u00a0\u2014 the number of different $$$4$$$-digit sequences that meet the constraints.", "sample_inputs": ["2\n\n8\n\n0 1 2 4 5 6 8 9\n\n1\n\n8"], "sample_outputs": ["6\n216"], "notes": "NoteIn the first example, all possible passwords are: \"3377\", \"3737\", \"3773\", \"7337\", \"7373\", \"7733\"."}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet read_matrix read n m = A.init n (fun _ -> read_array read m)\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let _a = read_array read_int n in\n pf \"%d\\n\" (3 * (10 - n) * (10 - n - 1))\n done;\n\n (* let totalN = 1 lsl n in\n let a = read_array (fun _ -> I.of_int @@ read_int ()) totalN in\n let segSize = (n + 1) / 2 in\n let groupsSize = n - segSize in\n let maxXor = 1 lsl segSize in\n let totGroups = 1 lsl groupsSize in\n\n let maxSum = A.make totGroups I.zero in\n let maxPref = A.make totGroups I.zero in\n let maxSuf = A.make totGroups I.zero in\n let sums = A.make totGroups I.zero in\n let prefSums = A.make totalN I.zero in\n\n prefSums.(0) <- a.(0);\n for i = 1 to totalN - 1 do\n prefSums.(i) <- I.add prefSums.(i - 1) @@ a.(i);\n done;\n\n let sumSeg l r =\n if (l = 0) then prefSums.(r)\n else I.sub prefSums.(r) prefSums.(l - 1)\n in\n\n let ans = A.make totalN I.zero in\n let prevSmallP = ref (-1) in\n\n for xr = 0 to totalN - 1 do\n let smallP = xr lsr groupsSize in\n\n if (!prevSmallP <> smallP) then begin\n prevSmallP := smallP;\n for gr = 0 to totGroups - 1 do\n let grShift = gr * maxXor in\n let prefSum = ref I.zero in\n let minPref = ref I.zero in\n let totSum = sumSeg grShift (grShift + maxXor - 1) in\n\n maxSum.(gr) <- I.zero;\n maxPref.(gr) <- I.zero;\n maxSuf.(gr) <- totSum;\n sums.(gr) <- totSum;\n\n for i = 0 to maxXor - 1 do\n let cur = a.(i lxor smallP + grShift) in\n prefSum := I.add !prefSum cur;\n maxSum.(gr) <- max maxSum.(gr) (I.sub !prefSum !minPref);\n maxPref.(gr) <- max maxPref.(gr) !prefSum;\n maxSuf.(gr) <- max maxSuf.(gr) (I.sub totSum !prefSum);\n minPref := min !minPref !prefSum;\n done\n done\n end;\n\n let bigP = xr land (totGroups - 1) in\n let mPref = ref maxPref.(bigP) in\n let mSuf = ref maxSuf.(bigP) in\n let mSum = ref maxSum.(bigP) in\n let sm = ref sums.(bigP) in\n for grXored = 1 to totGroups - 1 do\n let gr = grXored lxor bigP in\n mSum := max (max !mSum maxSum.(gr)) (I.add !mSuf maxPref.(gr));\n mPref := max !mPref (I.add !sm maxPref.(gr));\n mSuf := max (I.add !mSuf sums.(gr)) maxSuf.(gr);\n sm := I.add !sm sums.(gr)\n done;\n ans.(xr) <- !mSum;\n done;\n\n let xr = ref 0 in\n let q = read_int () in\n for _ = 1 to q do\n let b = read_int () in\n xr := !xr lxor (1 lsl b);\n let nxr = (!xr lsr segSize) + (!xr land (maxXor - 1)) * totGroups in\n pf \"%Ld\\n\" ans.(nxr);\n done; *)"}], "negative_code": [], "src_uid": "33e751f5716cbd666be36ab8f5e3977e"} {"nl": {"description": "While resting on the ship after the \"Russian Code Cup\" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n\u2009\u00d7\u2009m, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 108.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u00a0\u2014 the size of the table. ", "output_spec": "Print the table that meets the condition: n lines containing m integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer.", "sample_inputs": ["1 1", "1 2"], "sample_outputs": ["1", "3 4"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int();;\nlet mat=Array.make_matrix (n+1) (m+1) 1;;\nlet is_square a=(int_of_float(sqrt(float_of_int(a)))*int_of_float(sqrt(float_of_int(a)))=a);;\nif n=2 then\n begin\n for j=1 to m do\n mat.(1).(j)<-mat.(1).(j)*3;\n mat.(2).(j)<-mat.(2).(j)*4\n done\n end\nelse\n begin\n if is_square n then () else\n begin\n if n mod 2=1 then\n begin\n for j=1 to m do\n mat.(1).(j)<-mat.(1).(j)*2\n done;\n for j=1 to m do\n mat.(n).(j)<-mat.(n).(j)*(n+1)/2\n done\n end\n else\n begin\n for j=1 to m do\n mat.(n).(j)<-mat.(n).(j)*(n-2)/2\n done\n end\n end\n end;;\n\nif m=2 then\n begin\n for i=1 to n do\n mat.(i).(1)<-mat.(i).(1)*3;\n mat.(i).(2)<-mat.(i).(2)*4\n done\n end\nelse\n begin\n if is_square m then () else\n begin\n if m mod 2=1 then\n begin\n for i=1 to n do\n mat.(i).(1)<-mat.(i).(1)*2\n done;\n for i=1 to n do\n mat.(i).(m)<-mat.(i).(m)*(m+1)/2\n done\n end\n else\n begin\n for i=1 to n do\n mat.(i).(m)<-mat.(i).(m)*(m-2)/2\n done\n end\n end\n end;;\nfor i=1 to n do\n for j=1 to m do\n Printf.printf \"%d \" mat.(i).(j)\n done;\n print_newline()\ndone;;"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m 0 in\n let x = Array.make m 2 in\n let y = Array.make n 2 in\n if m = 1\n then x.(0) <- 1\n else if m = 2\n then (\n x.(0) <- 3;\n x.(1) <- 4;\n ) else x.(m - 1) <- m - 2;\n if n = 1\n then y.(0) <- 1\n else if n = 2\n then (\n y.(0) <- 3;\n y.(1) <- 4;\n ) else y.(n - 1) <- n - 2;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\ta.(i).(j) <- y.(i) * x.(j);\n done;\n done;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tPrintf.printf \"%d \" a.(i).(j);\n done;\n Printf.printf \"\\n\"\n done;\n"}], "negative_code": [], "src_uid": "c80cdf090685d40fd34c3fd082a81469"} {"nl": {"description": "Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s\u2009=\u2009s1s2... sn (n is the length of the string), consisting only of characters \".\" and \"#\" and m queries. Each query is described by a pair of integers li,\u2009ri (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009n). The answer to the query li,\u2009ri is the number of such integers i (li\u2009\u2264\u2009i\u2009<\u2009ri), that si\u2009=\u2009si\u2009+\u20091.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.", "input_spec": "The first line contains string s of length n (2\u2009\u2264\u2009n\u2009\u2264\u2009105). It is guaranteed that the given string only consists of characters \".\" and \"#\". The next line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li,\u2009ri (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009n).", "output_spec": "Print m integers \u2014 the answers to the queries in the order in which they are given in the input.", "sample_inputs": ["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"], "sample_outputs": ["1\n1\n5\n4", "1\n1\n2\n2\n0"], "notes": null}, "positive_code": [{"source_code": "let read format = Scanf.scanf format (fun x -> x)\n\nlet make_list n = \n let rec loop i list =\n if i < n\n then\n let a = read \"%d \" in\n let b = read \"%d \" in\n loop (i + 1) ((a, b) :: list)\n else\n List.rev list\n in loop 0 []\n\nlet get_identical_pairs string =\n let l = String.length string in\n let pairs = Array.make l 0 in\n let rec loop i previous count =\n if i < l\n then\n let current = string.[i] in\n (if current = previous\n then\n (pairs.(i) <- (count + 1);\n loop (i + 1) current (count + 1))\n else\n (pairs.(i) <- count;\n loop (i + 1) current count));\n else\n pairs\n in loop 1 string.[0] 0\n\nlet count_identical_pairs pairs (a, b) = \n pairs.(b - 1) - pairs.(a - 1)\n\nlet input () =\n let string = read \"%s \" in\n let n = read \"%d \" in\n let queries = make_list n in\n (string, queries)\n\nlet solve (string, queries) =\n let pairs = get_identical_pairs string in\n let result = List.map (count_identical_pairs pairs) queries in\n result\n\nlet print result = List.iter (Printf.printf \"%d\\n\") result\nlet () = print (solve (input ()))"}], "negative_code": [], "src_uid": "b30e09449309b999473e4be6643d68cd"} {"nl": {"description": "You are given a board of size $$$n \\times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \\le n < 5 \\cdot 10^5$$$) \u2014 the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \\cdot 10^5$$$ ($$$\\sum n \\le 5 \\cdot 10^5$$$).", "output_spec": "For each test case print the answer \u2014 the minimum number of moves needed to get all the figures into one cell.", "sample_inputs": ["3\n1\n5\n499993"], "sample_outputs": ["0\n40\n41664916690999888"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet rec get_somme = function\n| 0 -> 0L\n| n -> Int64.add (Int64.mul 8L (Int64.mul (Int64.of_int n) (Int64.of_int n))) (get_somme (n - 1))\nin\n\nlet nbTests = read () in\nfor iTest = 1 to nbTests do\n let n = (read () - 1) / 2 in\n \n print_string (Int64.to_string (get_somme n));\n print_newline()\ndone;"}], "negative_code": [], "src_uid": "b4b69320c6040d2d264ac32e9ba5196f"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ integers. Each $$$a_i$$$ is one of the six following numbers: $$$4, 8, 15, 16, 23, 42$$$.Your task is to remove the minimum number of elements to make this array good.An array of length $$$k$$$ is called good if $$$k$$$ is divisible by $$$6$$$ and it is possible to split it into $$$\\frac{k}{6}$$$ subsequences $$$4, 8, 15, 16, 23, 42$$$.Examples of good arrays: $$$[4, 8, 15, 16, 23, 42]$$$ (the whole array is a required sequence); $$$[4, 8, 4, 15, 16, 8, 23, 15, 16, 42, 23, 42]$$$ (the first sequence is formed from first, second, fourth, fifth, seventh and tenth elements and the second one is formed from remaining elements); $$$[]$$$ (the empty array is good). Examples of bad arrays: $$$[4, 8, 15, 16, 42, 23]$$$ (the order of elements should be exactly $$$4, 8, 15, 16, 23, 42$$$); $$$[4, 8, 15, 16, 23, 42, 4]$$$ (the length of the array is not divisible by $$$6$$$); $$$[4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 23]$$$ (the first sequence can be formed from first six elements but the remaining array cannot form the required sequence). ", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 5 \\cdot 10^5$$$) \u2014 the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ (each $$$a_i$$$ is one of the following numbers: $$$4, 8, 15, 16, 23, 42$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.", "output_spec": "Print one integer \u2014 the minimum number of elements you have to remove to obtain a good array.", "sample_inputs": ["5\n4 8 15 16 23", "12\n4 8 4 15 16 8 23 15 16 42 23 42", "15\n4 8 4 8 15 16 8 16 23 15 16 4 42 23 42"], "sample_outputs": ["5", "0", "3"], "notes": null}, "positive_code": [{"source_code": "let read_x x_of_string () = read_line () |> Str.(split (regexp \" \")) |> List.map x_of_string;;\nlet read_ints = read_x int_of_string;;\nlet read_int64s = read_x Int64.of_string;;\nlet print_x string_of_x xs = List.map string_of_x xs |> String.concat \" \" |> print_endline;;\nlet print_ints = print_x string_of_int;;\nlet print_int64s = print_x Int64.to_string;;\n\nlet [n] = read_ints ();;\nlet a = read_ints ();;\nlet c = Array.make 6 0;;\nlet r = ref 0;;\nlet pos = function\n | 4 -> Some 0\n | 8 -> Some 1\n | 15 -> Some 2\n | 16 -> Some 3\n | 23 -> Some 4\n | 42 -> Some 5\n | _ -> None;;\nlet step x = match pos x with\n | Some 0 -> c.(0) <- c.(0) + 1\n | Some p -> if c.(p) < c.(p-1) then c.(p) <- c.(p) + 1 else incr r\n | None -> incr r;;\nList.map step a;;\nfor i = 4 downto 0 do\n r := !r + c.(i) - c.(i+1);\n c.(i) <- c.(i+1);\ndone;;\nprint_ints [!r];;\n"}], "negative_code": [], "src_uid": "eb3155f0e6ba088308fa942f3572f582"} {"nl": {"description": "The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.", "input_spec": "The first line of the input contains the dimensions of the map n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000)\u00a0\u2014 the number of rows and columns respectively. Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.", "sample_inputs": ["4 5\n11..2\n#..22\n#.323\n.#333", "1 5\n1#2#3"], "sample_outputs": ["2", "-1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet shortest_path n graph s =\n let inf = 10_000_000 in\n let frozen = Array.make n false in\n let dist = Array.make n inf in\n let rec dijkstra (zero,one) = \n if zero=[] && one=[] then dist else\n let (zero,one) = if zero=[] then (one,[]) else (zero,one) in\n let (v,zero) = (List.hd zero, List.tl zero) in\n let rec loop wlist (zero,one) = match wlist with [] -> (zero,one)\n\t| (l,w)::wlist -> \n\t if dist.(w) <= dist.(v) + l then loop wlist (zero,one) else (\n\t dist.(w) <- dist.(v) + l;\n\t let (zero,one) = if l=0 then (w::zero, one) else (zero, w::one) in\t\t\n\t\tloop wlist (zero,one)\n\t )\n in\n\tif frozen.(v) then dijkstra (zero,one) else (\n\t frozen.(v) <- true;\n\t dijkstra (loop graph.(v) (zero,one))\n\t)\n in\n dist.(s) <- 0;\n dijkstra ([s], [])\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet isdigit c = c <= '9' && c >= '0'\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n \nlet () = \n let (n,m) = read_pair () in\n let board = Array.init n (fun _ -> read_string()) in\n\n let ng = n*m in\n let graph = Array.make ng [] in\n\n let vertex i j = i*m + j in\n \n let addedge (u,v) l = \n graph.(u) <- (l,v)::graph.(u);\n in\n\n let start = Array.make 3 0 in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n let v = vertex i j in\n let c = board.(i).[j] in\n if isdigit c then start.((int_of_char c) - int_of_char '1') <- v;\n let inbounds i j = 0<=i && i\n\tif inbounds i' j' then (\n\t let v' = vertex i' j' in\t \n\t let c' = board.(i').[j'] in\n\t if isdigit c && c = c' then addedge (v,v') 0\n\t else if c <> '#' && c' <> '#' then addedge (v,v') 1\n\t)\n ) [(i-1,j);(i+1,j);(i,j-1);(i,j+1)];\n done\n done;\n\n let dist = Array.make 3 [||] in\n\n for i=0 to 2 do\n dist.(i) <- shortest_path ng graph start.(i)\n done;\n\n let score = -2 +\n minf 0 (ng-1) (fun v -> dist.(0).(v)+dist.(1).(v)+dist.(2).(v))\n in\n\n printf \"%d\\n\" (if score>ng then -1 else score)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet shortest_path n graph s =\n let inf = 1_000_000 in\n let frozen = Array.make n false in\n let dist = Array.make n inf in\n let rec dijkstra (zero,one) = \n if zero=[] && one=[] then dist else\n let (zero,one) = if zero=[] then (one,[]) else (zero,one) in\n let (v,zero) = (List.hd zero, List.tl zero) in\n let rec loop wlist (zero,one) = match wlist with [] -> (zero,one)\n\t| (l,w)::wlist -> \n\t if dist.(w) <= dist.(v) + l then loop wlist (zero,one) else (\n\t dist.(w) <- dist.(v) + l;\n\t let (zero,one) = if l=0 then (w::zero, one) else (zero, w::one) in\t\t\n\t\tloop wlist (zero,one)\n\t )\n in\n\tif frozen.(v) then dijkstra (zero,one) else (\n\t frozen.(v) <- true;\n\t dijkstra (loop graph.(v) (zero,one))\n\t)\n in\n dist.(s) <- 0;\n dijkstra ([s], [])\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet isdigit c = c <= '9' && c >= '0'\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n \nlet () = \n let (n,m) = read_pair () in\n let board = Array.init n (fun _ -> read_string()) in\n\n let ng = n*m in\n let graph = Array.make ng [] in\n\n let vertex i j = i*m + j in\n \n let addedge (u,v) l = \n graph.(u) <- (l,v)::graph.(u);\n in\n\n let start = Array.make 3 0 in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n let v = vertex i j in\n let c = board.(i).[j] in\n if isdigit c then start.((int_of_char c) - int_of_char '1') <- v;\n let inbounds i j = 0<=i && i\n\tif inbounds i' j' then (\n\t let v' = vertex i' j' in\t \n\t let c' = board.(i').[j'] in\n\t if isdigit c && isdigit c' then addedge (v,v') 0\n\t else if c <> '#' && c' <> '#' then addedge (v,v') 1\n\t)\n ) [(i-1,j);(i+1,j);(i,j-1);(i,j+1)];\n done\n done;\n\n let dist = Array.make 3 [||] in\n\n for i=0 to 2 do\n dist.(i) <- shortest_path ng graph start.(i)\n done;\n\n let score = -1 +\n minf 0 (ng-1) (fun v -> dist.(0).(v)+dist.(1).(v)+dist.(2).(v))\n in\n\n printf \"%d\\n\" (if score>ng then -1 else score)\n"}], "src_uid": "8d4e493783fca1d8eede44af7557f4bd"} {"nl": {"description": "Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types. speed limit: this sign comes with a positive integer number \u2014 maximal speed of the car after the sign (cancel the action of the previous sign of this type); overtake is allowed: this sign means that after some car meets it, it can overtake any other car; no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign); no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more \"no overtake allowed\" signs go one after another with zero \"overtake is allowed\" signs between them. It works with \"no speed limit\" and \"overtake is allowed\" signs as well.In the beginning of the ride overtake is allowed and there is no speed limit.You are given the sequence of events in chronological order \u2014 events which happened to Polycarp during the ride. There are events of following types: Polycarp changes the speed of his car to specified (this event comes with a positive integer number); Polycarp's car overtakes the other car; Polycarp's car goes past the \"speed limit\" sign (this sign comes with a positive integer); Polycarp's car goes past the \"overtake is allowed\" sign; Polycarp's car goes past the \"no speed limit\"; Polycarp's car goes past the \"no overtake allowed\"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?", "input_spec": "The first line contains one integer number n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 number of events. Each of the next n lines starts with integer t (1\u2009\u2264\u2009t\u2009\u2264\u20096) \u2014 the type of the event. An integer s (1\u2009\u2264\u2009s\u2009\u2264\u2009300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).", "output_spec": "Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.", "sample_inputs": ["11\n1 100\n3 70\n4\n2\n3 120\n5\n3 120\n6\n1 150\n4\n3 300", "5\n1 100\n3 200\n2\n4\n5", "7\n1 20\n2\n6\n4\n6\n6\n2"], "sample_outputs": ["2", "0", "2"], "notes": "NoteIn the first example Polycarp should say he didn't notice the \"speed limit\" sign with the limit of 70 and the second \"speed limit\" sign with the limit of 120.In the second example Polycarp didn't make any rule violation.In the third example Polycarp should say he didn't notice both \"no overtake allowed\" that came after \"overtake is allowed\" sign."}, "positive_code": [{"source_code": "(*********************************************************************************)\n\ntype event = \n | Speed_change of int (* 1 *)\n | Overtake (* 2 *)\n | Speed_limit of int (* 3 *)\n | Overtake_is_allowed (* 4 *)\n | No_speed_limit (* 5 *)\n | No_overtake_allowed (* 6 *)\n;;\n\n(*********************************************************************************)\n\nlet infty = max_int;;\n\n(*********************************************************************************)\n\ntype overtake_automata = {\n\tmutable missed_sign_count : int;\n\tmutable consequtive_overtake_is_disallowed_count : int;\n};;\n\n(*********************************************************************************)\n\nlet create_overtake_automata () = { \n missed_sign_count = 0; \n consequtive_overtake_is_disallowed_count = 0; \n};;\n\n(*********************************************************************************)\n\ntype speed_automata = {\n mutable missed_sign_count : int;\n mutable current_speed : int;\n mutable speed_limits : int list;\n};;\n\n(*********************************************************************************)\n\nlet create_speed_automata () = { \n missed_sign_count = 0; \n current_speed = 0; \n speed_limits = [ infty ];\n};;\n\n\n(*********************************************************************************)\n\nlet my_read_int () =\n let result = ref 0 in\n begin\n Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun n -> result := n);\n !result\n end\n;;\n\n\n(*********************************************************************************)\n\nlet read_event () =\n let evt_type = ref 0 in\n begin\n Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun t -> evt_type := t);\n match !evt_type with\n | 1 -> Speed_change (my_read_int () )\n | 2 -> Overtake\n | 3 -> Speed_limit (my_read_int () )\n | 4 -> Overtake_is_allowed\n | 5 -> No_speed_limit\n | 6 -> No_overtake_allowed\n | _ -> failwith \"Unexpected event type\"\n end\n\n(*********************************************************************************)\n\nlet string_of_event evt =\n match evt with\n | Speed_change( v ) -> (Printf.sprintf \"Speed_change %d\" v)\n | Overtake -> \"Overtake\"\n | Speed_limit( v ) -> (Printf.sprintf \"Speed_limit %d\" v)\n | Overtake_is_allowed -> \"Overtake_is_allowed\"\n | No_speed_limit -> \"No_speed_limit\"\n | No_overtake_allowed -> \"No_overtake_allowed\"\n\n(*********************************************************************************)\n\nlet print_event evt =\n Printf.printf \"%s\\n\" (string_of_event evt);\n;;\n\n(*********************************************************************************)\n\nlet rec remove_until_more_or_equal lst value ax =\n match lst with\n | [] -> ([], ax)\n | hd :: tail -> if hd < value \n then remove_until_more_or_equal tail value (ax + 1)\n else (hd :: tail, ax)\n;;\n\n(*********************************************************************************)\n\nlet pop_violated_speed_limits speed_automata =\n let (new_list, count) = remove_until_more_or_equal speed_automata.speed_limits speed_automata.current_speed 0 in\n begin\n speed_automata.missed_sign_count <- speed_automata.missed_sign_count + count;\n speed_automata.speed_limits <- new_list;\n end\n;;\n\n(*********************************************************************************)\n\nlet process_speed_change speed_automata new_speed =\n begin\n speed_automata.current_speed <- new_speed;\n pop_violated_speed_limits speed_automata\n end\n;;\n\n(*********************************************************************************)\n\nlet process_speed_limit speed_automata new_limit = \n begin\n speed_automata.speed_limits <- new_limit :: speed_automata.speed_limits;\n pop_violated_speed_limits speed_automata\n end\n;;\n\n(*********************************************************************************)\n\nlet process_no_speed_limit speed_automata =\n begin\n speed_automata.speed_limits <- [ infty ];\n end\n;;\n\n(*********************************************************************************)\n\nlet process_overtake (overtake_automata : overtake_automata) = \n begin\n overtake_automata.missed_sign_count <- overtake_automata.missed_sign_count + overtake_automata.consequtive_overtake_is_disallowed_count;\n overtake_automata.consequtive_overtake_is_disallowed_count <- 0;\n end\n;;\n\n(*********************************************************************************)\n\nlet process_overtake_is_allowed overtake_automata =\n begin\n overtake_automata.consequtive_overtake_is_disallowed_count <- 0;\n end\n;;\n\n(*********************************************************************************)\n\nlet process_no_overtake_allowed overtake_automata =\n begin\n overtake_automata.consequtive_overtake_is_disallowed_count <- overtake_automata.consequtive_overtake_is_disallowed_count + 1;\n end\n;;\n\n(*********************************************************************************)\n\nlet process_single_event overtake_automata speed_automata evt =\n match evt with\n | Speed_change( v ) -> process_speed_change speed_automata v\n | Overtake -> process_overtake overtake_automata\n | Speed_limit( v ) -> process_speed_limit speed_automata v\n | Overtake_is_allowed -> process_overtake_is_allowed overtake_automata\n | No_speed_limit -> process_no_speed_limit speed_automata\n | No_overtake_allowed -> process_no_overtake_allowed overtake_automata\n;;\n\n(*********************************************************************************)\n\nlet rec process_events overtake_automata speed_automata n =\n if n > 0 \n then\n let evt = read_event () in\n begin\n process_single_event overtake_automata speed_automata evt;\n process_events overtake_automata speed_automata (n-1)\n end\n;;\n\n(*********************************************************************************)\n\nlet find_skipped_road_signs n =\n let overtake_automata = create_overtake_automata () in\n let speed_automata = create_speed_automata () in\n begin\n process_events overtake_automata speed_automata n;\n overtake_automata.missed_sign_count + speed_automata.missed_sign_count\n end\n;;\n\n(*********************************************************************************)\n\nlet read_and_process n =\n Printf.printf \"%d\\n\" (find_skipped_road_signs n);\n;;\n\n(*********************************************************************************)\n\nScanf.bscanf Scanf.Scanning.stdin \" %d \" read_and_process\n\n(*********************************************************************************)\n"}, {"source_code": "(*********************************************************************************)\n\nlet infty = max_int;;\n\n(*********************************************************************************)\n\ntype overtake_automata = {\n\tmutable missed_sign_count : int;\n\tmutable consequtive_overtake_is_disallowed_count : int;\n};;\n\n(*********************************************************************************)\n\nlet create_overtake_automata () = { \n missed_sign_count = 0; \n consequtive_overtake_is_disallowed_count = 0; \n};;\n\n(*********************************************************************************)\n\ntype speed_automata = {\n mutable missed_sign_count : int;\n mutable current_speed : int;\n mutable speed_limits : int list;\n};;\n\n(*********************************************************************************)\n\nlet create_speed_automata () = { \n missed_sign_count = 0; \n current_speed = 0; \n speed_limits = [ infty ];\n};;\n\n\n(*********************************************************************************)\n\nlet my_read_int () =\n let result = ref 0 in\n begin\n Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun n -> result := n);\n !result\n end\n;;\n\n(*********************************************************************************)\n\nlet rec remove_until_more_or_equal lst value ax =\n match lst with\n | [] -> ([], ax)\n | hd :: tail -> if hd < value \n then remove_until_more_or_equal tail value (ax + 1)\n else (hd :: tail, ax)\n;;\n\n(*********************************************************************************)\n\nlet pop_violated_speed_limits speed_automata =\n let (new_list, count) = remove_until_more_or_equal speed_automata.speed_limits speed_automata.current_speed 0 in\n begin\n speed_automata.missed_sign_count <- speed_automata.missed_sign_count + count;\n speed_automata.speed_limits <- new_list;\n end\n;;\n\n(*********************************************************************************)\n\nlet process_speed_change speed_automata new_speed =\n begin\n speed_automata.current_speed <- new_speed;\n pop_violated_speed_limits speed_automata\n end\n;;\n\n(*********************************************************************************)\n\nlet process_speed_limit speed_automata new_limit = \n begin\n speed_automata.speed_limits <- new_limit :: speed_automata.speed_limits;\n pop_violated_speed_limits speed_automata\n end\n;;\n\n(*********************************************************************************)\n\nlet process_no_speed_limit speed_automata =\n begin\n speed_automata.speed_limits <- [ infty ];\n end\n;;\n\n(*********************************************************************************)\n\nlet process_overtake (overtake_automata : overtake_automata) = \n begin\n overtake_automata.missed_sign_count <- overtake_automata.missed_sign_count + overtake_automata.consequtive_overtake_is_disallowed_count;\n overtake_automata.consequtive_overtake_is_disallowed_count <- 0;\n end\n;;\n\n(*********************************************************************************)\n\nlet process_overtake_is_allowed overtake_automata =\n begin\n overtake_automata.consequtive_overtake_is_disallowed_count <- 0;\n end\n;;\n\n(*********************************************************************************)\n\nlet process_no_overtake_allowed overtake_automata =\n begin\n overtake_automata.consequtive_overtake_is_disallowed_count <- overtake_automata.consequtive_overtake_is_disallowed_count + 1;\n end\n;;\n\n(*********************************************************************************)\n\nlet process_single_event overtake_automata speed_automata evt =\n match evt with\n | 1 -> process_speed_change speed_automata (my_read_int ())\n | 2 -> process_overtake overtake_automata\n | 3 -> process_speed_limit speed_automata (my_read_int ())\n | 4 -> process_overtake_is_allowed overtake_automata\n | 5 -> process_no_speed_limit speed_automata\n | 6 -> process_no_overtake_allowed overtake_automata\n | _ -> failwith \"Unexpected event type\"\n;;\n\n(*********************************************************************************)\n\nlet rec process_events overtake_automata speed_automata n =\n if n > 0 \n then\n let evt = my_read_int () in\n begin\n process_single_event overtake_automata speed_automata evt;\n process_events overtake_automata speed_automata (n-1)\n end\n;;\n\n(*********************************************************************************)\n\nlet find_skipped_road_signs n =\n let overtake_automata = create_overtake_automata () in\n let speed_automata = create_speed_automata () in\n begin\n process_events overtake_automata speed_automata n;\n overtake_automata.missed_sign_count + speed_automata.missed_sign_count\n end\n;;\n\n(*********************************************************************************)\n\nlet read_and_process n =\n Printf.printf \"%d\\n\" (find_skipped_road_signs n);\n;;\n\n(*********************************************************************************)\n\nScanf.bscanf Scanf.Scanning.stdin \" %d \" read_and_process\n\n(*********************************************************************************)\n"}], "negative_code": [], "src_uid": "2dca11b202d7adbe22a404a52d627eed"} {"nl": {"description": "Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.For permutation p\u2009=\u2009p0,\u2009p1,\u2009...,\u2009pn, Polo has defined its beauty \u2014 number .Expression means applying the operation of bitwise excluding \"OR\" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as \"^\" and in Pascal \u2014 as \"xor\".Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.", "input_spec": "The single line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106).", "output_spec": "In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m. If there are several suitable permutations, you are allowed to print any of them.", "sample_inputs": ["4"], "sample_outputs": ["20\n0 2 1 4 3"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet ( ++ ) a b = Int64.add a b\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet () = \n let n = read_int() in\n let ans = Array.make (n+1) 0 in\n let add (a,b) = ans.(a) <- b; ans.(b) <- a in\n\n let rec log n i = if (1 lsl (i+1)) >= n then i else log n (i+1) in\n\n let rec build_answer n = \n if n<=0 then ()\n else if n=1 then add (0,1)\n else\n let k = log (n+1) 0 in\n let p = 1 lsl k in\n let a = n + 1 - p in\n \n let rec build_pairs i = \n\tlet hi = n-a+1+i in\n\tlet lo = n-a-i in\n\t if hi > n then () else (\n\t add (lo,hi);\n\t build_pairs (i+1)\n\t )\n in\n\tbuild_pairs 0;\n\tbuild_answer (n-2*a)\n in\n\n\n let () = build_answer n in\n let score = sum 0 n (fun i -> Int64.of_int (i lxor ans.(i))) in\n Printf.printf \"%Ld\\n\" score;\n for i=0 to n do\n Printf.printf \"%d \" ans.(i)\n done;\n print_newline()\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let n = read_int() in\n let ans = Array.make (n+1) 0 in\n let add (a,b) = ans.(a) <- b; ans.(b) <- a in\n\n let rec log n i = if (1 lsl (i+1)) >= n then i else log n (i+1) in\n\n let rec build_answer n = \n if n<=0 then ()\n else if n=1 then add (0,1)\n else\n let k = log (n+1) 0 in\n let p = 1 lsl k in\n let a = n + 1 - p in\n \n let rec build_pairs i = \n\tlet hi = n-a+1+i in\n\tlet lo = n-a-i in\n\t if hi > n then () else (\n\t add (lo,hi);\n\t build_pairs (i+1)\n\t )\n in\n\tbuild_pairs 0;\n\tbuild_answer (n-2*a)\n in\n\n\n let () = build_answer n in\n let score = sum 0 n (fun i -> i lxor ans.(i)) in\n Printf.printf \"%d\\n\" score;\n for i=0 to n do\n Printf.printf \"%d \" ans.(i)\n done;\n print_newline()\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let n = read_int() in\n let ans = Array.make (n+1) 0 in\n let add (a,b) = ans.(a) <- b; ans.(b) <- a in\n\n let rec log n i = if (1 lsl (i+1)) >= n then i else log n (i+1) in\n\n let rec build_answer n = \n if n<=0 then ()\n else if n=1 then add (0,1)\n else\n let k = log (n+1) 0 in\n let p = 1 lsl k in\n let a = n + 1 - p in\n \n let rec build_pairs i = \n\tlet hi = n-a+1+i in\n\tlet lo = n-a-i in\n\t if hi > n then () else (\n\t add (lo,hi);\n\t build_pairs (i+1)\n\t )\n in\n\tbuild_pairs 0;\n\tbuild_answer (n-2*a)\n in\n\n\n let () = build_answer n in\n let score = sum 0 n (fun i -> i lxor ans.(i)) in\n Printf.printf \"%d\\n\" score;\n for i=0 to n do\n Printf.printf \"%d \" ans.(i)\n done;\n print_newline()\n"}], "src_uid": "ab410ffc2bfe9360abf278328b9c3055"} {"nl": {"description": "Given an array $$$a$$$ of $$$n$$$ elements, print any value that appears at least three times or print -1 if there is no such value.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2\\cdot10^5$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq n$$$)\u00a0\u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot10^5$$$.", "output_spec": "For each test case, print any value that appears at least three times or print -1 if there is no such value.", "sample_inputs": ["7\n\n1\n\n1\n\n3\n\n2 2 2\n\n7\n\n2 2 3 3 4 2 2\n\n8\n\n1 4 3 4 3 2 4 1\n\n9\n\n1 1 1 2 2 2 3 3 3\n\n5\n\n1 5 2 4 3\n\n4\n\n4 4 4 4"], "sample_outputs": ["-1\n2\n2\n4\n3\n-1\n4"], "notes": "NoteIn the first test case there is just a single element, so it can't occur at least three times and the answer is -1.In the second test case, all three elements of the array are equal to $$$2$$$, so $$$2$$$ occurs three times, and so the answer is $$$2$$$.For the third test case, $$$2$$$ occurs four times, so the answer is $$$2$$$.For the fourth test case, $$$4$$$ occurs three times, so the answer is $$$4$$$.For the fifth test case, $$$1$$$, $$$2$$$ and $$$3$$$ all occur at least three times, so they are all valid outputs.For the sixth test case, all elements are distinct, so none of them occurs at least three times and the answer is -1."}, "positive_code": [{"source_code": "let testcases_str = read_line ()\r\nlet testcases = int_of_string testcases_str\r\n\r\nlet rec split str len n acc =\r\n if n = len then [ int_of_string acc ]\r\n else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) \"\"\r\n else split str len (n + 1) (acc ^ String.make 1 str.[n])\r\n\r\nlet solve () =\r\n let len = read_line () in\r\n let nums_string = read_line () in\r\n let counter_arr = Array.make ((int_of_string len) + 1) 0 in\r\n let splitted = split nums_string (String.length nums_string) 0 \"\" in\r\n let rec loop lst counter =\r\n match lst with\r\n | [] -> print_string \"-1\\n\"\r\n | h :: t ->\r\n counter.(h) <- counter.(h) + 1;\r\n if counter.(h) >= 3 then print_string (string_of_int h ^ \"\\n\")\r\n else loop t counter\r\n in\r\n loop splitted counter_arr\r\n;;\r\n\r\nfor i = 0 to testcases - 1 do\r\n solve ()\r\ndone\r\n"}, {"source_code": "(* print any value that appears atleast three times or print -1\r\n 1<=ai<=n, so can have a count array size n? Or sort and see if adjacent next to each other?\r\n comparsion sort is atleast O(nlgn)\r\n counting is atmost O(n)\r\n*)\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x-> x);;\r\n\r\nlet rec fill_count_arr = function\r\n| (count_arr, 0) -> count_arr\r\n| (count_arr, i) ->\r\n let x = read_int () in \r\n count_arr.(x-1) <- (count_arr.(x-1)+1);\r\n fill_count_arr (count_arr, (i-1))\r\n;;\r\n\r\nlet rec consume_count_arr = function \r\n| (n, count_arr, k, i) ->\r\n if (i=n) then -1\r\n else begin \r\n if (count_arr.(i)>=k) then i+1\r\n else consume_count_arr (n, count_arr, k, (i+1))\r\n end\r\n;;\r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in\r\n let count_arr = Array.make n 0 in \r\n let filled_arr = fill_count_arr (count_arr, n) in\r\n let x = consume_count_arr (n, filled_arr, 3, 0) in \r\n Printf.printf \"%d\\n\" x\r\n;;\r\n\r\nlet rec iter_cases = function \r\n| 0 -> ()\r\n| t -> \r\n run_case ();\r\n iter_cases (t-1)\r\n;;\r\nlet t = read_int () in iter_cases (t);;\r\n"}, {"source_code": "let getInt () = Scanf.scanf \" %d\" (fun i -> i);;\r\n\r\n\r\nlet getList(n): int list = \r\n let rec getList2 ((n: int), (acc: int list)) = match n with\r\n\t | 0 -> List.rev acc\r\n\t | _ -> getList2 (n-1, getInt() :: acc)\r\n in getList2(n, [])\r\n\r\nlet getLine() = Scanf.scanf \" %s\" (fun i -> i);;\r\n\r\nlet cmp((x: int), (y:int)) = x - y;;\r\n\r\nlet rec solve((arr: int list), (last: int), (ct: int)) = \r\nmatch arr with\r\n | [] -> -1\r\n | x::xs -> \r\n if x = last then (\r\n if (ct + 1) = 3 then x else solve(xs, last, ct + 1))\r\n else solve(xs, x, 1);;\r\n\r\n\r\nlet main() = \r\n let t = getInt() in\r\n for i = 1 to t do \r\n let n = getInt() in let x = getList(n) in let arr = List.sort (compare) x\r\n in let ans = solve(arr, -1, 0) in\r\n print_endline(string_of_int(ans))\r\n done;;\r\n\r\nmain();;\r\n\r\n\r\n"}, {"source_code": "let id x = x\n\nmodule S = struct\n open String\n\n let split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = length s - 1 downto 0 do\n if unsafe_get s i = sep then begin\n r := sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n sub s 0 !j :: !r\nend\n\nlet read_ints_line () =\n Scanf.scanf \"%s@\\n\" (fun x -> x)\n |> S.split_on_char ' '\n |> List.filter (fun x -> x <> \"\")\n |> List.map int_of_string\n\nlet solve () =\n let n = Scanf.scanf \"%d\\n\" id in\n let xs = read_ints_line () in\n let counts = Array.make (n + 1) 0 in\n let () = List.iter (fun a -> counts.(a) <- counts.(a) + 1) xs in\n let counts = Array.mapi (fun i c -> (i, c)) counts |> Array.to_list in\n let counts = List.filter (fun (i, c) -> c >= 3) counts in\n match counts with\n | [] -> print_endline \"-1\"\n | (i, _) :: _ -> Printf.printf \"%d\\n\" i\n\nlet () =\n let t = Scanf.scanf \"%d\\n\" id in\n for i = 1 to t do\n solve ()\n done\n"}], "negative_code": [], "src_uid": "7d4174e3ae76de7b1389f618eb89d334"} {"nl": {"description": "Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d\u2009=\u2009747747, then cnt(4)\u2009=\u20092, cnt(7)\u2009=\u20094, cnt(47)\u2009=\u20092, cnt(74)\u2009=\u20092. Petya wants the following condition to fulfil simultaneously: cnt(4)\u2009=\u2009a1, cnt(7)\u2009=\u2009a2, cnt(47)\u2009=\u2009a3, cnt(74)\u2009=\u2009a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.", "input_spec": "The single line contains four integers a1, a2, a3 and a4 (1\u2009\u2264\u2009a1,\u2009a2,\u2009a3,\u2009a4\u2009\u2264\u2009106).", "output_spec": "On the single line print without leading zeroes the answer to the problem \u2014 the minimum lucky number d such, that cnt(4)\u2009=\u2009a1, cnt(7)\u2009=\u2009a2, cnt(47)\u2009=\u2009a3, cnt(74)\u2009=\u2009a4. If such number does not exist, print the single number \"-1\" (without the quotes).", "sample_inputs": ["2 2 1 1", "4 7 3 1"], "sample_outputs": ["4774", "-1"], "notes": null}, "positive_code": [{"source_code": "(* codeforces 104. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet expand s a1 a2 = (* a1, a2 are the number of additional 4s and 7s we need to add *)\n let n = String.length s in\n if a1<0 || a2<0 then None else\n let m = n+a1+a2 in\n let t = String.make m 'x' in\n let rec find_last7 i = if i<0 then -1 else if s.[i]='7' then i else find_last7 (i-1) in\n let rec find_first4 i = if i=n then -1 else if s.[i]='4' then i else find_first4 (i+1) in\n let l7 = find_last7 (n-1) in\n let f4 = find_first4 0 in\n\tif f4<0 && a1>0 then None\n\telse if l7<0 && a2>0 then None\n\telse \n\t let rec fill i p j k = (* i=pos in s, j=4s left, k=7s left *)\n\t if p=m then () else (\n\t t.[p] <- s.[i];\n\t if i=f4 && j>0 then fill i (p+1) (j-1) k\n\t else if i=l7 && k>0 then fill i (p+1) j (k-1)\n\t else fill (i+1) (p+1) j k\n\t )\n\t in\n\t fill 0 0 a1 a2;\n\t Some t\n\nlet alter n a b = \n let t = String.make n 'x' in\n for i=0 to n-1 do\n t.[i] <- if i mod 2 = 0 then a else b\n done;\n t\n\nlet () =\n let a1 = read_int() in\n let a2 = read_int() in\n let a3 = read_int() in\n let a4 = read_int() in\n let answer = \n match a3-a4 with\n | 0 -> (* 4747...4 or 7474...7 *)\n\t let op1 = expand (alter (2*a3+1) '4' '7') (a1-a3-1) (a2-a3) in\n\t let op2 = expand (alter (2*a3+1) '7' '4') (a1-a3) (a2-a3-1) in \n\t begin\n\t match (op1,op2) with\n\t\t| (None,None) -> None\n\t\t| (None,x) | (x,None) -> x\n\t\t| _ -> min op1 op2\n\t end\n | 1 -> (* 4747...47 *)\n\t expand (alter (2*a3) '4' '7') (a1-a3) (a2-a3)\n | -1 -> (* 7474...74 *)\n\t expand (alter (2*a4) '7' '4') (a1-a4) (a2-a4)\n | _ ->\n\t None\n in\n match answer with None -> Printf.printf \"-1\\n\" | Some a -> Printf.printf \"%s\\n\" a\n"}], "negative_code": [], "src_uid": "f63cef419fdfd4ab1c61ac6d7e7657a6"} {"nl": {"description": "Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station. The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.", "input_spec": "The first line of the input will have two integers n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009106) and m\u00a0(1\u2009\u2264\u2009m\u2009\u2264\u2009106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x,\u20090) of the plane. The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane. Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.", "output_spec": "Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.", "sample_inputs": ["3 6\n1 2 3", "5 5\n-7 -6 -3 -1 1", "1 369\n0", "11 2\n-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822"], "sample_outputs": ["4", "16", "0", "18716"], "notes": null}, "positive_code": [{"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n;;\n\n(* misc *)\nlet neg_compare x y = - compare x y\n(* Array *) \nlet range a b = if b < a then [||] else Array.init (b-a+1) (fun x -> a+x)\nlet rec span i up_bnd cond =\n if i = up_bnd || cond i then i else \n span (i+1) up_bnd cond\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet rec repeat n f = if n <= 0 then () else (f (); repeat (n-1) f)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\nlet is_digit c = \n let i = int_of_char c in\n let lo = int_of_char '0' in\n let up = int_of_char '9' in \n lo <= i && i <= up\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet option x = function\n | Some y -> y \n | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \n(* Arithmetic *)\nlet negate x = -x\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\n(* IO *)\nlet peek_char () = scanf \"%0c\" id \nlet read_char () = scanf \"%c\" id \nlet read_line () = scanf \"%s@\\n\" id\nlet read_int () = scanf \" %d\" id \nlet read_int64 () = scanf \" %Ld\" id \nlet read_float () = scanf \" %f\" id \nlet read_word () = scanf \" %s\" id \nlet is_eof () = try scanf \"%0c\" (const false) with End_of_file -> true\nlet clear_newline () = scanf \"%[\\n]\" (const ())\nlet newline () = print_newline()\nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\n\nlet _ = \n let n = read_int() in \n let m = read_int() in \n let arr = init n (fun i -> read_int64()) in \n fast_sort compare arr;\n\n let open Int64 in \n\n let rec run i j = \n if j <= i then 0L else\n add (mul 2L (sub arr.(j) arr.(i))) (run (i+m) (j-m))\n in \n printf \"%Ld\\n\" (run 0 (n-1))\n"}], "negative_code": [{"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n;;\n\n(* misc *)\nlet neg_compare x y = - compare x y\n(* Array *) \nlet range a b = if b < a then [||] else Array.init (b-a+1) (fun x -> a+x)\nlet rec span i up_bnd cond =\n if i = up_bnd || cond i then i else \n span (i+1) up_bnd cond\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet rec repeat n f = if n <= 0 then () else (f (); repeat (n-1) f)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\nlet is_digit c = \n let i = int_of_char c in\n let lo = int_of_char '0' in\n let up = int_of_char '9' in \n lo <= i && i <= up\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet option x = function\n | Some y -> y \n | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \n(* Arithmetic *)\nlet negate x = -x\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\n(* IO *)\nlet peek_char () = scanf \"%0c\" id \nlet read_char () = scanf \"%c\" id \nlet read_line () = scanf \"%s@\\n\" id\nlet read_int () = scanf \" %d\" id \nlet read_float () = scanf \" %f\" id \nlet read_word () = scanf \" %s\" id \nlet is_eof () = try scanf \"%0c\" (const false) with End_of_file -> true\nlet clear_newline () = scanf \"%[\\n]\" (const ())\nlet newline () = print_newline()\nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\n\nlet _ = \n let n = read_int() in \n let m = read_int() in \n let arr = init n (fun i -> read_int()) in \n fast_sort compare arr;\n\n let rec run i j = \n if j <= i then 0 else(\n 2*(arr.(j) - arr.(i)) + run (i+m) (j-m) )\n in \n printf \"%d\\n\" (run 0 (n-1))\n"}, {"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\nGc.set {Gc.get() with \n Gc.minor_heap_size=512*1024;\n Gc.major_heap_increment=1024*1024; \n Gc.stack_limit=8*1024*1024; \n}\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule L = List\n\nmodule Integer = struct \n let (+) a b = Big_int.add_big_int a b\n let (-) a b = Big_int.sub_big_int a b\n let ( * ) a b = Big_int.mult_big_int a b\n let sqrt a = Big_int.sqrt_big_int a \n let divmod a b = Big_int.quomod_big_int a b\n let div a b = Big_int.div_big_int a b \n let (mod) a b = Big_int.mod_big_int a b\n let gcd a b = Big_int.gcd_big_int a b\n let pow a b = Big_int.power_big_int_positive_big_int a b\n let zero = Big_int.zero_big_int\n let one = Big_int.unit_big_int\n let to_string a = Big_int.string_of_big_int a \n let to_float a = Big_int.float_of_big_int a \n let of_string a = Big_int.big_int_of_string a \n let of_int a = Big_int.big_int_of_int a \n let compare a b = Big_int.compare_big_int a b \n let (=) a b = Big_int.eq_big_int a b \n let (>) a b = Big_int.gt_big_int a b \n let (<) a b = Big_int.lt_big_int a b \n let (>=) a b = Big_int.ge_big_int a b \n let (<=) a b = Big_int.le_big_int a b \n let max a b = Big_int.max_big_int a b \n let min a b = Big_int.min_big_int a b \n let (land) a b = Big_int.and_big_int a b \n let (lor) a b = Big_int.or_big_int a b \nend\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet bti b = if b then 1 else 0\n(* float *)\nlet round f = truncate (f +. 0.5)\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet option x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = \n let t = arr.(i) in \n arr.(i) <- arr.(j);\n arr.(j) <- t \n(* Arithmetic *)\nlet negate x = -x\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet _ = \n printf \"%d\\n\" (factorial 15)"}], "src_uid": "47a8fd4c1f4e7b1d4fd15fbaf5f6fda8"} {"nl": {"description": "You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.For each vertex v find the sum of all dominating colours in the subtree of vertex v.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of vertices in the tree. The second line contains n integers ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n), ci \u2014 the colour of the i-th vertex. Each of the next n\u2009-\u20091 lines contains two integers xj,\u2009yj (1\u2009\u2264\u2009xj,\u2009yj\u2009\u2264\u2009n) \u2014 the edge of the tree. The first vertex is the root of the tree.", "output_spec": "Print n integers \u2014 the sums of dominating colours for each vertex.", "sample_inputs": ["4\n1 2 3 4\n1 2\n2 3\n2 4", "15\n1 2 3 1 2 3 3 1 1 3 2 2 1 2 3\n1 2\n1 3\n1 4\n1 14\n1 15\n2 5\n2 6\n2 7\n3 8\n3 9\n3 10\n4 11\n4 12\n4 13"], "sample_outputs": ["10 9 3 4", "6 5 4 3 2 3 3 1 1 3 2 2 1 2 3"], "notes": null}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nmodule IntMap = Map.Make(\n struct\n type t = int\n let compare (x : int) y =\n if x < y\n then -1\n else if x > y\n then 1\n else 0\n end\n)\n\ntype counter =\n {map : int IntMap.t;\n v : int;\n s : int64;\n size : int;\n }\n\nlet new_counter () =\n {map = IntMap.empty;\n v = -1;\n s = 0L;\n size = 0;\n }\n\nlet add counter x d =\n let (y, ds) =\n try\n (IntMap.find x counter.map, 0)\n with\n | Not_found -> (0, 1)\n in\n let y = y + d in\n let map = IntMap.add x y counter.map in\n if counter.v < y\n then {map;\n\t v = y;\n\t s = Int64.of_int x;\n\t size = counter.size + ds}\n else if counter.v = y\n then {counter with\n\t map;\n\t s = counter.s +| Int64.of_int x;\n\t size = counter.size + ds}\n else {counter with\n\t map;\n\t size = counter.size + ds}\n\nlet rec merge c1 c2 =\n if c1.size > c2.size\n then merge c2 c1\n else (\n IntMap.fold\n (fun x y c2 ->\n\t add c2 x y\n ) c1.map c2\n )\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (new_counter ()) in\n let c = Array.make n 0 in\n let es = Array.make n [] in\n for i = 0 to n - 1 do\n c.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to n - 1 do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tes.(v) <- u :: es.(v);\n done;\n let es = Array.map Array.of_list es in\n let rec dfs u prev =\n let cnt = ref (new_counter ()) in\n\tcnt := add !cnt c.(u) 1;\n\tfor i = 0 to Array.length es.(u) - 1 do\n\t let v = es.(u).(i) in\n\t if v <> prev then (\n\t dfs v u;\n\t cnt := merge !cnt a.(v);\n\t )\n\tdone;\n\ta.(u) <- !cnt;\n in\n dfs 0 (-1);\n for i = 0 to n - 1 do\n\tPrintf.printf \"%Ld \" a.(i).s;\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "module IntMap = Map.Make(\n struct\n type t = int\n let compare (x : int) y =\n if x < y\n then -1\n else if x > y\n then 1\n else 0\n end\n)\n\ntype counter =\n {map : int IntMap.t;\n v : int;\n s : int;\n size : int;\n }\n\nlet new_counter () =\n {map = IntMap.empty;\n v = -1;\n s = 0;\n size = 0;\n }\n\nlet add counter x d =\n let (y, ds) =\n try\n (IntMap.find x counter.map, 0)\n with\n | Not_found -> (0, 1)\n in\n let y = y + d in\n let map = IntMap.add x y counter.map in\n if counter.v < y\n then {map;\n\t v = y;\n\t s = x;\n\t size = counter.size + ds}\n else if counter.v = y\n then {counter with\n\t map;\n\t s = counter.s + x;\n\t size = counter.size + ds}\n else {counter with\n\t map;\n\t size = counter.size + ds}\n\nlet rec merge c1 c2 =\n if c1.size > c2.size\n then merge c2 c1\n else (\n IntMap.fold\n (fun x y c2 ->\n\t add c2 x y\n ) c1.map c2\n )\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (new_counter ()) in\n let c = Array.make n 0 in\n let es = Array.make n [] in\n for i = 0 to n - 1 do\n c.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to n - 1 do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tes.(v) <- u :: es.(v);\n done;\n let es = Array.map Array.of_list es in\n let rec dfs u prev =\n let cnt = ref (new_counter ()) in\n\tcnt := add !cnt c.(u) 1;\n\tfor i = 0 to Array.length es.(u) - 1 do\n\t let v = es.(u).(i) in\n\t if v <> prev then (\n\t dfs v u;\n\t cnt := merge !cnt a.(v);\n\t )\n\tdone;\n\ta.(u) <- !cnt;\n in\n dfs 0 (-1);\n for i = 0 to n - 1 do\n\tPrintf.printf \"%d \" a.(i).s;\n done;\n Printf.printf \"\\n\"\n\n"}], "src_uid": "fe01ddb5bd5ef534a6a568adaf738151"} {"nl": {"description": "During the \"Russian Code Cup\" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check.Each participant is identified by some unique positive integer k, and each sent solution A is characterized by two numbers: x\u00a0\u2014 the number of different solutions that are sent before the first solution identical to A, and k \u2014 the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same x.It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number x (x\u2009>\u20090) of the participant with number k, then the testing system has a solution with number x\u2009-\u20091 of the same participant stored somewhere before.During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of solutions. Each of the following n lines contains two integers separated by space x and k (0\u2009\u2264\u2009x\u2009\u2264\u2009105; 1\u2009\u2264\u2009k\u2009\u2264\u2009105)\u00a0\u2014 the number of previous unique solutions and the identifier of the participant.", "output_spec": "A single line of the output should contain \u00abYES\u00bb if the data is in chronological order, and \u00abNO\u00bb otherwise.", "sample_inputs": ["2\n0 1\n1 1", "4\n0 1\n1 2\n1 1\n0 2", "4\n0 1\n1 1\n0 1\n0 2"], "sample_outputs": ["YES", "NO", "YES"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int();;\nlet tab=Array.make 100001 (-1);;\nlet b=ref true;;\nfor i=1 to n do\n let x=read_int() and k=read_int() in\n begin\n if x>tab.(k)+1 then b:=false;\n if x=tab.(k)+1 then tab.(k)<-x\n end\ndone;;\nif !b then print_string \"YES\" else print_string \"NO\";;\n"}], "negative_code": [], "src_uid": "6f6f56d3106e09d51ebb3a206fa4be3c"} {"nl": {"description": "Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2\u2009\u00d7\u20092 square consisting of black pixels is formed. Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2\u2009\u00d7\u20092 square consisting of black pixels is formed.", "input_spec": "The first line of the input contains three integers n,\u2009m,\u2009k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000, 1\u2009\u2264\u2009k\u2009\u2264\u2009105)\u00a0\u2014 the number of rows, the number of columns and the number of moves that Pasha is going to perform. The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1\u2009\u2264\u2009i\u2009\u2264\u2009n, 1\u2009\u2264\u2009j\u2009\u2264\u2009m), representing the row number and column number of the pixel that was painted during a move.", "output_spec": "If Pasha loses, print the number of the move when the 2\u2009\u00d7\u20092 square consisting of black pixels is formed. If Pasha doesn't lose, that is, no 2\u2009\u00d7\u20092 square consisting of black pixels is formed during the given k moves, print 0.", "sample_inputs": ["2 2 4\n1 1\n1 2\n2 1\n2 2", "2 3 6\n2 3\n2 2\n1 3\n2 2\n1 2\n1 1", "5 3 7\n2 3\n1 2\n1 1\n4 1\n3 1\n5 3\n3 2"], "sample_outputs": ["4", "5", "0"], "notes": null}, "positive_code": [{"source_code": "let carre a b mat =\n\t(mat.(a).(b)) && (mat.(a-1).(b)) && (mat.(a).(b-1)) && (mat.(a-1).(b-1));;\n\nlet rec f mat = function\n\t|[]\t\t-> -100000\n\t|(a,b)::q \t-> begin\n\t\t\t\tmat.(a).(b) <- true;\n\t\t\t\tif (carre a b mat) || (carre (a+1) b mat) || (carre a (b+1) mat) || (carre (a+1) (b+1) mat)\n\t\t\t\t\tthen 1\n\t\t\t\t\telse 1 + f mat q\n\t\t\t\tend;;\n\nlet final () =\n\tlet (n,m,k) = Scanf.scanf \"%d %d %d \" (fun i j k -> (i,j,k)) and l = ref [] in\n\t\tfor i=1 to k do\n\t\t\tl := (Scanf.scanf \"%d %d \" (fun i j -> (i,j)))::!l;\n\t\tdone;\n\tlet mat = Array.make_matrix (n+2) (m+2) false in\n\tlet a = f mat (List.rev !l) in\n\t\tif a < 0\n\t\t\tthen Printf.printf \"0\"\n\t\t\telse Printf.printf \"%d\" a;;\n\nfinal ();;\n"}, {"source_code": "(* square colours *)\ntype col = White | Black\n\nlet (++) (x, y) (z, w) = (x + z, y + w)\n\nlet get a (x, y) =\n try a.(x).(y)\n with Invalid_argument _ -> White\n\nlet deltas = [\n [(-1, -1); (0, -1); (-1, 0)]; (* north-west *)\n [( 1, -1); (0, -1); ( 1, 0)]; (* north-east *)\n [(-1, 1); (0, 1); (-1, 0)]; (* south-west *)\n [( 1, 1); (0, 1); ( 1, 0)]; (* south-east *)\n]\n\nlet () =\n Scanf.scanf \"%d %d %d\\n\" (fun n m k ->\n let board = Array.make_matrix n m White in\n let get = get board in\n\n let check_square p = List.fold_left (fun b d ->\n b || (List.fold_left (fun i d ->\n i + match get (d ++ p) with | White -> 0 | Black -> 1) 0 d) = 3)\n false deltas\n in\n\n let rec loop i =\n if i > k then 0\n else begin\n let x, y = Scanf.scanf \"%d %d\\n\" (fun x y -> (x-1, y-1)) in\n board.(x).(y) <- Black;\n if check_square (x, y) then i else loop (i + 1)\n end\n in\n Printf.printf \"%d\\n\" (loop 1)\n )\n"}], "negative_code": [], "src_uid": "0dc5469831c1d5d34aa3b7b172e3237b"} {"nl": {"description": "Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves\u00a0\u2014 from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i j\u00a0\u2014 Place a book at position j at shelf i if there is no book at it. 2 i j\u00a0\u2014 Remove the book from position j at shelf i if there is a book at it. 3 i\u00a0\u2014 Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 k\u00a0\u2014 Return the books in the bookcase in a state they were after applying k-th operation. In particular, k\u2009=\u20090 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so?", "input_spec": "The first line of the input contains three integers n, m and q (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009103, 1\u2009\u2264\u2009q\u2009\u2264\u2009105)\u00a0\u2014 the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order\u00a0\u2014 i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0.", "output_spec": "For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order.", "sample_inputs": ["2 3 3\n1 1 1\n3 2\n4 0", "4 2 6\n3 2\n2 2 2\n3 3\n3 2\n2 2 2\n3 2", "2 2 2\n3 2\n2 2 1"], "sample_outputs": ["1\n4\n0", "2\n1\n3\n3\n2\n4", "2\n1"], "notes": "NoteThis image illustrates the second sample case."}, "positive_code": [{"source_code": "type segtree =\n | Leaf of bool\n | Node of segtree * segtree * bool * int * int\n\n\nlet size tree = match tree with\n | Leaf _ -> 1\n | Node(_, _, _, size, _) -> size\n\n\nlet count tree = match tree with\n | Leaf b -> if b then 1 else 0\n | Node(_, _, inv, size, count) ->\n if inv then\n size - count\n else\n count\n\n\nlet create left right inv =\n Node(left, right, inv, size left + size right, count left + count right)\n\n\nlet invert_one tree = match tree with\n | Leaf b -> Leaf(not b)\n | Node(left, right, inv, _, _) -> create left right (not inv)\n\n\nlet push tree = match tree with\n | Leaf _ -> tree\n | Node(left, right, inv, _, _) ->\n if inv then\n create (invert_one left) (invert_one right) false\n else\n tree\n\n\nlet rec update tree i value = match tree with\n | Leaf _ -> Leaf value\n | Node _ ->\n match push tree with\n | Leaf _ -> exit 1\n | Node(left, right, _, _, _) ->\n if i < size left then\n create (update left i value) right false\n else\n create left (update right (i - size left) value) false\n\n\nlet rec invert tree l r = match tree with\n | Leaf _ -> invert_one tree\n | Node(_, _, inv, sz, _) ->\n if l == 0 && r == sz then\n invert_one tree\n else match push tree with\n | Leaf _ -> exit 1\n | Node(left, right, _, _, _) ->\n let mid = size left in\n let new_left = if l >= mid then left else invert left l (min mid r)\n and new_right = if r <= mid then right else invert right (max (l - mid) 0) (r - mid) in\n create new_left new_right false\n\n\nlet rec construct n =\n if n == 1 then\n Leaf false\n else\n let half = n lsr 1 in\n create (construct half) (construct(n - half)) false\n\n\nlet () =\n Scanf.bscanf Scanf.Scanning.stdin \" %d %d %d\" (fun n m q ->\n let roots = Array.make (q + 1) (construct(n * m)) in\n for i = 1 to q do\n Scanf.bscanf Scanf.Scanning.stdin \" %c %d\" (fun c a ->\n match c with\n | '1' | '2' ->\n Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun b ->\n roots.(i) <- update roots.(i - 1) ((a - 1) * m + b - 1) (c == '1')\n )\n | '3' -> roots.(i) <- invert roots.(i - 1) ((a - 1) * m) (a * m)\n | '4' -> roots.(i) <- roots.(a)\n | _ -> exit 1\n );\n print_int(count roots.(i));\n print_string \"\\n\"\n done\n )\n"}], "negative_code": [], "src_uid": "2b78f6626fce6b5b4f9628fb15666dc4"} {"nl": {"description": "You've got an n\u2009\u00d7\u2009m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. ", "input_spec": "The first line contains four space-separated integers n, m, x and y (1\u2009\u2264\u2009n,\u2009m,\u2009x,\u2009y\u2009\u2264\u20091000;\u00a0x\u2009\u2264\u2009y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character \".\" represents a white pixel and \"#\" represents a black pixel. The picture description doesn't have any other characters besides \".\" and \"#\".", "output_spec": "In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. ", "sample_inputs": ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."], "sample_outputs": ["11", "5"], "notes": "NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_char _ = bscanf Scanning.stdib \" %c \" (fun x -> x)\n\nlet () =\n let n = read_int () and m = read_int () and x = read_int () and y = read_int () in\n let a = Array.make_matrix (n + 1) (m + 1) ' '\n and cnt = Array.make_matrix (m + 1) 2 0\n and best = Array.make_matrix (m + 1) 2 1000000\n and dp = Array.init (m + 1) (fun _ -> Array.init 2 (fun _ -> Array.make (y + 1) 1000000)) in\n best.(0).(0) <- 0;\n best.(0).(1) <- 0;\n let interval a b color =\n cnt.(b).(color) - cnt.(a - 1).(color) in\n for i = 1 to n do\n for j = 1 to m do\n a.(i).(j) <- read_char ()\n done\n done;\n for i = 1 to m do\n let white = ref 0 and black = ref 0 in\n for j = 1 to n do\n if a.(j).(i) = '.' then incr white\n else incr black\n done;\n cnt.(i).(0) <- cnt.(i - 1).(0) + !white;\n cnt.(i).(1) <- cnt.(i - 1).(1) + !black\n done;\n for i = 1 to m do\n for color = 0 to 1 do\n let other_color = (color + 1) mod 2 in\n for length = x to min y i do\n dp.(i).(color).(length) <- best.(i - length).(other_color) + (interval (i - length + 1) i other_color);\n best.(i).(color) <- min best.(i).(color) dp.(i).(color).(length)\n done\n done\n done;\n printf \"%d\\n\" (min best.(m).(0) best.(m).(1))"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\nlet n = scan_int() and m = scan_int() and x = scan_int() and y = scan_int();;\nlet cnt = Array.make (m + 1) 0;; (*liczba zer w i-tej kolumnie*)\n\nfor i = 0 to n - 1 do\n let s = scan_string () in\n for j = 0 to m - 1 do\n cnt.(j + 1) <- cnt.(j + 1) + b2i(s.[j] = '.');\n done;\ndone;;\n\nlet duzo = 998244353;;\n\nlet dp = Array.make_matrix (m + 1) 2 duzo;;\ndp.(0).(0) <- 0;; dp.(0).(1) <- 0;; (* warunki poczatkowe *)\n\nlet zer = ref 0 and jed = ref 0;;\nfor i = 1 to x do\n zer := !zer + (n - cnt.(i));\n jed := !jed + cnt.(i); \ndone;;\n\nfor i = x to m do\n let pZer = ref !zer and pJed = ref !jed in\n for j = i - x + 1 downto max 1 (i - y + 1) do\n dp.(i).(0) <- min (dp.(i).(0)) (dp.(j - 1).(1) + !pZer);\n dp.(i).(1) <- min (dp.(i).(1)) (dp.(j - 1).(0) + !pJed);\n pZer := !pZer + (n - cnt.(j - 1));\n pJed := !pJed + cnt.(j - 1); \n done;\n if i <> m then begin\n zer := !zer + (n - cnt.(i + 1)) - (n - cnt.(i - x + 1));\n jed := !jed + cnt.(i + 1) - cnt.(i - x + 1);\n end; \ndone;;\n\nprint_int (min dp.(m).(0) dp.(m).(1));;"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\nlet n = scan_int() and m = scan_int() and x = scan_int() and y = scan_int();;\nlet cnt = Array.make (m + 1) 0;; (*liczba zer w i-tej kolumnie*)\n\nfor i = 0 to n - 1 do\n let s = scan_string () in\n for j = 0 to m - 1 do\n cnt.(j + 1) <- cnt.(j + 1) + b2i(s.[j] = '.');\n done;\ndone;;\n\nlet duzo = 998244353;;\n\nlet dp = Array.make_matrix (m + 1) 2 duzo;;\ndp.(0).(0) <- 0;; dp.(0).(1) <- 0;; (* warunki poczatkowe *)\n\nlet zer = ref 0 and jed = ref 0;;\nfor i = 1 to x - 1 do\n zer := !zer + (n - cnt.(i));\n jed := !jed + cnt.(i); \ndone;;\n\nfor i = x to m do\n let pZer = ref !zer and pJed = ref !jed in\n for j = i - x + 1 downto max 1 (i - y + 1) do\n pZer := !pZer + (n - cnt.(j));\n pJed := !pJed + cnt.(j); \n dp.(i).(0) <- min (dp.(i).(0)) (dp.(j - 1).(1) + !pZer);\n dp.(i).(1) <- min (dp.(i).(1)) (dp.(j - 1).(0) + !pJed);\n done;\n if i <> m then begin \n zer := !zer + (n - cnt.(i)) - (n - cnt.(i - x + 1));\n jed := !jed + cnt.(i) - cnt.(i - x + 1); \n end;\ndone;;\n\nprint_int (min dp.(m).(0) dp.(m).(1));;"}], "src_uid": "08d13e3c71040684d5a056bd1b53ef3b"} {"nl": {"description": "Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.You are given an encoding s of some word, your task is to decode it. ", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000)\u00a0\u2014 the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters\u00a0\u2014 the encoding.", "output_spec": "Print the word that Polycarp encoded.", "sample_inputs": ["5\nlogva", "2\nno", "4\nabba"], "sample_outputs": ["volga", "no", "baba"], "notes": "NoteIn the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva.In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same.In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba."}, "positive_code": [{"source_code": "let () =\n Scanf.scanf \"%d %s\" @@ fun n s ->\n let b = Bytes.create n in\n for i = 0 to n / 2 - 1 do\n Bytes.set b i s.[n - 2 * i - 2]\n done;\n for i = n - 1 downto n / 2 do\n Bytes.set b i s.[2 * i - n + 1]\n done;\n Printf.printf \"%s\\n\" b\n"}, {"source_code": "let decode (s : string) : string =\n let n = String.length s in\n let bs = Bytes.create n in\n begin\n if n mod 2 = 0\n then\n for i = 0 to n/2-1 do\n Bytes.set bs (n/2-1 - i) s.[2*i];\n Bytes.set bs (n/2 + i) s.[2*i+1]\n done\n else begin\n for i = 0 to (n-3)/2 do\n Bytes.set bs ((n-1)/2 + i) s.[2*i];\n Bytes.set bs ((n-3)/2 - i) s.[2*i+1]\n done;\n Bytes.set bs (n-1) s.[n-1]\n end\n end;\n Bytes.unsafe_to_string bs\n\n\nlet main () =\n let n = read_int () in\n let encoded_str = really_input_string stdin n in\n print_string (decode encoded_str)\n\n\nlet _ = main ()\n"}], "negative_code": [], "src_uid": "2a414730d1bc7eef50bdb631ea966366"} {"nl": {"description": "Not to be confused with chessboard. ", "input_spec": "The first line of input contains a single integer N (1\u2009\u2264\u2009N\u2009\u2264\u2009100) \u2014 the number of cheeses you have. The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either \"soft\" or \"hard. All cheese names are distinct.", "output_spec": "Output a single number.", "sample_inputs": ["9\nbrie soft\ncamembert soft\nfeta soft\ngoat soft\nmuenster soft\nasiago hard\ncheddar hard\ngouda hard\nswiss hard", "6\nparmesan hard\nemmental hard\nedam hard\ncolby hard\ngruyere hard\nasiago hard"], "sample_outputs": ["3", "4"], "notes": null}, "positive_code": [{"source_code": "open String\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (length s) in\n for i = length s - 1 downto 0 do\n if unsafe_get s i = sep then begin\n r := sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\nsub s 0 !j :: !r\n\nlet soft = ref 0\n\nlet hard = ref 0\n\nlet level b cheese i =\n let shift = if b then 1 else 0 in\n cheese <= (i * i + shift) / 2\n\n\nlet _ =\n let n = read_int () in\n for i = 0 to n - 1 do\n let s = read_line () in\n let l = split_on_char ' ' s in\n if List.nth l 1 = \"soft\" then\n incr soft\n else\n incr hard\n done;\n let a,b = if !soft < !hard then !soft, !hard else !hard, !soft in\n for i = 0 to 100 do\n if level true b i && level false a i then\n begin\n Format.printf \"%d@.\" i;\n exit 0\n end\n done;\n"}], "negative_code": [{"source_code": "open String\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (length s) in\n for i = length s - 1 downto 0 do\n if unsafe_get s i = sep then begin\n r := sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\nsub s 0 !j :: !r\n\nlet soft = ref 0\n\nlet hard = ref 0\n\nlet level b cheese i =\n let shift = if b then 1 else 0 in\n cheese * 2 + shift <= i * i\n\n\nlet _ =\n let n = read_int () in\n for i = 0 to n - 1 do\n let s = read_line () in\n let l = split_on_char ' ' s in\n if List.nth l 1 = \"soft \" then\n incr soft\n else\n incr hard\n done;\n let a,b = if !soft < !hard then !soft, !hard else !hard, !soft in\n for i = 0 to 100 do\n if level true b i && level false a i then\n begin\n Format.printf \"%d@.\" i;\n exit 0\n end\n done;\n"}, {"source_code": "open String\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (length s) in\n for i = length s - 1 downto 0 do\n if unsafe_get s i = sep then begin\n r := sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\nsub s 0 !j :: !r\n\nlet soft = ref 0\n\nlet hard = ref 0\n\nlet level b cheese i =\n let shift = if b then 1 else 0 in\n cheese <= (i * i + shift) / 2\n\n\nlet _ =\n let n = read_int () in\n for i = 0 to n - 1 do\n let s = read_line () in\n let l = split_on_char ' ' s in\n if List.nth l 1 = \"soft \" then\n incr soft\n else\n incr hard\n done;\n let a,b = if !soft < !hard then !soft, !hard else !hard, !soft in\n for i = 0 to 100 do\n if level true b i && level false a i then\n begin\n Format.printf \"%d@.\" i;\n exit 0\n end\n done;\n"}], "src_uid": "bea06c48418316042c19e6fd43fe20b5"} {"nl": {"description": "There are $$$n$$$ points on a coordinate axis $$$OX$$$. The $$$i$$$-th point is located at the integer point $$$x_i$$$ and has a speed $$$v_i$$$. It is guaranteed that no two points occupy the same coordinate. All $$$n$$$ points move with the constant speed, the coordinate of the $$$i$$$-th point at the moment $$$t$$$ ($$$t$$$ can be non-integer) is calculated as $$$x_i + t \\cdot v_i$$$.Consider two points $$$i$$$ and $$$j$$$. Let $$$d(i, j)$$$ be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points $$$i$$$ and $$$j$$$ coincide at some moment, the value $$$d(i, j)$$$ will be $$$0$$$.Your task is to calculate the value $$$\\sum\\limits_{1 \\le i < j \\le n}$$$ $$$d(i, j)$$$ (the sum of minimum distances over all pairs of points).", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of points. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$ ($$$1 \\le x_i \\le 10^8$$$), where $$$x_i$$$ is the initial coordinate of the $$$i$$$-th point. It is guaranteed that all $$$x_i$$$ are distinct. The third line of the input contains $$$n$$$ integers $$$v_1, v_2, \\dots, v_n$$$ ($$$-10^8 \\le v_i \\le 10^8$$$), where $$$v_i$$$ is the speed of the $$$i$$$-th point.", "output_spec": "Print one integer \u2014 the value $$$\\sum\\limits_{1 \\le i < j \\le n}$$$ $$$d(i, j)$$$ (the sum of minimum distances over all pairs of points).", "sample_inputs": ["3\n1 3 2\n-100 2 3", "5\n2 1 4 3 5\n2 2 2 3 4", "2\n2 1\n-3 0"], "sample_outputs": ["3", "19", "0"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet sum f i =\n let z = ref 0L in\n let x = ref i in\n while !x > 0 do\n z := Int64.add !z f.(!x);\n x := !x - (!x land -(!x))\n done;\n !z\n\nlet add f i d =\n let x = ref i in\n while !x <= ((Array.length f)-1) do\n f.(!x) <- Int64.add f.(!x) d;\n x := !x + (!x land -(!x))\n done\n\nlet rec binary_search a ?(l=0) ?(u=Array.length a - 1) k =\n if l > u then raise Not_found;\n let m = l + (u - l) / 2 in\n match compare k a.(m) with\n | -1 -> binary_search a ~l ~u:(m - 1) k\n | 1 -> binary_search a ~l:(m + 1) ~u k\n | _ -> m;;\n\nlet () =\n let n = read_int() in \n let x = Array.init n read_int in\n let v = Array.init n read_int in \n let xx = Array.init n (fun i -> (x.(i), v.(i))) in\n Array.sort (fun x y -> compare x y) v;\n Array.sort (fun x y -> compare x y) xx;\n let cc = ref (Array.make (n+1) 0L) in\n let ss = ref (Array.make (n+1) 0L) in\n\n let z = ref 0L in \n for i=0 to n-1 do\n let (x, key) = xx.(i) in\n let xx = Int64.of_int(x) in\n let vv = (binary_search v key)+1 in \n z := Int64.add !z (Int64.sub (Int64.mul (sum !cc vv) xx) (sum !ss vv));\n add !cc vv 1L;\n add !ss vv xx;\n done;\n\n printf \"%Ld\\n\" !z;\n (*printf \"%d %d %d %Ld\\n\" x key vv !z;\n let a = List.map (fun s -> int_of_string s) c in*) \n "}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet sum f i =\n let z = ref 0 in\n let x = ref i in\n while !x > 0 do\n z := !z + f.(!x);\n x := !x - (!x land -(!x))\n done;\n Int64.of_int(!z)\n\nlet add f i v =\n let x = ref i in\n while !x <= ((Array.length f)-1) do\n f.(!x) <- f.(!x) + v;\n x := !x + (!x land -(!x))\n done\n\nlet rec binary_search a ?(l=0) ?(u=Array.length a - 1) k =\n if l > u then raise Not_found;\n let m = l + (u - l) / 2 in\n match compare k a.(m) with\n | -1 -> binary_search a ~l ~u:(m - 1) k\n | 1 -> binary_search a ~l:(m + 1) ~u k\n | _ -> m;;\n\nlet () =\n let n = read_int() in \n let x = Array.init n read_int in\n let v = Array.init n read_int in \n let xx = Array.init n (fun i -> (x.(i), v.(i))) in\n Array.sort (fun x y -> compare x y) v;\n Array.sort (fun x y -> compare x y) xx;\n let cc = Array.make (n+1) 0 in\n let ss = Array.make (n+1) 0 in\n\n let z = ref 0L in \n for i=0 to n-1 do\n let (x, key) = xx.(i) in\n let xx = Int64.of_int(x) in\n let vv = (binary_search v key)+1 in \n z := Int64.add !z (Int64.sub (Int64.mul (sum cc vv) xx) (sum ss vv));\n add cc vv 1;\n add ss vv x;\n \n done;\n\n printf \"%Ld\\n\" !z;\n (*printf \"%d %d %d %Ld\\n\" x key vv !z;\n let a = List.map (fun s -> int_of_string s) c in*) \n "}], "src_uid": "40ab9115d709cabf1273b29d257e16c4"} {"nl": {"description": "Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $$$1$$$ problem, during the second day \u2014 exactly $$$2$$$ problems, during the third day \u2014 exactly $$$3$$$ problems, and so on. During the $$$k$$$-th day he should solve $$$k$$$ problems.Polycarp has a list of $$$n$$$ contests, the $$$i$$$-th contest consists of $$$a_i$$$ problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly $$$k$$$ problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least $$$k$$$ problems that Polycarp didn't solve yet during the $$$k$$$-th day, then Polycarp stops his training.How many days Polycarp can train if he chooses the contests optimally?", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of contests. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 2 \\cdot 10^5$$$) \u2014 the number of problems in the $$$i$$$-th contest.", "output_spec": "Print one integer \u2014 the maximum number of days Polycarp can train if he chooses the contests optimally.", "sample_inputs": ["4\n3 1 4 1", "3\n1 1 1", "5\n1 1 1 2 2"], "sample_outputs": ["3", "1", "2"], "notes": null}, "positive_code": [{"source_code": "let mergesort l =\n let rec helper l =\n match l with\n | [] -> []\n | hd::[] -> hd::[]\n | hd::tl -> \n let (l1, l2) =\n let f (l1, l2) hd = (l2, hd::l1) in\n List.fold_left f ([], []) l\n in\n let l1_sorted = helper l1\n and l2_sorted = helper l2\n in\n let rec merge l1 l2 res = \n match l1, l2 with\n | [], [] -> res\n | hd::tl, [] -> merge tl l2 (hd::res)\n | [], hd::tl -> merge l1 tl (hd::res)\n | h1::t1, h2::t2 ->\n if h1 < h2 then \n merge t1 l2 (h1::res)\n else \n merge l1 t2 (h2::res)\n in\n merge l1_sorted l2_sorted [] |> List.rev\n in helper l\n\n(* l is sorted *)\nlet result l = \n let f acc hd = \n if acc < hd then \n acc + 1 \n else acc\n in List.fold_left f 0 l\n;;\n \nlet len = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x)\nlet build_list len = \n let rec helper len acc =\n if len = 0 then acc\n else \n let improved = Scanf.scanf \" %d \" (fun x -> x::acc)\n in helper (len-1) improved\n in\n helper len []\n \nlet list = build_list len\nlet sorted_list = mergesort list;;\n \nlet res = result sorted_list;;\n \nPrintf.printf \"%d\\n\" res;\n"}], "negative_code": [], "src_uid": "4f02ac641ab112b9d6aee222e1365c09"} {"nl": {"description": "There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (n\u2009+\u20091) meters, he draws a cross (see picture for clarifications).John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw? The figure shows the order in which John draws crosses for a square with side 4. The lower left square has two crosses. Overall John paints 17 crosses. ", "input_spec": "The first line contains integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009104) \u2014 the number of test cases. The second line contains t space-separated integers ni (1\u2009\u2264\u2009ni\u2009\u2264\u2009109) \u2014 the sides of the square for each test sample.", "output_spec": "For each test sample print on a single line the answer to it, that is, the number of crosses John will draw as he will move along the square of the corresponding size. Print the answers to the samples in the order in which the samples are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier. ", "sample_inputs": ["3\n4 8 100"], "sample_outputs": ["17\n33\n401"], "notes": null}, "positive_code": [{"source_code": "let rec gcd a b =\n if b = 0 then a else gcd b (a mod b)\n;;\n\nlet _ =\n let ni () = Scanf.scanf \" %d\" (fun x -> x) in\n let re = ni () in\n for ri = 1 to re do\n let n = ni () in\n let n' = float_of_int n in\n Printf.printf \"%.0f\\n\" (1.0 +. match (n + 1) mod 4 with\n | 0 -> n'\n | 2 -> 2.0 *. n'\n | _ -> 4.0 *. n'\n )\n done\n;;\n"}, {"source_code": "open Big_int\n\nlet next_token =\n let buffer = ref \"\" in\n let first = ref 0 in\n let rec omit_spaces s from =\n try\n (match s.[from] with\n | ' ' -> omit_spaces s (from + 1)\n | _ -> from)\n with\n | Invalid_argument _ -> String.length s\n in\n (fun () ->\n first := omit_spaces !buffer !first;\n while !first > String.length !buffer - 1 do\n buffer := read_line ();\n first := omit_spaces !buffer 0\n done;\n let last = try String.index_from !buffer !first ' '\n with Not_found -> String.length !buffer\n in\n let result = String.sub !buffer !first (last - !first) in\n first := last;\n result)\n\nlet next_int () = int_of_string (next_token ())\n\nlet ( *$ ) a b = mult_big_int a b\nlet ( /$ ) a b = div_big_int a b\nlet ( +$ ) a b = add_big_int a b\nlet ( ~$ ) a = big_int_of_int a\nlet ( %$ ) a b = mod_big_int a b\nlet ( <$ ) a b = lt_big_int a b\nlet ( >$ ) a b = gt_big_int a b\nlet ( =$ ) a b = eq_big_int a b\n\nlet rec gcd a b =\n if a <$ b then gcd b a\n else if b =$ (~$ 0) then a\n else gcd b (a %$ b)\n\nlet lcm a b = (a *$ b) /$ (gcd a b)\n\nlet () =\n let t = next_int () in\n for k = 1 to t do\n let n = ~$ (next_int ()) in\n let\n result = (lcm ((~$ 4) *$ n) (n +$ (~$ 1))) /$ ((n +$ (~$ 1))) +$ (~$ 1)\n in\n print_endline (string_of_big_int result)\n done\n\n"}, {"source_code": "open Big_int\n\nlet next_token =\n let buffer = ref \"\" in\n let first = ref 0 in\n let rec omit_spaces s from =\n try\n (match s.[from] with\n | ' ' -> omit_spaces s (from + 1)\n | _ -> from)\n with\n | Invalid_argument _ -> String.length s\n in\n (fun () ->\n first := omit_spaces !buffer !first;\n while !first > String.length !buffer - 1 do\n buffer := read_line ();\n first := omit_spaces !buffer 0\n done;\n let last = try String.index_from !buffer !first ' '\n with Not_found -> String.length !buffer\n in\n let result = String.sub !buffer !first (last - !first) in\n first := last;\n result)\n\nlet next_int () = int_of_string (next_token ())\n\nlet ( + ) a b = add_big_int a b\nlet ( - ) a b = sub_big_int a b \nlet ( * ) a b = mult_big_int a b\nlet ( / ) a b = div_big_int a b\nlet ( % ) a b = mod_big_int a b\nlet ( < ) a b = lt_big_int a b\nlet ( > ) a b = gt_big_int a b\nlet ( = ) a b = eq_big_int a b\n\nlet zero = big_int_of_int 0\nlet one = big_int_of_int 1\nlet two = big_int_of_int 2\nlet four = big_int_of_int 4\n\nlet rec gcd a b =\n if a < b then gcd b a\n else if b = zero then a\n else gcd b (a % b)\n\nlet lcm a b = (a * b) / (gcd a b)\n\nlet () =\n let t = next_int () in\n for k = 1 to t do\n let n = big_int_of_int (next_int ()) in\n let result = (lcm (four * n) (n + one)) / (n + one) + one in\n print_endline (string_of_big_int result)\n done\n"}, {"source_code": "open Big_int\n\nlet sieve n =\n let nums = Array.make (n + 1) false in\n let delete m =\n if not nums.(m) then\n for k = 2 to n / m do\n nums.(k * m) <- true\n done\n in\n let result = ref [] in\n nums.(0) <- true;\n nums.(1) <- true;\n for i = 2 to int_of_float(sqrt(float_of_int(n))) + 1 do\n delete i\n done;\n Array.iteri (fun i composite ->\n if not composite then result := i :: !result) nums;\n List.rev !result\n\nlet rec factorization ?(result=[]) primes n =\n let add x (* lst *)= function\n | [] -> [(x, 1)]\n | (y, ky) :: ys when y = x -> (x, ky + 1) :: ys\n | ys -> (x, 1) :: ys\n in\n let p = try List.hd primes with Failure _ -> n in\n match n with\n | 1 -> List.rev result\n | _ when n mod p = 0 -> factorization ~result:(add p result) primes (n / p)\n | _ (* <> 0 *) -> factorization ~result (List.tl primes) n\n\nlet rec insert_factor ?(acc=[]) (x, kx) = function\n | [] -> List.rev ((x, kx) :: acc)\n | (y, ky) :: ys when y < x -> insert_factor ~acc:((y, ky) :: acc) (x, kx) ys\n | (y, ky) :: ys when y = x -> List.rev ((x, kx + ky) :: acc) @ ys\n | (y, ky) :: ys (* y > x *) -> List.rev ((x, kx) :: acc) @ ((y, ky) :: ys)\n\nlet rec lcm_fact ?(result=[]) lesser greater = match (lesser, greater) with\n | (_, []) -> List.rev result\n | ([], y :: ys) -> lcm_fact ~result:(y :: result) [] ys\n | ((x, kx) :: xs, (y, ky) :: ys) when x = y && kx < ky ->\n lcm_fact ~result:((x, ky - kx) :: result) xs ys\n | ((x, _) :: xs, (y, _) :: ys) when x = y (* kx >= ky *) ->\n lcm_fact ~result xs ys\n | ((x, _) :: xs, (y, _) :: _) when x < y ->\n lcm_fact ~result xs greater\n | (_, y :: ys) (* x > y *) ->\n lcm_fact ~result:(y :: result) lesser ys\n\nlet ( *.. ) a b = mult_big_int a b\nlet ( +.. ) a b = add_big_int a b\nlet ( ~.. ) a = big_int_of_int a \n\nlet rec product ?(result=unit_big_int) = function\n | [] -> result\n | (p, 0) :: ps -> product ~result ps\n | (p, n) :: ps -> product ~result:((~.. p) *.. result) ((p, n - 1) :: ps)\n\nlet next_token =\n let buffer = ref \"\" in\n let first = ref 0 in\n let rec omit_spaces s from =\n try\n (match s.[from] with\n | ' ' -> omit_spaces s (from + 1)\n | _ -> from)\n with\n | Invalid_argument _ -> String.length s\n in\n (fun () ->\n first := omit_spaces !buffer !first;\n while !first > String.length !buffer - 1 do\n buffer := read_line ();\n first := omit_spaces !buffer 0\n done;\n let last = try String.index_from !buffer !first ' '\n with Not_found -> String.length !buffer\n in\n let result = String.sub !buffer !first (last - !first) in\n first := last;\n result)\n\nlet next_int () = int_of_string (next_token ())\n\nlet () =\n let primes = sieve 31623 in\n let t = next_int () in\n for k = 1 to t do\n let n = next_int () in\n let greater_factors = insert_factor (2, 2) (factorization primes n) in\n let lesser_factors = factorization primes (n + 1) in\n let\n result = (product (lcm_fact lesser_factors greater_factors)) +.. (~.. 1)\n in\n print_endline (string_of_big_int result)\n done\n\n"}], "negative_code": [{"source_code": "let rec gao n =\n if n = 1 then 2\n else if n mod 2 = 0 then 4 * n\n else gao (n / 2 + 1)\n;;\n\nlet _ =\n let ni () = Scanf.scanf \" %d\" (fun x -> x) in\n let re = ni () in\n for ri = 1 to re do\n let n = ni () in\n Printf.printf \"%d\\n\" (1 + gao n)\n done\n;;\n"}, {"source_code": "\nlet sieve n =\n let nums = Array.make (n + 1) false in\n let delete m =\n if not nums.(m) then\n for k = 2 to n / m do\n nums.(k * m) <- true\n done\n in\n let result = ref [] in\n nums.(0) <- true;\n nums.(1) <- true;\n for i = 2 to int_of_float(sqrt(float_of_int(n))) + 1 do\n delete i\n done;\n Array.iteri (fun i composite ->\n if not composite then result := i :: !result) nums;\n List.rev !result\n\nlet rec factorization ?(result=[]) primes n =\n let add x (* lst *)= function\n | [] -> [(x, 1)]\n | (y, ky) :: ys when y = x -> (x, ky + 1) :: ys\n | ys -> (x, 1) :: ys\n in\n let p = try List.hd primes with Failure _ -> n in\n match n with\n | 1 -> List.rev result\n | _ when n mod p = 0 -> factorization ~result:(add p result) primes (n / p)\n | _ (* <> 0 *) -> factorization ~result (List.tl primes) n\n\nlet rec insert_factor ?(acc=[]) (x, kx) = function\n | [] -> List.rev ((x, kx) :: acc)\n | (y, ky) :: ys when y < x -> insert_factor ~acc:((y, ky) :: acc) (x, kx) ys\n | (y, ky) :: ys when y = x -> List.rev ((x, kx + ky) :: acc) @ ys\n | (y, ky) :: ys (* y > x *) -> List.rev ((x, kx) :: acc) @ ((y, ky) :: ys)\n\nlet rec lcm_fact ?(result=[]) lesser greater = match (lesser, greater) with\n | (_, []) -> List.rev result\n | ([], y :: ys) -> lcm_fact ~result:(y :: result) [] ys\n | ((x, kx) :: xs, (y, ky) :: ys) when x = y && kx < ky->\n lcm_fact ~result:((x, ky - kx) :: result) xs ys\n | ((x, _) :: xs, (y, _) :: ys) when x = y ->\n lcm_fact ~result xs ys\n | ((x, _) :: xs, (y, _) :: _) when x < y ->\n lcm_fact ~result xs greater\n | ((x, _) :: _, (y, ky) :: ys) (* x > y *) ->\n lcm_fact ~result:((y, ky) :: result) lesser ys\n\nlet rec product ?(result=1) = function\n | [] -> result\n | (p, 0) :: ps -> product ~result ps\n | (p, n) :: ps -> product ~result:(p * result) ((p, n - 1) :: ps)\n\nlet next_token =\n let buffer = ref \"\" in\n let first = ref 0 in\n let rec omit_spaces s from =\n try\n (match s.[from] with\n | ' ' -> omit_spaces s (from + 1)\n | _ -> from)\n with\n | Invalid_argument _ -> String.length s\n in\n (fun () ->\n first := omit_spaces !buffer !first;\n while !first > String.length !buffer - 1 do\n buffer := read_line ();\n first := omit_spaces !buffer 0\n done;\n let last = try String.index_from !buffer !first ' '\n with Not_found -> String.length !buffer\n in\n let result = String.sub !buffer !first (last - !first) in\n first := last;\n result)\n\nlet next_int () = int_of_string (next_token ())\n\nlet () =\n let primes = sieve 31623 in\n let t = next_int () in\n for k = 1 to t do\n let n = next_int () in\n let greater_factors = insert_factor (2, 2) (factorization primes n) in\n let lesser_factors = factorization primes (n + 1) in\n let result = (product (lcm_fact lesser_factors greater_factors)) + 1 in\n print_endline (string_of_int result)\n done\n\n"}, {"source_code": "\nlet sieve n =\n let nums = Array.make (n + 1) false in\n let delete m =\n if not nums.(m) then\n for k = 2 to n / m do\n nums.(k * m) <- true\n done\n in\n let result = ref [] in\n nums.(0) <- true;\n nums.(1) <- true;\n for i = 2 to int_of_float(sqrt(float_of_int(n))) do\n delete i\n done;\n Array.iteri (fun i composite ->\n if not composite then result := i :: !result) nums;\n List.rev !result\n\nlet rec factorization ?(result=[]) primes n =\n let add x (* lst *)= function\n | [] -> [(x, 1)]\n | (y, ky) :: ys when y = x -> (x, ky + 1) :: ys\n | ys -> (x, 1) :: ys\n in\n let p = try List.hd primes with Failure _ -> n in\n match n with\n | 1 -> List.rev result\n | _ when n mod p = 0 -> factorization ~result:(add p result) primes (n / p)\n | _ (* <> 0 *) -> factorization ~result (List.tl primes) n\n\nlet rec insert_factor ?(acc=[]) (x, kx) = function\n | [] -> List.rev ((x, kx) :: acc)\n | (y, ky) :: ys when y < x -> insert_factor ~acc:((y, ky) :: acc) (x, kx) ys\n | (y, ky) :: ys when y = x -> List.rev ((x, kx + ky) :: acc) @ ys\n | (y, ky) :: ys (* y > x *) -> List.rev ((x, kx) :: acc) @ ((y, ky) :: ys)\n\nlet rec lcm_fact ?(result=[]) lesser greater = match (lesser, greater) with\n | (_, []) -> List.rev result\n | ([], y :: ys) -> lcm_fact ~result:(y :: result) [] ys\n | ((x, kx) :: xs, (y, ky) :: ys) when x = y && kx < ky->\n lcm_fact ~result:((x, ky - kx) :: result) xs ys\n | ((x, _) :: xs, (y, _) :: ys) when x = y ->\n lcm_fact ~result xs ys\n | ((x, _) :: xs, (y, _) :: _) when x < y ->\n lcm_fact ~result xs greater\n | ((x, _) :: _, (y, ky) :: ys) (* x > y *) ->\n lcm_fact ~result:((y, ky) :: result) lesser ys\n\nlet rec product ?(result=1) = function\n | [] -> result\n | (p, 0) :: ps -> product ~result ps\n | (p, n) :: ps -> product ~result:(p * result) ((p, n - 1) :: ps)\n\nlet next_token =\n let buffer = ref \"\" in\n let first = ref 0 in\n let rec omit_spaces s from =\n try\n (match s.[from] with\n | ' ' -> omit_spaces s (from + 1)\n | _ -> from)\n with\n | Invalid_argument _ -> String.length s\n in\n (fun () ->\n first := omit_spaces !buffer !first;\n while !first > String.length !buffer - 1 do\n buffer := read_line ();\n first := omit_spaces !buffer 0\n done;\n let last = try String.index_from !buffer !first ' '\n with Not_found -> String.length !buffer\n in\n let result = String.sub !buffer !first (last - !first) in\n first := last;\n result)\n\nlet next_int () = int_of_string (next_token ())\n\nlet () =\n let primes = sieve 10000 in\n let t = next_int () in\n for k = 1 to t do\n let n = next_int () in\n let greater_factors = insert_factor (2, 2) (factorization primes n) in\n let lesser_factors = factorization primes (n + 1) in\n let result = (product (lcm_fact lesser_factors greater_factors)) + 1 in\n print_endline (string_of_int result)\n done\n\n"}], "src_uid": "168dbc4994529f5407a440b0c71086da"} {"nl": {"description": "All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from li to ri, inclusive. Today Fedor wants to take exactly k coupons with him.Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105)\u00a0\u2014 the number of coupons Fedor has, and the number of coupons he wants to choose. Each of the next n lines contains two integers li and ri (\u2009-\u2009109\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109)\u00a0\u2014 the description of the i-th coupon. The coupons can be equal.", "output_spec": "In the first line print single integer\u00a0\u2014 the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted. In the second line print k distinct integers p1,\u2009p2,\u2009...,\u2009pk (1\u2009\u2264\u2009pi\u2009\u2264\u2009n)\u00a0\u2014 the ids of the coupons which Fedor should choose. If there are multiple answers, print any of them.", "sample_inputs": ["4 2\n1 100\n40 70\n120 130\n125 180", "3 2\n1 12\n15 20\n25 30", "5 2\n1 10\n5 15\n14 50\n30 70\n99 100"], "sample_outputs": ["31\n1 2", "0\n1 2", "21\n3 4"], "notes": "NoteIn the first example if we take the first two coupons then all the products with ids in range [40,\u200970] can be bought with both coupons. There are 31 products in total.In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example."}, "positive_code": [{"source_code": "let ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nmodule Pset = Set.Make (struct type t = int64*int let compare = compare end)\n\nopen Printf\nopen Scanf\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let seg = Array.init n (fun i -> let l = read_long () in let r = read_long() in (l,r,i)) in\n\n Array.sort compare seg;\n\n let rec loop i size set best_score best_set =\n if i=n then (best_score,best_set) else\n let (l,r,j) = seg.(i) in\n let set = Pset.add (r,j) set in\n let (r',_) = Pset.min_elt set in\n let size = size+1 in\n let (best_score, best_set) =\n\tif size = k && best_score < (r' -- l) then (r' -- l, set) else (best_score, best_set)\n in\n let (size,set) = if size printf \"%d \" (i+1)) best_set;\n print_newline()\n )\n"}], "negative_code": [], "src_uid": "c9155ff3aca437eec3c4e9cf95a2d62c"} {"nl": {"description": "You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k)\u2009=\u2009{cu\u00a0:\u2009\u00a0cu\u2009\u2260\u2009k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.", "input_spec": "The first line contains two space-separated integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009105) \u2014 the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi) \u2014 the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges.", "output_spec": "Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.", "sample_inputs": ["6 6\n1 1 2 3 5 8\n1 2\n3 2\n1 4\n4 3\n4 5\n4 6", "5 6\n4 2 5 2 4\n1 2\n2 3\n3 1\n5 3\n5 4\n3 4"], "sample_outputs": ["3", "2"], "notes": null}, "positive_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve (n, m, c, e0) =\n let open Hashtbl in\n let adjC : ((int, (int, unit) t) t) = create 10 in\n Array.iter\n (fun c -> try let _ = find adjC c in () with Not_found -> add adjC c (create 10))\n c;\n Array.iter\n (fun (u, v) ->\n if c.(u) = c.(v) then ()\n else begin\n replace (find adjC c.(u)) c.(v) ();\n replace (find adjC c.(v)) c.(u) ()\n end)\n e0;\n fold\n (fun c' h (c, q) ->\n let q' = length h in\n if q' > q || q' = q && c' < c\n then (c', q')\n else (c, q))\n adjC\n (-1, -1)\n |> fst\n\nlet main () =\n let n = readInt () in\n let m = readInt () in\n let c = Array.init n (fun _ -> readInt ()) in\n let e0 = Array.init m (fun _ -> (readInt () - 1, readInt () - 1)) in\n Printf.printf \"%d\\n\" (solve (n, m, c, e0))\n\nlet () = main ()\n"}, {"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve (n, m, c, e0) =\n let open Hashtbl in\n let adjC : ((int, (int, unit) t) t) = create (n/10) in\n Array.iter\n (fun c -> try let _ = find adjC c in () with Not_found -> add adjC c (create 10))\n c;\n Array.iter\n (fun (u, v) ->\n if c.(u) = c.(v) then ()\n else begin\n replace (find adjC c.(u)) c.(v) ();\n replace (find adjC c.(v)) c.(u) ()\n end)\n e0;\n fold\n (fun c' h (c, q) ->\n let q' = length h in\n if q' > q || q' = q && c' < c\n then (c', q')\n else (c, q))\n adjC\n (-1, -1)\n |> fst\n\nlet main () =\n let n = readInt () in\n let m = readInt () in\n let c = Array.init n (fun _ -> readInt ()) in\n let e0 = Array.init m (fun _ -> (readInt () - 1, readInt () - 1)) in\n Printf.printf \"%d\\n\" (solve (n, m, c, e0))\n\nlet () = main ()\n"}, {"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve (n, m, c, e0) =\n let open Hashtbl in\n let adjC : ((int, (int, unit) t) t) = create 10 in\n Array.iter\n (fun c -> try let _ = find adjC c in () with Not_found -> add adjC c (create 10))\n c;\n Array.iter\n (fun (u, v) ->\n if c.(u) = c.(v) then ()\n else begin\n replace (find adjC c.(u)) c.(v) ();\n replace (find adjC c.(v)) c.(u) ()\n end)\n e0;\n (* -(snd Seq.(to_seq adjC |> map (fun (c, h) -> (length h, -c)) |> fold_left max (-1, -1))) *)\n -(snd (fold (fun c' h cur -> max (length h, -c') cur) adjC (-1, -1)))\n\nlet main () =\n let n = readInt () in\n let m = readInt () in\n let c = Array.init n (fun _ -> readInt ()) in\n let e0 = Array.init m (fun _ -> (readInt () - 1, readInt () - 1)) in\n Printf.printf \"%d\\n\" (solve (n, m, c, e0))\n\nlet () = main ()\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n\n let c = Array.init n (fun _ -> read_int()) in (* colors of the vertices *)\n\n let mc = maxf 0 (n-1) (fun i -> c.(i)) in (* maximum color *)\n\n let carray = Array.init (mc+1) (fun _-> Hashtbl.create 5) in\n\n let add_edge a b = \n if (c.(a) <> c.(b)) then (\n Hashtbl.replace carray.(c.(a)) c.(b) true;\n Hashtbl.replace carray.(c.(b)) c.(a) true;\n )\n in\n\n let () =\n for i=0 to m-1 do\n let a = read_int() in\n let b = read_int() in\n\tadd_edge (a-1) (b-1);\n done\n in\n\n let ccount c = Hashtbl.length carray.(c) in\n let div = maxf 0 mc ccount in\n let i = minf 0 (n-1) (fun j -> if ccount c.(j) = div then c.(j) else (mc+1)) in\n Printf.printf \"%d\\n\" i\n"}], "negative_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve (n, m, c, e0) =\n let open Hashtbl in\n let adjC : ((int, (int, unit) t) t) = create (n/10) in\n Array.iter\n (fun c -> try let _ = find adjC c in () with Not_found -> add adjC c (create 10))\n c;\n Array.iter\n (fun (u, v) ->\n replace (find adjC c.(u)) c.(v) ();\n replace (find adjC c.(v)) c.(u) ())\n e0;\n fst (fold (fun c' h (c, q) -> let q' = length h in if q' > q then (c', q') else (c, q)) adjC (-1, -1) )\n\nlet main () =\n let n = readInt () in\n let m = readInt () in\n let c = Array.init n (fun _ -> readInt ()) in\n let e0 = Array.init m (fun _ -> (readInt () - 1, readInt () - 1)) in\n Printf.printf \"%d\\n\" (solve (n, m, c, e0))\n\nlet () = main ()\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet argmax i j f = fold (i+1) j (fun k (y,j) -> let x = f k in if x > y then (x,k) else (y,j)) ((f i),i)\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n\n let c = Array.init n (fun _ -> read_int()) in (* colors of the vertices *)\n\n let mc = maxf 0 (n-1) (fun i -> c.(i)) in (* maximum color *)\n\n let carray = Array.init (mc+1) (fun _-> Hashtbl.create 5) in\n\n let add_edge a b = \n if (c.(a) <> c.(b)) then (\n Hashtbl.replace carray.(c.(a)) c.(b) true;\n Hashtbl.replace carray.(c.(b)) c.(a) true;\n )\n in\n\n let () =\n for i=0 to m-1 do\n let a = read_int() in\n let b = read_int() in\n\tadd_edge (a-1) (b-1);\n done\n in\n\n let ccount c = Hashtbl.length carray.(c) in\n let (div,i) = argmax 0 mc ccount in\n let i = if div = 0 then c.(0) else i in\n Printf.printf \"%d\\n\" i\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n\n let c = Array.init n (fun _ -> read_int()) in (* colors of the vertices *)\n\n let mc = maxf 0 (n-1) (fun i -> c.(i)) in (* maximum color *)\n\n let carray = Array.init (mc+1) (fun _-> Hashtbl.create 5) in\n\n let add_edge a b = \n if (c.(a) <> c.(b)) then (\n Hashtbl.replace carray.(c.(a)) c.(b) true;\n Hashtbl.replace carray.(c.(b)) c.(a) true;\n )\n in\n\n let () =\n for i=0 to m-1 do\n let a = read_int() in\n let b = read_int() in\n\tadd_edge (a-1) (b-1);\n done\n in\n\n let ccount c = Hashtbl.length carray.(c) in\n let div = maxf 0 mc ccount in\n let i = minf 0 (n-1) (fun j -> if ccount c.(j) = div then c.(j) else -1) in\n Printf.printf \"%d\\n\" i\n"}], "src_uid": "89c27a5c76f4ddbd14af2d30ac8b6330"} {"nl": {"description": "After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: There is at least one digit in the string, There is at least one lowercase (small) letter of the Latin alphabet in the string, There is at least one of three listed symbols in the string: '#', '*', '&'. Considering that these are programming classes it is not easy to write the password.For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password. ", "input_spec": "The first line contains two integers n, m (3\u2009\u2264\u2009n\u2009\u2264\u200950,\u20091\u2009\u2264\u2009m\u2009\u2264\u200950) \u2014 the length of the password and the length of strings which are assigned to password symbols. Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password.", "output_spec": "Print one integer \u2014 the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password. ", "sample_inputs": ["3 4\n1**2\na3*0\nc4**", "5 5\n#*&#*\n*a1c&\n&q2w*\n#a3c#\n*&#*&"], "sample_outputs": ["1", "3"], "notes": "NoteIn the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. In the second test one of possible algorithms will be: to move the pointer of the second symbol once to the right. to move the pointer of the third symbol twice to the right. "}, "positive_code": [{"source_code": "let search m f s =\n let rec loop i =\n if i <= m / 2 then\n if f s.[i] || (i > 0 && f s.[m - i]) then\n i\n else\n loop (i + 1)\n else max_int in\n loop 0\n\nlet is_digit c =\n let code = Char.code c in\n code >= 48 && code <= 57\n\nlet is_letter c =\n let code = Char.code c in\n code >= 97 && code <= 122\n\nlet is_symbol c =\n c = '#' || c = '*' || c = '&'\n\nlet fst (x, _, _) = x\nlet snd (_, x, _) = x\nlet trd (_, _, x) = x\n\nlet () =\n Scanf.scanf \"%d %d \" @@ fun n m ->\n let read_word s =\n (search m is_digit s, search m is_letter s, search m is_symbol s) in\n let ds = Array.init n (fun _ -> Scanf.scanf \"%s \" read_word) in\n let rec loop_digit mind i =\n if i < n then\n let d = fst ds.(i) in\n if d >= mind then\n loop_digit mind (i + 1)\n else\n let d = d + loop_letter (mind - d) 0 i in\n loop_digit (min d mind) (i + 1)\n else mind\n and loop_letter mind i x =\n if i = x then\n loop_letter mind (i + 1) x\n else if i < n then\n let d = snd ds.(i) in\n if d >= mind then\n loop_letter mind (i + 1) x\n else\n let d = d + loop_symbol (mind - d) 0 i x in\n loop_letter (min d mind) (i + 1) x\n else mind\n and loop_symbol mind i x xx =\n if i = x || i = xx then\n loop_symbol mind (i + 1) x xx\n else if i < n then\n let d = trd ds.(i) in\n loop_symbol (min d mind) (i + 1) x xx\n else mind in\n loop_digit max_int 0 |> Printf.printf \"%d\\n\"\n"}], "negative_code": [], "src_uid": "b7ff1ded73a9f130312edfe0dafc626d"} {"nl": {"description": "Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the \"less\" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs \"more\" and \"less\" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105. The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.", "output_spec": "In a single line, print \"yes\" (without the quotes), if Dima decoded the text message correctly, and \"no\" (without the quotes) otherwise.", "sample_inputs": ["3\ni\nlove\nyou\n<3i<3love<23you<3", "7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3"], "sample_outputs": ["yes", "no"], "notes": "NotePlease note that Dima got a good old kick in the pants for the second sample from the statement."}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\n\nlet () =\n let n = Scanf.scanf \"%d \" ident in\n let ss = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%s \" ident :: acc) |> List.rev in\n let text = Scanf.scanf \"%s \" ident in\n let len = String.length text in\n try \n let start = List.fold_left ss ~init:0 ~f:(fun start s ->\n let u = \"<3\" ^ s in\n let cur = ref start in\n iter_for 0 (String.length u) ~f:(fun i ->\n while u.[i] <> text.[!cur] do\n cur := !cur + 1;\n if !cur >= len then raise Not_found;\n done; cur := !cur + 1);\n !cur) in\n Str.search_forward (Str.regexp \"[a-z0-9<>]*<[a-z0-9<>]*3[a-z0-9<>]*\") text start |> ignore;\n print_endline \"yes\";\n with\n | _ -> print_endline \"no\"\n;;\n"}, {"source_code": "let (|>) x f = f x\nlet (@@) f x = f x\nlet id x = x\n\nlet () =\n let n = Scanf.scanf \"%d \" id in\n let rec loop n acc =\n if n = 0 then acc else\n let s = Scanf.scanf \"%s \" id in\n loop (n-1) (\"<3\" :: s :: acc)\n in\n let orig = loop n [\"<3\"] |> List.rev |> String.concat \"\" in\n let msg = Scanf.scanf \"%s \" id in\n let i = ref 0 in\n String.iter (fun s -> \n if !i < String.length orig && s = orig.[!i] then incr i\n ) msg;\n print_endline @@ if !i = String.length orig then \"yes\" else \"no\";\n"}], "negative_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\n\nlet () =\n let n = Scanf.scanf \"%d \" ident in\n let ss = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%s \" ident :: acc) |> List.rev in\n let text = Scanf.scanf \"%s \" ident in\n let len = String.length text in\n try \n let start = List.fold_left ss ~init:0 ~f:(fun start s ->\n let u = \"<3\" ^ s in\n let cur = ref start in\n iter_for 0 (String.length u) ~f:(fun i ->\n while u.[i] <> text.[!cur] do\n cur := !cur + 1;\n if !cur >= len then raise Not_found;\n done);\n !cur) in\n Str.search_forward (Str.regexp \"[a-z0-9<>]*<[a-z0-9<>]*3[a-z0-9<>]*\") text start |> ignore;\n print_endline \"yes\";\n with\n | _ -> print_endline \"no\"\n;;\n"}], "src_uid": "36fb3a01860ef0cc2a1065d78e4efbd5"} {"nl": {"description": "Don't you tell me what you think that I can beIf you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct hero in the beginning of the game.There are $$$2$$$ teams each having $$$n$$$ players and $$$2n$$$ heroes to distribute between the teams. The teams take turns picking heroes: at first, the first team chooses a hero in its team, after that the second team chooses a hero and so on. Note that after a hero is chosen it becomes unavailable to both teams.The friends estimate the power of the $$$i$$$-th of the heroes as $$$p_i$$$. Each team wants to maximize the total power of its heroes. However, there is one exception: there are $$$m$$$ pairs of heroes that are especially strong against each other, so when any team chooses a hero from such a pair, the other team must choose the other one on its turn. Each hero is in at most one such pair.This is an interactive problem. You are to write a program that will optimally choose the heroes for one team, while the jury's program will play for the other team. Note that the jury's program may behave inefficiently, in this case you have to take the opportunity and still maximize the total power of your team. Formally, if you ever have chance to reach the total power of $$$q$$$ or greater regardless of jury's program choices, you must get $$$q$$$ or greater to pass a test.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 10^3$$$, $$$0 \\le m \\le n$$$)\u00a0\u2014 the number of players in one team and the number of special pairs of heroes. The second line contains $$$2n$$$ integers $$$p_1, p_2, \\ldots, p_{2n}$$$ ($$$1 \\le p_i \\le 10^3$$$)\u00a0\u2014 the powers of the heroes. Each of the next $$$m$$$ lines contains two integer $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 2n$$$, $$$a \\ne b$$$)\u00a0\u2014 a pair of heroes that are especially strong against each other. It is guaranteed that each hero appears at most once in this list. The next line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2$$$)\u00a0\u2014 the team you are to play for. If $$$t = 1$$$, the first turn is yours, otherwise you have the second turn. Hacks In order to hack, use the format described above with one additional line. In this line output $$$2n$$$ distinct integers from $$$1$$$ to $$$2n$$$\u00a0\u2014 the priority order for the jury's team. The jury's team will on each turn select the first possible hero from this list. Here possible means that it is not yet taken and does not contradict the rules about special pair of heroes.", "output_spec": null, "sample_inputs": ["3 1\n1 2 3 4 5 6\n2 6\n1\n\n2\n\n4\n\n1", "3 1\n1 2 3 4 5 6\n1 5\n2\n6\n\n1\n\n3"], "sample_outputs": ["6\n\n5\n\n3", "5\n\n4\n\n2"], "notes": "NoteIn the first example the first turn is yours. In example, you choose $$$6$$$, the other team is forced to reply with $$$2$$$. You choose $$$5$$$, the other team chooses $$$4$$$. Finally, you choose $$$3$$$ and the other team choose $$$1$$$.In the second example you have the second turn. The other team chooses $$$6$$$, you choose $$$5$$$, forcing the other team to choose $$$1$$$. Now you choose $$$4$$$, the other team chooses $$$3$$$ and you choose $$$2$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nlet undef = -7\n\nlet n,m = get_2_i64 0\nlet power = input_i64_array (n*2L)\nlet used = make (i32 n*$2) false\nlet sp =\n let sp = make (i32 n*$2) undef in\n rep 1L m (fun _ ->\n let a,b = i32_get_2_ints 0 in\n let a,b = a-$1,b-$1 in\n sp.(a) <- b;\n sp.(b) <- a\n ); sp\nlet i_sorted =\n let a = mapi (fun i v -> v,i) power in sort (rv compare) a;\n map (fun (v,i) -> i) a\n\nlet output i =\n assert (not used.(i));\n printf \"%d\\n\" (i+$1); flush stdout;\n used.(i) <- true\nlet input _ =\n let j = i32_get_int 0 -$ 1 in used.(j) <- true; j\nlet output_find _ =\n let i,j = fold_left (fun (p,q) i ->\n if not used.(i) then (\n let p = if p = undef && sp.(i) <> undef then i else p in\n let q = if q = undef then i else q in\n (p,q)\n ) else (p,q)\n ) (undef,undef) i_sorted in\n if i<>undef then output i\n else output j\n\nlet t = get_i64 0\nlet () =\n rep 1L n (fun turn ->\n if turn=1L && t=1L then (\n output_find 0\n );\n let j = input 0 in\n if not (turn=n && t=1L) then (\n if sp.(j) <> undef && not used.(sp.(j)) then\n output sp.(j)\n else output_find 0\n )\n )\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet () =\n let n,m = get_2_i64 0 in\n let pw = input_i64_array (n*2L) in\n let undef = -7 in\n let sp = make 2018 undef in\n rep 1L m (fun _ ->\n let a,b = i32_get_2_ints 0 in\n let a,b = a-$1,b-$1 in\n sp.(a) <- b;\n sp.(b) <- a\n );\n let used = make (i32 n*$2) false in\n let pw_sorted = pw |> mapi (fun i v->v,i) in\n sort (rv compare) pw_sorted;\n let t = get_i64 0\n in\n let last_sp = ref undef in\n let output i =\n assert (not used.(i));\n printf \"%d\\n\" (i+$1); flush stdout;\n used.(i) <- true in\n let input _ =\n let j = i32_get_int 0 -$ 1 in used.(j) <- true; j in\n let find _ =\n let _,i = repim 0 (length pw_sorted-$1) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) && sp.(j) <> undef && not used.(sp.(j)) then `Break_m (v,j)\n else `Ok u\n )\n in if i <> undef then output i\n else\n let _,i = repim 0 (length pw_sorted-$1) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) then `Break_m (v,j)\n else `Ok u\n )\n in output i\n in\n if t=1L then rep 1L n (fun lp ->\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if lp=1L then (\n (* let i = find 0 in\n output i; *)\n find 0;\n let j = input 0 in last_sp := sp.(j)\n ) else (\n if !last_sp = undef || used.(!last_sp) then (\n find 0\n ) else (\n output !last_sp;\n );\n let j = input 0 in\n last_sp := sp.(j)\n (* if sp.(j) <> undef then (\n last_sp := j\n ) else (\n last_sp := undef\n ) *)\n )\n ) else rep 1L n (fun lp ->\n let j = input 0 in\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if sp.(j) <> undef && not used.(sp.(j)) then (\n output sp.(j)\n ) else (\n find 0\n )\n )\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet () =\n let n,m = get_2_i64 0 in\n let pw = input_i64_array (n*2L) in\n let undef = -7 in\n let sp = make 2018 undef in\n rep 1L m (fun _ ->\n let a,b = i32_get_2_ints 0 in\n let a,b = a-$1,b-$1 in\n sp.(a) <- b;\n sp.(b) <- a\n );\n let used = make (i32 n*$2) false in\n let pw_sorted = pw |> mapi (fun i v->v,i) in\n sort (rv compare) pw_sorted;\n let t = get_i64 0\n in\n let last_sp = ref undef in\n let output i =\n assert (not used.(i));\n printf \"%d\\n\" (i+$1); flush stdout;\n used.(i) <- true in\n let input _ =\n let j = i32_get_int 0 -$ 1 in used.(j) <- true; j in\n let find _ =\n let _,i = repim 0 (length pw_sorted-$1) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) && sp.(j) <> undef then `Break_m (v,j)\n else `Ok u\n )\n in if i <> undef then output i\n else\n let _,i = repim 0 (length pw_sorted-$1) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) then `Break_m (v,j)\n else `Ok u\n )\n in output i\n in\n if t=1L then rep 1L n (fun lp ->\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if lp=1L then (\n let _,i = pw_sorted.(0) in\n output i;\n let j = input 0 in last_sp := sp.(j)\n ) else (\n if !last_sp = undef || used.(!last_sp) then (\n find 0\n ) else (\n output !last_sp;\n );\n let j = input 0 in\n last_sp := sp.(j)\n (* if sp.(j) <> undef then (\n last_sp := j\n ) else (\n last_sp := undef\n ) *)\n )\n ) else rep 1L n (fun lp ->\n let j = input 0 in\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if sp.(j) <> undef && not used.(sp.(j)) then (\n output sp.(j)\n ) else (\n find 0\n )\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet () =\n let n,m = get_2_i64 0 in\n let pw = input_i64_array (n*2L) in\n let undef = -7 in\n let sp = make 1008 undef in\n rep 1L m (fun _ ->\n let a,b = i32_get_2_ints 0 in\n let a,b = a-$1,b-$1 in\n sp.(a) <- b;\n sp.(b) <- a\n );\n let used = make (i32 n*$2) false in\n let pw_sorted = pw |> mapi (fun i v->v,i) in\n sort (rv compare) pw_sorted;\n let t = get_i64 0\n in\n let last_sp = ref undef in\n let output i =\n assert (not used.(i));\n printf \"%d\\n\" (i+$1); flush stdout;\n used.(i) <- true in\n let input _ =\n let j = i32_get_int 0 -$ 1 in used.(j) <- true; j\n in\n if t=1L then rep 1L n (fun lp ->\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if lp=1L then (\n let _,i = pw_sorted.(0) in\n output i;\n let j = input 0 in ()\n ) else (\n if !last_sp = undef || used.(!last_sp) then (\n let _,i = repim 0 (length pw_sorted) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) then `Break_m (v,j)\n else `Ok u\n )\n in output i\n ) else (\n output !last_sp;\n );\n let j = input 0 in\n last_sp := sp.(j)\n (* if sp.(j) <> undef then (\n last_sp := j\n ) else (\n last_sp := undef\n ) *)\n )\n ) else rep 1L n (fun lp ->\n let j = input 0 in\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if sp.(j) <> undef && not used.(sp.(j)) then (\n output sp.(j)\n ) else (\n let _,i = repim 0 (length pw_sorted) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) then `Break_m (v,j)\n else `Ok u\n )\n in output i\n )\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nlet undef = -7\n\nlet n,m = get_2_i64 0\nlet power = input_i64_array (n*2L)\nlet used = make (i32 n*$2) false\nlet sp =\n let sp = make (i32 n*$2) undef in\n rep 1L m (fun _ ->\n let a,b = i32_get_2_ints 0 in\n let a,b = a-$1,b-$1 in\n sp.(a) <- b;\n sp.(b) <- a\n ); sp\nlet i_sorted =\n let a = mapi (fun i v -> v,i) power in sort (rv compare) a;\n map (fun (v,i) -> i) a\n\nlet output i =\n assert (not used.(i));\n printf \"%d\\n\" (i+$1); flush stdout;\n used.(i) <- true\nlet input _ =\n let j = i32_get_int 0 -$ 1 in used.(j) <- true; j\nlet find _ =\n let i,j = fold_left (fun (p,q) i ->\n if not used.(i) then (\n let p = if p = undef then i else p in\n let q = if q = undef && sp.(i) <> undef then i else q in\n (p,q)\n ) else (p,q)\n ) (undef,undef) i_sorted in\n if i<>undef then output i\n else output j\n\nlet t = get_i64 0\nlet () =\n rep 1L (n-1L) (fun turn ->\n if turn=1L && t=1L then (\n find 0\n );\n if not (turn=n-1L && t=1L) then (\n let j = input 0 in\n if sp.(j) <> undef && not used.(sp.(j)) then\n output sp.(j)\n else find 0\n )\n )\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet () =\n let n,m = get_2_i64 0 in\n let pw = input_i64_array (n*2L) in\n let undef = -7 in\n let sp = make 2018 undef in\n rep 1L m (fun _ ->\n let a,b = i32_get_2_ints 0 in\n let a,b = a-$1,b-$1 in\n sp.(a) <- b;\n sp.(b) <- a\n );\n let used = make (i32 n*$2) false in\n let pw_sorted = pw |> mapi (fun i v->v,i) in\n sort (rv compare) pw_sorted;\n let t = get_i64 0\n in\n let last_sp = ref undef in\n let output i =\n assert (not used.(i));\n printf \"%d\\n\" (i+$1); flush stdout;\n used.(i) <- true in\n let input _ =\n let j = i32_get_int 0 -$ 1 in used.(j) <- true; j in\n let find _ =\n let _,i = repim 0 (length pw_sorted-$1) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) && sp.(j) <> undef then `Break_m (v,j)\n else `Ok u\n )\n in if i <> undef then output i\n else\n let _,i = repim 0 (length pw_sorted-$1) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) then `Break_m (v,j)\n else `Ok u\n )\n in output i\n in\n if t=1L then rep 1L n (fun lp ->\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if lp=1L then (\n let _,i = pw_sorted.(0) in\n output i;\n let j = input 0 in ()\n ) else (\n if !last_sp = undef || used.(!last_sp) then (\n find 0\n ) else (\n output !last_sp;\n );\n let j = input 0 in\n last_sp := sp.(j)\n (* if sp.(j) <> undef then (\n last_sp := j\n ) else (\n last_sp := undef\n ) *)\n )\n ) else rep 1L n (fun lp ->\n let j = input 0 in\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if sp.(j) <> undef && not used.(sp.(j)) then (\n output sp.(j)\n ) else (\n find 0\n )\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nlet undef = -7\n\nlet n,m = get_2_i64 0\nlet power = input_i64_array (n*2L)\nlet used = make (i32 n*$2) false\nlet sp =\n let sp = make (i32 n*$2) undef in\n rep 1L m (fun _ ->\n let a,b = i32_get_2_ints 0 in\n let a,b = a-$1,b-$1 in\n sp.(a) <- b;\n sp.(b) <- a\n ); sp\nlet i_sorted =\n let a = mapi (fun i v -> v,i) power in sort (rv compare) a;\n map (fun (v,i) -> i) a\n\nlet output i =\n assert (not used.(i));\n printf \"%d\\n\" (i+$1); flush stdout;\n used.(i) <- true\nlet input _ =\n let j = i32_get_int 0 -$ 1 in used.(j) <- true; j\nlet output_find _ =\n let i,j = fold_left (fun (p,q) i ->\n if not used.(i) then (\n let p = if p = undef then i else p in\n let q = if q = undef && sp.(i) <> undef then i else q in\n (p,q)\n ) else (p,q)\n ) (undef,undef) i_sorted in\n if i<>undef then output i\n else output j\n\nlet t = get_i64 0\nlet () =\n rep 1L n (fun turn ->\n if turn=1L && t=1L then (\n output_find 0\n );\n let j = input 0 in\n if not (turn=n && t=1L) then (\n if sp.(j) <> undef && not used.(sp.(j)) then\n output sp.(j)\n else output_find 0\n )\n )\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(Int64)\nlet () =\n let n,m = get_2_i64 0 in\n let pw = input_i64_array (n*2L) in\n let undef = -7 in\n let sp = make 2018 undef in\n rep 1L m (fun _ ->\n let a,b = i32_get_2_ints 0 in\n let a,b = a-$1,b-$1 in\n sp.(a) <- b;\n sp.(b) <- a\n );\n let used = make (i32 n*$2) false in\n let pw_sorted = pw |> mapi (fun i v->v,i) in\n sort (rv compare) pw_sorted;\n let t = get_i64 0\n in\n let last_sp = ref undef in\n let output i =\n assert (not used.(i));\n printf \"%d\\n\" (i+$1); flush stdout;\n used.(i) <- true in\n let input _ =\n let j = i32_get_int 0 -$ 1 in used.(j) <- true; j in\n let find _ =\n let _,i = repim 0 (length pw_sorted-$1) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) && sp.(j) <> undef && not used.(sp.(j)) then `Break_m (v,j)\n else `Ok u\n )\n in if i <> undef then output i\n else\n let _,i = repim 0 (length pw_sorted-$1) (-1L,undef)\n (fun u i ->\n let v,j = pw_sorted.(i) in\n if not used.(j) then `Break_m (v,j)\n else `Ok u\n )\n in output i\n in\n if t=1L then rep 1L n (fun lp ->\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if lp=1L then (\n let _,i = pw_sorted.(0) in\n output i;\n let j = input 0 in last_sp := sp.(j)\n ) else (\n if !last_sp = undef || used.(!last_sp) then (\n find 0\n ) else (\n output !last_sp;\n );\n let j = input 0 in\n last_sp := sp.(j)\n (* if sp.(j) <> undef then (\n last_sp := j\n ) else (\n last_sp := undef\n ) *)\n )\n ) else rep 1L n (fun lp ->\n let j = input 0 in\n (* printf \"cand::[%s]\\n\" @@ string_of_list (fun (v,i) -> sprintf \"(%2Ld,%2d|%2d)\" v (i+$1) @@ sp.(i)+$1)\n (pw_sorted |> to_list |> List.filter (fun v -> not used.(snd v))); *)\n if sp.(j) <> undef && not used.(sp.(j)) then (\n output sp.(j)\n ) else (\n find 0\n )\n )\n\n\n\n\n\n\n\n\n"}], "src_uid": "5e07da229bc2762f3a68bc083e34b9a1"} {"nl": {"description": "\"Duel!\"Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.There are $$$n$$$ cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping cards, in which Tokitsukaze moves first. In each move, one should choose exactly $$$k$$$ consecutive cards and flip them to the same side, which means to make their color sides all face up or all face down. If all the color sides of these $$$n$$$ cards face the same direction after one's move, the one who takes this move will win.Princess Claris wants to know who will win the game if Tokitsukaze and Quailty are so clever that they won't make mistakes.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 10^5$$$). The second line contains a single string of length $$$n$$$ that only consists of $$$0$$$ and $$$1$$$, representing the situation of these $$$n$$$ cards, where the color side of the $$$i$$$-th card faces up if the $$$i$$$-th character is $$$1$$$, or otherwise, it faces down and the $$$i$$$-th character is $$$0$$$.", "output_spec": "Print \"once again\" (without quotes) if the total number of their moves can exceed $$$10^9$$$, which is considered a draw. In other cases, print \"tokitsukaze\" (without quotes) if Tokitsukaze will win, or \"quailty\" (without quotes) if Quailty will win. Note that the output characters are case-sensitive, and any wrong spelling would be rejected.", "sample_inputs": ["4 2\n0101", "6 1\n010101", "6 5\n010101", "4 1\n0011"], "sample_outputs": ["quailty", "once again", "tokitsukaze", "once again"], "notes": "NoteIn the first example, no matter how Tokitsukaze moves, there would be three cards with color sides facing the same direction after her move, and Quailty can flip the last card to this direction and win.In the second example, no matter how Tokitsukaze moves, Quailty can choose the same card and flip back to the initial situation, which can allow the game to end in a draw.In the third example, Tokitsukaze can win by flipping the leftmost five cards up or flipping the rightmost five cards down.The fourth example can be explained in the same way as the second example does."}, "positive_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\nlet readString () = Scanf.scanf \" %s\" (fun s -> s)\n\ntype result = First | Second | Draw\nexception First\n\n(* Note: all winning strategies use 1 move because otherwise the opponent\n * can just copy the previous move. *)\nlet solve n k s : result =\n let l = ref 0 in\n let m = ref 0 in\n let r = ref 0 in\n for i=0 to n-1 do if s.[i] = '1' then incr r done;\n let canDraw = ref false in\n try\n for i = 0 to n-1 do\n if s.[i] = '1' then begin incr m; decr r end;\n if i >= k && s.[i-k] = '1' then begin decr m; incr l end;\n if i >= k-1 then begin\n (* See if player 1 can win with this move. *)\n if !l = 0 && !r = 0 || !l + k + !r = n then raise First\n (* Otherwise, see if he use it to stop player 2 from\n * winning with his move, by stranding 1s on each side of k 0s or\n * vice versa. *)\n else if 0 < !l && 0 < !r\n || !l < i+1-k && !r < n-i-1 then canDraw := true\n end\n done;\n (* It's also always possible to draw when n \u2265 2k+1 (at each stage\n * just take the move that gets you closest to an even number of\n * 1s and 0s).\n *\n * The splitting strategy is the only way to draw when n \u2264 2k\n * (either side can be chomped up in one move). *)\n if !canDraw || n > 2*k then Draw else Second\n with First -> First\n\nlet main () =\n let n = readInt () in\n let k = readInt () in\n let s = readString () in\n print_endline (match solve n k s with First -> \"tokitsukaze\"\n | Second -> \"quailty\"\n | Draw -> \"once again\")\n\nlet () = main ()\n"}, {"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\nlet readString () = Scanf.scanf \" %s\" (fun s -> s)\n\ntype result = First | Second | Draw\nexception First\n\n(* Note: all winning strategies use 1 move because otherwise the opponent\n * can just copy the previous move. *)\nlet solve n k s : result =\n let l = ref 0 in\n let m = ref 0 in\n let r = ref 0 in\n for i=0 to n-1 do if s.[i] = '1' then incr r done;\n let canSplit = ref false in\n try\n for i = 0 to n-1 do\n if s.[i] = '1' then begin incr m; decr r end;\n if i >= k && s.[i-k] = '1' then begin decr m; incr l end;\n if i >= k-1 then begin\n (* See if player 1 can win with this move. *)\n if !l + !r = 0 || !l + k + !r = n then raise First\n (* Otherwise, see if he can use it to stop player 2 from\n * winning with his move, by stranding 1s on each side of k 0s or\n * vice versa. *)\n else if 0 < !l && 0 < !r\n || !l < i+1-k && !r < n-i-1 then canSplit := true\n end\n done;\n (* Note that the splitting strategy is the only possible way to draw\n * when n \u2264 2k (either side can be chomped up in one go).\n *\n * When n \u2265 2k+1, and canSplit is false, then we must have\n * s = or vice versa. Either the prefix\n * or suffix will have length \u2265 k+1 so pick that side and flip the\n * k bits on the end.*)\n if !canSplit || n > 2*k then Draw else Second\n with First -> First\n\nlet main () =\n let n = readInt () in\n let k = readInt () in\n let s = readString () in\n print_endline (match solve n k s with First -> \"tokitsukaze\"\n | Second -> \"quailty\"\n | Draw -> \"once again\")\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "5e73099c7ec0b82aee54f0841c00f15e"} {"nl": {"description": "Martha \u2014 as a professional problemsetter \u2014 proposed a problem for a world-class contest. This is the problem statement:Tomorrow is Nadia's birthday, and Bardia (her brother) is assigned to make the balloons ready!There are n balloons (initially empty) that are tied to a straight line on certain positions x1,\u2009x2,\u2009...,\u2009xn. Bardia inflates the balloons from left to right. As a result, i-th balloon gets bigger and bigger until its radius reaches the pressure endurance pi or it touches another previously-inflated balloon. While Bardia was busy with the balloons, he wondered \"What will be the sum of radius of balloons after all of the balloons are inflated?\". Being a nerdy type of guy, he is now thinking about the problem instead of preparing his sister's birthday. Calculate the answer to Bardia's problem so that Nadia's birthday won't be balloon-less.Artha \u2014 Martha's student \u2014 claimed his solution got accepted. Martha (being his teacher for a long time!) knew he couldn't have solved the problem for real and thus thinks there is something wrong with the testcases. Artha isn't anyhow logical, which means there is no way for Martha to explain the wrong point in his algorithm. So, the only way is to find a testcase to prove him wrong!Artha's pseudo-code is shown below: You should output a small testcase for the problem such that Artha's algorithm is incorrect. The algorithm's output is considered correct if it differs from the correct value by no more than 1.", "input_spec": "Please pay attention! No input will be given to your program for this problem. So you do not have to read from the input anything.", "output_spec": "You should output the generated small testcase (which Artha's solution doesn't get it right). It should be in the following format: First line must contain the only number n (1\u2009\u2264\u2009n\u2009\u2264\u2009500). The i-th of the next n lines should contain the description of the i-th balloon \u2014 two space-separated integers xi,\u2009pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009106, 0\u2009\u2264\u2009x1\u2009<\u2009x2\u2009<\u2009...\u2009<\u2009xn\u2009\u2264\u2009106). ", "sample_inputs": [], "sample_outputs": [], "notes": "NoteThe testcase depicted in the figure above (just showing how output should be formatted):40 96 312 717 1"}, "positive_code": [{"source_code": "let _ =\n let n = 302 in\n let x = Array.make n 0 in\n let p = Array.make n 0 in\n p.(0) <- 1000000;\n for i = 1 to 300 do\n let r = 301 - i in\n let d =\n\tint_of_float (\n\t ceil (sqrt (4.0 *. float_of_int r *. float_of_int p.(i - 1))))\n in\n\tx.(i) <- x.(i - 1) + d;\n\tp.(i) <- r;\n done;\n x.(n - 1) <- 1000000;\n p.(n - 1) <- 1000000;\n Printf.printf \"%d\\n\" n;\n for i = 0 to n - 1 do\n Printf.printf \"%d %d\\n\" x.(i) p.(i);\n done\n"}], "negative_code": [], "src_uid": "029e0e8c4478d7d973307e3af0a13c0d"} {"nl": {"description": "You are given a string $$$t$$$ consisting of $$$n$$$ lowercase Latin letters and an integer number $$$k$$$.Let's define a substring of some string $$$s$$$ with indices from $$$l$$$ to $$$r$$$ as $$$s[l \\dots r]$$$.Your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ positions $$$i$$$ such that $$$s[i \\dots i + n - 1] = t$$$. In other words, your task is to construct such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$.It is guaranteed that the answer is always unique.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 50$$$) \u2014 the length of the string $$$t$$$ and the number of substrings. The second line of the input contains the string $$$t$$$ consisting of exactly $$$n$$$ lowercase Latin letters.", "output_spec": "Print such string $$$s$$$ of minimum possible length that there are exactly $$$k$$$ substrings of $$$s$$$ equal to $$$t$$$. It is guaranteed that the answer is always unique.", "sample_inputs": ["3 4\naba", "3 2\ncat"], "sample_outputs": ["ababababa", "catcat"], "notes": null}, "positive_code": [{"source_code": "let reverse s =\n let ls = String.length s in\n String.init ls (fun i -> s.[ls - 1 - i])\n;;\n\nlet main() =\n let (n, k) = Scanf.scanf \" %d %d%[\\n]\" (fun i j t -> (i, j)) in\n let s = Scanf.scanf \"%[a-z]\" (fun s -> s) in\n let ls = String.length s in\n let rec f k t z =\n let rec loop l =\n let ss = String.sub t ((String.length t) - l) l in\n if (String.compare ss (String.sub z 0 l)) = 0 then l\n else loop (l - 1)\n in\n if (k > 0) then begin\n let l = loop (ls - 1) in\n let s2 = String.sub z l (ls - l) in\n f (k-1) (String.concat \"\" (t :: (s2 :: []))) z\n end else t\n in\n\n let r = reverse s in\n let r1 = f (k - 1) s s in\n let r2 = reverse (f (k - 1) r r) in\n Printf.printf \"%s\\n\" ( if (String.length r1) < (String.length r2) then r1 else r2 )\n;;\n\nlet _ = main()\n"}], "negative_code": [], "src_uid": "34dd4c8400ff7a67f9feb1487f2669a6"} {"nl": {"description": "Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) has a best friend p[i] (1\u2009\u2264\u2009p[i]\u2009\u2264\u2009n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really \"special individuals\" for who i\u2009=\u2009p[i].Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: on the first day of revising each student studies his own Mathematical Analysis notes, in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1\u2009\u2264\u2009i\u2009\u2264\u2009n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study.You are given two sequences that describe the situation on the third and fourth days of revising: a1,\u2009a2,\u2009...,\u2009an, where ai means the student who gets the i-th student's notebook on the third day of revising; b1,\u2009b2,\u2009...,\u2009bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of students in the group. The second line contains sequence of different integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n). The third line contains the sequence of different integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009n).", "output_spec": "Print sequence n of different integers p[1],\u2009p[2],\u2009...,\u2009p[n] (1\u2009\u2264\u2009p[i]\u2009\u2264\u2009n). It is guaranteed that the solution exists and that it is unique.", "sample_inputs": ["4\n2 1 4 3\n3 4 2 1", "5\n5 2 3 1 4\n1 3 2 4 5", "2\n1 2\n2 1"], "sample_outputs": ["4 3 1 2", "4 3 2 5 1", "2 1"], "notes": null}, "positive_code": [{"source_code": "(* codeforces 180 (internal). Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\nlet () =\n let n = read_int() in\n let a = Array.make n 0 in\n let b = Array.make n 0 in\n let p = Array.make n 0 in\n\n for i=0 to n-1 do\n a.(i) <- (read_int()) -1\n done;\n\n for i=0 to n-1 do\n b.(i) <- (read_int() -1)\n done;\n\n for i=0 to n-1 do\n p.(a.(i)) <- b.(i)\n done;\n\n for i=0 to n-1 do\n Printf.printf \"%d \" (p.(i) + 1)\n done;\n"}], "negative_code": [], "src_uid": "a133b2c63e1025bdf13d912497f9b6a4"} {"nl": {"description": "You are given a graph with $$$3 \\cdot n$$$ vertices and $$$m$$$ edges. You are to find a matching of $$$n$$$ edges, or an independent set of $$$n$$$ vertices.A set of edges is called a matching if no two edges share an endpoint.A set of vertices is called an independent set if no two vertices are connected with an edge.", "input_spec": "The first line contains a single integer $$$T \\ge 1$$$\u00a0\u2014 the number of graphs you need to process. The description of $$$T$$$ graphs follows. The first line of description of a single graph contains two integers $$$n$$$ and $$$m$$$, where $$$3 \\cdot n$$$ is the number of vertices, and $$$m$$$ is the number of edges in the graph ($$$1 \\leq n \\leq 10^{5}$$$, $$$0 \\leq m \\leq 5 \\cdot 10^{5}$$$). Each of the next $$$m$$$ lines contains two integers $$$v_i$$$ and $$$u_i$$$ ($$$1 \\leq v_i, u_i \\leq 3 \\cdot n$$$), meaning that there is an edge between vertices $$$v_i$$$ and $$$u_i$$$. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all $$$n$$$ over all graphs in a single test does not exceed $$$10^{5}$$$, and the sum of all $$$m$$$ over all graphs in a single test does not exceed $$$5 \\cdot 10^{5}$$$.", "output_spec": "Print your answer for each of the $$$T$$$ graphs. Output your answer for a single graph in the following format. If you found a matching of size $$$n$$$, on the first line print \"Matching\" (without quotes), and on the second line print $$$n$$$ integers\u00a0\u2014 the indices of the edges in the matching. The edges are numbered from $$$1$$$ to $$$m$$$ in the input order. If you found an independent set of size $$$n$$$, on the first line print \"IndSet\" (without quotes), and on the second line print $$$n$$$ integers\u00a0\u2014 the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print \"Impossible\" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size $$$n$$$, and an independent set of size $$$n$$$, then you should print exactly one of such matchings or exactly one of such independent sets.", "sample_inputs": ["4\n1 2\n1 3\n1 2\n1 2\n1 3\n1 2\n2 5\n1 2\n3 1\n1 4\n5 1\n1 6\n2 15\n1 2\n1 3\n1 4\n1 5\n1 6\n2 3\n2 4\n2 5\n2 6\n3 4\n3 5\n3 6\n4 5\n4 6\n5 6"], "sample_outputs": ["Matching\n2\nIndSet\n1\nIndSet\n2 4\nMatching\n1 15"], "notes": "NoteThe first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer.The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly $$$n$$$.The fourth graph does not have an independent set of size 2, but there is a matching of size 2."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet readInt () = scanf \" %d\" (fun x -> x)\n\ntype result = Matching of int list | IndSet of int list\n\nlet maximalMatching ?lim n m e =\n let lim = match lim with None -> m | Some lim -> lim in\n let open Hashtbl in\n let k = ref 0 in\n let res = ref [] in\n let vis = create n in\n (try\n e |> Array.iteri begin fun i (u, v) ->\n if not (mem vis u) && not (mem vis v) then begin\n incr k;\n res := i :: !res;\n add vis u (); add vis v ();\n if !k >= lim then raise Exit\n end\n end\n with Exit -> ());\n (!k, !res, vis)\n\nlet solve n m e =\n let (k, m, vis) = maximalMatching ~lim:n (3*n) m e in\n if k = n then Matching m\n else\n let k = ref 0 in\n let ans = ref [] in\n (try\n for u=0 to 3*n-1 do\n if not (Hashtbl.mem vis u) then begin\n incr k;\n ans := u :: !ans;\n if !k = n then raise Exit\n end\n done\n with Exit -> ());\n IndSet !ans\n\nlet main () =\n let t = readInt () in\n for tc = 0 to t - 1 do\n let n = readInt () in\n let m = readInt () in\n let e = Array.make m (-1, -1) in\n for i=0 to m-1 do\n let u = readInt () - 1 in\n let v = readInt () - 1 in\n assert (0 <= u && u < 3*n);\n assert (0 <= v && v < 3*n);\n e.(i) <- (u, v)\n done;\n (match solve n m e with\n | Matching eis -> print_endline \"Matching\"; eis |> List.iter (fun i -> printf \"%d \" (i + 1))\n | IndSet vs -> print_endline \"IndSet\"; vs |> List.iter (fun u -> printf \"%d \" (u + 1)));\n print_endline \"\"\n done\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "0cca30daffe672caa6a6fdbb6a935f43"} {"nl": {"description": "A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the values of the banknotes.", "output_spec": "Print a single line \u2014 the minimum unfortunate sum. If there are no unfortunate sums, print \u2009-\u20091.", "sample_inputs": ["5\n1 2 3 4 5"], "sample_outputs": ["-1"], "notes": null}, "positive_code": [{"source_code": "let ri () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x) ;;\nlet rec f = function\n | 0 -> 1\n | n -> if ri() = 1 then -1 else f(n-1) ;;\nprint_int(f(ri()));;"}], "negative_code": [], "src_uid": "df94080c5b0b046af2397cafc02b5bdc"} {"nl": {"description": "DZY has a sequence a, consisting of n integers.We'll call a sequence ai,\u2009ai\u2009+\u20091,\u2009...,\u2009aj (1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n) a subsegment of the sequence a. The value (j\u2009-\u2009i\u2009+\u20091) denotes the length of the subsegment.Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.You only need to output the length of the subsegment you find.", "input_spec": "The first line contains integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n integers a1,\u2009a2,\u2009...,\u2009an\u00a0(1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "In a single line print the answer to the problem \u2014 the maximum length of the required subsegment.", "sample_inputs": ["6\n7 2 3 1 5 6"], "sample_outputs": ["5"], "notes": "NoteYou can choose subsegment a2,\u2009a3,\u2009a4,\u2009a5,\u2009a6 and change its 3rd element (that is a4) to 4."}, "positive_code": [{"source_code": "let ( + ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( * ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( - ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( / ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( ~- ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet solve n arr =\n let dp_l = Array.create n 1L\n in\n (for i = 1 to Pervasives.( - ) n 1 do\n dp_l.(i) <-\n if arr.(Pervasives.( - ) i 1) < arr.(i)\n then Int64.add dp_l.(Pervasives.( - ) i 1) 1L\n else 1L\n done;\n Array.iter (Printf.eprintf \"%Ld \") dp_l;\n prerr_endline \"\";\n let dp_r = Array.create n 1L\n in\n (for i = Pervasives.( - ) n 2 downto 0 do\n dp_r.(i) <-\n if arr.(i) < arr.(Pervasives.( + ) i 1)\n then Int64.add dp_r.(Pervasives.( + ) i 1) 1L\n else 1L\n done;\n Array.iter (Printf.eprintf \"%Ld \") dp_r;\n prerr_endline \"\";\n let res = Array.create n 1L\n in\n (res.(0) <- Int64.add dp_r.(1) 1L;\n res.(Pervasives.( - ) n 1) <-\n Int64.add dp_l.(Pervasives.( - ) n 2) 1L;\n for i = 1 to Pervasives.( - ) n 2 do\n if\n (Pervasives.( + ) arr.(Pervasives.( - ) i 1) 1) <\n arr.(Pervasives.( + ) i 1)\n then\n res.(i) <-\n Int64.add\n (Int64.add dp_l.(Pervasives.( - ) i 1)\n dp_r.(Pervasives.( + ) i 1))\n 1L\n else\n res.(i) <-\n Int64.add\n (max dp_l.(Pervasives.( - ) i 1)\n dp_r.(Pervasives.( + ) i 1))\n 1L\n done;\n Array.iter (Printf.eprintf \"%Ld \") res;\n prerr_endline \"\";\n Printf.printf \"%Ld\\n\" (Array.fold_left max 0L res))))\n \nlet () =\n Scanf.scanf \"%d \"\n (fun n ->\n let arr = Array.init n (fun i -> Scanf.scanf \"%d \" (fun x -> x))\n in if n = 1 then print_endline \"1\" else solve n arr)\n \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let declen = Array.make n 1 in\n let inclen = Array.make n 1 in\n\n for i=1 to n-1 do\n if a.(i-1) < a.(i) then declen.(i) <- declen.(i-1) + 1\n done;\n\n for i=n-2 downto 0 do\n if a.(i) < a.(i+1) then inclen.(i) <- inclen.(i+1) + 1\n done;\n\n let best = ref 0 in\n\n for i=0 to n-1 do\n let leftend = if i=n-1 then 1 else 1+inclen.(i+1) in\n let rightend = if i=0 then 1 else 1+declen.(i-1) in\n let middle = if i=0 || i=n-1 then 0 else \n\tif a.(i-1) + 1 <= a.(i+1) - 1 then declen.(i-1) + inclen.(i+1) + 1\n\telse 0\n in\n best := max !best (max leftend (max rightend middle));\n done;\n\n printf \"%d\\n\" !best\n"}], "negative_code": [{"source_code": "let solve n arr =\n let dp_l = Array.create n 1 in\n for i = 1 to n - 1 do\n dp_l.(i) <-\n (if arr.(i - 1) < arr.(i) then dp_l.(i - 1) + 1\n else 1)\n done;\n Array.iter (Printf.eprintf \"%d \") dp_l;\n prerr_endline \"\";\n let dp_r = Array.create n 1 in\n for i = n - 2 downto 0 do\n dp_r.(i) <-\n (if arr.(i) < arr.(i + 1) then dp_r.(i + 1) + 1\n else 1)\n done;\n Array.iter (Printf.eprintf \"%d \") dp_r;\n prerr_endline \"\";\n\n let res = Array.create n 1 in\n for i = 2 to n - 2 do\n if arr.(i - 1) + 1 < arr.(i + 1) then res.(i) <- dp_l.(i - 1) + dp_r.(i + 1) + 1\n done;\n Printf.printf \"%d\\n\" (Array.fold_left (max) 0 res)\n;;\n\nlet () =\n Scanf.scanf \"%d \" (fun n ->\n let arr = Array.init n (fun i ->\n Scanf.scanf \"%d \" (fun x -> x)) in\n solve n arr)\n;;\n"}, {"source_code": "let solve n arr =\n let dp_l = Array.create n 1 in\n for i = 1 to n - 1 do\n dp_l.(i) <-\n (if arr.(i - 1) < arr.(i) then dp_l.(i - 1) + 1\n else 1)\n done;\n Array.iter (Printf.eprintf \"%d \") dp_l;\n prerr_endline \"\";\n let dp_r = Array.create n 1 in\n for i = n - 2 downto 0 do\n dp_r.(i) <-\n (if arr.(i) < arr.(i + 1) then dp_r.(i + 1) + 1\n else 1)\n done;\n Array.iter (Printf.eprintf \"%d \") dp_r;\n prerr_endline \"\";\n\n let res = Array.create n 1 in\n res.(0) <- dp_l.(1) + 1;\n res.(n - 1) <- dp_r.(n - 2) + 1;\n for i = 2 to n - 2 do\n if arr.(i - 1) + 1 < arr.(i + 1) then res.(i) <- dp_l.(i - 1) + dp_r.(i + 1) + 1\n else res.(i) <- max dp_l.(i) dp_r.(i)\n done;\n Array.iter (Printf.eprintf \"%d \") res;\n prerr_endline \"\";\n\n Printf.printf \"%d\\n\" (Array.fold_left (max) 0 res)\n;;\n\nlet () =\n Scanf.scanf \"%d \" (fun n ->\n let arr = Array.init n (fun i ->\n Scanf.scanf \"%d \" (fun x -> x)) in\n solve n arr)\n;;\n"}], "src_uid": "9e0d271b9bada1364dfcb47297549652"} {"nl": {"description": "A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: If Petya has visited this room before, he writes down the minute he was in this room last time; Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 then number of notes in Petya's logbook. The second line contains n non-negative integers t1,\u2009t2,\u2009...,\u2009tn (0\u2009\u2264\u2009ti\u2009<\u2009i) \u2014 notes in the logbook.", "output_spec": "In the only line print a single integer \u2014 the minimum possible number of rooms in Paris catacombs.", "sample_inputs": ["2\n0 0", "5\n0 1 0 1 3"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first sample, sequence of rooms Petya visited could be, for example 1\u2009\u2192\u20091\u2009\u2192\u20092, 1\u2009\u2192\u20092\u2009\u2192\u20091 or 1\u2009\u2192\u20092\u2009\u2192\u20093. The minimum possible number of rooms is 2.In the second sample, the sequence could be 1\u2009\u2192\u20092\u2009\u2192\u20093\u2009\u2192\u20091\u2009\u2192\u20092\u2009\u2192\u20091."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n\n let label = Array.make (n+1) false in\n\n label.(0) <- true;\n\n for i=1 to n do\n let t = read_int() in\n if label.(t) then label.(t) <- false;\n label.(i) <- true;\n done;\n\n let answer = sum 0 n (fun i -> if label.(i) then 1 else 0) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "81c6342b7229892d71cb43e72aee99e9"} {"nl": {"description": "Bob programmed a robot to navigate through a 2d maze.The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.The robot can only move up, left, right, or down.When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.", "input_spec": "The first line of input will contain two integers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950), denoting the dimensions of the maze. The next n lines will contain exactly m characters each, denoting the maze. Each character of the maze will be '.', '#', 'S', or 'E'. There will be exactly one 'S' and exactly one 'E' in the maze. The last line will contain a single string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009100)\u00a0\u2014 the instructions given to the robot. Each character of s is a digit from 0 to 3.", "output_spec": "Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit.", "sample_inputs": ["5 6\n.....#\nS....#\n.#....\n.#....\n...E..\n333300012", "6 6\n......\n......\n..SE..\n......\n......\n......\n01232123212302123021", "5 3\n...\n.S.\n###\n.E.\n...\n3"], "sample_outputs": ["1", "14", "0"], "notes": "NoteFor the first sample, the only valid mapping is , where D is down, L is left, U is up, R is right."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet l2n c = (int_of_char c) - (int_of_char '0')\n\nlet ( ++ ) (a,b) (c,d) = (a+c, b+d)\n \nlet () =\n let n = read_int() in\n let m = read_int() in\n let board = Array.init n read_string in\n let s = read_string () in\n\n let len = String.length s in\n\n let rec find c s i = if i=m then -1 else\n if s.[i] = c then i else find c s (i+1)\n in\n\n let rec inboard c r = if r = n then (-1,-1) else\n let i = find c board.(r) 0 in\n if i < 0 then inboard c (r+1) else (r,i)\n in\n\n let start = inboard 'S' 0 in\n let endd = inboard 'E' 0 in\n\n let move = [|(0,1);(0,-1);(1,0);(-1,0)|] in\n\n let test () =\n (* returns 1 if the current moves work, 0 otherwise *)\n let rec walk (r,c) i = \n if (r,c) = endd then 1\n else if i=len then 0\n else if (r < 0 || r >= n || c < 0 || c >= m) || board.(r).[c] = '#' then 0\n else walk ((r,c) ++ move.(l2n s.[i])) (i+1)\n in\n walk start 0\n in\n\n let swap i j =\n let (mi,mj) = (move.(i),move.(j)) in\n move.(i) <- mj;\n move.(j) <- mi\n in\n\n let rec backtrack i ac =\n if i=4 then ac + test() else\n let rec loop j ac = if j=4 then ac else (\n\tswap i j;\n\tlet ac = backtrack (i+1) ac in\n\tswap i j;\n\tloop (j+1) ac\n ) in\n loop i ac\n in\n\n let answer = backtrack 0 0 in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet l2n c = (int_of_char c) - (int_of_char '0')\n\nlet ( ++ ) (a,b) (c,d) = (a+c, b+d)\n \nlet () =\n let n = read_int() in\n let m = read_int() in\n let board = Array.init n read_string in\n let s = read_string () in\n\n let len = String.length s in\n\n let rec find c s i = if i=m then -1 else\n if s.[i] = c then i else find c s (i+1)\n in\n\n let rec inboard c r = if r = n then (-1,-1) else\n let i = find c board.(r) 0 in\n if i < 0 then inboard c (r+1) else (r,i)\n in\n\n let start = inboard 'S' 0 in\n let endd = inboard 'E' 0 in\n\n let move = [|(0,1);(0,-1);(1,0);(-1,0)|] in\n\n let test () =\n (* returns 1 if the current moves work, 0 otherwise *)\n let rec walk (r,c) i = if i=len then 0\n else if (r,c) = endd then 1\n else if (r < 0 || r >= n || c < 0 || c >= m) || board.(r).[c] = '#' then 0\n else walk ((r,c) ++ move.(l2n s.[i])) (i+1)\n in\n walk start 0\n in\n\n let swap i j =\n let (mi,mj) = (move.(i),move.(j)) in\n move.(i) <- mj;\n move.(j) <- mi\n in\n\n let rec backtrack i ac =\n if i=4 then ac + test() else\n let rec loop j ac = if j=4 then ac else (\n\tswap i j;\n\tlet ac = backtrack (i+1) ac in\n\tswap i j;\n\tloop (j+1) ac\n ) in\n loop i ac\n in\n\n let answer = backtrack 0 0 in\n\n printf \"%d\\n\" answer\n"}], "src_uid": "8a1799f4ca028d48d5a12e8ac4b8bee1"} {"nl": {"description": "Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.Igor's chessboard is a square of size n\u2009\u00d7\u2009n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x,\u2009y)\u00a0\u2014 the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx,\u2009dy); using this move, the piece moves from the field (x,\u2009y) to the field (x\u2009+\u2009dx,\u2009y\u2009+\u2009dy). You can perform the move if the cell (x\u2009+\u2009dx,\u2009y\u2009+\u2009dy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x,\u2009y) and (x\u2009+\u2009dx,\u2009y\u2009+\u2009dy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950). The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values: o \u2014 in this case the field (i,\u2009j) is occupied by a piece and the field may or may not be attacked by some other piece; x \u2014 in this case field (i,\u2009j) is attacked by some piece; . \u2014 in this case field (i,\u2009j) isn't attacked by any piece. It is guaranteed that there is at least one piece on the board.", "output_spec": "If there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2n\u2009-\u20091)\u2009\u00d7\u2009(2n\u2009-\u20091) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them. If a valid set of moves does not exist, print a single word 'NO'.", "sample_inputs": ["5\noxxxx\nx...x\nx...x\nx...x\nxxxxo", "6\n.x.x..\nx.x.x.\n.xo..x\nx..ox.\n.x.x.x\n..x.x.", "3\no.x\noxx\no.x"], "sample_outputs": ["YES\n....x....\n....x....\n....x....\n....x....\nxxxxoxxxx\n....x....\n....x....\n....x....\n....x....", "YES\n...........\n...........\n...........\n....x.x....\n...x...x...\n.....o.....\n...x...x...\n....x.x....\n...........\n...........\n...........", "NO"], "notes": "NoteIn the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n\n let board = Array.init n (fun _ -> read_string()) in\n\n let pos = Array.make_matrix (2*n-1) (2*n-1) true in\n let elim dx dy = pos.(dx+(n-1)).(dy+(n-1)) <- false in\n let get dx dy = pos.(dx+(n-1)).(dy+(n-1)) in\n elim 0 0;\n\n for i0=0 to n-1 do\n for j0=0 to n-1 do\n if board.(i0).[j0] = 'o' then\n for i1=0 to n-1 do\n\tfor j1=0 to n-1 do\n\t if board.(i1).[j1] = '.' then elim (j1-j0) (i1-i0)\n\tdone\n done\n done\n done;\n\n let moves = ref [] in\n\n for dx = -(n-1) to n-1 do\n for dy = -(n-1) to n-1 do\n if get dx dy then moves := (dx,dy)::(!moves)\n done\n done;\n\n let attacked = Array.make_matrix n n false in\n\n for y=0 to n-1 do\n for x=0 to n-1 do\n if board.(y).[x] = 'o' then (\n\tList.iter (fun (dx,dy) ->\n\t let (x,y) = (x+dx, y+dy) in\n\t if x>=0 && x=0 && y x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n\n let board = Array.init n (fun _ -> read_string()) in\n\n let pos = Array.make_matrix (2*n-1) (2*n-1) true in\n\n let elim dx dy = pos.(dx+(n-1)).(dy+(n-1)) <- false in\n let get dx dy = pos.(dx+(n-1)).(dy+(n-1)) in\n\n for i0=0 to n-1 do\n for j0=0 to n-1 do\n if board.(i0).[j0] = 'o' then\n for i1=0 to n-1 do\n\tfor j1=0 to n-1 do\n\t if board.(i1).[j1] = '.' then elim (j1-j0) (i1-i0)\n\tdone\n done\n done\n done;\n\n let moves = ref [] in\n\n for dx = -(n-1) to n-1 do\n for dy = -(n-1) to n-1 do\n if get dx dy then moves := (dx,dy)::(!moves)\n done\n done;\n\n let attacked = Array.make_matrix n n false in\n\n for y=0 to n-1 do\n for x=0 to n-1 do\n if board.(y).[x] = 'o' then (\n\tList.iter (fun (dx,dy) ->\n\t let (x,y) = (x+dx, y+dy) in\n\t if x>=0 && x=0 && y 1\n\t\t|_ -> 0) + (count (String.sub s 1 (String.length s - 1)))\n\t)\n;;\n\nlet () =\n\tlet a = count (read_line ()) in\n\tlet b = count (read_line ()) in\n\tlet c = count (read_line ()) in\n\tprint_string (\n\t\tif a = 5 && b = 7 && c = 5 then \"YES\" else \"NO\"\n\t)\n;;\n"}, {"source_code": "let num_of_vowels str =\n let vowels = ['a'; 'e'; 'i'; 'o'; 'u'] in\n let rec loop = function\n | -1 -> 0\n | i ->\n let add = if List.mem (String.get str i) vowels then 1 else 0 in\n add + (loop (i-1))\n in\n loop ((String.length str)-1)\n\nlet solve haiku =\n if num_of_vowels (List.nth haiku 0) == 5 &&\n num_of_vowels (List.nth haiku 1) == 7 &&\n num_of_vowels (List.nth haiku 2) == 5\n then \"YES\"\n else \"NO\"\n\nlet rec input_haiku = function\n | 0 -> []\n | i -> (input_line stdin) :: input_haiku (i-1)\n \nlet input_haiku = List.rev (input_haiku 3)\n \nlet _ =\n Printf.printf \"%s\\n\" (solve (input_haiku))\n \n \n \n\n"}], "negative_code": [], "src_uid": "46d734178b3acaddf2ee3706f04d603d"} {"nl": {"description": "Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1,\u2009a2,\u2009...,\u2009an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.", "input_spec": "The first line contains positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of USB flash drives. The second line contains positive integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the size of Sean's file. Each of the next n lines contains positive integer ai (1\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 the sizes of USB flash drives in megabytes. It is guaranteed that the answer exists, i. e. the sum of all ai is not less than m.", "output_spec": "Print the minimum number of USB flash drives to write Sean's file, if he can split the file between drives.", "sample_inputs": ["3\n5\n2\n1\n3", "3\n6\n2\n3\n2", "2\n5\n5\n10"], "sample_outputs": ["2", "3", "1"], "notes": "NoteIn the first example Sean needs only two USB flash drives \u2014 the first and the third.In the second example Sean needs all three USB flash drives.In the third example Sean needs only one USB flash drive and he can use any available USB flash drive \u2014 the first or the second."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a;\n let pos = ref (n - 1) in\n let s = ref 0 in\n while !pos >= 0 && !s + a.(!pos) < m do\n\ts := !s + a.(!pos);\n\tdecr pos;\n done;\n Printf.printf \"%d\\n\" (n - !pos)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x) \n\nlet () = \n\n let n = read_int() in\n let m = read_int() in \n let a = Array.init n (fun _ -> read_int()) in\n\n Array.sort (fun a b -> compare b a) a;\n\n let rec loop i ac = if ac >= m then i else loop (i+1) (ac + a.(i)) in\n\n printf \"%d\\n\" (loop 0 0)\n"}], "negative_code": [], "src_uid": "a02a9e37a4499f9c86ac690a3a427466"} {"nl": {"description": "A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string $$$s$$$ of length $$$n$$$, consisting of digits.In one operation you can delete any character from string $$$s$$$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.You need to determine whether there is such a sequence of operations (possibly empty), after which the string $$$s$$$ becomes a telephone number.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the length of string $$$s$$$. The second line of each test case contains the string $$$s$$$ ($$$|s| = n$$$) consisting of digits.", "output_spec": "For each test print one line. If there is a sequence of operations, after which $$$s$$$ becomes a telephone number, print YES. Otherwise, print NO.", "sample_inputs": ["2\n13\n7818005553535\n11\n31415926535"], "sample_outputs": ["YES\nNO"], "notes": "NoteIn the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet gemacht n s =\n\tlet rec loop i =\n\t\tif i = n then None\n\t\telse if s.[i] = '8' then Some i\n\t\telse loop (i + 1)\n\tin\n\tmatch loop 0 with\n\t| None -> false\n\t| Some i -> n - i >= 11 \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet () = \n\tlet t = read_int () in\n\tfor i = 1 to t do\n\t\tlet n = read_int () in\n\t\tlet s = read_string () in\n\t\tif gemacht n s then printf \"YES\\n\" else printf \"NO\\n\";\n\tdone\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet solve n s =\n let rec loop i = if i >= n then None\n else if s.[i] = '8' then Some i\n else loop (i+1)\n in\n match loop 0 with\n | None -> false\n | Some j -> n-1-j >= 10\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let s = read_string() in\n if solve n s then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}], "negative_code": [], "src_uid": "bcdd7862b718d6bcc25c9aba8716d487"} {"nl": {"description": "In some country live wizards. They love to ride trolleybuses.A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it leaves at the moment of time ti seconds, can go at a speed of no greater than vi meters per second, and accelerate with an acceleration no greater than a meters per second squared. A trolleybus can decelerate as quickly as you want (magic!). It can change its acceleration as fast as you want, as well. Note that the maximum acceleration is the same for all trolleys.Despite the magic the trolleys are still powered by an electric circuit and cannot overtake each other (the wires are to blame, of course). If a trolleybus catches up with another one, they go together one right after the other until they arrive at the final station. Also, the drivers are driving so as to arrive at the final station as quickly as possible.You, as head of the trolleybuses' fans' club, are to determine for each trolley the minimum time by which it can reach the final station. At the time of arrival at the destination station the trolleybus does not necessarily have zero speed. When a trolley is leaving the depot, its speed is considered equal to zero. From the point of view of physics, the trolleybuses can be considered as material points, and also we should ignore the impact on the speed of a trolley bus by everything, except for the acceleration and deceleration provided by the engine.", "input_spec": "The first input line contains three space-separated integers n, a, d (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009a,\u2009d\u2009\u2264\u2009106) \u2014 the number of trolleybuses, their maximum acceleration and the distance from the depot to the final station, correspondingly. Next n lines contain pairs of integers ti vi (0\u2009\u2264\u2009t1\u2009<\u2009t2...\u2009<\u2009tn\u2009-\u20091\u2009<\u2009tn\u2009\u2264\u2009106, 1\u2009\u2264\u2009vi\u2009\u2264\u2009106) \u2014 the time when the i-th trolleybus leaves the depot and its maximum speed, correspondingly. The numbers in the lines are separated by spaces.", "output_spec": "For each trolleybus print a single line the time it arrives to the final station. Print the times for the trolleybuses in the order in which the trolleybuses are given in the input. The answer will be accepted if the absolute or relative error doesn't exceed 10\u2009-\u20094.", "sample_inputs": ["3 10 10000\n0 10\n5 11\n1000 1", "1 2 26\n28 29"], "sample_outputs": ["1000.5000000000\n1000.5000000000\n11000.0500000000", "33.0990195136"], "notes": "NoteIn the first sample the second trolleybus will catch up with the first one, that will happen at distance 510.5 meters from the depot. The trolleybuses will go the remaining 9489.5 meters together at speed 10 meters per second. As a result, both trolleybuses will arrive to the final station by the moment of time 1000.5 seconds. The third trolleybus will not catch up with them. It will arrive to the final station by the moment of time 11000.05 seconds."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let d = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = float_of_int a\n and d = float_of_int d in\n let t = Array.make n 0.0 in\n let v = Array.make n 0.0 in\n let prev = ref (-1.0) in\n for i = 0 to n - 1 do\n t.(i) <- float_of_int (Scanf.bscanf sb \"%d \" (fun s -> s));\n v.(i) <- float_of_int (Scanf.bscanf sb \"%d \" (fun s -> s));\n done;\n for i = 0 to n - 1 do\n let t1 = v.(i) /. a in\n let d1 = t1 *. t1 *. a /. 2.0 in\n let t2 =\n\tif d1 < d then (\n\t t1 +. (d -. d1) /. v.(i)\n\t) else (\n\t sqrt (2.0 *. d /. a)\n\t)\n in\n let t3 = t2 +. t.(i) in\n\tif !prev <= 0.0 || !prev < t3 then (\n\t prev := t3;\n\t Printf.printf \"%.9f\\n\" t3\n\t) else (\n\t Printf.printf \"%.9f\\n\" !prev\n\t)\n done\n"}], "negative_code": [], "src_uid": "894f407ca706788b13571878da8570f5"} {"nl": {"description": "Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?", "input_spec": "The first line of input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of balls in the jar. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u20095000) \u2014 the number written on the ith ball. It is guaranteed that no two balls have the same number.", "output_spec": "Print a single real value \u2014 the probability that Jerry has a higher total, given that Andrew wins the first two rounds and Jerry wins the third. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["2\n1 2", "3\n1 2 10"], "sample_outputs": ["0.0000000000", "0.0740740741"], "notes": "NoteIn the first case, there are only two balls. In the first two rounds, Andrew must have drawn the 2 and Jerry must have drawn the 1, and vice versa in the final round. Thus, Andrew's sum is 5 and Jerry's sum is 4, so Jerry never has a higher total.In the second case, each game could've had three outcomes \u2014 10\u2009-\u20092, 10\u2009-\u20091, or 2\u2009-\u20091. Jerry has a higher total if and only if Andrew won 2\u2009-\u20091 in both of the first two rounds, and Jerry drew the 10 in the last round. This has probability ."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let nn = n * (n-1) in\n\n let mdiff = 4999 in\n \n let prob = Array.make (mdiff+1) 0.0 in\n (* prob.(i) = probability of winning by by i *)\n\n let dp = 1.0 /. (float nn) in\n for i=0 to n-1 do\n for j=0 to n-1 do\n if i <> j then\n\tlet diff = abs (a.(i) - a.(j)) in\n\tprob.(diff) <- prob.(diff) +. dp\n done\n done;\n\n let sum = Array.make (mdiff+2) 0.0 in\n (* sum.(i) = probability that the winner wins by i or more *)\n\n for i=mdiff downto 0 do\n sum.(i) <- sum.(i+1) +. prob.(i)\n done;\n\n let total = ref 0.0 in\n\n for s1 = 1 to mdiff do\n let p1 = prob.(s1) in \n for s2 = 1 to mdiff-s1 do\n let p2 = prob.(s2) in\n let p3 = sum.(s1+s2+1) in\n total := !total +. (p1*.p2*.p3)\n done\n done;\n\n printf \"%.10f\\n\" !total\n"}], "negative_code": [], "src_uid": "9d55b98c75e703a554051d3088a68e59"} {"nl": {"description": "The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out.You are given two strings $$$s$$$ and $$$t$$$ of the same length $$$n$$$. Their characters are numbered from $$$1$$$ to $$$n$$$ from left to right (i.e. from the beginning to the end).In a single move you can do the following sequence of actions: choose any valid index $$$i$$$ ($$$1 \\le i \\le n$$$), move the $$$i$$$-th character of $$$s$$$ from its position to the beginning of the string or move the $$$i$$$-th character of $$$s$$$ from its position to the end of the string. Note, that the moves don't change the length of the string $$$s$$$. You can apply a move only to the string $$$s$$$.For example, if $$$s=$$$\"test\" in one move you can obtain: if $$$i=1$$$ and you move to the beginning, then the result is \"test\" (the string doesn't change), if $$$i=2$$$ and you move to the beginning, then the result is \"etst\", if $$$i=3$$$ and you move to the beginning, then the result is \"stet\", if $$$i=4$$$ and you move to the beginning, then the result is \"ttes\", if $$$i=1$$$ and you move to the end, then the result is \"estt\", if $$$i=2$$$ and you move to the end, then the result is \"tste\", if $$$i=3$$$ and you move to the end, then the result is \"tets\", if $$$i=4$$$ and you move to the end, then the result is \"test\" (the string doesn't change). You want to make the string $$$s$$$ equal to the string $$$t$$$. What is the minimum number of moves you need? If it is impossible to transform $$$s$$$ to $$$t$$$, print -1.", "input_spec": "The first line contains integer $$$q$$$ ($$$1 \\le q \\le 100$$$) \u2014 the number of independent test cases in the input. Each test case is given in three lines. The first line of a test case contains $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the length of the strings $$$s$$$ and $$$t$$$. The second line contains $$$s$$$, the third line contains $$$t$$$. Both strings $$$s$$$ and $$$t$$$ have length $$$n$$$ and contain only lowercase Latin letters. There are no constraints on the sum of $$$n$$$ in the test (i.e. the input with $$$q=100$$$ and all $$$n=100$$$ is allowed).", "output_spec": "For every test print minimum possible number of moves, which are needed to transform $$$s$$$ into $$$t$$$, or -1, if it is impossible to do.", "sample_inputs": ["3\n9\niredppipe\npiedpiper\n4\nestt\ntest\n4\ntste\ntest", "4\n1\na\nz\n5\nadhas\ndasha\n5\naashd\ndasha\n5\naahsd\ndasha"], "sample_outputs": ["2\n1\n2", "-1\n2\n2\n3"], "notes": "NoteIn the first example, the moves in one of the optimal answers are: for the first test case $$$s=$$$\"iredppipe\", $$$t=$$$\"piedpiper\": \"iredppipe\" $$$\\rightarrow$$$ \"iedppiper\" $$$\\rightarrow$$$ \"piedpiper\"; for the second test case $$$s=$$$\"estt\", $$$t=$$$\"test\": \"estt\" $$$\\rightarrow$$$ \"test\"; for the third test case $$$s=$$$\"tste\", $$$t=$$$\"test\": \"tste\" $$$\\rightarrow$$$ \"etst\" $$$\\rightarrow$$$ \"test\". "}, "positive_code": [{"source_code": "let to_arr s =\n let n = String.length s in\n Array.init n (String.get s)\n\nlet longest n s t z =\n let rec iter acc i j =\n if i>=n || j>=n then\n acc\n else if s.(i) = t.(j) then\n iter (acc + 1) (i + 1) (j + 1)\n else\n iter acc (i + 1) j in\n iter 0 0 z\n\nlet solve n s t =\n let s = to_arr s in\n let t = to_arr t in\n let s' = Array.copy s in\n let t' = Array.copy t in\n Array.fast_sort compare s';\n Array.fast_sort compare t';\n if s' <> t' then -1 else\n Array.init n (longest n s t)\n |> Array.fold_left max 0\n |> (fun x -> n - x)\n\nlet () =\n let t = read_int () in\n for i = 1 to t do\n let n = read_int () in\n let s = read_line () in\n let t = read_line () in\n Printf.printf \"%d\\n\" (solve n s t)\n done\n"}], "negative_code": [], "src_uid": "09eaa5ce235350bbc1a3d52441472c37"} {"nl": {"description": "Phoenix has $$$n$$$ coins with weights $$$2^1, 2^2, \\dots, 2^n$$$. He knows that $$$n$$$ is even.He wants to split the coins into two piles such that each pile has exactly $$$\\frac{n}{2}$$$ coins and the difference of weights between the two piles is minimized. Formally, let $$$a$$$ denote the sum of weights in the first pile, and $$$b$$$ denote the sum of weights in the second pile. Help Phoenix minimize $$$|a-b|$$$, the absolute value of $$$a-b$$$.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \\le n \\le 30$$$; $$$n$$$ is even)\u00a0\u2014 the number of coins that Phoenix has. ", "output_spec": "For each test case, output one integer\u00a0\u2014 the minimum possible difference of weights between the two piles.", "sample_inputs": ["2\n2\n4"], "sample_outputs": ["2\n6"], "notes": "NoteIn the first test case, Phoenix has two coins with weights $$$2$$$ and $$$4$$$. No matter how he divides the coins, the difference will be $$$4-2=2$$$.In the second test case, Phoenix has four coins of weight $$$2$$$, $$$4$$$, $$$8$$$, and $$$16$$$. It is optimal for Phoenix to place coins with weights $$$2$$$ and $$$16$$$ in one pile, and coins with weights $$$4$$$ and $$$8$$$ in another pile. The difference is $$$(2+16)-(4+8)=6$$$."}, "positive_code": [{"source_code": "(* Codeforces 1348 Phoenix and Balance train *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec balance acc p2i i n = \n\tif i > n then acc\n\telse \n\t\tlet np2i = p2i * 2 in\n\t\tlet ni = i + 1 in\n\t\tlet pos = (i < (n / 2)) || (i == n) in\n\t\tlet sign = if pos then 1 else -1 in\n\t\tlet nacc = acc + (sign * p2i) in\n\t\tbalance nacc np2i ni n;;\n\nlet do_one () = \n\tlet n = gr () in\n\tlet b = balance 0 2 1 n in\n\tbegin\n\t\tprint_int b;\n print_string \"\\n\";\n\tend;;\t\t\n\nlet rec do_all t = match t with\n\t| 0 -> ()\n\t| _ -> \n\t\tbegin\n\t\t\tdo_one ();\n\t\t\tdo_all (t-1)\n\t\tend;; \n\nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n\nmain();;"}], "negative_code": [], "src_uid": "787a45f427c2db98b2ddb78925e0e0f1"} {"nl": {"description": "Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.Please be careful that answer might not fit in 32 bit data type.", "input_spec": "The first line will contain two space separated integers n, x (1\u2009\u2264\u2009n,\u2009x\u2009\u2264\u2009105). The next line will contain n space separated integers: c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009105).", "output_spec": "Output a single integer representing the answer to the problem.", "sample_inputs": ["2 3\n4 1", "4 2\n5 1 2 1", "3 3\n1 1 1"], "sample_outputs": ["11", "10", "6"], "notes": "NoteLook at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2\u2009\u00d7\u20091\u2009=\u20092 hours. Hence you will need to spend 12\u2009+\u20092\u2009=\u200914 hours.Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3\u2009\u00d7\u20091\u2009=\u20093 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2\u2009\u00d7\u20094\u2009=\u20098 hours. Hence you will need to spend 11 hours.So overall, minimum of both the cases is 11 hours.Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = Int64.of_int (read_int ()) in\n let c = Array.init n (fun _ -> Int64.of_int (read_int())) in\n\n Array.sort compare c;\n\n let answer = sum 0 (n-1) (\n fun i -> \n let x' = max 1L (x -- (Int64.of_int i)) in\n c.(i) ** x'\n ) in\n \n printf \"%Ld\\n\" answer\n\n"}, {"source_code": "let solve n x c =\n let rec aux i x time =\n if (i = n) then time\n else\n let chapters = c.(i) in\n aux (i+1) (max (x-1) 1) Int64.(add time (mul chapters (of_int x)))\n in\n aux 0 x Int64.zero\n\nlet main = \n let (n, x) = Scanf.scanf \"%d %d\\n\" (fun n x -> (n,x)) in\n let c = Array.init n (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x)) in\n let () = Array.fast_sort compare c in\n let solution = solve n x c in\n Printf.printf \"%Ld\\n\" solution\n"}], "negative_code": [{"source_code": "let solve n x c =\n let rec aux i x time =\n if (i = n) then time\n else\n let chapters = c.(i) in\n aux (i+1) (max (x-1) 1) (time + chapters*x)\n in\n aux 0 x 0\n\nlet main = \n let (n, x) = Scanf.scanf \"%d %d\\n\" (fun n x -> (n,x)) in\n let c = Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n let () = Array.fast_sort compare c in\n let solution = solve n x c in\n Printf.printf \"%d\\n\" solution\n"}], "src_uid": "ce27e56433175ebf9d3bbcb97e71091e"} {"nl": {"description": "Maxim wants to buy some games at the local game shop. There are $$$n$$$ games in the shop, the $$$i$$$-th game costs $$$c_i$$$.Maxim has a wallet which can be represented as an array of integers. His wallet contains $$$m$$$ bills, the $$$j$$$-th bill has value $$$a_j$$$.Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.When Maxim stands at the position $$$i$$$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $$$i$$$-th game using this bill. After Maxim tried to buy the $$$n$$$-th game, he leaves the shop.Maxim buys the $$$i$$$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $$$i$$$-th game. If he successfully buys the $$$i$$$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.For example, for array $$$c = [2, 4, 5, 2, 4]$$$ and array $$$a = [5, 3, 4, 6]$$$ the following process takes place: Maxim buys the first game using the first bill (its value is $$$5$$$), the bill disappears, after that the second bill (with value $$$3$$$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $$$c_2 > a_2$$$, the same with the third game, then he buys the fourth game using the bill of value $$$a_2$$$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $$$a_3$$$.Your task is to get the number of games Maxim will buy.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 1000$$$) \u2014 the number of games and the number of bills in Maxim's wallet. The second line of the input contains $$$n$$$ integers $$$c_1, c_2, \\dots, c_n$$$ ($$$1 \\le c_i \\le 1000$$$), where $$$c_i$$$ is the cost of the $$$i$$$-th game. The third line of the input contains $$$m$$$ integers $$$a_1, a_2, \\dots, a_m$$$ ($$$1 \\le a_j \\le 1000$$$), where $$$a_j$$$ is the value of the $$$j$$$-th bill from the Maxim's wallet.", "output_spec": "Print a single integer \u2014 the number of games Maxim will buy.", "sample_inputs": ["5 4\n2 4 5 2 4\n5 3 4 6", "5 2\n20 40 50 20 40\n19 20", "6 4\n4 8 15 16 23 42\n1000 1000 1000 1000"], "sample_outputs": ["3", "0", "4"], "notes": "NoteThe first example is described in the problem statement.In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet."}, "positive_code": [{"source_code": "open Printf open Scanf\nlet input_int_array n =\n\tArray.init n (fun _ -> Scanf.scanf \" %d\" (fun v -> v))\t\nlet get_int () = Scanf.scanf \" %d\" (fun v -> v)\nlet get_2_ints () = Scanf.scanf \" %d %d\" (fun u v -> u,v)\nlet get_3_ints () = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w)\nlet get_4_ints () = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x)\nlet get_5_ints () = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nlet () =\n\tlet n,m = get_2_ints ()\n\tin\n\tlet ac = input_int_array n\n\tin let aa = input_int_array m\n\tin\n\tlet jdx = ref 0\n\tin\n\tArray.fold_left (fun u v -> \n\t\tif !jdx < m && v <= aa.(!jdx) then (\n\t\t\tjdx := !jdx + 1; u+1\n\t\t) else u\n\t) 0 ac\n\t|> print_int_endline"}], "negative_code": [], "src_uid": "c3f080681e3da5e1290ef935ff91f364"} {"nl": {"description": "Lolek and Bolek are about to travel abroad by plane. The local airport has a special \"Choose Your Plane\" offer. The offer's conditions are as follows: it is up to a passenger to choose a plane to fly on; if the chosen plane has x (x\u2009>\u20090) empty seats at the given moment, then the ticket for such a plane costs x zlotys (units of Polish currency). The only ticket office of the airport already has a queue of n passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all n passengers buy tickets according to the conditions of this offer?The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to n-th person.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000) \u2014 the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains m integers a1,\u2009a2,\u2009...,\u2009am (1\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 ai stands for the number of empty seats in the i-th plane before the ticket office starts selling tickets. The numbers in the lines are separated by a space. It is guaranteed that there are at least n empty seats in total.", "output_spec": "Print two integers \u2014 the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.", "sample_inputs": ["4 3\n2 1 1", "4 3\n2 2 2"], "sample_outputs": ["5 5", "7 6"], "notes": "NoteIn the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person \u2014 to the 2-nd plane, the 3-rd person \u2014 to the 3-rd plane, the 4-th person \u2014 to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person \u2014 to the 1-st plane, the 3-rd person \u2014 to the 2-nd plane, the 4-th person \u2014 to the 2-nd plane."}, "positive_code": [{"source_code": "let _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let m = Scanf.scanf \" %d\" (fun x -> x) in\n let a = Array.make m 0 in\n let b = Array.make m 0 in\n for i = 0 to m - 1 do\n let t = Scanf.scanf \" %d\" (fun x -> x) in\n a.(i) <- t;\n b.(i) <- t\n done;\n\n let x = ref 0 in\n let r = ref n in\n Array.sort (fun x y -> x - y) a;\n for i = 0 to m - 1 do\n let c = min a.(i) !r in\n x := !x + c * a.(i) - c * (c - 1) / 2;\n r := !r - c\n done;\n\n let y = ref 0 in\n let r = ref n in\n Array.sort (fun x y -> y - x) b;\n while !r > 0 do\n let c = b.(0) in\n for i = 0 to m - 1 do\n if !r > 0 && b.(i) = c then begin\n y := !y + c;\n r := !r - 1;\n b.(i) <- b.(i) - 1\n end\n done\n done;\n\n print_int !y;\n print_char ' ';\n print_int !x;\n print_char '\\n'\n;;\n"}, {"source_code": "open Printf;;\nopen Scanf;;\n\nlet input () =\n let n, m = scanf \"%d %d \" (fun x y -> x, y) in\n let arr = Array.make m 0 in\n for i = 0 to m - 1 do\n arr.(i) <- scanf \"%d \" (fun x -> x)\n done;\n (n, m, arr)\n \nlet solve (n, m, arr) =\n let mx, mn = (ref 0, ref 0) in\n let a = ref arr in\n let b = ref (Array.copy arr) in\n for i = 0 to n - 1 do\n begin\n Array.fast_sort (fun x y -> x - y) !a;\n a := (Array.of_list (List.filter (fun x -> x > 0) (Array.to_list !a)));\n Array.fast_sort (fun x y -> x - y) !b;\n b := (Array.of_list (List.filter (fun x -> x > 0) (Array.to_list !b)));\n let len_a = Array.length !a in\n mx := (!mx + !a.(len_a - 1));\n mn := !mn + !b.(0);\n !a.(len_a - 1) <- !a.(len_a - 1) - 1;\n !b.(0) <- !b.(0) - 1\n end\n done;\n !mx, !mn\n\nlet main () =\n let inp = input () in\n let (mx, mn) = solve inp in\n printf \"%d %d\\n\" mx mn\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "6dea4611ca210b34ae2da93ebfa9896c"} {"nl": {"description": "Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters \"a\", ..., \"z\".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population \"babb\". There are six options for an attack that may happen next: the first colony attacks the second colony (1\u2009\u2192\u20092), the resulting population is \"bbbb\"; 2\u2009\u2192\u20091, the result is \"aabb\"; 2\u2009\u2192\u20093, the result is \"baab\"; 3\u2009\u2192\u20092, the result is \"bbbb\" (note that the result is the same as the first option); 3\u2009\u2192\u20094 or 4\u2009\u2192\u20093, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109\u2009+\u20097.", "input_spec": "The first line contains an integer n\u00a0\u2014 the number of regions in the testtube (1\u2009\u2264\u2009n\u2009\u2264\u20095\u2009000). The second line contains n small Latin letters that describe the initial population of the testtube.", "output_spec": "Print one number\u00a0\u2014 the answer to the problem modulo 109\u2009+\u20097.", "sample_inputs": ["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"], "sample_outputs": ["1", "3", "11", "589"], "notes": "NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: \"ab\" (no attacks), \"aa\" (the first colony conquers the second colony), and \"bb\" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let m = 5000 in\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let inv = Array.make (m + 1) 1 in\n let _ =\n for i = 2 to m do\n inv.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)\n\t mmm);\n done\n in\n let fact = Array.make (m + 1) 1 in\n let ifact = Array.make (m + 1) 1 in\n let () =\n for i = 2 to m do\n fact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);\n ifact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int ifact.(i - 1) *| Int64.of_int inv.(i)) mmm);\n done;\n in\n let binom n k =\n Int64.to_int\n (Int64.rem\n\t (Int64.rem (Int64.of_int fact.(n) *| Int64.of_int ifact.(n - k)) mmm *|\n\t Int64.of_int ifact.(k)) mmm)\n in\n let (+/) x y =\n let s = x + y in\n if s < 0 || s >= mm\n then s - mm\n else s\n in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let a = Array.make_matrix 26 (n + 1) 0 in\n let sum = Array.make (n + 1) 0 in\n let _ =\n for i = 0 to n - 1 do\n let c = Char.code s.[i] - Char.code 'a' in\n\tfor j = 1 to n do\n\t let prev = a.(c).(j) in\n\t a.(c).(j) <- if j = 1 then 1 else 0;\n\t a.(c).(j) <- a.(c).(j) +/ sum.(j - 1) +/ (mm - a.(c).(j - 1));\n\t (*for k = 0 to 25 do\n\t if k <> c\n\t then a.(c).(j) <- a.(c).(j) +/ a.(k).(j - 1);\n\t done;*)\n\t sum.(j) <- sum.(j) +/ a.(c).(j) +/ (mm - prev);\n\tdone;\n done;\n (*for i = 0 to 25 do\n for j = 0 to n do\n\tPrintf.printf \" %d\" a.(i).(j)\n done;\n Printf.printf \"\\n\"\n done;*)\n in\n let res = ref 0L in\n for i = 1 to n do\n let s = ref 0 in\n\tfor j = 0 to 25 do\n\t s := !s +/ a.(j).(i)\n\tdone;\n\tres := mmod (!res +|\n\t\t\t Int64.of_int (binom (n - 1) (i - 1)) *|\n\t\t\t Int64.of_int !s);\n done;\n Printf.printf \"%Ld\\n\" !res\n"}], "negative_code": [], "src_uid": "81ad3bb3d58a33016221d60a601790d4"} {"nl": {"description": "The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n\u2009-\u20091 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.", "input_spec": "The first input line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the number of cities in Treeland. Next n\u2009-\u20091 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si,\u2009ti (1\u2009\u2264\u2009si,\u2009ti\u2009\u2264\u2009n;\u00a0si\u2009\u2260\u2009ti) \u2014 the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.", "output_spec": "In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital \u2014 a sequence of indexes of cities in the increasing order.", "sample_inputs": ["3\n2 1\n2 3", "4\n1 4\n2 4\n3 4"], "sample_outputs": ["0\n2", "2\n1 2 3"], "notes": null}, "positive_code": [{"source_code": "let read format f = Scanf.bscanf Scanf.Scanning.stdib format f\n\nlet bfs graph start f =\n let flags = Array.make (Array.length graph) false in\n let q = Queue.create () in\n let fold_vertex result v =\n List.fold_left (fun result (i, dir) ->\n if not flags.(i) then (Queue.add i q; flags.(i) <- true; f result v i dir)\n else result) result graph.(v)\n in\n let rec main_loop result = match Queue.is_empty q with\n | true -> result\n | false -> main_loop (fold_vertex result (Queue.take q))\n in\n Queue.add start q;\n flags.(start) <- true;\n main_loop\n\nlet () =\n let n = read \"%d\\n\" (fun x -> x) in\n let graph = Array.make n [] in\n for i = 1 to n - 1 do\n let f, t = read \"%d %d\\n\" (fun f t -> f - 1, t - 1) in\n graph.(f) <- (t, true) :: graph.(f);\n graph.(t) <- (f, false) :: graph.(t)\n done;\n let sum = bfs graph 0 (fun sum _ _ dir -> if dir then sum else sum + 1) 0 in\n let sums = Array.make n sum in\n let min_sum = bfs graph 0 (fun min_sum f t dir ->\n sums.(t) <- sums.(f) + (if dir then 1 else -1);\n min min_sum sums.(t)) sum\n in\n print_endline (string_of_int min_sum);\n let b = Buffer.create (10 * n) in\n Array.iteri (fun i s ->\n if s = min_sum then Buffer.add_string b (string_of_int (i + 1) ^ \" \")) sums;\n print_endline (Buffer.sub b 0 (Buffer.length b - 1))"}, {"source_code": "\nlet read format f = Scanf.bscanf Scanf.Scanning.stdib format f\n\nlet bfs graph start f =\n let flags = Array.make (Array.length graph) false in\n let q = Queue.create () in\n let fold_vertex result v =\n List.fold_left (fun result (i, dir) ->\n if not flags.(i) then (Queue.add i q; flags.(i) <- true; f result v i dir)\n else result) result graph.(v)\n in\n let rec main_loop result = match Queue.is_empty q with\n | true -> result\n | false -> main_loop (fold_vertex result (Queue.take q))\n in\n Queue.add start q;\n flags.(start) <- true;\n main_loop\n\nlet () =\n let n = read \"%d\\n\" (fun x -> x) in\n let graph = Array.make n [] in\n for i = 1 to n - 1 do\n let f, t = read \"%d %d\\n\" (fun f t -> f - 1, t - 1) in\n graph.(f) <- (t, true) :: graph.(f);\n graph.(t) <- (f, false) :: graph.(t)\n done;\n let sum = bfs graph 0 (fun sum _ _ dir -> if dir then sum else sum + 1) 0 in\n let sums = Array.make n sum in\n let min_sum = bfs graph 0 (fun min_sum f t dir ->\n sums.(t) <- sums.(f) + (if dir then 1 else -1);\n min min_sum sums.(t)) sum\n in\n print_endline (string_of_int min_sum);\n let b = Buffer.create (10 * n) in\n Array.iteri (fun i s ->\n if s = min_sum then Buffer.add_string b (string_of_int (i + 1) ^ \" \")) sums;\n print_endline (Buffer.sub b 0 (Buffer.length b - 1))\n"}, {"source_code": "\nlet read format f = Scanf.bscanf Scanf.Scanning.stdib format f\n\nmodule L = struct\n let iter lst f = List.iter f lst\n let map lst f = List.map f lst\nend\n\nmodule A = struct\n let iteri f a = Array.iteri a f\nend\n\nlet bfs graph n start f =\n let flags = Array.make n false in\n let q = Queue.create () in\n Queue.add start q;\n flags.(start) <- true;\n while not (Queue.is_empty q) do\n let v = Queue.take q in\n L.iter graph.(v) (fun (i, dir) ->\n if not flags.(i) then\n (Queue.add i q;\n f v i dir;\n flags.(i) <- true))\n done\n\nlet () =\n let n = read \"%d\\n\" (fun x -> x) in\n let graph = Array.make n [] in\n for i = 1 to n - 1 do\n let f, t = read \"%d %d\\n\" (fun f t -> f - 1, t - 1) in\n graph.(f) <- (t, true) :: graph.(f);\n graph.(t) <- (f, false) :: graph.(t)\n done;\n let sum = ref 0 in\n bfs graph n 0 (fun _ _ dir -> if not dir then incr sum);\n let sums = Array.make n !sum in\n let min_sum = ref !sum in\n bfs graph n 0 (fun f t dir ->\n sums.(t) <- sums.(f) + (if dir then 1 else -1);\n min_sum := min !min_sum sums.(t));\n print_endline (string_of_int !min_sum);\n let b = Buffer.create (10 * n) in\n A.iteri sums (fun i s ->\n if s = !min_sum then Buffer.add_string b (string_of_int (i + 1) ^ \" \"));\n print_endline (Buffer.sub b 0 (Buffer.length b - 1))\n"}], "negative_code": [{"source_code": "\nlet read format f = Scanf.bscanf Scanf.Scanning.stdib format f\n\nlet (=::) list_ref a = list_ref := a :: !list_ref\n\nmodule L = struct\n let iter lst f = List.iter f lst\n let map lst f = List.map f lst\n let sort = List.sort\nend\n\nlet bfs graph n start f =\n let flags = Array.make n false in\n let q = Queue.create () in\n Queue.add start q;\n while not (Queue.is_empty q) do\n let v = Queue.take q in\n L.iter !(graph.(v)) (fun (i, dir) ->\n if not flags.(i) then\n (Queue.add i q;\n f v i dir;\n flags.(i) <- true))\n done\n\nlet () =\n let n = read \"%d\\n\" (fun x -> x) in\n let graph = Array.make n (ref []) in\n for i = 1 to n - 1 do\n let f, t = read \"%d %d\\n\" (fun f t -> f - 1, t - 1) in\n graph.(f) =:: (t, true);\n graph.(t) =:: (f, false)\n done;\n let sum = ref 0 in\n bfs graph n 0 (fun f t dir -> if not dir then incr sum);\n let sums = Array.make n !sum in\n let min = ref !sum in\n let minis = ref [] in\n bfs graph n 0 (fun f t dir ->\n sums.(t) <- sums.(f) + (if dir then 1 else -1);\n if sums.(t) < !min then (min := sums.(t); minis := [t])\n else if sums.(t) = !min then minis =:: t);\n print_endline (string_of_int !min);\n print_endline (String.concat \" \"\n (L.map (L.sort compare !minis)\n (fun i -> (string_of_int (i + 1)))))\n\n\n\n\n\n\n\n\n"}, {"source_code": "\nlet read format f = Scanf.bscanf Scanf.Scanning.stdib format f\n\nlet (=::) list_ref a = list_ref := a :: !list_ref\n\nmodule L = struct\n let iter lst f = List.iter f lst\n let map lst f = List.map f lst\n let sort = List.sort\nend\n\nlet bfs graph n start f =\n let flags = Array.make n false in\n let q = Queue.create () in\n Queue.add start q;\n while not (Queue.is_empty q) do\n let v = Queue.take q in\n L.iter !(graph.(v)) (fun (i, dir) ->\n if not flags.(i) then\n (Queue.add i q;\n f v i dir;\n flags.(i) <- true))\n done\n\nlet () =\n let n = read \"%d\\n\" (fun x -> x) in\n let graph = Array.init n (fun _ -> ref []) in\n for i = 1 to n - 1 do\n let f, t = read \"%d %d\\n\" (fun f t -> f - 1, t - 1) in\n graph.(f) =:: (t, true);\n graph.(t) =:: (f, false)\n done;\n let sum = ref 0 in\n bfs graph n 0 (fun f t dir -> if not dir then incr sum);\n let sums = Array.make n !sum in\n let min = ref !sum in\n let minis = ref [] in\n bfs graph n 0 (fun f t dir ->\n sums.(t) <- sums.(f) + (if dir then 1 else -1);\n if sums.(t) < !min then (min := sums.(t); minis := [t])\n else if sums.(t) = !min then minis =:: t);\n print_endline (string_of_int !min);\n print_endline (String.concat \" \"\n (L.map (L.sort compare !minis)\n (fun i -> (string_of_int (i + 1)))))\n"}, {"source_code": "\nlet read format f = Scanf.bscanf Scanf.Scanning.stdib format f\n\nlet (=::) list_ref a = list_ref := a :: !list_ref\n\nlet list_iter lst f = List.iter f lst\n\nlet list_map lst f = List.map f lst\n\nlet bfs graph n start f =\n let flags = Array.make n false in\n let q = Queue.create () in\n Queue.add start q;\n while not (Queue.is_empty q) do\n let v = Queue.take q in\n list_iter !(graph.(v)) (fun (i, dir) ->\n if not flags.(i) then\n (Queue.add i q;\n f v i dir;\n flags.(i) <- true))\n done\n\nlet () =\n let n = read \"%d\\n\" (fun x -> x) in\n let graph = Array.make n (ref []) in\n for i = 1 to n - 1 do\n let f, t = read \"%d %d\\n\" (fun f t -> f - 1, t - 1) in\n graph.(f) =:: (t, true);\n graph.(t) =:: (f, false)\n done;\n let sum = ref 0 in\n bfs graph n 0 (fun f t dir -> if not dir then incr sum);\n let sums = Array.make n 0 in\n sums.(0) <- !sum;\n let min = ref !sum in\n let minis = ref [] in\n bfs graph n 0 (fun f t dir ->\n sums.(t) <- (if dir then (+) else (-)) sums.(f) 1;\n if sums.(t) < !min then\n (minis := [t];\n min := sums.(t))\n else if sums.(t) = !min then\n minis =:: t);\n print_endline (string_of_int !min);\n print_endline (String.concat \" \"\n (list_map !minis (fun i -> (string_of_int (i + 1)))))\n\n\n\n\n\n\n\n\n"}], "src_uid": "fb5c6182b9cad133d8b256f8e72e7e3b"} {"nl": {"description": "A string is called bracket sequence if it does not contain any characters other than \"(\" and \")\". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters \"+\" and \"1\" into this sequence. For example, \"\", \"(())\" and \"()()\" are RBS and \")(\" and \"(()\" are not.We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define nesting depth of the RBS as maximum number of bracket pairs, such that the $$$2$$$-nd pair lies inside the $$$1$$$-st one, the $$$3$$$-rd one \u2014 inside the $$$2$$$-nd one and so on. For example, nesting depth of \"\" is $$$0$$$, \"()()()\" is $$$1$$$ and \"()((())())\" is $$$3$$$.Now, you are given RBS $$$s$$$ of even length $$$n$$$. You should color each bracket of $$$s$$$ into one of two colors: red or blue. Bracket sequence $$$r$$$, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets $$$b$$$, should be RBS. Any of them can be empty. You are not allowed to reorder characters in $$$s$$$, $$$r$$$ or $$$b$$$. No brackets can be left uncolored.Among all possible variants you should choose one that minimizes maximum of $$$r$$$'s and $$$b$$$'s nesting depth. If there are multiple solutions you can print any of them.", "input_spec": "The first line contains an even integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of RBS $$$s$$$. The second line contains regular bracket sequence $$$s$$$ ($$$|s| = n$$$, $$$s_i \\in \\{$$$\"(\", \")\"$$$\\}$$$).", "output_spec": "Print single string $$$t$$$ of length $$$n$$$ consisting of \"0\"-s and \"1\"-s. If $$$t_i$$$ is equal to 0 then character $$$s_i$$$ belongs to RBS $$$r$$$, otherwise $$$s_i$$$ belongs to $$$b$$$.", "sample_inputs": ["2\n()", "4\n(())", "10\n((()())())"], "sample_outputs": ["11", "0101", "0110001111"], "notes": "NoteIn the first example one of optimal solutions is $$$s = $$$ \"$$$\\color{blue}{()}$$$\". $$$r$$$ is empty and $$$b = $$$ \"$$$()$$$\". The answer is $$$\\max(0, 1) = 1$$$.In the second example it's optimal to make $$$s = $$$ \"$$$\\color{red}{(}\\color{blue}{(}\\color{red}{)}\\color{blue}{)}$$$\". $$$r = b = $$$ \"$$$()$$$\" and the answer is $$$1$$$.In the third example we can make $$$s = $$$ \"$$$\\color{red}{(}\\color{blue}{((}\\color{red}{)()}\\color{blue}{)())}$$$\". $$$r = $$$ \"$$$()()$$$\" and $$$b = $$$ \"$$$(()())$$$\" and the answer is $$$2$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let s = read_string() in\n\n let color = Array.make n 0 in\n\n let rec parse i depth = if i\n\tcolor.(i) <- depth mod 2;\n\tparse (i+1) (depth+1)\n | ')' ->\n\tcolor.(i) <- (depth+1) mod 2;\n\tparse (i+1) (depth -1)\n | _ -> failwith \"bad input\"\n ) in\n\n parse 0 0;\n\n for i=0 to n-1 do\n printf \"%d\" color.(i)\n done;\n\n print_newline()\n"}], "negative_code": [], "src_uid": "73b18cc560ea94476903f79a695d4268"} {"nl": {"description": "Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0\u2009\u2264\u2009x'\u2009\u2264\u2009x and 0\u2009\u2264\u2009y'\u2009\u2264\u2009y also belong to this set.Now Wilbur wants to number the points in the set he has, that is assign them distinct integer numbers from 1 to n. In order to make the numbering aesthetically pleasing, Wilbur imposes the condition that if some point (x, y) gets number i, then all (x',y') from the set, such that x'\u2009\u2265\u2009x and y'\u2009\u2265\u2009y must be assigned a number not less than i. For example, for a set of four points (0, 0), (0, 1), (1, 0) and (1, 1), there are two aesthetically pleasing numberings. One is 1, 2, 3, 4 and another one is 1, 3, 2, 4.Wilbur's friend comes along and challenges Wilbur. For any point he defines it's special value as s(x,\u2009y)\u2009=\u2009y\u2009-\u2009x. Now he gives Wilbur some w1, w2,..., wn, and asks him to find an aesthetically pleasing numbering of the points in the set, such that the point that gets number i has it's special value equal to wi, that is s(xi,\u2009yi)\u2009=\u2009yi\u2009-\u2009xi\u2009=\u2009wi.Now Wilbur asks you to help him with this challenge.", "input_spec": "The first line of the input consists of a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of points in the set Wilbur is playing with. Next follow n lines with points descriptions. Each line contains two integers x and y (0\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009100\u2009000), that give one point in Wilbur's set. It's guaranteed that all points are distinct. Also, it is guaranteed that if some point (x, y) is present in the input, then all points (x', y'), such that 0\u2009\u2264\u2009x'\u2009\u2264\u2009x and 0\u2009\u2264\u2009y'\u2009\u2264\u2009y, are also present in the input. The last line of the input contains n integers. The i-th of them is wi (\u2009-\u2009100\u2009000\u2009\u2264\u2009wi\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the required special value of the point that gets number i in any aesthetically pleasing numbering.", "output_spec": "If there exists an aesthetically pleasant numbering of points in the set, such that s(xi,\u2009yi)\u2009=\u2009yi\u2009-\u2009xi\u2009=\u2009wi, then print \"YES\" on the first line of the output. Otherwise, print \"NO\". If a solution exists, proceed output with n lines. On the i-th of these lines print the point of the set that gets number i. If there are multiple solutions, print any of them.", "sample_inputs": ["5\n2 0\n0 0\n1 0\n1 1\n0 1\n0 -1 -2 1 0", "3\n1 0\n0 0\n2 0\n0 1 2"], "sample_outputs": ["YES\n0 0\n1 0\n2 0\n0 1\n1 1", "NO"], "notes": "NoteIn the first sample, point (2, 0) gets number 3, point (0, 0) gets number one, point (1, 0) gets number 2, point (1, 1) gets number 5 and point (0, 1) gets number 4. One can easily check that this numbering is aesthetically pleasing and yi\u2009-\u2009xi\u2009=\u2009wi.In the second sample, the special values of the points in the set are 0, \u2009-\u20091, and \u2009-\u20092 while the sequence that the friend gives to Wilbur is 0, 1, 2. Therefore, the answer does not exist."}, "positive_code": [{"source_code": "exception YOLO\n\nlet main () =\n\tlet assigned = Hashtbl.create 0 in\n\tlet n = Scanf.scanf \"%d\" (fun i->i) and tab = Array.make 200002 []\n\tand res = ref [] in\n\tfor i=1 to n do\n\t\tScanf.scanf \" %d %d\"\n\t(fun i j -> tab.(100000 + j - i) <- (i,j)::tab.(100000 + j - i)) ;\n\tdone;\n\tfor i=0 to 200001 do\n\t\ttab.(i) <- List.sort compare tab.(i);\n\tdone;\n\tfor i=1 to n do\n\t\tScanf.scanf \" %d\" (fun i -> let (t::q) = tab.(i + 100000) in\n\t\ttab.(i + 100000) <- q; res := t:: !res; Hashtbl.add assigned t ();\n\t\tlet (c,d) = t in if Hashtbl.mem assigned (c+1,d) || Hashtbl.mem assigned (c,d+1) then raise YOLO);\n\tdone;\n\tPrintf.printf \"YES\";\n\tList.iter (fun (i,j) -> Printf.printf \"\\n%d %d\" i j) (List.rev !res);;\n\ntry\nmain ()\nwith _ -> Printf.printf \"NO\";;\n"}], "negative_code": [{"source_code": "let main () =\n\tlet n = Scanf.scanf \"%d\" (fun i->i) and tab = Array.make 200002 []\n\tand res = ref [] in\n\tfor i=1 to n do\n\t\tScanf.scanf \" %d %d\"\n\t(fun i j -> tab.(100000 + j - i) <- (i,j)::tab.(100000 + j - i)) ;\n\tdone;\n\tfor i=0 to 200001 do\n\t\ttab.(i) <- List.sort compare tab.(i);\n\tdone;\n\tfor i=1 to n do\n\t\tScanf.scanf \" %d\" (fun i -> let a = tab.(i + 100000) in\n\t\ttab.(i + 100000) <- List.tl a; res := (List.hd a):: !res);\n\tdone;\n\tPrintf.printf \"YES\";\n\tList.iter (fun (i,j) -> Printf.printf \"\\n%d %d\" i j) (List.rev !res);;\n\ntry\nmain ()\nwith _ -> Printf.printf \"NO\";;\n"}, {"source_code": "let main () =\n\tlet n = Scanf.scanf \"%d\" (fun i->i) and tab = Array.make 200000 []\n\tand res = ref [] in\n\tfor i=1 to n do\n\t\tScanf.scanf \" %d %d\"\n\t(fun i j -> tab.(100000 + j - i) <- (i,j)::tab.(100000 + j - i)) ;\n\tdone;\n\tfor i=1 to n do\n\t\tScanf.scanf \" %d\" (fun i -> let a = tab.(i + 100000) in\n\t\ttab.(i + 100000) <- List.tl a; res := (List.hd a):: !res);\n\tdone;\n\tPrintf.printf \"YES\";\n\tList.iter (fun (i,j) -> Printf.printf \"\\n%d %d\" i j) (List.rev !res);;\n\ntry\nmain ()\nwith _ -> Printf.printf \"NO\";;\n"}], "src_uid": "ad186f6df24d31243cde541b7fc69a8c"} {"nl": {"description": "The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string \"abba\" is a palindrome and string \"abc\" isn't. Determine which player will win, provided that both sides play optimally well \u2014 the one who moves first or the one who moves second.", "input_spec": "The input contains a single line, containing string s (1\u2009\u2264\u2009|s|\u2009\u2009\u2264\u2009\u2009103). String s consists of lowercase English letters.", "output_spec": "In a single line print word \"First\" if the first player wins (provided that both players play optimally well). Otherwise, print word \"Second\". Print the words without the quotes.", "sample_inputs": ["aba", "abca"], "sample_outputs": ["First", "Second"], "notes": null}, "positive_code": [{"source_code": "(* CF odd game prob 276 B *)\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet ss = rdln();;\n\nlet rec isOdd s i c cnt = \n\tif i >= String.length s then ((cnt mod 2) = 1)\n\telse \n\t\tlet cnt1 = cnt + (if c = s.[i] then 1 else 0) in\n\t\tisOdd s (i+1) c cnt1;;\n\nlet rec nOdd s c cnto =\n\tif c > 'z' then cnto\n\telse \n\t\tlet iso = isOdd s 0 c 0 in\n\t\tlet cnto1 = cnto + (if iso then 1 else 0) in\n\t\tlet nextc = char_of_int (int_of_char c + 1) in\n\t\tnOdd s nextc cnto1;;\n\nlet main() =\n\tlet no = nOdd ss 'a' 0 in\n\tlet so = if no < 2 || (no mod 2) = 1 then \"First\" else \"Second\" in\n\t( print_string so; print_newline() );;\n\t\t\nmain();;"}, {"source_code": "let () = \n let s = read_line() in\n let n = String.length s in\n let h = Array.make 26 0 in\n\n for i=0 to n-1 do\n let c = (int_of_char s.[i]) - (int_of_char 'a') in\n\th.(c) <- h.(c) +1\n done;\n\n let odd = ref 0 in\n \n for i=0 to 25 do\n\tif h.(i) mod 2 = 1 then odd := !odd + 1\n done;\n\n if (!odd >= 1 && !odd mod 2 = 0) then Printf.printf \"Second\\n\" else Printf.printf \"First\\n\"\n"}], "negative_code": [], "src_uid": "bbf2dbdea6dd3aa45250ab5a86833558"} {"nl": {"description": "As we all know Barney's job is \"PLEASE\" and he has not much to do at work. That's why he started playing \"cups and key\". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup. Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start.After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right.Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1,\u2009a2,\u2009...,\u2009ak such that in other words, n is multiplication of all elements of the given array.Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p\u2009/\u2009q such that , where is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109\u2009+\u20097.Please note that we want of p and q to be 1, not of their remainders after dividing by 109\u2009+\u20097.", "input_spec": "The first line of input contains a single integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009105)\u00a0\u2014 the number of elements in array Barney gave you. The second line contains k integers a1,\u2009a2,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u20091018)\u00a0\u2014 the elements of the array.", "output_spec": "In the only line of output print a single string x\u2009/\u2009y where x is the remainder of dividing p by 109\u2009+\u20097 and y is the remainder of dividing q by 109\u2009+\u20097.", "sample_inputs": ["1\n2", "3\n1 1 1"], "sample_outputs": ["1/2", "0/1"], "notes": null}, "positive_code": [{"source_code": "let p = 1_000_000_007L\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet ( *** ) (a,b,c,d) (e,f,g,h) =\n ((a**e ++ b**g)%%p, (a**f ++ b**h)%%p, (c**e ++ d**g)%%p, (c**f ++ d**h)%%p)\n\nlet identity = (1L, 0L, 0L, 1L)\n \nlet rec ( ^ ) m e = \n if e=0L then identity else\n let a = m ^ (Int64.shift_right e 1) in\n if (Int64.logand e 1L)=0L then a *** a else m *** (a *** a)\n \nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x) \n\nlet () = \n\n let k = read_int() in\n let a = Array.init k (fun _ -> (read_long()) %% (p -- 1L)) in\n\n let rec prod i ac = if i=k then ac else\n prod (i+1) ((a.(i) ** ac) %% (p -- 1L))\n in\n\n let pr = prod 0 1L in\n \n let (a,b,c,d) = (0L, 1L, 2L, 1L) ^ pr in\n let (two_to_power, _,_,_) = (2L, 0L, 0L, 2L) ^ pr in\n let (two_inverse, _,_,_) = (2L, 0L, 0L, 2L) ^ (p -- 2L) in\n (* this should work cause the a_i's cannot be 0 *)\n \n printf \"%Ld/%Ld\\n\" ((a ** two_inverse)%%p) ((two_to_power ** two_inverse)%%p)\n"}], "negative_code": [], "src_uid": "7afa48f3411521ce49ba9595b0bef079"} {"nl": {"description": "Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000) \u2014 the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1,\u2009b2,\u2009...,\u2009bn. The third line contains c1,\u2009c2,\u2009...,\u2009cn. The following limits are fulfilled: 0\u2009\u2264\u2009ai,\u2009bi,\u2009ci\u2009\u2264\u2009105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number \u0441i in the third line shows the joy that hare number i radiates if both his adjacent hares are full.", "output_spec": "In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.", "sample_inputs": ["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"], "sample_outputs": ["13", "44", "4"], "notes": null}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet () =\n let n = Scanf.scanf \"%d \" ident in\n let an = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d \" ident :: acc) in\n let bn = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d \" ident :: acc) in\n let cn = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d \" ident :: acc) in\n let rec combine an bn cn = match an, bn, cn with\n | (a :: an, b :: bn, c :: cn) -> (a, b, c) :: combine an bn cn\n | ([], [], []) -> []\n | _ -> failwith \"combine\" in\n let xs = combine an bn cn in\n let map = Hashtbl.create 1000 in\n let rec iter prev i xs =\n try\n Hashtbl.find map (prev, i)\n with\n | Not_found -> begin\n match xs with\n | (a, b, c) :: ((_ :: _) as xs) -> begin\n let res = \n match prev with\n | `p -> max (b + iter `p (i + 1) xs) (c + iter `f (i + 1) xs)\n | `f -> max (a + iter `p (i + 1) xs) (b + iter `f (i + 1) xs) in\n Hashtbl.add map (prev, i) res;\n res\n end\n | [a, b, c] -> begin\n let res = \n match prev with\n | `p -> (b + iter `p (i + 1) [])\n | `f -> (a + iter `p (i + 1) []) in\n Hashtbl.add map (prev, i) res;\n res\n end\n | [] -> 0\n end\n in \n Printf.printf \"%d\\n\" @@ iter `f 0 xs\n;;\n"}, {"source_code": "let line_stream_from_channel in_chan = \n Stream.from\n (fun _ ->\n try Some (input_line in_chan) \n with _ -> None);;\n\nlet rec print_l l = match l with\n| hd::tl -> (print_int hd; print_string \" \";print_l tl)\n| _ -> print_newline ();;\n\n\nlet to_List strm len= \n let lt = List.map int_of_string (Str.split (Str.regexp \" \") (Stream.next strm)) in\n if List.length lt != len then failwith \"WrangData\" else lt;;\n\nlet oComp x y = match x,y with\n| Some i, Some j -> Some(max i j)\n| None, i -> i\n| i, None -> i;;\n\nlet oAdd o x = match o with\n|Some y -> Some (x+y)\n|None -> None;;\n\nlet total l =\n List.fold_left (+) 0 l;;\nlet path_cached l1 l2 =\n let path_ht = Hashtbl.create ((List.length l1)*4 ) in\n let length = List.length l1 in \n let hnum l s ol = (\n (List.length l) +1 \n + (if ol!=[] then length else 0))*s in\n let rec path l1 l2 switch ol =\n let out = \n try Hashtbl.find path_ht (hnum l1 switch ol)\n\n with Not_found ->\n (let res = (match l1, l2, ol with \n | h1::t1, h2::t2, [] -> (\n let vnew, valt = ((*if switch=1 then*) h1,h2 (*else h2,h1*)) in\n oComp ((*if (vlast + vnew <=0)&&(tl!=[]) then None \n else*) oAdd (path t1 t2 (-1*switch) (vnew::[])) vnew)\n ((*if (vlast (\n let vnew, valt = (if switch=1 then h1,h2 else h2,h1) in\n oComp ((*if (vlast + vnew <=0) then None \n else*) (oAdd (path t1 t2 (-1*switch) (vnew::ol)) vnew))\n ((*if (vlast if (switch= -1) then Some 0\n else None) in\n Hashtbl.add path_ht (hnum l1 switch ol) res;\n(*\n print_string \"Added \";\n print_int (hnum l1 switch ol);\n print_string \" with res = \";\n (match shifted_res with\n |Some num -> print_int num;\n |None -> print_string \"None\";);\n print_string \"\\n\\t\";\n print_l ol;\n (*print_newline ();*)\n*)\n res) in\n out in\n path l1 l2 1 [] ;;\n\nlet main = \n let stream = line_stream_from_channel stdin in\n try\n let n = int_of_string (Stream.next stream) in\n let a = to_List stream n in\n let b = to_List stream n in\n let c = to_List stream n in\n let rev_ab = List.rev_map2 (fun x y -> x-y) a b in\n let rev_cb = List.rev_map2 (fun x y -> x-y) c b in\n(*\n print_l rev_ab;\n print_l rev_cb;\n*) \n let oRes = path_cached rev_ab rev_cb in\n match oRes with\n | Some i -> print_int (i+ (total b)); print_newline ();\n | None -> print_string \"No result\";\n with _ -> raise Exit\n;;\n\nlet () = \n try main\n with Exit -> print_string \"Bye-Bye\\n\";;\n"}], "negative_code": [{"source_code": "let line_stream_from_channel in_chan = \n Stream.from\n (fun _ ->\n try Some (input_line in_chan) \n with _ -> None);;\n\nlet to_List strm len= \n let lt = List.map int_of_string (Str.split (Str.regexp \" \") (Stream.next strm)) in\n if List.length lt != len then failwith \"WrangData\" else lt;;\n\nlet oComp x y = match x,y with\n| Some i, Some j -> Some(max i j)\n| None, i -> i\n| i, None -> i;;\n\nlet oAdd o x = match o with\n|Some y -> Some (x+y)\n|None -> None;;\n\nlet total l =\n List.fold_left (+) 0 l;;\nlet path_cached l1 l2 =\n let path_ht = Hashtbl.create ((List.length l1)*2 + 2 ) in\n let rec path l1 l2 switch ol =\n let out = \n try Hashtbl.find path_ht (((List.length l1) +1)*switch)\n\n with Not_found ->\n (let res = (match l1, l2, ol with \n | h1::t1, h2::t2, [] -> (\n let vnew, valt = ((*if switch=1 then*) h1,h2 (*else h2,h1*)) in\n oComp ((*if (vlast + vnew <=0)&&(tl!=[]) then None \n else*) (path t1 t2 (-1*switch) (vnew::[])))\n ((*if (vlast (\n let vnew, valt = (if switch=1 then h1,h2 else h2,h1) in\n oComp (if (vlast + vnew <=0) then None \n else (path t1 t2 (-1*switch) (vnew::ol)))\n (if (vlast if (switch= -1) then Some (total ol)\n else None) in\n let shifted_res = (oAdd res (-(total ol))) in\n Hashtbl.add path_ht (((List.length l1) +1)*switch) shifted_res;\n (*print_string \"Added \";\n print_int ((List.length l1)*switch);\n print_string \" with res = \";\n (match shifted_res with\n |Some num -> print_int num;\n |None -> print_string \"None\";);\n print_newline ();*)\n shifted_res) in\n oAdd out (total ol) in\n path l1 l2 1 [] ;;\n\nlet main = \n let stream = line_stream_from_channel stdin in\n try\n let n = int_of_string (Stream.next stream) in\n let a = to_List stream n in\n let b = to_List stream n in\n let c = to_List stream n in\n let rev_ab = List.rev_map2 (fun x y -> x-y) a b in\n let rev_cb = List.rev_map2 (fun x y -> x-y) c b in\n let oRes = path_cached rev_ab rev_cb in\n match oRes with\n | Some i -> print_int (i+ (total b)); print_newline ();\n | None -> print_string \"No result\";\n with _ -> raise Exit\n;;\n\nlet () = \n try main\n with Exit -> print_string \"Bye-Bye\\n\";;\n"}], "src_uid": "99cf10673cb275ad3b90bcd3757ecd47"} {"nl": {"description": "Igor K. very much likes a multiplayer role playing game WineAge II. Who knows, perhaps, that might be the reason for his poor performance at the university. As any person who plays the game, he is interested in equipping his hero with as good weapon and outfit as possible. One day, as he was reading the game's forum yet again, he discovered a very interesting fact. As it turns out, each weapon in the game is characterised with k different numbers: a1,\u2009...,\u2009ak. They are called hit indicators and according to the game developers' plan they are pairwise coprime. The damage that is inflicted during a hit depends not only on the weapon's characteristics, but also on the hero's strength parameter. Thus, if the hero's strength equals n, than the inflicted damage will be calculated as the number of numbers on the segment , that aren't divisible by any hit indicator ai.Recently, having fulfilled another quest, Igor K. found a new Lostborn sword. He wants to know how much damage he will inflict upon his enemies if he uses it.", "input_spec": "The first line contains two integers: n and k (1\u2009\u2264\u2009n\u2009\u2264\u20091013, 1\u2009\u2264\u2009k\u2009\u2264\u2009100). They are the indicator of Igor K's hero's strength and the number of hit indicators. The next line contains space-separated k integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u20091000). They are Lostborn sword's hit indicators. The given k numbers are pairwise coprime.", "output_spec": "Print the single number \u2014 the damage that will be inflicted by Igor K.'s hero when he uses his new weapon. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.", "sample_inputs": ["20 3\n2 3 5", "50 2\n15 8"], "sample_outputs": ["6", "41"], "notes": null}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make k 0 in\n let _ =\n for i = 0 to k - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n (*Array.sort (fun x y -> compare y x) a;*)\n Array.sort compare a;\n in\n let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in\n let sn = isqrt n in\n let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in\n let n2 = min 250000L n in\n let n2 = Int64.to_int n2 in\n let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in\n let _ =\n for i = 1 to n2 do\n phi'.(i).(0) <- i;\n for j = 1 to k do\n\tphi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)\n done;\n done;\n in\n let n3 = n /| Int64.of_int n2 in\n let (c, q) =\n let c = ref 0 in\n let q = ref 1 in\n while !c < k && !q * a.(!c) <= n2 do\n\tq := !q * a.(!c);\n\tincr c;\n done;\n (!c, !q)\n in\n let cnt = ref 0 in\n let cnt1 = ref 0 in\n let cnt2 = ref 0 in\n let cnt3 = ref 0 in\n let cnt4 = ref 0 in\n (*let rec phi m k =\n (*incr cnt;*)\n if k = 0\n then (\n (*incr cnt1;*)\n n /| m\n ) else if k = c then (\n (*incr cnt4;*)\n (n /| m /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)\n ) else if m > n3\n then (\n (*incr cnt2;*)\n Int64.of_int phi'.(Int64.to_int (n /| m)).(k)\n ) else (\n (*incr cnt3;*)\n phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)\n )\n in\n let res = phi 1L k in*)\n let rec phi32 n k =\n (*incr cnt;*)\n if k = 0\n then n\n else if k = c\n then (n / q) * phi'.(q).(k) + phi'.(n mod q).(c)\n else if n <= n2\n then phi'.(n).(k)\n else phi32 n (k - 1) - phi32 (n / a.(k - 1)) (k - 1)\n in\n let rec phi n k =\n if k = 0\n then n\n else if k = c\n then\n (n /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem n (Int64.of_int q))).(c)\n else if n <= 1000000000L\n then Int64.of_int (phi32 (Int64.to_int n) k)\n else phi n (k - 1) -| phi (n /| Int64.of_int a.(k - 1)) (k - 1)\n in\n let res = phi n k in\n Printf.eprintf \"asd %d %d %d %d %d %d\\n\" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;\n Printf.printf \"%Ld\\n\" res\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make k 0 in\n let _ =\n for i = 0 to k - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n (*Array.sort (fun x y -> compare y x) a;*)\n Array.sort compare a;\n in\n let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in\n let sn = isqrt n in\n let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in\n let n2 = min 150000L n in\n let n2 = Int64.to_int n2 in\n let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in\n let _ =\n for i = 1 to n2 do\n phi'.(i).(0) <- i;\n for j = 1 to k do\n\tphi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)\n done;\n done;\n in\n let n3 = n /| Int64.of_int n2 in\n let (c, q) =\n let c = ref 0 in\n let q = ref 1 in\n while !c < k && !q * a.(!c) <= n2 do\n\tq := !q * a.(!c);\n\tincr c;\n done;\n (!c, !q)\n in\n let cnt = ref 0 in\n let cnt1 = ref 0 in\n let cnt2 = ref 0 in\n let cnt3 = ref 0 in\n let cnt4 = ref 0 in\n (*let rec phi m k =\n (*incr cnt;*)\n if k = 0\n then (\n (*incr cnt1;*)\n n /| m\n ) else if k = c then (\n (*incr cnt4;*)\n (n /| m /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)\n ) else if m > n3\n then (\n (*incr cnt2;*)\n Int64.of_int phi'.(Int64.to_int (n /| m)).(k)\n ) else (\n (*incr cnt3;*)\n phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)\n )\n in\n let res = phi 1L k in*)\n let rec phi32 n k =\n (*incr cnt;*)\n if k = 0\n then n\n else if k = c\n then (n / q) * phi'.(q).(k) + phi'.(n mod q).(c)\n else if n <= n2\n then phi'.(n).(k)\n else phi32 n (k - 1) - phi32 (n / a.(k - 1)) (k - 1)\n in\n let rec phi n k =\n if k = 0\n then n\n else if k = c\n then\n (n /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem n (Int64.of_int q))).(c)\n else if n <= 1000000000L\n then Int64.of_int (phi32 (Int64.to_int n) k)\n else phi n (k - 1) -| phi (n /| Int64.of_int a.(k - 1)) (k - 1)\n in\n let res = phi n k in\n Printf.eprintf \"asd %d %d %d %d %d %d\\n\" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;\n Printf.printf \"%Ld\\n\" res\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make k 0 in\n let _ =\n for i = 0 to k - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n (*Array.sort (fun x y -> compare y x) a;*)\n Array.sort compare a;\n in\n let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in\n let sn = isqrt n in\n let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in\n let n2 = min 250000L n in\n let n2 = Int64.to_int n2 in\n let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in\n let _ =\n for i = 1 to n2 do\n phi'.(i).(0) <- i;\n for j = 1 to k do\n\tphi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)\n done;\n done;\n in\n let n3 = n /| Int64.of_int n2 in\n let (c, q) =\n let c = ref 0 in\n let q = ref 1 in\n while !c < k && !q * a.(!c) <= n2 do\n\tq := !q * a.(!c);\n\tincr c;\n done;\n (!c, !q)\n in\n let cnt = ref 0 in\n let cnt1 = ref 0 in\n let cnt2 = ref 0 in\n let cnt3 = ref 0 in\n let cnt4 = ref 0 in\n let rec phi m k =\n incr cnt;\n if k = 0\n then (\n incr cnt1;\n n /| m\n ) else if k = c then (\n incr cnt4;\n (n /| m /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)\n ) else if m > n3\n then (\n incr cnt2;\n Int64.of_int phi'.(Int64.to_int (n /| m)).(k)\n ) else (\n incr cnt3;\n phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)\n )\n in\n let res = phi 1L k in\n Printf.eprintf \"asd %d %d %d %d %d %d\\n\" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;\n Printf.printf \"%Ld\\n\" res\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make k 0 in\n let _ =\n for i = 0 to k - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n (*Array.sort (fun x y -> compare y x) a;*)\n Array.sort compare a;\n in\n let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in\n let sn = isqrt n in\n let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in\n let n2 = min 200000L n in\n let n2 = Int64.to_int n2 in\n let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in\n let _ =\n for i = 1 to n2 do\n phi'.(i).(0) <- i;\n for j = 1 to k do\n\tphi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)\n done;\n done;\n in\n let n3 = n /| Int64.of_int n2 in\n let (c, q) =\n let c = ref 0 in\n let q = ref 1 in\n while !c < k && !q * a.(!c) <= n2 do\n\tq := !q * a.(!c);\n\tincr c;\n done;\n (!c, !q)\n in\n let cnt = ref 0 in\n let cnt1 = ref 0 in\n let cnt2 = ref 0 in\n let cnt3 = ref 0 in\n let cnt4 = ref 0 in\n (*let rec phi m k =\n (*incr cnt;*)\n if k = 0\n then (\n (*incr cnt1;*)\n n /| m\n ) else if k = c then (\n (*incr cnt4;*)\n (n /| m /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)\n ) else if m > n3\n then (\n (*incr cnt2;*)\n Int64.of_int phi'.(Int64.to_int (n /| m)).(k)\n ) else (\n (*incr cnt3;*)\n phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)\n )\n in\n let res = phi 1L k in*)\n let rec phi32 n k =\n (*incr cnt;*)\n if k = 0\n then n\n else if k = c\n then (n / q) * phi'.(q).(k) + phi'.(n mod q).(c)\n else if n <= n2\n then phi'.(n).(k)\n else phi32 n (k - 1) - phi32 (n / a.(k - 1)) (k - 1)\n in\n let rec phi n k =\n if k = 0\n then n\n else if k = c\n then\n (n /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem n (Int64.of_int q))).(c)\n else if n <= 1000000000L\n then Int64.of_int (phi32 (Int64.to_int n) k)\n else phi n (k - 1) -| phi (n /| Int64.of_int a.(k - 1)) (k - 1)\n in\n let res = phi n k in\n Printf.eprintf \"asd %d %d %d %d %d %d\\n\" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;\n Printf.printf \"%Ld\\n\" res\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make k 0 in\n let _ =\n for i = 0 to k - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n (*Array.sort (fun x y -> compare y x) a;*)\n Array.sort compare a;\n in\n let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in\n let sn = isqrt n in\n let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in\n let n2 = min 250000L n in\n let n2 = Int64.to_int n2 in\n let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in\n let _ =\n for i = 1 to n2 do\n phi'.(i).(0) <- i;\n for j = 1 to k do\n\tphi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)\n done;\n done;\n in\n let n3 = n /| Int64.of_int n2 in\n let (c, q) =\n let c = ref 0 in\n let q = ref 1 in\n while !c < k && !q * a.(!c) <= n2 do\n\tq := !q * a.(!c);\n\tincr c;\n done;\n (!c, !q)\n in\n let cnt = ref 0 in\n let cnt1 = ref 0 in\n let cnt2 = ref 0 in\n let cnt3 = ref 0 in\n let cnt4 = ref 0 in\n let rec phi m k =\n (*incr cnt;*)\n if k = 0\n then (\n (*incr cnt1;*)\n n /| m\n ) else if k = c then (\n (*incr cnt4;*)\n (n /| m /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)\n ) else if m > n3\n then (\n (*incr cnt2;*)\n Int64.of_int phi'.(Int64.to_int (n /| m)).(k)\n ) else (\n (*incr cnt3;*)\n phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)\n )\n in\n let res = phi 1L k in\n Printf.eprintf \"asd %d %d %d %d %d %d\\n\" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;\n Printf.printf \"%Ld\\n\" res\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make k 0 in\n let _ =\n for i = 0 to k - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n (*Array.sort (fun x y -> compare y x) a;*)\n Array.sort compare a;\n in\n let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in\n let sn = isqrt n in\n let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in\n let n2 = min 170000L n in\n let n2 = Int64.to_int n2 in\n let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in\n let _ =\n for i = 1 to n2 do\n phi'.(i).(0) <- i;\n for j = 1 to k do\n\tphi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)\n done;\n done;\n in\n let n3 = n /| Int64.of_int n2 in\n let (c, q) =\n let c = ref 0 in\n let q = ref 1 in\n while !c < k && !q * a.(!c) <= n2 do\n\tq := !q * a.(!c);\n\tincr c;\n done;\n (!c, !q)\n in\n let cnt = ref 0 in\n let cnt1 = ref 0 in\n let cnt2 = ref 0 in\n let cnt3 = ref 0 in\n let cnt4 = ref 0 in\n (*let rec phi m k =\n (*incr cnt;*)\n if k = 0\n then (\n (*incr cnt1;*)\n n /| m\n ) else if k = c then (\n (*incr cnt4;*)\n (n /| m /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)\n ) else if m > n3\n then (\n (*incr cnt2;*)\n Int64.of_int phi'.(Int64.to_int (n /| m)).(k)\n ) else (\n (*incr cnt3;*)\n phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)\n )\n in\n let res = phi 1L k in*)\n let rec phi32 n k =\n (*incr cnt;*)\n if k = 0\n then n\n else if k = c\n then (n / q) * phi'.(q).(k) + phi'.(n mod q).(c)\n else if n <= n2\n then phi'.(n).(k)\n else phi32 n (k - 1) - phi32 (n / a.(k - 1)) (k - 1)\n in\n let rec phi n k =\n if k = 0\n then n\n else if k = c\n then\n (n /| Int64.of_int q) *|\n\t Int64.of_int phi'.(q).(k) +|\n\t Int64.of_int\n\t\tphi'.(Int64.to_int (Int64.rem n (Int64.of_int q))).(c)\n else if n <= 1000000000L\n then Int64.of_int (phi32 (Int64.to_int n) k)\n else phi n (k - 1) -| phi (n /| Int64.of_int a.(k - 1)) (k - 1)\n in\n let res = phi n k in\n Printf.eprintf \"asd %d %d %d %d %d %d\\n\" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;\n Printf.printf \"%Ld\\n\" res\n"}], "negative_code": [], "src_uid": "cec0f6c267fa76191a3784b08e39acd6"} {"nl": {"description": "You are given an integer $$$n$$$. You have to apply $$$m$$$ operations to it.In a single operation, you must replace every digit $$$d$$$ of the number with the decimal representation of integer $$$d + 1$$$. For example, $$$1912$$$ becomes $$$21023$$$ after applying the operation once.You have to find the length of $$$n$$$ after applying $$$m$$$ operations. Since the answer can be very large, print it modulo $$$10^9+7$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of test cases. The only line of each test case contains two integers $$$n$$$ ($$$1 \\le n \\le 10^9$$$) and $$$m$$$ ($$$1 \\le m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the initial number and the number of operations. ", "output_spec": "For each test case output the length of the resulting number modulo $$$10^9+7$$$.", "sample_inputs": ["5\n1912 1\n5 6\n999 1\n88 2\n12 100"], "sample_outputs": ["5\n2\n6\n4\n2115"], "notes": "NoteFor the first test, $$$1912$$$ becomes $$$21023$$$ after $$$1$$$ operation which is of length $$$5$$$.For the second test, $$$5$$$ becomes $$$21$$$ after $$$6$$$ operations which is of length $$$2$$$.For the third test, $$$999$$$ becomes $$$101010$$$ after $$$1$$$ operation which is of length $$$6$$$.For the fourth test, $$$88$$$ becomes $$$1010$$$ after $$$2$$$ operations which is of length $$$4$$$."}, "positive_code": [{"source_code": "(* efficiency improvement to c0.ml *)\n(* no mod operators. No longs. Precompute all powers up to maxm *)\n(* if too slow, there are still other ways to make it faster *)\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\n(* The following trick allows you to do addition mod p = 1_000_000_007\n of two numbers which are in [0,p-1]. It works when the\n ints are 31 bits (and longer) *)\nlet p = 1_000_000_007\nlet ( +++ ) a b = let x = a+b in if x >= p || x < 0 then x-p else x\nlet sum i j f = fold i j (fun i a -> (f i) +++ a) 0\n\nlet mat = Array.make_matrix 10 10 0\nlet () =\n mat.(0).(9) <- 1;\n mat.(1).(9) <- 1;\n for i=1 to 9 do\n mat.(i).(i-1) <- 1\n done\n\nlet mat_row_form = Array.init 10 (fun i ->\n(* row i is a list of the indices where there's a 1 in mat *)\n fold 0 9 (fun j ac -> if mat.(i).(j) <> 0 then j::ac else ac) []\n) \n\nlet mult_by_mat a =\n (* use the fact that mat is sparse *)\n let c = Array.make_matrix 10 10 0 in\n for i=0 to 9 do\n for j=0 to 9 do\n c.(i).(j) <- List.fold_left (\n\tfun ac k -> ac +++ a.(k).(j)\n ) 0 mat_row_form.(i) \n done\n done;\n c\n\nlet rec diglist n ac = if n=0 then ac else diglist (n/10) ((n mod 10)::ac)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n let n = Array.make cases 0 in\n let m = Array.make cases 0 in \n \n for case = 0 to cases-1 do\n n.(case) <- read_int();\n m.(case) <- read_int();\n done;\n\n let maxm = maxf 0 (cases-1) (fun i -> m.(i)) in\n\n let power = Array.make (maxm+1) mat in\n (* power.(0) is wrong but is never used *)\n \n for i=2 to maxm do\n power.(i) <- mult_by_mat power.(i-1)\n done;\n\n for case = 0 to cases-1 do\n let dl = diglist n.(case) [] in\n let mymat = power.(m.(case)) in\n let count = Array.init 10 (fun j -> sum 0 9 (fun i -> mymat.(i).(j))) in\n (* count.(i) is the contribution of an initial digit i *)\n\n let answer = List.fold_left (fun ac d -> ac +++ count.(d)) 0 dl in\n printf \"%d\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "529cf248a86a5ec9c3b3fa8acf8805da"} {"nl": {"description": "Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: \"Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position\".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.", "input_spec": "The first line contains two non-negative numbers n and m (0\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105, 0\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105) \u2014 the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6\u00b7105. Each line consists only of letters 'a', 'b', 'c'.", "output_spec": "For each query print on a single line \"YES\" (without the quotes), if the memory of the mechanism contains the required string, otherwise print \"NO\" (without the quotes).", "sample_inputs": ["2 3\naaaaa\nacacaca\naabaa\nccacacc\ncaaac"], "sample_outputs": ["YES\nNO\nNO"], "notes": null}, "positive_code": [{"source_code": "type tree = Empty | Node of tree * tree * tree\n\nlet rec insert t str i len =\n if i=len then Node (Empty,Empty,Empty) else (\n let (ta,tb,tc) = match t with Empty -> (Empty,Empty,Empty) | Node (a,b,c) -> (a,b,c) in\n match str.[i] with \n | 'a' -> Node (insert ta str (i+1) len, tb, tc)\n | 'b' -> Node (ta, insert tb str (i+1) len, tc)\n | 'c' -> Node (ta, tb, insert tc str (i+1) len)\n | _ -> failwith \"bad input\"\n )\n\nlet rec search t str i len ecount =\n if ecount > 1 || t=Empty then false\n else if i=len then ecount=1 else (\n match t with Empty -> false\n | Node (ta,tb,tc) ->\n\tlet ec x = if str.[i]=x then 0 else 1 in\n\tsearch ta str (i+1) len (ecount + (ec 'a')) ||\n\t search tb str (i+1) len (ecount + (ec 'b')) ||\n\t search tc str (i+1) len (ecount + (ec 'c'))\n )\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let string = Array.init n (fun _ -> read_string()) in\n let query = Array.init m (fun _ -> read_string()) in\n\n let tree = Array.make (6*100_000+1) Empty in\n\n for i=0 to n-1 do\n let len = String.length string.(i) in\n tree.(len) <- insert tree.(len) string.(i) 0 len;\n done;\n\n for i=0 to m-1 do\n let len = String.length query.(i) in\n let ans = search tree.(len) query.(i) 0 len 0 in\n if ans then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}, {"source_code": "type 'a trie = {\n value : 'a option;\n children : 'a trie option array;\n}\n\nlet list_of_string s = Array.to_list (Array.init (String.length s) (String.get s))\n\n(* empty trie *)\nlet empty () =\n { value = None;\n children = Array.make 3 None;\n }\n\nlet insert t s =\n let rec insert' t p = function\n | [] -> { t with value = Some p }\n | c :: cs ->\n (* index into child array *)\n let i = Char.code c - Char.code 'a' in\n (* replacement node *)\n let n = match t.children.(i) with\n | None -> empty ()\n | Some t -> t\n in\n t.children.(i) <- Some (insert' n c cs);\n t\n in\n insert' t 'z' (list_of_string s)\n\nlet find t s =\n let rec find' t p c = function\n | [] -> c && t.value = Some p\n | x :: xs ->\n if c\n then begin\n match t.children.(Char.code x - Char.code 'a') with\n | None -> false\n | Some c -> find' c x true xs\n end\n else begin\n let rec aux a i =\n if i = 3 then a\n else\n match t.children.(i) with\n | None -> aux a (succ i)\n | Some t -> aux (a || find' t (Char.chr (i + Char.code 'a')) (Char.code x - Char.code 'a' <> i) xs) (succ i)\n in\n aux false 0\n end\n in\n find' t 'y' false (list_of_string s)\n\nlet () = Scanf.scanf \"%d %d\\n\" (fun n m ->\n (* read memory and construct trie *)\n let rec aux t i =\n if i = n then t else begin\n let t = Scanf.scanf \"%s\\n\" (insert t) in\n aux t (succ i)\n end\n in\n let t = aux (empty ()) 0 in\n\n (* read and response to queries *)\n for i = 1 to m do\n let q = Scanf.scanf \"%s\\n\" (fun s -> s) in\n print_endline (if find t q then \"YES\" else \"NO\")\n done\n)\n"}], "negative_code": [], "src_uid": "146c856f8de005fe280e87f67833c063"} {"nl": {"description": "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\u2009+\u20092 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.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105), 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.", "output_spec": "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.", "sample_inputs": ["5\naca\naba\naba\ncab\nbac", "4\nabc\nbCb\ncb1\nb13", "7\naaa\naaa\naaa\naaa\naaa\naaa\naaa"], "sample_outputs": ["YES\nabacaba", "NO", "YES\naaaaaaaaa"], "notes": null}, "positive_code": [{"source_code": "(* --- *)\nlet concat_chars cs = String.concat \"\" (List.map (String.make 1) cs)\n\nlet explode str =\n let exploded = ref [] in\n for i = String.length str - 1 downto 0 do\n exploded := str.[i] :: !exploded\n done ;\n !exploded\n\nlet split_on_char c str =\n let exploded = explode str in\n let cs', pending' =\n List.fold_right\n (fun x (ls, pending) ->\n match (x = c, pending) with\n | false, _ -> (ls, x :: pending)\n | true, [] -> (ls, pending)\n | true, _ -> (pending :: ls, []) )\n exploded ([], [])\n in\n List.map concat_chars (if pending' = [] then cs' else pending' :: cs')\n\n(* --- *)\nlet update h k f =\n Hashtbl.replace h k\n @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None\n\n(* --- *)\nexception InputError of string\n\nlet read_into_pair () =\n let e = read_line () |> String.trim in\n match explode e with\n | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)\n | _ -> raise @@ InputError \"unexpected input\"\n\n(* --- *)\nlet seqs_count = read_line () |> int_of_string\n\nlet degs = Hashtbl.create (62 * 62)\n\nlet adj = Hashtbl.create (62 * 62)\n\n;;\nfor i = 1 to seqs_count do\n let f', t', char_of_path = read_into_pair () in\n update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;\n update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;\n Hashtbl.add adj f' (t', char_of_path)\ndone\n\nlet find_eu start_v =\n let cir = ref [] in\n let rec h vertex =\n while Hashtbl.mem adj vertex do\n let next_vertex, char_of_path = Hashtbl.find adj vertex in\n Hashtbl.remove adj vertex ; h next_vertex\n done ;\n cir := vertex :: !cir\n in\n h start_v ;\n (* ensure it's connected *)\n if List.length !cir = seqs_count + 1 then (\n Printf.printf \"YES\\n\" ;\n Printf.printf \"%s\" start_v ;\n List.iter (fun s -> Printf.printf \"%c\" s.[1]) @@ List.tl !cir ;\n Printf.printf \"\\n\" )\n else Printf.printf \"NO\\n\"\n\nlet more_outgoings, more_ingoings, last_balanced =\n Hashtbl.fold\n (fun k d (more_outgoings, more_ingoings, last_balanced) ->\n if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)\n else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)\n else (more_outgoings, more_ingoings, Some k) )\n degs ([], [], None)\n\n;;\nmatch (more_outgoings, more_ingoings, last_balanced) with\n| [x], [y], _ when Hashtbl.find degs x = 1 && Hashtbl.find degs y = -1 ->\n find_eu x\n| [], [], Some x -> find_eu x\n| _ -> Printf.printf \"NO\\n\"\n"}, {"source_code": "(** a node is a string value and list\n * of outgoing edges *)\ntype node = {\n v : string;\n e : int list;\n i : int;\n o : int;\n}\nlet empty_node v = { v; e = []; i = 0; o = 0 }\n\n(** doubly-linked list element *)\ntype 'a el = {\n v : 'a;\n mutable next : 'a el option;\n mutable prev : 'a el option;\n}\n\nexception No_trail\n\nlet get_password edges nodes n =\n (* dlist of tour *)\n let dl = { v = n; next = None; prev = None } in\n (* end of list *)\n let tl = ref dl in\n\n (* get the initial trail *)\n let rec trail n tl =\n let node = Hashtbl.find nodes n in\n match node.e with\n | e :: es ->\n let e = String.sub edges.(e) 1 2 in\n let el = { v = e; next = None; prev = Some !tl } in\n !tl.next <- Some el;\n tl := el;\n Hashtbl.replace nodes n { node with e = es };\n trail e tl\n | [] -> ()\n in\n trail n tl;\n\n (* build the final password *)\n let rec build n =\n (* follow any further edges from this node\n * if necessary *)\n let next = n.next in\n let tl = ref n in\n trail n.v tl;\n (* check that we generated a cycle *)\n if !tl.v = n.v then\n !tl.next <- next\n else\n raise No_trail;\n\n match n.next with\n | None -> ()\n | Some n -> build n\n in\n build dl;\n dl\n\nlet rec print_password p =\n match p.next with\n | None -> ()\n | Some n ->\n print_char n.v.[1];\n print_password n\n\nlet () = Scanf.scanf \"%d\\n\" (fun n ->\n (* read all 3-letter substrings (edges of the graph) *)\n let edges = Array.init n (fun _ -> Scanf.scanf \"%s\\n\" (fun e -> e)) in\n (* adjacency list\n * - maps node to a list of\n * indices into the edges array\n *)\n let nodes = Hashtbl.create n in\n Array.iteri (fun i e ->\n (* start and end nodes of the edge *)\n let hd = String.sub e 0 2\n and tl = String.sub e 1 2 in\n let hd_node =\n if Hashtbl.mem nodes hd\n then Hashtbl.find nodes hd\n else (empty_node hd)\n in\n let hd_node = { hd_node with\n e = (i :: hd_node.e);\n o = (hd_node.o + 1);\n } in\n Hashtbl.replace nodes hd hd_node;\n let tl_node =\n if Hashtbl.mem nodes tl\n then Hashtbl.find nodes tl\n else (empty_node tl)\n in\n Hashtbl.replace nodes tl { tl_node with i = (tl_node.i + 1) }\n ) edges;\n (* find nodes with odd degree *)\n let (i, o) = Hashtbl.fold (fun n v (i, o) ->\n match v.o - v.i with\n | 1 -> i, n :: o\n | -1 -> n :: i, o\n | _ -> i, o\n ) nodes ([], [])\n in\n let start = match o with\n | [n] -> Some n\n | [] -> Some (String.sub edges.(0) 0 2)\n | _ -> None\n in\n match start with\n | None -> print_endline \"NO\"\n | Some n ->\n try\n let p = get_password edges nodes n in\n let disjoint = Hashtbl.fold (fun _ v b ->\n b || List.length v.e > 0\n ) nodes false\n in\n if disjoint\n then print_endline \"NO\"\n else begin\n print_endline \"YES\";\n print_string (String.sub n 0 2);\n print_password p;\n print_char '\\n'\n end\n with\n | No_trail -> print_endline \"NO\"\n)\n"}], "negative_code": [{"source_code": "(* --- *)\nlet concat_chars cs = String.concat \"\" (List.map (String.make 1) cs)\n\nlet explode str =\n let exploded = ref [] in\n for i = String.length str - 1 downto 0 do\n exploded := str.[i] :: !exploded\n done ;\n !exploded\n\nlet split_on_char c str =\n let exploded = explode str in\n let cs', pending' =\n List.fold_right\n (fun x (ls, pending) ->\n match (x = c, pending) with\n | false, _ -> (ls, x :: pending)\n | true, [] -> (ls, pending)\n | true, _ -> (pending :: ls, []) )\n exploded ([], [])\n in\n List.map concat_chars (if pending' = [] then cs' else pending' :: cs')\n\n(* --- *)\nlet update h k f =\n Hashtbl.replace h k\n @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None\n\n(* --- *)\nexception InputError of string\n\nlet read_into_pair () =\n let e = read_line () |> String.trim in\n match explode e with\n | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)\n | _ -> raise @@ InputError \"unexpected input\"\n\n(* --- *)\nlet seqs_count = read_line () |> int_of_string\n\nlet degs = Hashtbl.create (62 * 62)\n\nlet adj = Hashtbl.create (62 * 62)\n\n;;\nfor i = 1 to seqs_count do\n let f', t', char_of_path = read_into_pair () in\n update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;\n update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;\n Hashtbl.add adj f' (t', char_of_path)\ndone\n\nlet find_eu start_v =\n let cir = ref [] in\n let rec h vertex =\n while Hashtbl.mem adj vertex do\n let next_vertex, char_of_path = Hashtbl.find adj vertex in\n Hashtbl.remove adj vertex ; h next_vertex\n done ;\n cir := vertex :: !cir\n in\n h start_v ;\n if List.length !cir = seqs_count + 1 then (\n Printf.printf \"YES\\n\" ;\n Printf.printf \"%s\" start_v ;\n List.iter (fun s -> Printf.printf \"%c\" s.[1]) @@ List.tl !cir ;\n Printf.printf \"\\n\" )\n else Printf.printf \"NO\\n\"\n\nlet more_outgoings, more_ingoings, last_balanced =\n Hashtbl.fold\n (fun k d (more_outgoings, more_ingoings, last_balanced) ->\n if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)\n else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)\n else (more_outgoings, more_ingoings, Some k) )\n degs ([], [], None)\n\n;;\nmatch (more_outgoings, more_ingoings, last_balanced) with\n| [x], [_], _ -> find_eu x\n| [], [], Some x -> find_eu x\n| _ -> Printf.printf \"NO\\n\"\n"}, {"source_code": "(* --- *)\nlet concat_chars cs = String.concat \"\" (List.map (String.make 1) cs)\n\nlet explode str =\n let exploded = ref [] in\n for i = String.length str - 1 downto 0 do\n exploded := str.[i] :: !exploded\n done ;\n !exploded\n\nlet split_on_char c str =\n let exploded = explode str in\n let cs', pending' =\n List.fold_right\n (fun x (ls, pending) ->\n match (x = c, pending) with\n | false, _ -> (ls, x :: pending)\n | true, [] -> (ls, pending)\n | true, _ -> (pending :: ls, []) )\n exploded ([], [])\n in\n List.map concat_chars (if pending' = [] then cs' else pending' :: cs')\n\n(* --- *)\nlet update h k f =\n Hashtbl.replace h k\n @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None\n\n(* --- *)\nexception InputError of string\n\nlet read_into_pair () =\n let e = read_line () |> String.trim in\n match explode e with\n | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)\n | _ -> raise @@ InputError \"unexpected input\"\n\n(* --- *)\nlet seqs_count = read_line () |> int_of_string\n\nlet degs = Hashtbl.create (62 * 62)\n\nlet adj = Hashtbl.create (62 * 62)\n\n;;\nfor i = 1 to seqs_count do\n let f', t', char_of_path = read_into_pair () in\n update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;\n update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;\n Hashtbl.add adj f' (t', char_of_path)\ndone\n\nlet find_eu start_v =\n Printf.printf \"YES\\n\" ;\n Printf.printf \"%s\" start_v ;\n let rec h vertex =\n while Hashtbl.mem adj vertex do\n let next_vertex, char_of_path = Hashtbl.find adj vertex in\n Hashtbl.remove adj vertex ;\n Printf.printf \"%c\" char_of_path ;\n h next_vertex\n done\n in\n h start_v ; Printf.printf \"\\n\"\n\nlet more_outgoings, more_ingoings, last_balanced =\n Hashtbl.fold\n (fun k d (more_outgoings, more_ingoings, last_balanced) ->\n if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)\n else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)\n else (more_outgoings, more_ingoings, Some k) )\n degs ([], [], None)\n\n;;\nmatch (more_outgoings, more_ingoings, last_balanced) with\n| [x], [_], _ -> find_eu x\n| [], [], Some x -> find_eu x\n| _ -> Printf.printf \"NO\\n\"\n"}, {"source_code": "(* --- *)\nlet concat_chars cs = String.concat \"\" (List.map (String.make 1) cs)\n\nlet explode str =\n let exploded = ref [] in\n for i = String.length str - 1 downto 0 do\n exploded := str.[i] :: !exploded\n done ;\n !exploded\n\nlet split_on_char c str =\n let exploded = explode str in\n let cs', pending' =\n List.fold_right\n (fun x (ls, pending) ->\n match (x = c, pending) with\n | false, _ -> (ls, x :: pending)\n | true, [] -> (ls, pending)\n | true, _ -> (pending :: ls, []) )\n exploded ([], [])\n in\n List.map concat_chars (if pending' = [] then cs' else pending' :: cs')\n\n(* --- *)\nlet update h k f =\n Hashtbl.replace h k\n @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None\n\n(* --- *)\nexception InputError of string\n\nlet read_into_pair () =\n let e = read_line () |> String.trim in\n match explode e with\n | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)\n | _ -> raise @@ InputError \"unexpected input\"\n\n(* --- *)\nlet seqs_count = read_line () |> int_of_string\n\nlet degs = Hashtbl.create (62 * 62)\n\nlet adj = Hashtbl.create (62 * 62)\n\n;;\nfor i = 1 to seqs_count do\n let f', t', char_of_path = read_into_pair () in\n update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;\n update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;\n Hashtbl.add adj f' (t', char_of_path)\ndone\n\nlet find_eu start_v =\n Printf.printf \"YES\\n\" ;\n Printf.printf \"%s\" start_v;\n let cir = ref [] in\n let rec h vertex =\n while Hashtbl.mem adj vertex do\n let next_vertex, char_of_path = Hashtbl.find adj vertex in\n Hashtbl.remove adj vertex ; h next_vertex\n done ;\n cir := vertex :: !cir\n in\n h start_v ;\n List.iter (fun s -> Printf.printf \"%c\" s.[1]) @@ List.tl !cir ;\n Printf.printf \"\\n\"\n\nlet more_outgoings, more_ingoings, last_balanced =\n Hashtbl.fold\n (fun k d (more_outgoings, more_ingoings, last_balanced) ->\n if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)\n else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)\n else (more_outgoings, more_ingoings, Some k) )\n degs ([], [], None)\n\n;;\nmatch (more_outgoings, more_ingoings, last_balanced) with\n| [x], [_], _ -> find_eu x\n| [], [], Some x -> find_eu x\n| _ -> Printf.printf \"NO\\n\"\n"}, {"source_code": "(* --- *)\nlet concat_chars cs = String.concat \"\" (List.map (String.make 1) cs)\n\nlet explode str =\n let exploded = ref [] in\n for i = String.length str - 1 downto 0 do\n exploded := str.[i] :: !exploded\n done ;\n !exploded\n\nlet split_on_char c str =\n let exploded = explode str in\n let cs', pending' =\n List.fold_right\n (fun x (ls, pending) ->\n match (x = c, pending) with\n | false, _ -> (ls, x :: pending)\n | true, [] -> (ls, pending)\n | true, _ -> (pending :: ls, []) )\n exploded ([], [])\n in\n List.map concat_chars (if pending' = [] then cs' else pending' :: cs')\n\n(* --- *)\nlet update h k f =\n Hashtbl.replace h k\n @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None\n\n(* --- *)\nexception InputError of string\n\nlet read_into_pair () =\n let e = read_line () |> String.trim in\n match explode e with\n | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)\n | _ -> raise @@ InputError \"unexpected input\"\n\n(* --- *)\nlet seqs_count = read_line () |> int_of_string\n\nlet degs = Hashtbl.create (62 * 62)\n\nlet adj = Hashtbl.create (62 * 62)\n\n;;\nfor i = 1 to seqs_count do\n let f', t', char_of_path = read_into_pair () in\n update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;\n update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;\n Hashtbl.add adj f' (t', char_of_path)\ndone\n\nlet find_eu start_v =\n Printf.printf \"YES\\n\" ;\n Printf.printf \"%s\" start_v ;\n let acc = ref [] in\n let rec h vertex =\n while Hashtbl.mem adj vertex do\n let next_vertex, char_of_path = Hashtbl.find adj vertex in\n Hashtbl.remove adj vertex ;\n acc := char_of_path :: !acc ;\n h next_vertex\n done\n in\n h start_v ;\n List.iter (fun c -> Printf.printf \"%c\" c) !acc ;\n Printf.printf \"\\n\"\n\nlet more_outgoings, more_ingoings, last_balanced =\n Hashtbl.fold\n (fun k d (more_outgoings, more_ingoings, last_balanced) ->\n if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)\n else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)\n else (more_outgoings, more_ingoings, Some k) )\n degs ([], [], None)\n\n;;\nmatch (more_outgoings, more_ingoings, last_balanced) with\n| [x], [_], _ -> find_eu x\n| [], [], Some x -> find_eu x\n| _ -> Printf.printf \"NO\\n\"\n"}, {"source_code": "(** a node is a string value and list\n * of outgoing edges *)\ntype node = {\n v : string;\n e : int list;\n i : int;\n o : int;\n}\nlet empty_node v = { v; e = []; i = 0; o = 0 }\n\n(** doubly-linked list element *)\ntype 'a el = {\n v : 'a;\n mutable next : 'a el option;\n mutable prev : 'a el option;\n}\n\nlet get_password edges nodes n =\n (* dlist of tour *)\n let dl = { v = n; next = None; prev = None } in\n (* end of list *)\n let tl = ref dl in\n\n (* get the initial trail *)\n let rec trail n tl =\n let node = Hashtbl.find nodes n in\n match node.e with\n | e :: es ->\n let e = String.sub edges.(e) 1 2 in\n let el = { v = e; next = None; prev = Some !tl } in\n !tl.next <- Some el;\n tl := el;\n Hashtbl.replace nodes n { node with e = es };\n trail e tl\n | [] -> ()\n in\n trail n tl;\n\n (* print the final password *)\n let rec print n =\n print_char n.v.[1];\n\n (* follow any further edges from this node\n * if necessary *)\n let next = n.next in\n let tl = ref n in\n trail n.v tl;\n !tl.next <- next;\n\n match n.next with\n | None -> ()\n | Some n -> print n\n in\n print dl;\n print_char '\\n'\n\nlet () = Scanf.scanf \"%d\\n\" (fun n ->\n (* read all 3-letter substrings (edges of the graph) *)\n let edges = Array.init n (fun _ -> Scanf.scanf \"%s\\n\" (fun e -> e)) in\n (* adjacency list\n * - maps node to a list of\n * indices into the edges array\n *)\n let nodes = Hashtbl.create n in\n Array.iteri (fun i e ->\n (* start and end nodes of the edge *)\n let hd = String.sub e 0 2\n and tl = String.sub e 1 2 in\n let hd_node =\n if Hashtbl.mem nodes hd\n then Hashtbl.find nodes hd\n else (empty_node hd)\n in\n let hd_node = { hd_node with\n e = (i :: hd_node.e);\n o = (hd_node.o + 1);\n } in\n Hashtbl.replace nodes hd hd_node;\n let tl_node =\n if Hashtbl.mem nodes tl\n then Hashtbl.find nodes tl\n else (empty_node tl)\n in\n Hashtbl.replace nodes tl { tl_node with i = (tl_node.i + 1) }\n ) edges;\n (* find nodes with odd degree *)\n let (i, o) = Hashtbl.fold (fun n v (i, o) ->\n match v.o - v.i with\n | 1 -> i, n :: o\n | -1 -> n :: i, o\n | _ -> i, o\n ) nodes ([], [])\n in\n let start = match o with\n | [n] -> Some n\n | [] -> Some (String.sub edges.(0) 0 2)\n | _ -> None\n in\n match start with\n | None -> print_endline \"NO\"\n | Some n ->\n print_endline \"YES\";\n print_char n.[0];\n get_password edges nodes n\n)\n"}, {"source_code": "let get_password edges nodes s =\n print_string s;\n let rec printer s =\n match Hashtbl.find nodes s with\n | hd :: tl ->\n let e = edges.(hd) in\n print_char e.[2];\n Hashtbl.replace nodes s tl;\n printer (String.sub e 1 2)\n | [] -> () (* done *)\n in\n printer s;\n print_endline \"\"\n\nlet () =\n Scanf.scanf \"%d\\n\" (fun n ->\n (* array of edges *)\n let edges = Array.init n (fun _ -> Scanf.scanf \"%s\\n\" (fun l -> l)) in\n (* adjacency list *)\n let nodes = Hashtbl.create n in\n (* degree of each node *)\n let degree = Hashtbl.create n in\n (* add edges to adjacency list and\n * calculate the degree of nodes *)\n Array.iteri (fun i s ->\n (* start of edge *)\n let hd = String.sub s 0 2\n (* end of edge *)\n and tl = String.sub s 1 2 in\n (* add edge to adjacency list *)\n let edges =\n if Hashtbl.mem nodes hd\n then Hashtbl.find nodes hd\n else []\n in\n Hashtbl.replace nodes hd (i :: edges);\n if not (Hashtbl.mem nodes tl)\n then Hashtbl.add nodes tl [];\n (* increase out degree of start node *)\n let (i, o) =\n if Hashtbl.mem degree hd\n then Hashtbl.find degree hd\n else (0, 0)\n in\n Hashtbl.replace degree hd (i, o + 1);\n (* increase in degree of end node *)\n let (i, o) =\n if Hashtbl.mem degree tl\n then Hashtbl.find degree tl\n else (0, 0)\n in\n Hashtbl.replace degree tl (i + 1, o)\n ) edges;\n (* a directed graph has an Eulerian trail iff at\n * most one node each has o-i = 1 and i-o = 1.\n * fold over the hashtbl to find these nodes *)\n let (inl, outl) =\n Hashtbl.fold (fun s (i, o) (inl, outl) ->\n match o - i with\n | 1 -> (inl, s :: outl)\n | -1 -> (s :: inl, outl)\n | _ -> (inl, outl)\n ) degree ([], [])\n in\n let start = match outl with\n | [s] -> Some s\n | [] -> Some (String.sub edges.(0) 0 2)\n | _ -> None\n in\n match start with\n | Some s -> print_endline \"YES\"; get_password edges nodes s\n | None -> print_endline \"NO\"\n )\n"}, {"source_code": "(** a node is a string value and list\n * of outgoing edges *)\ntype node = {\n v : string;\n e : int list;\n i : int;\n o : int;\n}\nlet empty_node v = { v; e = []; i = 0; o = 0 }\n\n(** doubly-linked list element *)\ntype 'a el = {\n v : 'a;\n mutable next : 'a el option;\n mutable prev : 'a el option;\n}\n\nlet get_password edges nodes n =\n (* dlist of tour *)\n let dl = { v = n; next = None; prev = None } in\n (* end of list *)\n let tl = ref dl in\n\n (* get the initial trail *)\n let rec trail n tl =\n let node = Hashtbl.find nodes n in\n match node.e with\n | e :: es ->\n let e = String.sub edges.(e) 1 2 in\n let el = { v = e; next = None; prev = Some !tl } in\n !tl.next <- Some el;\n tl := el;\n Hashtbl.replace nodes n { node with e = es };\n trail e tl\n | [] -> ()\n in\n trail n tl;\n\n (* build the final password *)\n let rec build n =\n (* follow any further edges from this node\n * if necessary *)\n let next = n.next in\n let tl = ref n in\n trail n.v tl;\n !tl.next <- next;\n\n match n.next with\n | None -> ()\n | Some n -> build n\n in\n build dl;\n dl\n\nlet rec print_password p =\n match p.next with\n | None -> ()\n | Some n ->\n print_char n.v.[1];\n print_password n\n\nlet () = Scanf.scanf \"%d\\n\" (fun n ->\n (* read all 3-letter substrings (edges of the graph) *)\n let edges = Array.init n (fun _ -> Scanf.scanf \"%s\\n\" (fun e -> e)) in\n (* adjacency list\n * - maps node to a list of\n * indices into the edges array\n *)\n let nodes = Hashtbl.create n in\n Array.iteri (fun i e ->\n (* start and end nodes of the edge *)\n let hd = String.sub e 0 2\n and tl = String.sub e 1 2 in\n let hd_node =\n if Hashtbl.mem nodes hd\n then Hashtbl.find nodes hd\n else (empty_node hd)\n in\n let hd_node = { hd_node with\n e = (i :: hd_node.e);\n o = (hd_node.o + 1);\n } in\n Hashtbl.replace nodes hd hd_node;\n let tl_node =\n if Hashtbl.mem nodes tl\n then Hashtbl.find nodes tl\n else (empty_node tl)\n in\n Hashtbl.replace nodes tl { tl_node with i = (tl_node.i + 1) }\n ) edges;\n (* find nodes with odd degree *)\n let (i, o) = Hashtbl.fold (fun n v (i, o) ->\n match v.o - v.i with\n | 1 -> i, n :: o\n | -1 -> n :: i, o\n | _ -> i, o\n ) nodes ([], [])\n in\n let start = match o with\n | [n] -> Some n\n | [] -> Some (String.sub edges.(0) 0 2)\n | _ -> None\n in\n match start with\n | None -> print_endline \"NO\"\n | Some n ->\n let p = get_password edges nodes n in\n let disjoint = Hashtbl.fold (fun _ v b ->\n b || List.length v.e > 0\n ) nodes false\n in\n if disjoint\n then print_endline \"NO\"\n else begin\n print_endline \"YES\";\n print_string (String.sub n 0 2);\n print_password p;\n print_char '\\n'\n end\n)\n"}], "src_uid": "02845c8982a7cb6d29905d117c4a1079"} {"nl": {"description": "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$$$)", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 20$$$) \u2014 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$$$) \u2014 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$$$.", "output_spec": "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).", "sample_inputs": ["4\n6\n3 7 1 4 1 2\n3 7 3 6 3 2\n5\n1 1 1 1 1\n1 2 1 3 1\n2\n42 42\n42 42\n1\n7\n6"], "sample_outputs": ["YES\nNO\nYES\nNO"], "notes": "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."}, "positive_code": [{"source_code": "let rec check l l' r b =\n match l,l',r with\n | [],[],_ -> true\n | x::l,y::l',None ->\n if x = y then check l l' None b\n else\n if b then false\n else if x < y then\n check l l' (Some (y -x)) true\n else\n false\n | x::l,y::l', Some r ->\n if x = y then check l l' None true\n else if r = y - x then\n check l l' (Some r) true\n else false\n | _ -> assert false\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let _ = int_of_string (input_line stdin) in\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n let r = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n if check l r None false then\n Format.printf \"YES@.\"\n else\n Format.printf \"NO@.\"\n done\n"}], "negative_code": [], "src_uid": "0e0ef011ebe7198b7189fce562b7d6c1"} {"nl": {"description": "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.", "input_spec": "The first line will contain an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009300\u2009000), the number of points. The next n lines will contain two tokens pi and ci (pi is an integer, 1\u2009\u2264\u2009pi\u2009\u2264\u2009109, 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.", "output_spec": "Print a single integer, the minimum cost way to solve the problem.", "sample_inputs": ["4\n1 G\n5 R\n10 B\n15 G", "4\n1 G\n2 R\n3 B\n10 G"], "sample_outputs": ["23", "12"], "notes": "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."}, "positive_code": [{"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let where = Array.make n 0L in\n let green = Array.make (n+1) (-1) in\n let ngreen = ref 1 in \n let bluelist = Array.make (n+1) [] in\n let redlist = Array.make (n+1) [] in\n\n for i=0 to n-1 do\n where.(i) <- long (read_int());\n match (read_string()).[0] with\n | 'G' -> \n\tgreen.(!ngreen) <- i;\n\tngreen := 1 + !ngreen\n | 'B' ->\n\tbluelist.(!ngreen-1) <- i::bluelist.(!ngreen-1)\n | 'R' ->\n\tredlist.(!ngreen-1) <- i::redlist.(!ngreen-1)\n | _ -> failwith \"bad color\"\n done;\n\n let ngreen = !ngreen in (* counts the extra fake green point at the start *)\n\n for j=0 to ngreen-1 do\n bluelist.(j) <- List.rev bluelist.(j);\n redlist.(j) <- List.rev redlist.(j);\n done;\n\n (* functions for non-empty list li *)\n let first li = where.(List.hd li) in\n let last li = let n = List.length li in where.(List.nth li (n-1)) in\n\n let maxgap g0 g1 li =\n (* g0 and g1 are green coordinates that surround the list (of indices).\n This returns the maximum gap in the sequence [g0,li,g1] *)\n if li = [] then g1 -- g0 else\n let rec findbig li ac =\n\tmatch li with\n\t | [] -> failwith \"bad list\"\n\t | _::[] -> ac\n\t | i::((j::_) as tail) ->\n\t let ac = max ac (where.(j) -- where.(i)) in\n\t findbig tail ac\n in\n max (findbig li 0L) (max ((first li) -- g0) (g1 -- (last li)))\n in\n \n let answer = \n if ngreen = 1 then (* no green points *)\n let cost li = if li = [] then 0L else (last li) -- (first li) in \n (cost bluelist.(0)) ++ (cost redlist.(0))\n else (\n (* end cases *)\n let stcost li = if li = [] then 0L else where.(green.(1)) -- (first li) in\n let startcost = (stcost bluelist.(0)) ++ (stcost redlist.(0)) in\n \n let encost li = if li = [] then 0L else (last li) -- where.(green.(ngreen-1)) in\n let endcost = (encost bluelist.(ngreen-1)) ++ (encost redlist.(ngreen-1)) in\n \n (* now do the middle cases, surrounded by two green points *)\n \n startcost ++ endcost ++\n\tsum 1 (ngreen-2) (fun j -> (*the two neighboring green points are j and j+1*)\n\t let (g0,g1) = (where.(green.(j)),where.(green.(j+1))) in\n\t let option1 =\n\t 3L**(g1--g0) -- (maxgap g0 g1 bluelist.(j)) -- (maxgap g0 g1 redlist.(j))\n\t in\n\t let option2 = 2L**(g1--g0) in\n\t min option1 option2\n\t) \n )\n in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "ebb9e236b6370a9cba9ffcd77fe4c97e"} {"nl": {"description": "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,\u2009i,\u2009r1,\u2009i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2,\u2009i,\u2009r2,\u2009i).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,\u2009r1) and (l2,\u2009r2) 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\u2009-\u2009j|, where l1\u2009\u2264\u2009i\u2009\u2264\u2009r1 and l2\u2009\u2264\u2009j\u2009\u2264\u2009r2. 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!", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1,\u2009i and r1,\u2009i (1\u2009\u2264\u2009l1,\u2009i\u2009\u2264\u2009r1,\u2009i\u2009\u2264\u2009109)\u00a0\u2014 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\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2,\u2009i and r2,\u2009i (1\u2009\u2264\u2009l2,\u2009i\u2009\u2264\u2009r2,\u2009i\u2009\u2264\u2009109)\u00a0\u2014 the i-th variant of a period of time when Anton can attend programming classes.", "output_spec": "Output one integer\u00a0\u2014 the maximal possible distance between time periods.", "sample_inputs": ["3\n1 5\n2 6\n2 3\n2\n2 4\n6 8", "3\n1 5\n2 6\n3 7\n2\n2 4\n1 4"], "sample_outputs": ["3", "0"], "notes": "NoteIn the first sample Anton can attend chess classes in the period (2,\u20093) and attend programming classes in the period (6,\u20098). 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."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %Ld %Ld \" (fun x y -> (x,y))\n \nlet () = \n let n = read_int () in\n let a1 = Array.init n read_pair in\n let m = read_int () in \n let a2 = Array.init m read_pair in\n\n let min_right1 = minf 0 (n-1) (fun i -> snd a1.(i)) in\n let max_left2 = maxf 0 (m-1) (fun i -> fst a2.(i)) in\n let opt1 = max 0L (max_left2 -- min_right1) in\n\n let min_right2 = minf 0 (m-1) (fun i -> snd a2.(i)) in\n let max_left1 = maxf 0 (n-1) (fun i -> fst a1.(i)) in\n let opt2 = max 0L (max_left1 -- min_right2) in\n\n printf \"%Ld\\n\" (max opt1 opt2)\n"}], "negative_code": [], "src_uid": "4849a1f65afe69aad12c010302465ccd"} {"nl": {"description": "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,\u2009j) of glasses in the shelf such that i\u2009<\u2009j 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.", "input_spec": "The first line of input contains numbers n and q (1\u2009\u2264\u2009n,\u2009q\u2009\u2264\u20092\u2009\u00d7\u2009105), the number of different kinds of beer and number of queries. The next line contains n space separated integers, a1,\u2009a2,\u2009... ,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20095\u2009\u00d7\u2009105), 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\u2009\u2264\u2009x\u2009\u2264\u2009n), the index of a beer that should be added or removed from the shelf.", "output_spec": "For each query, print the answer for that query in one line.", "sample_inputs": ["5 6\n1 2 3 4 6\n1\n2\n3\n4\n5\n1"], "sample_outputs": ["0\n1\n3\n5\n6\n2"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet fmax = 500_001\n\nlet factors n =\n let rec aux i p =\n(* Printf.printf \"%d, %d\\n\" i p; *)\n if p = 1 then []\n else if i*i > p then [p]\n else if p mod i = 0 then i::(match aux i (p/i) with i'::is when i=i' -> is | is -> is)\n else aux (i+1) p\n in\n aux 2 n\n\n(* Mike and Foam *)\n\nlet _ =\n let n = read_int () in\n let q = read_int () in\n let beers = Array.init n (fun _ -> read_int ()) in\n let queries = Array.init q (fun _ -> read_int ()) in\n let slots = Array.make fmax 0 in\n let pres = Array.make n false in\n let register sc n =\n let rec it prod = function\n | [] -> ()\n | l::ls -> count (prod*l) ls; it prod ls\n and count prod l =\n slots.(prod) <- slots.(prod)+sc;\n it prod l\n in\n count 1 (factors n)\n in\n let count n =\n let rec count prod l =\n slots.(prod) - it prod l\n and it prod = function\n | [] -> 0\n | l::ls -> count (prod * l) ls + it prod ls\n in\n count 1 (factors n)\n in\n let cur = ref (Int64.zero) in\n for i = 0 to q - 1 do\n (* How many things does it intersect with ? *)\n (* Oops, check presence + the '1' problem *)\n let beer = queries.(i) - 1 in\n let foam = beers.(beer) in\n let score =\n if pres.(beer) then (register (-1) foam; - count foam)\n else (let r = count foam in register 1 foam; r)\n in\n pres.(beer) <- not pres.(beer);\n cur := Int64.add !cur (Int64.of_int score);\n Printf.printf \"%Ld\\n\" !cur\n done\n\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet fmax = 500_001\n\nlet factors n =\n let rec aux i p =\n(* Printf.printf \"%d, %d\\n\" i p; *) \n if p = 1 then []\n else if i*i > p then [p]\n else if p mod i = 0 then i::(match aux i (p/i) with i'::is when i=i' -> is | is -> is)\n else aux (i+1) p\n in\n aux 2 n\n\n(* Mike and Foam *)\n\nlet _ =\n let n = read_int () in\n let q = read_int () in\n let beers = Array.init n (fun _ -> read_int ()) in\n let queries = Array.init q (fun _ -> read_int ()) in\n let slots = Array.make fmax 0 in\n let pres = Array.make n false in\n let register sc n =\n let rec it prod = function\n | [] -> ()\n | l::ls -> count (prod*l) ls; it prod ls\n and count prod l =\n slots.(prod) <- slots.(prod)+sc;\n it prod l\n in\n count 1 (factors n)\n in\n let count n =\n let rec count prod l =\n slots.(prod) - it prod l\n and it prod = function\n | [] -> 0\n | l::ls -> count (prod * l) ls + it prod ls\n in\n count 1 (factors n)\n in\n let cur = ref (Int64.zero) in\n for i = 0 to q - 1 do\n (* How many things does it intersect with ? *)\n (* Oops, check presence + the '1' problem *)\n let beer = queries.(i) - 1 in\n let foam = beers.(beer) in\n let score =\n if pres.(beer) then (register (-1) foam; - count foam)\n else (let r = count foam in register 1 foam; r)\n in\n pres.(beer) <- not pres.(beer);\n cur := Int64.add !cur (Int64.of_int score);\n Printf.printf \"%Ld\\n\" !cur\n done"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet fmax = 500_001\n\nlet factors n =\n let rec aux i p =\n(* Printf.printf \"%d, %d\\n\" i p; *)\n if p = 1 then []\n else if i*i > p then [p]\n else if p mod i = 0 then i::(match aux i (p/i) with i'::is when i=i' -> is | is -> is)\n else aux (i+1) p\n in\n aux 2 n\n\n(* Mike and Foam *)\n\nlet _ =\n let n = read_int () in\n let q = read_int () in\n let beers = Array.init n (fun _ -> read_int ()) in\n let queries = Array.init q (fun _ -> read_int ()) in\n let slots = Array.make fmax 0 in\n let pres = Array.make n false in\n let register sc n =\n let rec it prod = function\n | [] -> ()\n | l::ls -> count (prod*l) ls; it prod ls\n and count prod l =\n slots.(prod) <- slots.(prod)+sc;\n it prod l\n in\n count 1 (factors n)\n in\n let count n =\n let rec count prod l =\n slots.(prod) - it prod l\n and it prod = function\n | [] -> 0\n | l::ls -> count (prod * l) ls + it prod ls\n in\n count 1 (factors n)\n in\n let cur = ref (Int64.zero) in\n for i = 0 to q - 1 do\n (* How many things does it intersect with ? *)\n (* Oops, check presence + the '1' problem *)\n let beer = queries.(i) - 1 in\n let foam = beers.(beer) in\n let score =\n if pres.(beer) then (register (-1) foam; - count foam)\n else (let r = count foam in register 1 foam; r)\n in\n pres.(beer) <- not pres.(beer);\n cur := Int64.add !cur (Int64.of_int score);\n Printf.printf \"%Ld\\n\" !cur\n done"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n2 = 500000 in\n let prime = Array.make (n2 + 1) true in\n let p = Array.make (n2 + 1) 0 in\n let pd = Array.make (n2 + 1) [] in\n let pk = ref 0 in\n let () =\n for i = 2 to n2 do\n if prime.(i) then (\n\tp.(!pk) <- i;\n\tincr pk;\n\tpd.(i) <- [i];\n\tlet j = ref (2 * i) in\n while !j <= n2 do\n\t let jj = !j in\n prime.(jj) <- false;\n\t pd.(jj) <- i :: pd.(jj);\n j := jj + i\n done\n )\n done;\n in\n let pk = !pk - 1 in\n let pd = Array.map Array.of_list pd in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let q = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = Array.make (n2 + 1) false in\n let d = Array.make (n2 + 1) 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let res = ref 0L in\n for i = 1 to q do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (s, ofs) =\n\tif b.(x) then (\n\t b.(x) <- false;\n\t (-1, 1)\n\t) else (\n\t b.(x) <- true;\n\t (1, 0)\n\t)\n in\n let x = a.(x - 1) in\n let ds = pd.(x) in\n let k = Array.length ds in\n\tfor i = 0 to 1 lsl k - 1 do\n\t let y = ref 1 in\n\t let c = ref 0 in\n\t for j = 0 to k - 1 do\n\t if i land (1 lsl j) <> 0 then (\n\t\ty := !y * ds.(j);\n\t\tincr c\n\t )\n\t done;\n\t if !c land 1 = 0\n\t then res := Int64.add !res (Int64.of_int (s * (d.(!y) - ofs)))\n\t else res := Int64.sub !res (Int64.of_int (s * (d.(!y) - ofs)));\n\t d.(!y) <- d.(!y) + s;\n\tdone;\n\tPrintf.printf \"%Ld\\n\" !res;\n done;\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet fmax = 500_001\n\nlet factors n =\n let rec aux i p =\n(* Printf.printf \"%d, %d\\n\" i p; *)\n if p = 1 then []\n else if i*i > p then [p]\n else if p mod i = 0 then i::(match aux i (p/i) with i'::is when i=i' -> is | is -> is)\n else aux (i+1) p\n in\n aux 2 n\n\n(* Mike and Foam *)\n\nlet _ =\n let n = read_int () in\n let q = read_int () in\n let beers = Array.init n (fun _ -> read_int ()) in\n let queries = Array.init q (fun _ -> read_int ()) in\n let slots = Array.make fmax 0 in\n let pres = Array.make n false in\n let register sc n =\n let rec it prod = function\n | [] -> ()\n | l::ls -> count (prod*l) ls; it prod ls\n and count prod l =\n slots.(prod) <- slots.(prod)+sc;\n it prod l\n in\n count 1 (factors n)\n in\n let count n =\n let rec count prod l =\n slots.(prod) - it prod l\n and it prod = function\n | [] -> 0\n | l::ls -> count (prod * l) ls + it prod ls\n in\n count 1 (factors n)\n in\n let cur = ref 0 in\n for i = 0 to q - 1 do\n (* How many things does it intersect with ? *)\n (* Oops, check presence + the '1' problem *)\n let beer = queries.(i) - 1 in\n let foam = beers.(beer) in\n let score =\n if pres.(beer) then (register (-1) foam; - count foam)\n else (let r = count foam in register 1 foam; r)\n in\n pres.(beer) <- not pres.(beer);\n cur := !cur + score;\n Printf.printf \"%d\\n\" !cur\n done\n\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet fmax = 500_001\n\nlet factors n =\n let rec aux i p =\n(* Printf.printf \"%d, %d\\n\" i p; *)\n if p = 1 then []\n else if i*i > p then [p]\n else if p mod i = 0 then i::(match aux i (p/i) with i'::is when i=i' -> is | is -> is)\n else aux (i+1) p\n in\n aux 2 n\n\n(* Mike and Foam *)\n\nlet _ =\n let n = read_int () in\n let q = read_int () in\n let beers = Array.init n (fun _ -> read_int ()) in\n let queries = Array.init q (fun _ -> read_int ()) in\n let slots = Array.make fmax 0 in\n let pres = Array.make n false in\n let register sc n =\n let rec it par prod = function\n | [] -> 0\n | l::ls -> count par (prod*l) ls + it par prod ls\n and count par prod l =\n let t = slots.(prod) in\n slots.(prod) <- t+sc;\n par*(if sc > 0 then t else t + sc) + it (-par) prod l\n in\n sc * count 1 1 (factors n)\n in\n let cur = ref 0 in\n for i = 0 to q - 1 do\n (* How many things does it intersect with ? *)\n (* Oops, check presence + the '1' problem *)\n let beer = queries.(i) - 1 in\n let score = register (if pres.(beer) then -1 else 1) beers.(beer) in\n pres.(beer) <- true;\n cur := !cur + score;\n Printf.printf \"%d\\n\" !cur\n done\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n2 = 500000 in\n let prime = Array.make (n2 + 1) true in\n let p = Array.make (n2 + 1) 0 in\n let pd = Array.make (n2 + 1) [] in\n let pk = ref 0 in\n let () =\n for i = 2 to n2 do\n if prime.(i) then (\n\tp.(!pk) <- i;\n\tincr pk;\n\tpd.(i) <- [i];\n\tlet j = ref (2 * i) in\n while !j <= n2 do\n\t let jj = !j in\n prime.(jj) <- false;\n\t pd.(jj) <- i :: pd.(jj);\n j := jj + i\n done\n )\n done;\n in\n let pk = !pk - 1 in\n let pd = Array.map Array.of_list pd in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let q = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = Array.make (n2 + 1) false in\n let d = Array.make (n2 + 1) 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let res = ref 0L in\n for i = 1 to q do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = a.(x - 1) in\n let (s, ofs) =\n\tif b.(x) then (\n\t b.(x) <- false;\n\t (-1, 1)\n\t) else (\n\t b.(x) <- true;\n\t (1, 0)\n\t)\n in\n let ds = pd.(x) in\n let k = Array.length ds in\n\tfor i = 0 to 1 lsl k - 1 do\n\t let y = ref 1 in\n\t let c = ref 0 in\n\t for j = 0 to k - 1 do\n\t if i land (1 lsl j) <> 0 then (\n\t\ty := !y * ds.(j);\n\t\tincr c\n\t )\n\t done;\n\t if !c land 1 = 0\n\t then res := Int64.add !res (Int64.of_int (s * (d.(!y) - ofs)))\n\t else res := Int64.sub !res (Int64.of_int (s * (d.(!y) - ofs)));\n\t d.(!y) <- d.(!y) + s;\n\tdone;\n\tPrintf.printf \"%Ld\\n\" !res;\n done;\n"}], "src_uid": "adc9fe6121f6ed1ba805a3b8c97824b4"} {"nl": {"description": "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.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000)\u00a0\u2014 the number of balls. The second line contains n integers t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009ti\u2009\u2264\u2009n) where ti is the color of the i-th ball.", "output_spec": "Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.", "sample_inputs": ["4\n1 2 1 2", "3\n1 1 1"], "sample_outputs": ["7 3 0 0", "6 0 0"], "notes": "NoteIn the first sample, color 2 is dominant in three intervals: An interval [2,\u20092] contains one ball. This ball's color is 2 so it's clearly a dominant color. An interval [4,\u20094] contains one ball, with color 2 again. An interval [2,\u20094] 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."}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\nlet print_int x = Printf.printf \"%d \" x;;\n\nlet () =\n let n = read_int() in\n let a = Array.init n read_int in\n let res = Array.make n 0 in\n for i = 0 to (n-1) do\n let seen = Array.make n 0 in\n let index = ref (a.(i)-1) in\n seen.(!index) <- 1;\n res.(!index) <- res.(!index) + 1;\n for j = i+1 to (n-1) do\n let k = a.(j)-1 in\n seen.(k) <- seen.(k) + 1;\n if seen.(k) > seen.(!index) || \n (seen.(k) == seen.(!index) && k < !index) then\n (index := k);\n res.(!index) <- res.(!index) + 1\n done\n done;\n Array.iter print_int res;;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let t = Array.init n (fun _ -> -1 + read_int()) in\n let wins = Array.make n 0 in\n\n for i=0 to n-1 do\n let counts = Array.make n 0 in\n let rec loop j maxcount maxcolor = if j < n then (\n let c = t.(j) in\n let nv = counts.(c) + 1 in\n counts.(c) <- nv;\n if nv > maxcount then (\n\twins.(c) <- wins.(c) + 1;\n\tloop (j+1) nv c\n ) else if nv = maxcount then (\n\tif c < maxcolor then (\n\t wins.(c) <- wins.(c) + 1;\n\t loop (j+1) nv c\n\t) else (\n\t wins.(maxcolor) <- wins.(maxcolor) + 1;\n\t loop (j+1) nv maxcolor\t \n\t)\n ) else (\n\twins.(maxcolor) <- wins.(maxcolor) + 1;\t\n\tloop (j+1) maxcount maxcolor\n )\n )\n in\n loop i 0 0\n done;\n\n for i=0 to n-1 do\n printf \"%d \" wins.(i)\n done;\n\n print_newline()\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let t = Array.init n (fun _ -> -1 + read_int()) in\n let wins = Array.make n 0 in\n\n for i=0 to n-1 do\n let counts = Array.make n 0 in\n let rec loop j maxcount maxcolor = if j = n then () else (\n let c = t.(j) in\n let nv = counts.(c) + 1 in\n counts.(c) <- nv;\n if nv > maxcount then (\n\twins.(c) <- wins.(c) + 1;\n\tloop (j+1) nv c\n ) else if nv = maxcount then (\n\tif c < maxcolor then (\n\t wins.(c) <- wins.(c) + 1;\n\t loop (j+1) nv c\n\t) else (\n\t wins.(maxcolor) <- wins.(maxcolor) + 1;\n\t loop (j+1) nv maxcolor\t \n\t)\n ) else loop (j+1) maxcount maxcolor\n )\n in\n loop i 0 0\n done;\n\n for i=0 to n-1 do\n printf \"%d \" wins.(i)\n done;\n\n print_newline()\n"}], "src_uid": "f292c099e4eac9259a5bc9e42ff6d1b5"} {"nl": {"description": "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.", "input_spec": "The first line contains an integer number n (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2009\u2264\u2009\u20091000), 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.", "output_spec": "Print the name of the winner.", "sample_inputs": ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"], "sample_outputs": ["andrew", "andrew"], "notes": null}, "positive_code": [{"source_code": "let rec read_rounds n score_tbl =\n if n > 0 then \n\tlet line = read_line () in\n\tlet (name, score) = Scanf.sscanf line \"%s %d\" (fun x y -> (x, y)) in\n\t(* Printf.printf \"line: %s\\n\" line; *)\n\tlet so_far = (try Hashtbl.find score_tbl name with _ -> 0) + score in\n\tHashtbl.replace score_tbl name so_far;\n\t(* Printf.printf \"%s %d\\n\" name score; *)\n\t(name, so_far) :: read_rounds (n - 1) score_tbl\n else\n\t[]\n\nlet rec winner rounds max_final_score score_tbl =\n match rounds with\n | [] -> None\n | (name, score) :: tl -> if (score >= max_final_score) && ((Hashtbl.find score_tbl name) = max_final_score) then \n\t\t\t\t\t\t\t Some name \n\t\t\t\t\t\t else \n\t\t\t\t\t\t\t winner tl max_final_score score_tbl\n\nlet () =\n let n = read_int () in\n let score_tbl = Hashtbl.create n in\n let rounds = read_rounds n score_tbl in\n let max_final_score = ref 0 in \n Hashtbl.iter (fun name score -> max_final_score := max !max_final_score score) score_tbl;\n match winner rounds !max_final_score score_tbl with\n | Some name -> Printf.printf \"%s\\n\" name\n"}, {"source_code": "open Hashtbl;;\nopen Scanf;;\nopen List;;\n\nlet players = Hashtbl.create 0;;\nlet scores = ref [];;\n\n\nlet ib = Scanf.Scanning.stdib;;\nlet add_player name x =\n\tif not (Hashtbl.mem players name) then begin\n\t\tHashtbl.add players name 0\n\tend;\n\t\n\tlet player = Hashtbl.find players name in\n\tlet score = player + x in\n\tlet _ = scores := ((name, score) :: !scores) in\n\tHashtbl.replace players name score\n;;\n\nlet ln = read_int ();;\nfor i = 0 to ln-1 do\n\tScanf.bscanf ib \"%s %d\\n\" add_player\ndone;;\n\nlet m = Hashtbl.fold (fun _ p m -> max p m) players 0;;\n\n\nfor i = ln-1 downto 0 do\n\tlet name, score = List.nth (!scores) i in\n\tif (score >= m) && ((Hashtbl.find players name) = m) then begin\n\t\tprint_string name;\n\t\texit 0\n\tend\ndone;\n"}, {"source_code": "exception Winner of string\n\nlet maximal_score l = \n let t = Hashtbl.create 13 in\n List.iter (fun (p,s) ->\n try \n let s' = Hashtbl.find t p in\n Hashtbl.replace t p (s' + s)\n with\n |Not_found -> Hashtbl.add t p s\n ) l;\n let maxs = Hashtbl.fold (fun _ s v -> max v s) t 0 in\n let pls = Hashtbl.fold (fun p s l -> if s = maxs then p :: l else l) t [] in\n (maxs, pls)\n\nlet winner l =\n let (maxs, pls) = maximal_score l in\n let t = Hashtbl.create 13 in \n List.iter (fun (p,s) ->\n try\n let s' = Hashtbl.find t p in\n Hashtbl.replace t p (s' + s);\n if s' + s >= maxs && List.mem p pls then (raise (Winner p))\n with\n |Not_found -> \n Hashtbl.add t p s;\n if s >= maxs && List.mem p pls then (raise (Winner p))\n ) l\n\nlet rec input_list n = \n if n = 0 then []\n else begin try \n let (p,s) = Scanf.fscanf stdin \"%s %i\\n\" (fun a b -> (a,b)) in\n (p,s) :: (input_list (n-1))\n with\n |Not_found -> []\n end\n\nlet () = \n let n = int_of_string (read_line ()) in\n try\n winner (input_list n)\n with\n |Winner(s) -> Printf.printf \"%s\\n\" s\n\n"}, {"source_code": "let (|>) x f = f x\n\nmodule Player = struct\n type t = String.t\n let equal = (=)\n let hash = Hashtbl.hash\nend\n\ntype game = {\n nr : int;\n player : Player.t;\n score : int;\n}\n\nlet make_game nr player score = { nr; player; score }\n\nmodule Scoretbl = Hashtbl.Make (Player)\n\nlet parse_games () : game array =\n let parse n =\n Array.init n\n (fun i -> Scanf.scanf \"%s %d\\n\"\n (fun p s -> make_game i p s)) in\n Scanf.scanf \"%d\\n\" parse\n\nlet score_players games : game list Scoretbl.t =\n let scores = Scoretbl.create 10 in\n let add_score g =\n match Scoretbl.mem scores g.player with\n | true -> Scoretbl.replace scores g.player (g :: (Scoretbl.find scores g.player))\n | false -> Scoretbl.add scores g.player [g] in\n Array.iter add_score games;\n scores\n\nlet total_score games : int =\n List.fold_left (fun a g -> a + g.score) 0 games\n\nlet leaders scores =\n let highscore = ref min_int\n and leaders = ref [] in\n let check p games =\n let s = total_score games in\n if s = !highscore\n then leaders := p :: !leaders\n else if s > !highscore\n then begin\n highscore := s;\n leaders := [p]\n end in\n Scoretbl.iter check scores;\n !highscore, !leaders\n \nlet threshold high games =\n let rec count i s = function\n | [] -> i\n | h::t -> if s >= high then i else count h.nr (s + h.score) t\n in count 0 0 (List.rev games)\n\nlet winner scores (high, players) =\n let (p,_) =\n List.fold_left (fun ((w,r) as m) pl ->\n let round = threshold high (Scoretbl.find scores pl) in\n if round < r then (pl,round) else m)\n (\"\",max_int)\n players in\n p\n\n\n\nlet _ =\n let scores = parse_games () |> score_players in\n Printf.printf \"%s\\n\" (winner scores (leaders scores))\n"}, {"source_code": "let (|>) x f = f x\n\nlet read_rounds n a =\n let rec go n acc =\n if n = 0 then\n List.rev acc\n else (\n let line = read_line () in\n let name, v = Scanf.sscanf line \"%s %d\" (fun x y -> x,y) in\n let vv = (try Hashtbl.find a name with _ -> 0) + v in\n Hashtbl.replace a name vv;\n go (n-1) ((name,vv)::acc)\n )\n in go n []\n\nlet rec f maxv a = function\n | [] -> None\n | (name,v)::tl -> if v >= maxv && Hashtbl.find a name = maxv then\n Some name\n else\n f maxv a tl\n\nlet () =\n let n = read_int () in\n let a = Hashtbl.create n in\n let rounds = read_rounds n a in\n let maxv = Hashtbl.fold (fun name v maxv -> max maxv v) a 0 in\n match f maxv a rounds with\n | Some name -> print_endline name\n"}], "negative_code": [{"source_code": "let rec read_rounds n score_tbl =\n if n > 0 then \n\tlet line = read_line () in\n\tlet (name, score) = Scanf.sscanf line \"%s %d\" (fun x y -> (x, y)) in\n\t(* Printf.printf \"line: %s\\n\" line; *)\n\tHashtbl.replace score_tbl name ((try Hashtbl.find score_tbl name with _ -> 0) + score);\n\t(* Printf.printf \"%s %d\\n\" name score; *)\n\t(name, score) :: read_rounds (n - 1) score_tbl\n else\n\t[]\n\nlet rec winner rounds max_final_score score_tbl =\n match rounds with\n | [] -> None\n | (name, score) :: tl -> let x = (try Hashtbl.find score_tbl name with _ -> 0) + score in\n\t\t\t\t\t\t if x >= max_final_score then \n\t\t\t\t\t\t\t Some name \n\t\t\t\t\t\t else (\n\t\t\t\t\t\t\t Hashtbl.replace score_tbl name x; \n\t\t\t\t\t\t\t winner tl max_final_score score_tbl\n\t\t\t\t\t\t )\n\nlet () =\n let n = read_int () in\n let score_tbl = Hashtbl.create n in\n let rounds = read_rounds n score_tbl in\n let max_final_score = ref 0 in \n Hashtbl.iter (fun name score -> max_final_score := max !max_final_score score) score_tbl;\n let score_tbl2 = Hashtbl.create n in \n match winner rounds !max_final_score score_tbl2 with\n | Some name -> Printf.printf \"%s\\n\" name\n"}, {"source_code": "let rec read_rounds n score_tbl =\n if n > 0 then \n\tlet line = read_line () in\n\tlet (name, score) = Scanf.sscanf line \"%s %d\" (fun x y -> (x, y)) in\n\t(* Printf.printf \"line: %s\\n\" line; *)\n\tlet so_far = (try Hashtbl.find score_tbl name with _ -> 0) + score in\n\tHashtbl.replace score_tbl name so_far;\n\t(* Printf.printf \"%s %d\\n\" name score; *)\n\t(name, so_far) :: read_rounds (n - 1) score_tbl\n else\n\t[]\n\nlet rec winner rounds max_final_score =\n match rounds with\n | [] -> None\n | (name, score) :: tl -> if score >= max_final_score then Some name else winner tl max_final_score\n\nlet () =\n let n = read_int () in\n let score_tbl = Hashtbl.create n in\n let rounds = read_rounds n score_tbl in\n let max_final_score = ref 0 in \n Hashtbl.iter (fun name score -> max_final_score := max !max_final_score score) score_tbl;\n match winner rounds !max_final_score with\n | Some name -> Printf.printf \"%s\\n\" name\n"}, {"source_code": "let rec read_rounds n score_tbl =\n if n > 0 then \n\tlet line = read_line () in\n\tlet (name, score) = Scanf.sscanf line \"%s %d\" (fun x y -> (x, y)) in\n\t(* Printf.printf \"line: %s\\n\" line; *)\n\tHashtbl.replace score_tbl name ((try Hashtbl.find score_tbl name with _ -> 0) + score);\n\t(* Printf.printf \"%s %d\\n\" name score; *)\n\t(name, score) :: read_rounds (n - 1) score_tbl\n else\n\t[]\n\nlet rec winner rounds max_final_score score_tbl =\n match rounds with\n | [] -> None\n | (name, score) :: tl -> let x = (try Hashtbl.find score_tbl name with _ -> 0) + score in\n\t\t\t\t\t\t if x >= max_final_score then \n\t\t\t\t\t\t\t Some name \n\t\t\t\t\t\t else (\n\t\t\t\t\t\t\t Hashtbl.replace score_tbl name x; \n\t\t\t\t\t\t\t\t winner tl max_final_score score_tbl\n\t\t\t\t\t\t )\n\nlet () =\n let n = read_int () in\n let score_tbl = Hashtbl.create n in\n let rounds = read_rounds n score_tbl in\n let max_final_score = ref 0 in \n Hashtbl.iter (fun name score -> max_final_score := max !max_final_score score) score_tbl;\n Hashtbl.reset score_tbl;\n match winner rounds !max_final_score score_tbl with\n | Some name -> Printf.printf \"%s\\n\" name\n"}, {"source_code": "open Hashtbl;;\nopen Scanf;;\nopen List;;\n\nlet players = Hashtbl.create 0;;\nlet scores = ref [];;\n\n\nlet ib = Scanf.Scanning.stdib;;\nlet add_player name x =\n\tif not (Hashtbl.mem players name) then begin\n\t\tHashtbl.add players name 0\n\tend;\n\t\n\tlet player = Hashtbl.find players name in\n\tlet score = player + x in\n\tlet _ = scores := ((name, score) :: !scores) in\n\tHashtbl.replace players name score\n;;\n\nlet ln = read_int ();;\nfor i = 0 to ln-1 do\n\tScanf.bscanf ib \"%s %d\\n\" add_player\ndone;;\n\nlet m = Hashtbl.fold (fun _ p m -> max p m) players 0;;\n\nif ln = 15 then print_int m;\n\nfor i = ln-1 downto 0 do\n\tlet name, score = List.nth (!scores) i in\n\tif (score = m) && ((Hashtbl.find players name) = m) then begin\n\t\tprint_string name;\n\t\texit 0\n\tend\ndone;\n"}, {"source_code": "open Hashtbl;;\nopen Scanf;;\nopen List;;\n\nlet players = Hashtbl.create 0;;\nlet scores = ref [];;\n\n\nlet ib = Scanf.Scanning.stdib;;\nlet add_player name x =\n\tif not (Hashtbl.mem players name) then begin\n\t\tHashtbl.add players name 0\n\tend;\n\t\n\tlet player = Hashtbl.find players name in\n\tlet score = player + x in\n\tlet _ = scores := ((name, score) :: !scores) in\n\tHashtbl.replace players name score\n;;\n\nlet ln = read_int ();;\nfor i = 0 to ln-1 do\n\tScanf.bscanf ib \"%s %d\\n\" add_player\ndone;;\n\nlet m = Hashtbl.fold (fun _ p m -> max p m) players 0;;\n\nfor i = List.length (!scores) - 1 downto 0 do\n\tlet name, score = List.nth (!scores) i in\n\tif (score = m) && ((Hashtbl.find players name) = m) then begin\n\t\tprint_string name;\n\t\texit 0\n\tend\ndone;\n"}, {"source_code": "open Hashtbl;;\nopen Scanf;;\nopen List;;\n\nlet players = Hashtbl.create 0;;\nlet scores = ref [];;\n\n\nlet ib = Scanf.Scanning.stdib;;\nlet add_player name x =\n\tif not (Hashtbl.mem players name) then begin\n\t\tHashtbl.add players name 0\n\tend;\n\t\n\tlet player = Hashtbl.find players name in\n\tlet score = player + x in\n\tlet _ = scores := ((name, score) :: !scores) in\n\tHashtbl.replace players name score\n;;\n\nlet ln = read_int ();;\nfor i = 0 to ln-1 do\n\tScanf.bscanf ib \"%s %d\\n\" add_player\ndone;;\n\nlet m = Hashtbl.fold (fun _ p m -> max p m) players 0;;\n\nfor i = ln-1 downto 0 do\n\tlet name, score = List.nth (!scores) i in\n\tif (score = m) && ((Hashtbl.find players name) = m) then begin\n\t\tprint_string name;\n\t\texit 0\n\tend\ndone;\n"}, {"source_code": "exception Winner of string\n\nlet maximal_score l = \n let t = Hashtbl.create 13 in\n List.iter (fun (p,s) ->\n try \n let s' = Hashtbl.find t p in\n Hashtbl.replace t p (s' + s)\n with\n |Not_found -> Hashtbl.add t p s\n ) l;\n Hashtbl.fold (fun _ s v -> max v s) t 0\n\nlet winner l =\n let maxs = maximal_score l in\n let t = Hashtbl.create 13 in \n List.iter (fun (p,s) ->\n try\n let s' = Hashtbl.find t p in\n Hashtbl.replace t p (s' + s);\n if s' + s = maxs then (raise (Winner p))\n with\n |Not_found -> \n Hashtbl.add t p s;\n if s = maxs then (raise (Winner p))\n ) l\n\nlet rec input_list n = \n if n = 0 then []\n else begin try \n let (p,s) = Scanf.fscanf stdin \"%s %i\\n\" (fun a b -> (a,b)) in\n (p,s) :: (input_list (n-1))\n with\n |Not_found -> []\n end\n\nlet () = \n let n = int_of_string (read_line ()) in\n try\n winner (input_list n)\n with\n |Winner(s) -> Printf.printf \"%s\\n\" s\n\n"}, {"source_code": "exception Winner of string\n\nlet maximal_score l = \n let t = Hashtbl.create 13 in\n List.iter (fun (p,s) ->\n try \n let s' = Hashtbl.find t p in\n Hashtbl.replace t p (s' + s)\n with\n |Not_found -> Hashtbl.add t p s\n ) l;\n Hashtbl.fold (fun _ s v -> max v s) t 0\n\nlet winner l =\n let maxs = maximal_score l in\n let t = Hashtbl.create 13 in \n List.iter (fun (p,s) ->\n try\n let s' = Hashtbl.find t p in\n Hashtbl.replace t p (s' + s);\n if s' + s >= maxs then (raise (Winner p))\n with\n |Not_found -> \n Hashtbl.add t p s;\n if s >= maxs then (raise (Winner p))\n ) l\n\nlet rec input_list n = \n if n = 0 then []\n else begin try \n let (p,s) = Scanf.fscanf stdin \"%s %i\\n\" (fun a b -> (a,b)) in\n (p,s) :: (input_list (n-1))\n with\n |Not_found -> []\n end\n\nlet () = \n let n = int_of_string (read_line ()) in\n try\n winner (input_list n)\n with\n |Winner(s) -> Printf.printf \"%s\\n\" s\n\n"}, {"source_code": "exception Winner of string\n\nlet maximal_score l = \n let t = Hashtbl.create 13 in\n List.iter (fun (p,s) ->\n try \n let s' = Hashtbl.find t p in\n Hashtbl.replace t p (s' + s)\n with\n |Not_found -> Hashtbl.add t p s\n ) l;\n Hashtbl.fold (fun _ s v -> max v s) t 0\n\nlet winner l =\n let maxs = maximal_score l in\n print_int maxs;\n print_endline \"\";\n let t = Hashtbl.create 13 in \n List.iter (fun (p,s) ->\n try\n let s' = Hashtbl.find t p in\n Hashtbl.replace t p (s' + s);\n if s' + s >= maxs then (raise (Winner p))\n with\n |Not_found -> \n Hashtbl.add t p s;\n if s >= maxs then (raise (Winner p))\n ) l\n\nlet rec input_list n = \n if n = 0 then []\n else begin try \n let (p,s) = Scanf.fscanf stdin \"%s %i\\n\" (fun a b -> (a,b)) in\n (p,s) :: (input_list (n-1))\n with\n |Not_found -> []\n end\n\nlet () = \n let n = int_of_string (read_line ()) in\n try\n winner (input_list n)\n with\n |Winner(s) -> Printf.printf \"%s\\n\" s\n\n"}, {"source_code": "let (|>) x f = f x\nlet identity x = x\n\nmodule Player = struct\n type t = String.t\n let equal = (=)\n let hash = Hashtbl.hash\nend\n\nmodule Gametbl = Hashtbl.Make (Player)\n\nmodule Score = struct\n type t = int\n let equal = (=)\n let hash = identity\nend\n\nmodule Scoretbl = Hashtbl.Make (Score)\n\nlet parse_games () =\n let games = Gametbl.create 10 in\n let push k v =\n match Gametbl.mem games k with\n true -> Gametbl.replace games k (v::(Gametbl.find games k))\n | false -> Gametbl.add games k [v] in\n let rec loop = function\n 0 -> ()\n | n -> Scanf.scanf \"%s %d\\n\" push; loop (n - 1) in\n Scanf.scanf \"%d\\n\" loop;\n games\n\nlet best_players gt =\n let scores = Scoretbl.create 10 in\n let max_score = ref 0 in\n let score_player p game_scores =\n let s = List.fold_left (+) 0 game_scores in\n max_score := max !max_score s;\n match Scoretbl.mem scores s with\n true -> Scoretbl.replace scores s (p::(Scoretbl.find scores s))\n | false -> Scoretbl.add scores s [p] in\n Gametbl.iter score_player gt;\n !max_score, Scoretbl.find scores !max_score\n\nlet winner gt (m,players) =\n match players with\n [] -> raise (Invalid_argument \"No Player\")\n | p::ps -> let rec score_reached scores cs i =\n if cs >= m\n then i\n else \n match scores with\n [] -> i\n | h::t -> score_reached t (cs+h) (i+1) in\n let game = ref (score_reached (List.rev (Gametbl.find gt p)) 0 0) in\n let better_player bp pl =\n let g = score_reached (List.rev (Gametbl.find gt pl)) 0 0 in\n if g < !game then (game := g; pl) else bp in\n List.fold_left better_player p ps\n\n\nlet _ =\n let gt = parse_games () in\n Printf.printf \"%s\\n\" (winner gt (best_players gt))\n"}, {"source_code": "let (|>) x f = f x\n\nmodule Player = struct\n type t = String.t\n let equal = (=)\n let hash = Hashtbl.hash\nend\n\ntype game = {\n nr : int;\n player : Player.t;\n score : int;\n}\n\nlet make_game nr player score = { nr; player; score }\n\nmodule Scoretbl = Hashtbl.Make (Player)\n\nlet parse_games () : game array =\n let parse n =\n Array.init n\n (fun i -> Scanf.scanf \"%s %d\\n\"\n (fun p s -> make_game i p s)) in\n Scanf.scanf \"%d\\n\" parse\n\nlet score_players games : game list Scoretbl.t =\n let scores = Scoretbl.create 10 in\n let add_score g =\n match Scoretbl.mem scores g.player with\n | true -> Scoretbl.replace scores g.player (g :: (Scoretbl.find scores g.player))\n | false -> Scoretbl.add scores g.player [g] in\n Array.iter add_score games;\n scores\n\nlet total_score games : int =\n List.fold_left (fun a g -> a + g.score) 0 games\n\nlet leaders scores =\n let highscore = ref min_int\n and leaders = ref [] in\n let check p games =\n let s = total_score games in\n if s = !highscore\n then leaders := p :: !leaders\n else if s > !highscore\n then begin\n highscore := s;\n leaders := [p]\n end in\n Scoretbl.iter check scores;\n !highscore, !leaders\n \nlet threshold high games =\n let rec count i s = function\n | [] -> i\n | h::t -> if s >= high then i else count (i + 1) (s + h.score) t\n in count 0 0 (List.rev games)\n\nlet winner scores (high, players) =\n let (p,_) =\n List.fold_left (fun ((w,r) as m) pl ->\n let round = threshold high (Scoretbl.find scores pl) in\n if round < r then (pl,round) else m)\n (\"\",max_int)\n players in\n p\n\n\n\nlet _ =\n let scores = parse_games () |> score_players in\n Printf.printf \"%s\\n\" (winner scores (leaders scores))\n"}], "src_uid": "c9e9b82185481951911db3af72fd04e7"} {"nl": {"description": "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.", "input_spec": "The first line of input will be a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). 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.", "output_spec": "The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.", "sample_inputs": ["4\n0101\n1000\n1111\n0101", "3\n111\n111\n111"], "sample_outputs": ["2", "3"], "notes": "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."}, "positive_code": [{"source_code": "let read_int _ = Scanf.scanf \" %d\" (fun x -> x)\nlet read_line _ = Scanf.scanf \" %s\" (fun x -> x)\n\nlet (--) i j = \n let rec aux n acc =\n if n < i then acc else aux (n-1) (n :: acc)\n in aux j []\n\nlet flip = function\n | '1' -> '0'\n | '0' -> '1'\n | _ -> assert false\n \n\nlet () = \n let n = read_int () in\n let grid = Array.init n read_line in\n let best = List.fold_left (fun x y -> max x y) 0 in\n let change grid col = List.iter (fun i -> grid.(i).[col] <- flip grid.(i).[col]) (0 -- (n-1)) in\n let check grid row = List.fold_right (fun col ok ->\n if grid.(row).[col] = grid.(row).[0] then ok else false) (1 -- (n-1)) (grid.(row).[0] = '0')\n in\n let solve row n = \n let tmp_grid = Array.copy grid in\n if tmp_grid.(row).[0] <> '0' then change tmp_grid 0;\n List.iter (fun col -> \n if tmp_grid.(row).[0] <> tmp_grid.(row).[col] then change tmp_grid col\n ) (1 -- (n-1));\n let answer = List.fold_right (fun row answer -> if check tmp_grid row then answer + 1 else answer) (0 -- (n-1)) 0 in\n answer\n in\n let answer = best (List.map (fun row -> solve row n) (0 -- (n-1))) in\n Printf.printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.scanf \" %d\" (fun x -> x)\nlet read_line _ = Scanf.scanf \" %s\" (fun x -> x)\n\nlet (--) i j = \n let rec aux n acc =\n if n < i then acc else aux (n-1) (n :: acc)\n in aux j []\n\nlet flip = function\n | '1' -> '0'\n | '0' -> '1'\n | _ -> assert false\n \n\nlet () = \n let n = read_int () in\n let grid = Array.init n read_line in\n let best = List.fold_left (fun x y -> max x y) 0 in\n let change grid col = List.iter (fun i -> grid.(i).[col] <- flip grid.(i).[col]) (0 -- (n-1)) in\n let check grid row = List.fold_right (fun col ok ->\n if grid.(row).[col] = grid.(row).[0] then ok else false) (1 -- (n-1)) (grid.(row).[0] = '0')\n in\n let solve row n = \n let tmp_grid = Array.copy grid in\n List.iter (fun col -> \n if tmp_grid.(row).[0] <> tmp_grid.(row).[col] then change tmp_grid col\n ) (1 -- (n-1));\n let answer = List.fold_right (fun row answer -> if check tmp_grid row then answer + 1 else answer) (0 -- (n-1)) 0 in\n answer\n in\n let answer = best (List.map (fun row -> solve row n) (0 -- (n-1))) in\n Printf.printf \"%d\\n\" answer\n"}, {"source_code": "let read_int _ = Scanf.scanf \" %d\" (fun x -> x)\nlet read_line _ = Scanf.scanf \" %s\" (fun x -> x)\n\nlet (--) i j = \n let rec aux n acc =\n if n < i then acc else aux (n-1) (n :: acc)\n in aux j []\n\nlet flip = function\n | '1' -> '0'\n | '0' -> '1'\n | _ -> assert false\n \n\nlet () = \n let n = read_int () in\n let grid = Array.init n read_line in\n let best = List.fold_left (fun x y -> max x y) 0 in\n let change grid col = List.iter (fun i -> grid.(i).[col] <- flip grid.(i).[col]) (0 -- (n-1)) in\n let check grid row = List.fold_right (fun col ok ->\n if grid.(row).[col] = grid.(row).[0] then ok else false) (1 -- (n-1)) true\n in\n let solve row n = \n let tmp_grid = Array.copy grid in\n List.iter (fun col -> \n if tmp_grid.(row).[0] <> tmp_grid.(row).[col] then change tmp_grid col\n ) (1 -- (n-1));\n let answer = List.fold_right (fun row answer -> if check tmp_grid row then answer + 1 else answer) (0 -- (n-1)) 0 in\n answer\n in\n let answer = best (List.map (fun row -> solve row n) (0 -- (n-1))) in\n Printf.printf \"%d\\n\" answer\n"}], "src_uid": "f48ddaf1e1db5073d74a2aa318b46704"} {"nl": {"description": "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.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of elements in the given array. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the elements of the array a.", "output_spec": "Print integer k on the first line \u2014 the least number of elements needed to add to the array a to make it co-prime. The second line should contain n\u2009+\u2009k integers aj \u2014 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.", "sample_inputs": ["3\n2 7 28"], "sample_outputs": ["1\n2 7 9 28"], "notes": null}, "positive_code": [{"source_code": "let rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = ref [] in\n let res = ref 0 in\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n b := [a.(0)];\n for i = 1 to n - 1 do\n if gcd (List.hd !b) a.(i) > 1 then (\n\tb := 1 :: !b;\n\tincr res;\n );\n b := a.(i) :: !b;\n done;\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") (List.rev !b);\n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "b0b4cadc46f9fd056bf7dc36d1cf51f2"} {"nl": {"description": "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\u2009+\u20097.", "input_spec": "First line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of elements in the array. Second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u200970)\u00a0\u2014 the elements of the array.", "output_spec": "Print one integer\u00a0\u2014 the number of different ways to choose some elements so that their product is a square of a certain integer modulo 109\u2009+\u20097.", "sample_inputs": ["4\n1 1 1 1", "4\n2 2 2 2", "5\n1 2 4 5 8"], "sample_outputs": ["15", "7", "7"], "notes": "NoteIn first sample product of elements chosen by any way is 1 and 1\u2009=\u200912. So the answer is 24\u2009-\u20091\u2009=\u200915.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\u2009+\u20091\u2009=\u20097."}, "positive_code": [{"source_code": "(* 4:22 *)\nopen Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet mm = 1_000_000_007L\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet prod i j f = fold i j (fun i a -> ((f i) ** a) %% mm) 1L\n\n(*\n For these numbers (primes): 37, 41, 43, 47, 53, 59, 61, 67\n Just count the number of each, say k, and compute 2^(k-1)\n and multiply these all together.\n\n For the rest of the numbers there are only the following primes:\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31\n\n So compute a bit vector for each number in the array which is which\n of these primes have even powers for that number. Then use DP on\n these array elements to construct all possible subsets of these\n bits using the array.\n*)\n\nlet rec powermod a b = (* a^b mod m *)\n if b=0 then 1L else\n let r = powermod a (b / 2) in\n let r2 = (r**r) %% mm in\n if b mod 2 = 0 then r2 else (r2**a) %% mm\n \nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n\n let hist = Array.make 71 0 in\n\n for i=0 to n-1 do\n hist.(a.(i)) <- hist.(a.(i)) + 1\n done;\n \n let rec power_in p j = if p>j || j mod p <> 0 then 0 else 1 + power_in p (j/p) in\n\n let bits_of x =\n let l = [2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31] in\n let l = List.map (fun p -> (power_in p x) mod 2) l in\n List.fold_left (fun ac b -> b + (ac lsl 1)) 0 l\n in\n\n let count0 = Array.make 2048 0L in\n let count1 = Array.make 2048 0L in \n count0.(0) <- 1L;\n\n let rec scan i c0 c1 = if i=71 then c0 else (\n if List.exists (fun p -> p = i) [37; 41; 43; 47; 53; 59; 61; 67] then scan (i+1) c0 c1 \n else if hist.(i) = 0 then scan (i+1) c0 c1 else (\n Array.blit c0 0 c1 0 2048;\n let bits = bits_of i in\n for j=0 to 2048-1 do\n\tc1.(j) <- ((powermod 2L (hist.(i) - 1)) ** (c1.(j) ++ c0.(j lxor bits))) %% mm;\n done;\n scan (i+1) c1 c0\n )\n ) in\n\n let count = scan 1 count0 count1 in\n\n let bc = List.fold_left (fun ac i ->\n if hist.(i) <= 0 then ac else (ac ** powermod 2L (hist.(i) - 1)) %% mm)\n 1L [37; 41; 43; 47; 53; 59; 61; 67]\n in\n\n printf \"%Ld\\n\" ((mm -- 1L ++ count.(0) ** bc) %% mm)\n"}], "negative_code": [], "src_uid": "f8bb458793ae828094248a22d4508dd0"} {"nl": {"description": "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.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of elements in the array. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 the array elements.", "output_spec": "In the single line print \"YES\" (without the quotes) if Yaroslav can obtain the array he needs, and \"NO\" (without the quotes) otherwise.", "sample_inputs": ["1\n1", "3\n1 1 2", "4\n7 7 7 7"], "sample_outputs": ["YES", "YES", "NO"], "notes": "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. "}, "positive_code": [{"source_code": "(* Codeforces 287C - HappyPermutations DONE *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet rec readlist n acc = match n with | 0 -> List.rev acc | _ -> readlist (n -1) (gr() :: acc);;\nlet debug = false;;\n\nlet n = gr();; (* size of permutation *)\n\nlet rec cntmax li last curs mx = match li with\n\t| [] -> (max curs mx)\n\t| hd :: tl ->\n\t\t\tif hd = last\n\t\t\tthen cntmax tl last (curs +1) mx\n\t\t\telse cntmax tl hd 1 (max curs mx);;\n\nlet canraz m n = \n\tif n = 1 then true\n\telse if (n mod 2 = 0) && (m > n / 2) then false\n\telse if (2 * m - 1 > n) then false\n\telse true;;\n\nlet main() =\n\tlet li = readlist n [] in\n\tlet sli = List.sort compare li in\n\tlet maxi = cntmax sli 0 0 0 in\n\t(\n\t\t(* print_string \"maxi n = \";\n\t\tprint_int maxi;\n\t\tprint_string \" \"; print_int n; *)\n\tprint_string (if (canraz maxi n) then \"YES\" else \"NO\")\n\t);;\t\n\t\n\tmain();;\n"}], "negative_code": [], "src_uid": "2c58d94f37a9dd5fb09fd69fc7788f0d"} {"nl": {"description": "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).", "input_spec": "Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 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$$$) \u2014 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$$$.", "output_spec": "For each test case print the answer: \"YES\" (without quotes) if the great hero can kill all the monsters. Otherwise, print \"NO\" (without quotes).", "sample_inputs": ["5\n3 17 1\n2\n16\n10 999 3\n10 20 30\n100 50 30\n1000 1000 4\n200 300 400 500\n1000 1000 1000 1000\n999 999 1\n1000\n1000\n999 999 1\n1000000\n999"], "sample_outputs": ["YES\nYES\nYES\nNO\nYES"], "notes": "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\"."}, "positive_code": [{"source_code": "open Printf\r\nopen Scanf\r\n\r\nlet ( ** ) a b = Int64.mul a b\r\nlet ( ++ ) a b = Int64.add a b\r\nlet ( -- ) a b = Int64.sub a b\r\nlet ( // ) a b = Int64.div a b\r\nlet ( %% ) a b = Int64.rem a b\r\n\r\nlet long x = Int64.of_int x\r\nlet short x = Int64.to_int x\r\n\r\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\r\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\r\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \r\n \r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \r\n \r\nlet () = \r\n let cases = read_int () in\r\n for case = 1 to cases do\r\n let aa = read_long() in\r\n let bb = read_long() in\r\n let n = read_int() in\r\n let a = Array.init n read_long in\r\n let b = Array.init n read_long in\r\n\r\n let health_needed_to_survive p h =\r\n (* monster has power p and health h, how much health do I\r\n\t need to beat it and survive. I have power aa *)\r\n let nhits = (h++aa--1L)//aa in (* number of hits needed to kill it *)\r\n nhits ** p ++ 1L (* I have to have at least 1 health left over *)\r\n in\r\n\r\n let health_needed_to_beat_it p h =\r\n (* monster has power p and health h, how much health do I\r\n\t need to beat it and not survive. I have power aa *)\r\n let nhits = (h++aa--1L)//aa in (* number of hits needed to kill it *)\r\n (nhits -- 1L) ** p ++ 1L (* I have to have at least 1 health left over *)\r\n in\r\n\r\n let thts = (* total health to survive *)\r\n sum 0 (n-1) (fun i -> health_needed_to_survive a.(i) b.(i))\r\n in\r\n\r\n let health_needed_to_win =\r\n minf 0 (n-1) (fun i -> (* do the ith monster last *)\r\n\tthts -- (health_needed_to_survive a.(i) b.(i))\r\n\t++ (health_needed_to_beat_it a.(i) b.(i)) )\r\n in\r\n\r\n if health_needed_to_win <= bb then printf \"YES\\n\" else printf \"NO\\n\"\r\n done\r\n"}], "negative_code": [], "src_uid": "b63a6369023642a8e7e8f449d7d4b73f"} {"nl": {"description": "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\u2009+\u20091][j] or a[i][j\u2009+\u20091]. 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\u2009+\u20091] or a[i\u2009-\u20091][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.", "input_spec": "The first line of the input contains two integers n and m (3\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0\u2009\u2264\u2009a[i][j]\u2009\u2264\u2009105).", "output_spec": "The output contains a single number \u2014 the maximum total gain possible. ", "sample_inputs": ["3 3\n100 100 100\n100 1 100\n100 100 100"], "sample_outputs": ["800"], "notes": "NoteIahub will choose exercises a[1][1]\u2009\u2192\u2009a[1][2]\u2009\u2192\u2009a[2][2]\u2009\u2192\u2009a[3][2]\u2009\u2192\u2009a[3][3]. Iahubina will choose exercises a[3][1]\u2009\u2192\u2009a[2][1]\u2009\u2192\u2009a[2][2]\u2009\u2192\u2009a[2][3]\u2009\u2192\u2009a[1][3]."}, "positive_code": [{"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule H = Hashtbl\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\nlet rec bsearch_min a b test =\n if b - a = 1 then b else \n let mid = (a-b)/2 + b in \n if test mid then bsearch_min a mid test else \n bsearch_min mid b test\nlet rec bsearch_max a b test = \n if b - a = 1 then a else \n let mid = (a-b)/2 + b in \n if test mid then bsearch_max mid b test else \n bsearch_max a mid test\n(* int *)\nlet sqrt_floor n = bsearch_max 0 (1 lsl 31) (fun i -> i*i <= n)\nlet sqrt_ceil n = bsearch_min (-1) (1 lsl 31) (fun i -> n <= i*i) \n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet default x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* int, int *)\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\n(* number theory *)\nlet sieve_under len = (* len > 0 *)\n let sieve = Array.make len true in \n Array.fill sieve 0 (min len 2) false;\n let rec erase i k = if i >= len then () else (sieve.(i) <- false; erase (i+k) k) in \n for i = 2 to sqrt_floor len do if sieve.(i) then erase (2*i) i done;\n sieve\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 128 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create (4*1024) in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet _ = \n let row = read_int() in \n let col = read_int() in \n let mat = make_matrix row col 0 in \n for i = 0 to row -1 do \n for j = 0 to col -1 do \n mat.(i).(j) <- read_int() \n done\n done;\n\n let is_valid (y,x) = \n 0 <= x && x < col &&\n 0 <= y && y < row \n in \n let save mat (y,x) v = mat.(y).(x) <- v; v in\n let read mat (y,x) = mat.(y).(x) in \n\n let cub = init 4 (fun i -> make_matrix row col (-1)) in \n let config = [|\n [| (row-1,col-1); (-1,0); (0,-1) |];\n [| (0,0) ; (1,0) ; (0,1) |];\n [| (row-1,0) ; (-1,0); (0, 1) |];\n [| (0,col-1) ; (1,0) ; (0,-1) |];\n |] in \n\n for i = 0 to 3 do \n let rec dp pos = \n if not (is_valid pos) then 0 else \n let t = read cub.(i) pos in \n if t <> (-1) then t else begin \n let m = max (dp (pos +: config.(i).(1))) (dp (pos +: config.(i).(2))) in \n save cub.(i) pos (m + read mat pos)\n end \n in \n dp config.(i).(0) |> ignore;\n done;\n\n let rec run i j m = \n if i = row-1 then m else \n if j = col-1 then run (i+1) 1 m else \n let pos = (i,j) in \n let a = read cub.(0) (pos -: (0,1)) + read cub.(1) (pos +: (0,1)) \n + read cub.(2) (pos -: (1,0)) + read cub.(3) (pos +: (1,0)) in \n let b = read cub.(0) (pos -: (1,0)) + read cub.(1) (pos +: (1,0)) \n + read cub.(2) (pos +: (0,1)) + read cub.(3) (pos -: (0,1)) in \n let m' = max a b in \n run i (j+1) (max m m')\n in \n\n (* for i = 0 to 3 do print_matrix (\"%d \") cub.(i) done;\n *)\n printf \"%d\\n\" (run 1 1 0)"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n\n let a = Array.make_matrix n m 0L in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n a.(i).(j) <- read_long ()\n done\n done;\n\n let ur = Array.make_matrix n m 0L in\n let dr = Array.make_matrix n m 0L in\n let ul = Array.make_matrix n m 0L in\n let dl = Array.make_matrix n m 0L in\n\n let probe a i j = if i<0 || j<0 || i>n-1 || j>m-1 then 0L else a.(i).(j) in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n ul.(i).(j) <- a.(i).(j) ++ (max (probe ul (i-1) j) (probe ul i (j-1)))\n done;\n for j=m-1 downto 0 do\n ur.(i).(j) <- a.(i).(j) ++ (max (probe ur (i-1) j) (probe ur i (j+1)))\n done\n done;\n\n for i=n-1 downto 0 do\n for j=0 to m-1 do\n dl.(i).(j) <- a.(i).(j) ++ (max (probe dl (i+1) j) (probe dl i (j-1)))\n done;\n for j=m-1 downto 0 do\n dr.(i).(j) <- a.(i).(j) ++ (max (probe dr (i+1) j) (probe dr i (j+1)))\n done\n done;\n\n let best = ref 0L in\n\n for i=1 to n-2 do\n for j=1 to m-2 do\n let opt1 = ul.(i-1).(j) ++ ur.(i).(j+1) ++ dl.(i).(j-1) ++ dr.(i+1).(j) in\n let opt2 = ur.(i-1).(j) ++ dr.(i).(j+1) ++ ul.(i).(j-1) ++ dl.(i+1).(j) in\n best := max (max opt1 opt2) !best\n done\n done;\n\n printf \"%Ld\\n\" !best\n"}], "negative_code": [{"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule H = Hashtbl\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\nlet rec bsearch_min a b test =\n if b - a = 1 then b else \n let mid = (a-b)/2 + b in \n if test mid then bsearch_min a mid test else \n bsearch_min mid b test\nlet rec bsearch_max a b test = \n if b - a = 1 then a else \n let mid = (a-b)/2 + b in \n if test mid then bsearch_max mid b test else \n bsearch_max a mid test\n(* int *)\nlet sqrt_floor n = bsearch_max 0 (1 lsl 31) (fun i -> i*i <= n)\nlet sqrt_ceil n = bsearch_min (-1) (1 lsl 31) (fun i -> n <= i*i) \n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet default x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* int, int *)\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\n(* number theory *)\nlet sieve_under len = (* len > 0 *)\n let sieve = Array.make len true in \n Array.fill sieve 0 (min len 2) false;\n let rec erase i k = if i >= len then () else (sieve.(i) <- false; erase (i+k) k) in \n for i = 2 to sqrt_floor len do if sieve.(i) then erase (2*i) i done;\n sieve\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 128 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create (4*1024) in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet _ = \n let row = read_int() in \n let col = read_int() in \n let mat = make_matrix row col 0 in \n for i = 0 to row -1 do \n for j = 0 to col -1 do \n mat.(i).(j) <- read_int() \n done\n done;\n\n let is_valid (y,x) = \n 0 <= x && x < col &&\n 0 <= y && y < row \n in \n let save mat (y,x) v = mat.(y).(x) <- v; v in\n let read mat (y,x) = mat.(y).(x) in \n\n let cub = init 4 (fun i -> make_matrix row col (-1)) in \n let config = [|\n [| (row-1,col-1); (-1,0); (0,-1) |];\n [| (row-1,0) ; (-1,0); (0, 1) |];\n [| (0,col-1) ; (1,0) ; (0,-1) |];\n [| (0,0) ; (1,0) ; (0,1) |];\n |] in \n\n for i = 0 to 3 do \n let rec dp pos = \n if not (is_valid pos) then 0 else \n let t = read cub.(i) pos in \n if t <> (-1) then t else begin \n let m = max (dp (pos +: config.(i).(1))) (dp (pos +: config.(i).(2))) in \n save cub.(i) pos (m + read mat pos)\n end \n in \n dp config.(i).(0) |> ignore;\n done;\n\n let rec run i j m = \n if i = row then m else \n if j = col then run (i+1) 0 m else \n let pos = (i,j) in \n let m' = for_ 0 4 0 (fun i c -> c + read cub.(i) pos) - 4 * read mat pos in \n run i (j+1) (max m m')\n in \n\n (* for i = 0 to 3 do print_matrix (\"%d \") cub.(i) done; *)\n printf \"%d\\n\" (run 0 0 0)"}], "src_uid": "ed5d0eca057f2a2e371b1fc7e3b618bb"} {"nl": {"description": "Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message \u2014 string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully \"YAY!\", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says \"WHOOPS\".Tanya wants to make such message that lets her shout \"YAY!\" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says \"WHOOPS\". Your task is to help Tanya make the message.", "input_spec": "The first line contains line s (1\u2009\u2264\u2009|s|\u2009\u2264\u20092\u00b7105), consisting of uppercase and lowercase English letters \u2014 the text of Tanya's message. The second line contains line t (|s|\u2009\u2264\u2009|t|\u2009\u2264\u20092\u00b7105), consisting of uppercase and lowercase English letters \u2014 the text written in the newspaper. Here |a| means the length of the string a.", "output_spec": "Print two integers separated by a space: the first number is the number of times Tanya shouts \"YAY!\" while making the message, the second number is the number of times Tanya says \"WHOOPS\" while making the message. ", "sample_inputs": ["AbC\nDCbA", "ABC\nabc", "abacaba\nAbaCaBA"], "sample_outputs": ["3 0", "0 3", "3 4"], "notes": null}, "positive_code": [{"source_code": "let compte mot =\n\tlet tab = Array.make 123 0 in\n\tfor i=0 to String.length mot-1 do\n\t\ttab.(int_of_char (mot.[i])) <- 1 + tab.(int_of_char (mot.[i]));\n\tdone;\n\ttab;;\n\nlet f mot1 mot2 =\n\tlet tab1 = compte mot1 and tab2 = compte mot2 \n\tand compteur = ref 0 and compteur2 = ref 0 in\n\tfor i=0 to 122 do\n\t\tlet a = min (tab1.(i)) (tab2.(i)) in\n\t\t\tcompteur := a + !compteur;\n\t\t\ttab1.(i) <- tab1.(i) - a;\n\t\t\ttab2.(i) <- tab2.(i) - a;\n\tdone;\n\tlet tab_r1 = Array.init 26 (fun i -> tab1.(65 +i) + tab1.(97 + i))\n\tand tab_r2 = Array.init 26 (fun i -> tab2.(65 +i) + tab2.(97 + i))\n\tin\n\tfor i=0 to 25 do\n\t\tlet a = min (tab_r1.(i)) (tab_r2.(i)) in\n\t\t\tcompteur2 := a + !compteur2;\n\t\t\ttab_r1.(i) <- tab_r1.(i) - a;\n\t\t\ttab_r2.(i) <- tab_r2.(i) - a;\n\tdone;\n\t!compteur, !compteur2;;\n\nlet main () =\n\tlet mot1 = Scanf.scanf \"%s \" (fun i -> String.trim i) in\n\tlet mot2 = Scanf.scanf \"%s \" (fun i -> String.trim i) in\n\tlet (a,b) = f mot1 mot2 in\n\t\tPrintf.printf \"%d %d \" a b;;\n\nmain ();;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet isupper c = c <= 'Z' && c >= 'A'\nlet l2n c = (int_of_char c) - (int_of_char 'a')\nlet l2N c = (int_of_char c) - (int_of_char 'A')\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let s = read_string () in\n let t = read_string () in\n\n let compute_hist s =\n let h = Array.make_matrix 26 2 0 in\n let n = String.length s in\n for i=0 to n-1 do\n if isupper s.[i] then (\n\tlet x = l2N s.[i] in\n\th.(x).(1) <- h.(x).(1) + 1;\n ) else (\n\tlet x = l2n s.[i] in\n\th.(x).(0) <- h.(x).(0) + 1;\n )\n done;\n h\n in\n\n let hist_s = compute_hist s in\n let hist_t = compute_hist t in\n\n let ( ++ ) (a,b) (c,d) = (a+c, b+d) in\n \n let eval_letter ls hs lt ht =\n let yay = (min ls lt) + (min hs ht) in\n let short = min (ls+hs) (lt+ht) in\n (yay, short-yay)\n in\n\n let (x,y) = fold 0 25 (\n fun i ac -> \n (eval_letter hist_s.(i).(0) hist_s.(i).(1) hist_t.(i).(0) hist_t.(i).(1)) ++ ac\n ) (0,0)\n in\n\n printf \"%d %d\\n\" x y\n \n"}], "negative_code": [], "src_uid": "96e2ba997eff50ffb805b6be62c56222"} {"nl": {"description": "Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below. So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted. The battery of the newest device allows to highlight at most n sections on the display. Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.", "input_spec": "The first line contains the integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) \u2014 the maximum number of sections which can be highlighted on the display.", "output_spec": "Print the maximum integer which can be shown on the display of Stepan's newest device.", "sample_inputs": ["2", "3"], "sample_outputs": ["1", "7"], "notes": null}, "positive_code": [{"source_code": "open Printf;;\n\nlet n=read_int();;\n\n(if (n mod 2 == 1) then\n printf \"%d\" (7)\n);\n\nfor i = 1 to (n / 2 - (n mod 2)) do\n printf \"%d\" (1)\ndone;;\n"}, {"source_code": "let n=read_int();;\nif n == 1 then print_endline(\"0\")\nelse \n\tfor i = 1 to n/2 do \n\t if n mod 2 == 1 && i==1 then Printf.printf \"%d\" 7\n \telse Printf.printf \"%d\" 1\n \tdone;;"}, {"source_code": "let a = read_int();;\nlet n = ref a;;\n\nif (a mod 2 == 1) then\n\tprint_int 7;\n\tn := a-3;;\n\nif (a mod 2 == 0) then\n\tn := a;;\n\nlet x = (!n)/2\nfor i=1 to x do\n\tPrintf.printf \"1\"\ndone"}, {"source_code": "let n=read_int();;\nlet g = n;\nif n mod 2 == 1 then print_string(\"7\");\nlet n = if n mod 2 == 1 then n - 3 else n in\nfor i = 1 to n / 2 do\nprint_string(\"1\");\ndone;;\n"}, {"source_code": "open Printf;;\nlet n=read_int();;\n\nif n mod 2 > 0 then begin\n printf \"7\";\n for i=1 to (n-3)/2 do\n printf \"1\"\n done\nend\nelse begin\n for i=1 to n/2 do\n printf \"1\"\n done\nend;;"}, {"source_code": "let rec print1 n =\n for i = 1 to n do\n \tPrintf.printf \"1\";\n done;;\n\nlet n = read_int () ;;\nif n mod 2 == 0 then print1 (n / 2)\nelse begin\n\tprint_int 7;\n\tprint1 (n / 2 - 1)\nend"}], "negative_code": [{"source_code": "let rec print1 n =\n for i = 1 to n do\n \tPrintf.printf \"1\";\n done;;\n\nlet n = read_int () ;;\nif n mod 2 == 0 then print1 (n / 2)\nelse begin\n\tprint1 (n / 2 - 1) ;\n\tprint_int 7\nend"}, {"source_code": "let rec print1 n =\n match n with\n | -1 -> true;\n | 0 -> true;\n | nn -> print_int 1 ; print1 (n-1)\n\nlet n = read_int () ;;\nif n mod 2 == 0 then print1 (n / 2)\nelse begin\n\tprint1 (n / 2 - 1) ;\n\tprint_int 7;\n\ttrue\nend"}], "src_uid": "4ebea3f56ffd43efc9e1496a0ef7fa2d"} {"nl": {"description": "Amr has got a large array of size n. Amr doesn't like large arrays so he intends to make it smaller.Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array.Help Amr by choosing the smallest subsegment possible.", "input_spec": "The first line contains one number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the size of the array. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106), representing elements of the array.", "output_spec": "Output two integers l,\u2009r (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n), the beginning and the end of the subsegment chosen respectively. If there are several possible answers you may output any of them. ", "sample_inputs": ["5\n1 1 2 2 1", "5\n1 2 2 3 1", "6\n1 2 2 1 1 2"], "sample_outputs": ["1 5", "2 3", "1 5"], "notes": "NoteA subsegment B of an array A from l to r is an array of size r\u2009-\u2009l\u2009+\u20091 where Bi\u2009=\u2009Al\u2009+\u2009i\u2009-\u20091 for all 1\u2009\u2264\u2009i\u2009\u2264\u2009r\u2009-\u2009l\u2009+\u20091"}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let h = Hashtbl.create 10 in\n\n let add_to t index = \n let c = try Hashtbl.find h t with Not_found -> [] in\n Hashtbl.replace h t (index::c)\n in\n\n for i=0 to n-1 do\n add_to a.(i) i\n done;\n\n let len = Hashtbl.fold (fun _ v ac -> max ac (List.length v)) h 0 in\n\n let (first,last) = Hashtbl.fold (\n fun _ v (f,l) ->\n if List.length v <> len then (f,l)\n else\n\tlet l1 = List.hd v in\n\tlet f1 = List.nth v (len-1) in\n\tif l1-f1 < l-f then (f1,l1) else (f,l)\n ) h (0,n-1) in\n\n printf \"%d %d\\n\" (first+1) (last+1)\n"}], "negative_code": [], "src_uid": "ecd9bbc05b97f3cd43017dd0eddd014d"} {"nl": {"description": "Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.", "input_spec": "The first line of the input contains two integers, n and w (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009w\u2009\u2264\u2009109)\u00a0\u2014 the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109, 1\u2009\u2264\u2009i\u2009\u2264\u20092n)\u00a0\u2014\u00a0the capacities of Pasha's tea cups in milliliters.", "output_spec": "Print a single real number \u2014 the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["2 4\n1 1 1 1", "3 18\n4 4 4 2 2 2", "1 5\n2 3"], "sample_outputs": ["3", "18", "4.5"], "notes": "NotePasha also has candies that he is going to give to girls but that is another task..."}, "positive_code": [{"source_code": "let xint _ = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () = \n let min x y = \n if x < y then x\n else y\n in\n let n = xint() and w = xint() in\n let a = Array.make (n * 2) 0 in\n for i = 0 to (n * 2 - 1) do\n a.(i) <- xint();\n done;\n Array.sort compare a;\n let x = a.(0) and y = a.(n) in\n let z = min (float_of_int y) ((float_of_int x) *. 2.) in\n Printf.printf \"%.10f\\n\" (min (float_of_int w) (z *. 1.5 *. (float_of_int n)));\n\n"}, {"source_code": "module A = Array\nmodule C = Char\nmodule I = Int64\nmodule L = List\nmodule Q = Queue\nmodule S = String\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet ssf = Scanf.sscanf\n\nlet (|>) x f = f x\nlet (@@) f x = f x\n\nlet id x = x\nlet id2 x y = (x, y)\nlet id3 x y z = (x, y, z)\nlet id4 a b c d = (a, b, c, d)\nlet id5 a b c d e = (a, b, c, d, e)\n\nlet err s = raise (Failure s)\n\nlet inf = 1000000000\nlet eps = 1e-11\n\nlet _ =\n let n, w = sf \"%d %f \" id2 in\n let a = A.make (2 * n) 0. in\n for i = 0 to 2 * n - 1 do\n let ai = sf \"%d \" id in\n a.(i) <- float ai\n done;\n A.sort compare a;\n let r = A.mapi (fun x y -> if x < n then 2. *. y else y) a |> A.fold_left min 1e9 in\n r *. 1.5 *. float n |> min w |> pf \"%.9f\\n\"\n;;\n"}], "negative_code": [{"source_code": "module A = Array\nmodule C = Char\nmodule I = Int64\nmodule L = List\nmodule Q = Queue\nmodule S = String\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet ssf = Scanf.sscanf\n\nlet (|>) x f = f x\nlet (@@) f x = f x\n\nlet id x = x\nlet id2 x y = (x, y)\nlet id3 x y z = (x, y, z)\nlet id4 a b c d = (a, b, c, d)\nlet id5 a b c d e = (a, b, c, d, e)\n\nlet err s = raise (Failure s)\n\nlet inf = 1000000000\nlet eps = 1e-11\n\nlet _ =\n let n, w = sf \"%d %d \" id2 in\n let a = A.make (2 * n) 0. in\n for i = 0 to 2 * n - 1 do\n let ai = sf \"%d \" id in\n a.(i) <- float ai\n done;\n A.sort compare a;\n let r = A.mapi (fun x y -> if x < n then 2. *. y else y) a |> A.fold_left min 1e9 in\n r *. 1.5 *. float n |> max 1. |> pf \"%.9f\\n\"\n;;\n"}, {"source_code": "module A = Array\nmodule C = Char\nmodule I = Int64\nmodule L = List\nmodule Q = Queue\nmodule S = String\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet ssf = Scanf.sscanf\n\nlet (|>) x f = f x\nlet (@@) f x = f x\n\nlet id x = x\nlet id2 x y = (x, y)\nlet id3 x y z = (x, y, z)\nlet id4 a b c d = (a, b, c, d)\nlet id5 a b c d e = (a, b, c, d, e)\n\nlet err s = raise (Failure s)\n\nlet inf = 1000000000\nlet eps = 1e-11\n\nlet _ =\n let n, w = sf \"%d %d \" id2 in\n let a = A.make (2 * n) 0. in\n for i = 0 to 2 * n - 1 do\n let ai = sf \"%d \" id in\n a.(i) <- float ai\n done;\n A.sort compare a;\n let r = A.mapi (fun x y -> if x < n then 2. *. y else y) a |> A.fold_left min 1e9 in\n pf \"%.9f\\n\" @@ r *. 1.5 *. float n\n;;\n"}], "src_uid": "b2031a328d72b464f965b4789fd35b93"} {"nl": {"description": "Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1,\u2009a2,\u2009...,\u2009an.While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to b1,\u2009b2,\u2009...,\u2009bn. Stepan said that he swapped only cubes which where on the positions between l and r, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions l and r, inclusive, in some way).Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.", "input_spec": "The first line contains three integers n, l, r (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n) \u2014 the number of Vasya's cubes and the positions told by Stepan. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 the sequence of integers written on cubes in the Vasya's order. The third line contains the sequence b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009n) \u2014 the sequence of integers written on cubes after Stepan rearranged their order. It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes.", "output_spec": "Print \"LIE\" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print \"TRUTH\" (without quotes).", "sample_inputs": ["5 2 4\n3 4 2 3 1\n3 2 3 4 1", "3 1 2\n1 2 3\n3 1 2", "4 2 4\n1 1 1 1\n1 1 1 1"], "sample_outputs": ["TRUTH", "LIE", "TRUTH"], "notes": "NoteIn the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became equal to [3, 2, 3, 4, 1]).In the second example it is not possible that Stepan said truth because he said that he swapped cubes only between positions 1 and 2, but we can see that it is guaranteed that he changed the position of the cube which was on the position 3 at first. So it is guaranteed that Stepan deceived his brother.In the third example for any values l and r there is a situation when Stepan said the truth."}, "positive_code": [{"source_code": "open List;;\nlet inp = Array.of_list (map (fun x -> int_of_string x) (Str.split (Str.regexp \"[ \\t]+\") (read_line())));;\nlet n = Array.get inp 0;;\nlet l = (Array.get inp 1) - 1;;\nlet r = (Array.get inp 2) - 1;;\nlet a = Array.of_list (map (fun x -> int_of_string x) (Str.split (Str.regexp \"[ \\t]+\") (read_line())));;\nlet b = Array.of_list (map (fun x -> int_of_string x) (Str.split (Str.regexp \"[ \\t]+\") (read_line())));;\nlet flag2 = (Array.sub a 0 l) = (Array.sub b 0 l);;\nlet flag3 = (Array.sub a (r + 1) (n - r - 1)) = (Array.sub b (r + 1) (n - r - 1));;\n(Array.sort compare a);;\n(Array.sort compare b);;\nlet flag1 = a = b;;\nprint_string (if (flag1 && flag2 && flag3) then (\"TRUTH\") else (\"LIE\"));;"}], "negative_code": [], "src_uid": "1951bf085050c7e32fcf713132b30605"} {"nl": {"description": "Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of the points painted on the plane. Next n lines contain two integers each xi,\u2009yi (\u2009-\u2009100\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009100) \u2014 the coordinates of the i-th point. It is guaranteed that no two given points coincide.", "output_spec": "In the first line print an integer \u2014 the number of triangles with the non-zero area among the painted points.", "sample_inputs": ["4\n0 0\n1 1\n2 0\n2 2", "3\n0 0\n1 1\n2 0", "1\n1 1"], "sample_outputs": ["3", "1", "0"], "notes": "NoteNote to the first sample test. There are 3 triangles formed: (0,\u20090)\u2009-\u2009(1,\u20091)\u2009-\u2009(2,\u20090); (0,\u20090)\u2009-\u2009(2,\u20092)\u2009-\u2009(2,\u20090); (1,\u20091)\u2009-\u2009(2,\u20092)\u2009-\u2009(2,\u20090).Note to the second sample test. There is 1 triangle formed: (0,\u20090)\u2009-\u2009(1,\u20091)\u2009-\u2009(2,\u20090).Note to the third sample test. A single point doesn't form a single triangle."}, "positive_code": [{"source_code": "let xint _ = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let slope x y =\n if y == 0 then 1e12\n else (float_of_int x) /. (float_of_int y)\n in\n let n = xint () in\n if n <= 2 then (\n print_endline \"0\";\n exit 0;\n );\n let x = Array.make n 0 and y = Array.make n 0 in\n for i = 0 to n - 1 do\n x.(i) <- xint ();\n y.(i) <- xint ();\n done;\n let ret = ref 0l in\n for i = 0 to n - 1 do\n let v = Array.make (n - i - 1) 0.0 in\n for j = i + 1 to n - 1 do\n v.(j - i - 1) <- slope (y.(j) - y.(i)) (x.(j) - x.(i));\n done;\n Array.sort compare v;\n let cnt = ref 0 in\n for x = 1 to n - i - 2 do\n if v.(x) = v.(x - 1) then cnt := !cnt + 1\n else cnt := 0;\n ret := Int32.add !ret (Int32.of_int !cnt);\n done;\n done;\n let total = ref (Int64.of_int n) in\n total := Int64.mul !total (Int64.of_int (n - 1));\n total := Int64.mul !total (Int64.of_int (n - 2));\n total := Int64.div !total 6L;\n total := Int64.sub !total (Int64.of_int32 !ret);\n print_endline (Int64.to_string !total);\n"}], "negative_code": [{"source_code": "let xint _ = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let rec gcd a b = \n if b == 0 then a\n else gcd b (a mod b)\n in\n let abs x = \n if x < 0 then -x\n else x\n in\n let n = xint () in\n if n <= 2 then (\n print_endline \"0\";\n exit 0;\n );\n let x = Array.make n 0 and y = Array.make n 0 in\n for i = 0 to n - 1 do\n x.(i) <- xint ();\n y.(i) <- xint ();\n done;\n let ret = ref 0L in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n let dx = ref (x.(j) - x.(i)) in\n let dy = ref (y.(j) - y.(i)) in\n let g = gcd (abs !dx) (abs !dy) in\n if g != 0 then (\n dx := !dx / g;\n dy := !dy / g;\n if !dx < 0 then (\n dx := 0 - !dx; dy := 0 - !dy;\n )\n );\n a.(j) <- !dx * 100000 + !dy;\n done;\n Array.sort compare a;\n let s = ref 0 in\n while !s < n do\n let t = ref !s in\n while !t < n && a.(!t) == a.(!s) do\n t := !t + 1;\n done;\n if a.(!s) != 0 then (\n let c = !t - !s in\n ret := Int64.add !ret (Int64.of_int (c * (n - c - 1)));\n );\n s := !t;\n done;\n done;\n ret := Int64.div !ret 6L;\n print_endline (Int64.to_string !ret);\n"}], "src_uid": "d5913f8208efa1641f53caaee7624622"} {"nl": {"description": "There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091), such that ai\u2009+\u20091\u2009>\u2009ai.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of painting. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000), where ai means the beauty of the i-th painting.", "output_spec": "Print one integer\u00a0\u2014 the maximum possible number of neighbouring pairs, such that ai\u2009+\u20091\u2009>\u2009ai, after the optimal rearrangement.", "sample_inputs": ["5\n20 30 10 50 40", "4\n200 100 100 200"], "sample_outputs": ["4", "2"], "notes": "NoteIn the first sample, the optimal order is: 10,\u200920,\u200930,\u200940,\u200950.In the second sample, the optimal order is: 100,\u2009200,\u2009100,\u2009200."}, "positive_code": [{"source_code": "\nopen Printf\nopen Scanf\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let hist = Array.make 1000 0 in\n for i=0 to n-1 do\n let a = read_int() - 1 in\n hist.(a) <- hist.(a) + 1\n done;\n\n let rec loop remain a ac = if remain=0 then List.rev ac else (\n if hist.(a) > 0 then (\n hist.(a) <- hist.(a) - 1;\n loop (remain-1) ((a+1) mod 1000) (a::ac)\n ) else loop remain ((a+1) mod 1000) ac\n ) in\n\n let list = loop n 0 [] in\n\n let rec countup ac li = match li with\n | [] -> ac\n | x::[] -> ac\n | x::(y::t) ->\n let ac = ac + (if x < y then 1 else 0) in\n countup ac (y::t)\n in\n\n printf \"%d\\n\" (countup 0 list)\n\t\t\t\t\t\t \n"}], "negative_code": [], "src_uid": "30ad5bdc019fcd8a4e642c90decca58f"} {"nl": {"description": "Gerald plays the following game. He has a checkered field of size n\u2009\u00d7\u2009n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n\u2009-\u20091 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: At least one of the chips at least once fell to the banned cell. At least once two chips were on the same cell. At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.", "input_spec": "The first line contains two space-separated integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u20091000, 0\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n) \u2014 the coordinates of the i-th banned cell. All given cells are distinct. Consider the field rows numbered from top to bottom from 1 to n, and the columns \u2014 from left to right from 1 to n.", "output_spec": "Print a single integer \u2014 the maximum points Gerald can earn in this game.", "sample_inputs": ["3 1\n2 2", "3 0", "4 3\n3 1\n3 2\n3 3"], "sample_outputs": ["0", "1", "1"], "notes": "NoteIn the first test the answer equals zero as we can't put chips into the corner cells.In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4)."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\n\nlet (m, n) = (read_int(), read_int()) in\nlet frow = Array.make (n + 1) 1 in\nlet fcol = Array.make (n + 1) 1 in\nfor i = 1 to m do\n let (a, b) = (read_int(), read_int()) in (frow.(a) <- 0; fcol.(b) <- 0)\ndone;\nlet rec accum_res i = \n if i = 1 then 0\n else (accum_res (i - 1)) + frow.(i) + fcol.(i)\nin\n Printf.printf \"%d\\n\" ((accum_res (n - 1)) + (if (n mod 2 = 1) & (frow.((n + 1) / 2) == 1) & (fcol.((n + 1) / 2) == 1) then -1 else 0))\n\n"}], "negative_code": [], "src_uid": "a26a97586d4efb5855aa3b930e9effa7"} {"nl": {"description": "Alice has just learned addition. However, she hasn't learned the concept of \"carrying\" fully\u00a0\u2014 instead of carrying to the next column, she carries to the column two columns to the left.For example, the regular way to evaluate the sum $$$2039 + 2976$$$ would be as shown: However, Alice evaluates it as shown: In particular, this is what she does: add $$$9$$$ and $$$6$$$ to make $$$15$$$, and carry the $$$1$$$ to the column two columns to the left, i.\u00a0e. to the column \"$$$0$$$ $$$9$$$\"; add $$$3$$$ and $$$7$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i.\u00a0e. to the column \"$$$2$$$ $$$2$$$\"; add $$$1$$$, $$$0$$$, and $$$9$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i.\u00a0e. to the column above the plus sign; add $$$1$$$, $$$2$$$ and $$$2$$$ to make $$$5$$$; add $$$1$$$ to make $$$1$$$. Thus, she ends up with the incorrect result of $$$15005$$$.Alice comes up to Bob and says that she has added two numbers to get a result of $$$n$$$. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$. Note that pairs $$$(a, b)$$$ and $$$(b, a)$$$ are considered different if $$$a \\ne b$$$.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$2 \\leq n \\leq 10^9$$$)\u00a0\u2014 the number Alice shows Bob.", "output_spec": "For each test case, output one integer\u00a0\u2014 the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$. ", "sample_inputs": ["5\n100\n12\n8\n2021\n10000"], "sample_outputs": ["9\n4\n7\n44\n99"], "notes": "NoteIn the first test case, when Alice evaluates any of the sums $$$1 + 9$$$, $$$2 + 8$$$, $$$3 + 7$$$, $$$4 + 6$$$, $$$5 + 5$$$, $$$6 + 4$$$, $$$7 + 3$$$, $$$8 + 2$$$, or $$$9 + 1$$$, she will get a result of $$$100$$$. The picture below shows how Alice evaluates $$$6 + 4$$$: "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet count ci co d =\n(* given carry in, carry out and d, how many ways to do it? *)\n let s = 10*co + d - ci in\n if s <= 9 then s+1 else 19-s\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () =\n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n\n let rec digits n ac =\n if n = 0 then List.rev ac else\n\tdigits (n/10) ((n mod 10) :: ac)\n in\n\n let dig = Array.of_list (digits n []) in\n let nd = Array.length dig in (* number of digits *)\n(*\n for i=0 to nd-1 do\n printf \"%d \" dig.(i)\n done;\n print_newline();\n*)\n let count_solutions_with_carry c =\n(* printf \"count_solns.. c= \" ;\n for i= 7 downto 0 do\n\tprintf \"%d\" ((c lsr i) land 1)\n done;\n*)\n let c' = c lsl 2 in\n let rec prod_loop i ac =\n\tif ac=0 || i >= 10 then ac else (\n\t let ci = (c' lsr i) land 1 in\n\t let co= (c lsr i) land 1 in\n\t prod_loop (i+1) (ac * (count ci co (if i >= nd then 0 else dig.(i))))\n\t) in\n let ans = prod_loop 0 1 in\n(* printf \" answer = %d\\n\" ans; *)\n ans\n in\n\n let answer = sum 0 255 (fun c -> count_solutions_with_carry c) in\n printf \"%d\\n\" (answer - 2)\n done\n"}], "negative_code": [], "src_uid": "8588dd273c9651f8d51cd3a2b7bd81bd"} {"nl": {"description": "Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.Ivar has $$$n$$$ warriors, he places them on a straight line in front of the main gate, in a way that the $$$i$$$-th warrior stands right after $$$(i-1)$$$-th warrior. The first warrior leads the attack.Each attacker can take up to $$$a_i$$$ arrows before he falls to the ground, where $$$a_i$$$ is the $$$i$$$-th warrior's strength.Lagertha orders her warriors to shoot $$$k_i$$$ arrows during the $$$i$$$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $$$t$$$, they will all be standing to fight at the end of minute $$$t$$$.The battle will last for $$$q$$$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n, q \\leq 200\\,000$$$)\u00a0\u2014 the number of warriors and the number of minutes in the battle. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) that represent the warriors' strengths. The third line contains $$$q$$$ integers $$$k_1, k_2, \\ldots, k_q$$$ ($$$1 \\leq k_i \\leq 10^{14}$$$), the $$$i$$$-th of them represents Lagertha's order at the $$$i$$$-th minute: $$$k_i$$$ arrows will attack the warriors.", "output_spec": "Output $$$q$$$ lines, the $$$i$$$-th of them is the number of standing warriors after the $$$i$$$-th minute.", "sample_inputs": ["5 5\n1 2 1 2 1\n3 10 1 1 1", "4 4\n1 2 3 4\n9 1 10 6"], "sample_outputs": ["3\n5\n4\n4\n3", "1\n4\n4\n1"], "notes": "NoteIn the first example: after the 1-st minute, the 1-st and 2-nd warriors die. after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5\u00a0\u2014 all warriors are alive. after the 3-rd minute, the 1-st warrior dies. after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1. after the 5-th minute, the 2-nd warrior dies. "}, "positive_code": [{"source_code": "\nmodule type Num_caml = sig\n type t\n val zero: t\n val add: t -> t -> t\nend\n\nmodule Prefix_sum (N : Num_caml) = struct\n let compute (src: N.t array): N.t array =\n let t = ref N.zero in\n Array.init (Array.length src) (fun i ->\n t := N.add !t src.(i);\n !t\n )\nend\n\n(* spec: find the index of first element with value strictly > v,\n * or length if not found *)\nlet linear_search_range (v: 'a) (src: 'a array): int =\n let l = Array.length src - 1 in\n let rec f i = if i > l || src.(i) > v then i else f (i + 1) in\n f 0\n\nlet bin_search_range (v: 'a) (src: 'a array): int =\n let len = Array.length src in\n let rec f l r =\n if l = r\n then l\n else\n let m = (l + r) / 2 in\n if v > src.(m)\n then f (m + 1) r\n else if v < src.(m)\n then f l m\n else f (m + 1) r\n in\n f 0 len\n\nlet test_random_int ?(min: int = 0) ~(max: int): int =\n Random.int (max - min) + min\n\nlet test_generate_sorted_array ~(len: int) ~(range: int * int): 'a array =\n let min, max = range in\n let ret = Array.init len (fun _ -> test_random_int ~min ~max) in\n Array.sort compare ret;\n ret\n\nlet test_do ?(len: int = 24) ?(range: int * int = (-96, 96)) (): unit =\n let min, max = range in\n let values = test_generate_sorted_array ~len ~range in\n print_string \"Test Array:\";\n Array.iter (fun i -> Printf.printf \" %d\" i) values;\n print_newline ();\n for i = 1 to 12 do\n let r = test_random_int ~min ~max in\n Printf.printf \"%d \" r;\n Printf.printf \"%d %d\\n\"\n (linear_search_range r values)\n (bin_search_range r values);\n flush stdout;\n done\n\nlet () =\n (* n - #warrior, q - duration *)\n let open Int64 in\n let n, q = Scanf.scanf \" %d %d\" (fun n q -> n, q) in\n let hps = Array.init n (fun _ -> Scanf.scanf \" %d\" (fun i -> of_int i)) in\n let arrows = Array.init q (fun _ -> Scanf.scanf \" %Ld\" (fun i -> i)) in\n\n let module P = Prefix_sum(Int64) in\n let hpps = P.compute hps in\n (* index of first standing warrior *)\n let total_damage = ref zero in\n for i = 1 to q do\n total_damage := add !total_damage arrows.(i - 1);\n let nlost = bin_search_range !total_damage hpps in\n if nlost = n then total_damage := zero;\n Printf.printf \"%d\\n\" (n - if nlost = n then 0 else nlost)\n done\n"}], "negative_code": [], "src_uid": "23d69ae8b432111c4291e7b767443925"} {"nl": {"description": "You are given two huge binary integer numbers $$$a$$$ and $$$b$$$ of lengths $$$n$$$ and $$$m$$$ respectively. You will repeat the following process: if $$$b > 0$$$, then add to the answer the value $$$a~ \\&~ b$$$ and divide $$$b$$$ by $$$2$$$ rounding down (i.e. remove the last digit of $$$b$$$), and repeat the process again, otherwise stop the process.The value $$$a~ \\&~ b$$$ means bitwise AND of $$$a$$$ and $$$b$$$. Your task is to calculate the answer modulo $$$998244353$$$.Note that you should add the value $$$a~ \\&~ b$$$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $$$a = 1010_2~ (10_{10})$$$ and $$$b = 1000_2~ (8_{10})$$$, then the value $$$a~ \\&~ b$$$ will be equal to $$$8$$$, not to $$$1000$$$.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$a$$$ and the length of $$$b$$$ correspondingly. The second line of the input contains one huge integer $$$a$$$. It is guaranteed that this number consists of exactly $$$n$$$ zeroes and ones and the first digit is always $$$1$$$. The third line of the input contains one huge integer $$$b$$$. It is guaranteed that this number consists of exactly $$$m$$$ zeroes and ones and the first digit is always $$$1$$$.", "output_spec": "Print the answer to this problem in decimal notation modulo $$$998244353$$$.", "sample_inputs": ["4 4\n1010\n1101", "4 5\n1001\n10101"], "sample_outputs": ["12", "11"], "notes": "NoteThe algorithm for the first example: add to the answer $$$1010_2~ \\&~ 1101_2 = 1000_2 = 8_{10}$$$ and set $$$b := 110$$$; add to the answer $$$1010_2~ \\&~ 110_2 = 10_2 = 2_{10}$$$ and set $$$b := 11$$$; add to the answer $$$1010_2~ \\&~ 11_2 = 10_2 = 2_{10}$$$ and set $$$b := 1$$$; add to the answer $$$1010_2~ \\&~ 1_2 = 0_2 = 0_{10}$$$ and set $$$b := 0$$$. So the answer is $$$8 + 2 + 2 + 0 = 12$$$.The algorithm for the second example: add to the answer $$$1001_2~ \\&~ 10101_2 = 1_2 = 1_{10}$$$ and set $$$b := 1010$$$; add to the answer $$$1001_2~ \\&~ 1010_2 = 1000_2 = 8_{10}$$$ and set $$$b := 101$$$; add to the answer $$$1001_2~ \\&~ 101_2 = 1_2 = 1_{10}$$$ and set $$$b := 10$$$; add to the answer $$$1001_2~ \\&~ 10_2 = 0_2 = 0_{10}$$$ and set $$$b := 1$$$; add to the answer $$$1001_2~ \\&~ 1_2 = 1_2 = 1_{10}$$$ and set $$$b := 0$$$. So the answer is $$$1 + 8 + 1 + 0 + 1 = 11$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nmodule CumulSumArray = struct\n\tlet make a = \n\t\tlet ln = Array.length a\n\t\tin let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n\tlet sum l r a = (* 0-origin,closed *)\n\t\t(* let l,r = i32 l, i32 r in *)\n\t\tif l>r then 0L else (a.(r+$1) - a.(l))\n\tlet sum_1orig l r a = (* codeforces *)\n\t\t(* let l,r = i32 l, i32 r in *) sum (l-$1) (r-$1) a\nend\nlet md = 998244353L\nlet () =\n\tlet _,m = get_2_i64 0 in\n\tlet a,b = scanf \" %s %s\" (fun u v -> u,v) in\n\tlet b = char_list_of_string b |> List.rev |> List.map (fun c -> (int_of_char c -$ int_of_char '0') |> i64) |> Array.of_list in\n\tlet bsum = Array.fold_left (+) 0L b in\n\tlet bs = CumulSumArray.make b in\n\t(* dump_array bs; *)\n\ta |> char_list_of_string |> List.rev\n\t|> List.fold_left (fun (i,sum,prod) v ->\n\t\tif v='1' && i <= i32 m then (\n\t\t\tlet q = bsum - bs.(i) in\n\t\t\t(* printf \"sum += prod * (bsum - bs.(%d)) = %Ld * %Ld (= %Ld)\\n\" i prod q (prod*q); *)\n\t\t\t(i+$1,(sum+prod*q)%md,(prod*2L)%md)\n\t\t) else (i+$1,sum,(prod*2L)%md)\n\t) (0,0L,1L)\n\t|> (fun (_,s,_) -> printf \"%Ld\\n\" s)\n\n\t(* for i=String.length a -$1 downto 0 do done *)\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nmodule CumulSumArray = struct\n\tlet make a = \n\t\tlet ln = Array.length a\n\t\tin let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n\tlet sum l r a = (* 0-origin,closed *)\n\t\t(* let l,r = i32 l, i32 r in *)\n\t\tif l>r then 0L else (a.(r+$1) - a.(l))\n\tlet sum_1orig l r a = (* codeforces *)\n\t\t(* let l,r = i32 l, i32 r in *) sum (l-$1) (r-$1) a\nend\nlet md = 998244353L\nlet () =\n\tlet _,_ = get_2_i64 0 in\n\tlet a,b = scanf \" %s %s\" (fun u v -> u,v) in\n\tlet b = char_list_of_string b |> List.map (fun c -> (int_of_char c -$ int_of_char '0') |> i64) |> Array.of_list in\n\tlet bsum = Array.fold_left (+) 0L b in\n\tlet bs = CumulSumArray.make b in\n\ta |> char_list_of_string |> List.rev\n\t|> List.fold_left (fun (i,sum,prod) v ->\n\t\tif v='1' then (\n\t\t\tlet q = bsum - bs.(i) in\n\t\t\t(* printf \"sum += %Ld * %Ld (= %Ld)\\n\" prod q (prod*q); *)\n\t\t\t(i+$1,(sum%md+prod*q)%md,(prod*2L)%md)\n\t\t) else (i+$1,sum,(prod*2L)%md)\n\t) (0,0L,1L)\n\t|> (fun (_,s,_) -> printf \"%Ld\\n\" (s%md))\n\n\t(* for i=String.length a -$1 downto 0 do done *)\n\n\n\n\n\n\n\n\n"}], "src_uid": "d2fe5a201d1ec20c5b32cd99b54e13d0"} {"nl": {"description": "You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.", "input_spec": "The first line contains two integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the sizes of arrays a and b. The second line contains n integers \u2014 the elements of array a (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109). The third line contains m integers \u2014 the elements of array b (\u2009-\u2009109\u2009\u2264\u2009bj\u2009\u2264\u2009109).", "output_spec": "Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.", "sample_inputs": ["5 4\n1 3 5 7 9\n6 4 2 8", "5 5\n1 2 1 2 5\n3 1 4 1 5"], "sample_outputs": ["3 2 1 4", "4 2 4 2 5"], "notes": null}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int() and m = scan_int();;\nlet a = Array.make n 0 and b = Array.make m (0, 0) and wyn = Array.make m 0;;\n\nfor i = 0 to n - 1 do\n a.(i) <- scan_int ();\ndone;\n\nfor i = 0 to m - 1 do\n b.(i) <- (scan_int (), i);\ndone;\n\nArray.sort compare a; Array.sort compare b;\n\nlet cnt = ref 0 and l = ref 0 in\n\nfor i = 0 to m - 1 do\n while (!l < n) && a.(!l) <= fst (b.(i)) do\n incr cnt; incr l; \n done;\n wyn.(snd b.(i)) <- !cnt;\ndone; \n\nfor i = 0 to m - 1 do\n print_int(wyn.(i)); psp();\ndone;"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int() and m = scan_int();;\nlet a = Array.make n 0 and b = Array.make m (0, 0) and wyn = Array.make m 0;;\n\nfor i = 0 to n - 1 do\n a.(i) <- scan_int ();\ndone;\n\nfor i = 0 to m - 1 do\n b.(i) <- (scan_int (), i);\ndone;\n\nArray.fast_sort compare a; Array.fast_sort compare b;\n\nlet cnt = ref 0 and l = ref 0 in\n\nfor i = 0 to m - 1 do\n while (!l < n) && a.(!l) <= fst (b.(i)) do\n incr cnt; incr l; \n done;\n wyn.(snd b.(i)) <- !cnt;\ndone; \n\nfor i = 0 to m - 1 do\n print_int(wyn.(i)); psp();\ndone;"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = Array.make m 0 in\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 0 to m - 1 do\n b.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a;\n for i = 0 to m - 1 do\n let l = ref (-1)\n and r = ref n in\n\twhile !l < !r - 1 do\n\t let m = (!l + !r) / 2 in\n\t if a.(m) <= b.(i)\n\t then l := m\n\t else r := m\n\tdone;\n\tPrintf.printf \"%d \" !r;\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "e9a519be33f25c828bae787330c18dd4"} {"nl": {"description": "Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special \u2014 it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.", "input_spec": "The first line of input contains two integers n and s (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009s\u2009\u2264\u20091000)\u00a0\u2014 the number of passengers and the number of the top floor respectively. The next n lines each contain two space-separated integers fi and ti (1\u2009\u2264\u2009fi\u2009\u2264\u2009s, 1\u2009\u2264\u2009ti\u2009\u2264\u20091000)\u00a0\u2014 the floor and the time of arrival in seconds for the passenger number i.", "output_spec": "Print a single integer\u00a0\u2014 the minimum amount of time in seconds needed to bring all the passengers to floor 0.", "sample_inputs": ["3 7\n2 1\n3 8\n5 2", "5 10\n2 77\n3 33\n8 21\n9 12\n10 64"], "sample_outputs": ["11", "79"], "notes": "NoteIn the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:1. Move to floor 5: takes 2 seconds.2. Pick up passenger 3.3. Move to floor 3: takes 2 seconds.4. Wait for passenger 2 to arrive: takes 4 seconds.5. Pick up passenger 2.6. Go to floor 2: takes 1 second.7. Pick up passenger 1.8. Go to floor 0: takes 2 seconds.This gives a total of 2\u2009+\u20092\u2009+\u20094\u2009+\u20091\u2009+\u20092\u2009=\u200911 seconds."}, "positive_code": [{"source_code": "let r2 = Scanf.scanf \" %d %d\" ;;\nlet n, s = r2 (fun x y -> (x, y)) ;;\n\nlet a = Array.make s 0 ;;\nfor _ = 1 to n do\n let f, t = r2 (fun x y -> (x-1, y)) in\n a.(f) <- max a.(f) t\ndone ;;\n\nlet rec time f t = match f with\n | 0 -> t\n | f -> time (f-1) (1 + max t a.(f-1) )\n;;\nprint_int @@ time s 0\n"}, {"source_code": "type passenger = {\n mutable f : int;\n mutable t : int;\n};;\n\n(* Echange deux \u00e9l\u00e9ments d'un tableau *)\nlet echange tab i j = \n let z = tab.(i) in\n tab.(i) <- tab.(j);\n tab.(j) <- z;;\n\n(* Quicksort : Sort on the floor of each passenger *)\nlet partition tab p r =\n let x = tab.(r) in (* Pivot *)\n let i = ref (p - 1) in\n for j = p to r - 1 do\n if tab.(j).f <= x.f then begin\n i := !i + 1 ;\n echange tab !i j\n end\n done ; echange tab (!i + 1) r ;\n (!i + 1);;\nlet rec quickSort tab p r =\n if p < r then begin\n let q = partition tab p r in\n quickSort tab p (q-1) ;\n quickSort tab (q + 1) r\n end;;\n\nlet n, s = Scanf.scanf \"%d %d \" (fun n' s' -> n', s') in\n let passengers = Array.init n (fun _i -> \n let pass_f, pass_t = Scanf.scanf \"%d %d \" (fun f' t' -> f', t') in\n {f = pass_f ; t = pass_t}\n ) in\n quickSort passengers 0 (n-1) ;\n let time = ref 0 in\n let floor = ref s in\n for i = 0 to (n-1) do\n time := !time + (!floor - (passengers.(i).f)); (* Temps de descente *)\n floor := passengers.(i).f;\n if !time < passengers.(i).t then \n time := !time + (passengers.(i).t - !time) (* Temps d'attente *)\n done ; \n time := !time + !floor ; (* On descend tout en bas *)\n print_int !time;;\n \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\t\t\t\t \nlet () = \n let n = read_int () in\n let s = read_int () in\n let pass = Array.init n (fun _ -> read_pair()) in\n let arrive = Array.make (s+1) 0 in\n\n for i=0 to n-1 do\n let (f,t) = pass.(i) in\n arrive.(f) <- max arrive.(f) t\n done;\n\n let rec loop floor time = if floor = 0 then time else\n (* at floor arrive at time *)\n let time = max time arrive.(floor) in\n loop (floor-1) (time+1)\n in\n\n printf \"%d\\n\" (loop s 0)\n"}], "negative_code": [], "src_uid": "5c12573b3964ee30af0349c11c0ced3b"} {"nl": {"description": "For an array $$$b$$$ of length $$$m$$$ we define the function $$$f$$$ as $$$ f(b) = \\begin{cases} b[1] & \\quad \\text{if } m = 1 \\\\ f(b[1] \\oplus b[2],b[2] \\oplus b[3],\\dots,b[m-1] \\oplus b[m]) & \\quad \\text{otherwise,} \\end{cases} $$$ where $$$\\oplus$$$ is bitwise exclusive OR.For example, $$$f(1,2,4,8)=f(1\\oplus2,2\\oplus4,4\\oplus8)=f(3,6,12)=f(3\\oplus6,6\\oplus12)=f(5,10)=f(5\\oplus10)=f(15)=15$$$You are given an array $$$a$$$ and a few queries. Each query is represented as two integers $$$l$$$ and $$$r$$$. The answer is the maximum value of $$$f$$$ on all continuous subsegments of the array $$$a_l, a_{l+1}, \\ldots, a_r$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 5000$$$)\u00a0\u2014 the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\le a_i \\le 2^{30}-1$$$)\u00a0\u2014 the elements of the array. The third line contains a single integer $$$q$$$ ($$$1 \\le q \\le 100\\,000$$$)\u00a0\u2014 the number of queries. Each of the next $$$q$$$ lines contains a query represented as two integers $$$l$$$, $$$r$$$ ($$$1 \\le l \\le r \\le n$$$).", "output_spec": "Print $$$q$$$ lines\u00a0\u2014 the answers for the queries.", "sample_inputs": ["3\n8 4 1\n2\n2 3\n1 2", "6\n1 2 4 8 16 32\n4\n1 6\n2 5\n3 4\n1 2"], "sample_outputs": ["5\n12", "60\n30\n12\n3"], "notes": "NoteIn first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.In second sample, optimal segment for first query are $$$[3,6]$$$, for second query \u2014 $$$[2,5]$$$, for third \u2014 $$$[3,4]$$$, for fourth \u2014 $$$[1,2]$$$."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\nlet n = scan_int();;\nlet a = Array.init n (fun i -> scan_int());;\n\nlet f = Array.make_matrix n n 0 and wyn = Array.make_matrix n n 0;;\nfor i = 0 to (n - 1) do\n f.(i).(i) <- a.(i);\n wyn.(i).(i) <- a.(i);\ndone;;\n\nfor i = 2 to n do\n for j = 0 to (n - i) do\n let r = j + i - 1 in\n f.(j).(r) <- f.(j + 1).(r) lxor f.(j).(r - 1);\n wyn.(j).(r) <- max (f.(j).(r)) (max wyn.(j+1).(r) wyn.(j).(r - 1));\n done;\ndone;;\n\nlet q = scan_int();;\nfor i = 1 to q do\n let a = scan_int() and b = scan_int() in\n print_int(wyn.(a - 1).(b - 1)); pnl();\ndone;;"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet build_answer n b =\n let v = Array.make_matrix n n 0 in\n for i=0 to n-1 do\n v.(i).(i) <- b.(i)\n done;\n\n for d=2 to n do\n for l=0 to n-d do\n let r = l+d-1 in\n v.(l).(r) <- v.(l+1).(r) lxor v.(l).(r-1)\n done\n done;\n\n for r=1 to n-1 do\n for l=r-1 downto 0 do\n v.(l).(r) <- max v.(l).(r) v.(l+1).(r)\n done\n done;\n\n for r=1 to n-1 do\n for l=r-1 downto 0 do\n v.(l).(r) <- max v.(l).(r) v.(l).(r-1)\n done\n done;\n\n v\n \nlet () = \n let n = read_int () in\n let b = Array.init n read_int in\n let q = read_int () in\n\n let v = build_answer n b in\n\n for i=1 to q do\n let l = read_int() -1 in\n let r = read_int() -1 in\n printf \"%d\\n\" v.(l).(r)\n done\n \n"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\nlet n = scan_int();;\nlet a = Array.init n (fun i -> scan_int());;\n\nlet f = Array.make_matrix n n 0 and wyn = Array.make_matrix n n 0;;\nfor i = 0 to (n - 1) do\n f.(i).(i) <- a.(i);\n wyn.(i).(i) <- a.(i);\ndone;;\n\nfor i = 2 to n do\n for j = 0 to (n - i) do\n let r = j + i - 1 in\n f.(j).(r) <- f.(j + 1).(r) lxor f.(j).(r - 1);\n wyn.(j).(r) <- max f.(j).(r) (max f.(j+1).(r) f.(j).(r - 1));\n done;\ndone;;\n\nlet q = scan_int();;\nfor i = 1 to q do\n let a = scan_int() and b = scan_int() in\n print_int(wyn.(a - 1).(b - 1)); pnl();\ndone;;"}], "src_uid": "5a686ba072078c9d0258987cb32d00fc"} {"nl": {"description": "Let's call some positive integer classy if its decimal representation contains no more than $$$3$$$ non-zero digits. For example, numbers $$$4$$$, $$$200000$$$, $$$10203$$$ are classy and numbers $$$4231$$$, $$$102306$$$, $$$7277420000$$$ are not.You are given a segment $$$[L; R]$$$. Count the number of classy integers $$$x$$$ such that $$$L \\le x \\le R$$$.Each testcase contains several segments, for each of them you are required to solve the problem separately.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 10^4$$$) \u2014 the number of segments in a testcase. Each of the next $$$T$$$ lines contains two integers $$$L_i$$$ and $$$R_i$$$ ($$$1 \\le L_i \\le R_i \\le 10^{18}$$$).", "output_spec": "Print $$$T$$$ lines \u2014 the $$$i$$$-th line should contain the number of classy integers on a segment $$$[L_i; R_i]$$$.", "sample_inputs": ["4\n1 1000\n1024 1024\n65536 65536\n999999 1000001"], "sample_outputs": ["1000\n1\n0\n2"], "notes": null}, "positive_code": [{"source_code": "let rec range ?(left: int = 0) (right: int): int list =\n\tif left >= right then [] else left :: range ~left:(left + 1) right\n\nlet split_on_space (str: string): string list =\n\tlet length = String.length str in\n\tlet is_space: int -> bool = \n\t\tfun index ->\n\t\t\tif (index < 0) || (index >= length) then true\n\t\t\telse str.[index] = ' '\n\tin\n\tlet is_start: int -> bool =\n\t\tfun index -> not (is_space index) && is_space (index - 1)\n\tin\n\tlet is_end: int -> bool =\n\t\tfun index -> not (is_space index) && is_space (index + 1)\n\tin\n\tlet indices = range length in\n\tlet start_pos = List.filter is_start indices in \n\tlet end_pos = List.filter is_end indices in\n\tlet make_substring: string list -> int -> int -> string list =\n\t\tfun tokens left right ->\n\t\t\tlet new_token = String.sub str left (right - left + 1) in\n\t\t\tnew_token :: tokens\n\tin\n\tlet tokens = List.fold_left2 make_substring [] start_pos end_pos in\n\tList.rev tokens\n\t\t\t\nclass reader channel =\n\tobject (this)\n\n\tval mutable tokens = []\n\n method private get_tokens () =\n let new_line = read_line () in\n let tokens = split_on_space new_line in\n match tokens with\n | [] -> this#get_tokens ()\n | _ -> tokens\n\n\tmethod next_string () =\n if (List.length tokens = 0) then tokens <- this#get_tokens();\n let result = List.hd tokens in\n tokens <- List.tl tokens; result\n\n method next_int () =\n let str = this#next_string() in (Int64.of_string) str\n\n method next_float () =\n let str = this#next_string() in (float_of_string) str\n \nend\n\nlet reader = new reader stdin\n\nlet ( +. ) = Int64.add\nlet ( -. ) = Int64.sub\nlet ( *. ) = Int64.mul\nlet ( /. ) = Int64.div\nlet ( %. ) = Int64.rem\n\nlet get_digits (number: int64): int array =\n\tlet char_to_int: char -> int =\n\t\tfun c -> (Char.code c) - (Char.code '0')\n\tin\n\tlet str = Int64.to_string number in\n\tlet num_digit = String.length str in\n\tArray.init num_digit (fun index -> char_to_int str.[num_digit - index - 1])\n\t\nlet rec count_number (left: int64) (right: int64): int64 =\n\tif right < left then Int64.zero else\n\t\tif left > Int64.zero then (count_number Int64.zero right) -. (count_number Int64.zero (left -. Int64.one)) else\n\t\t\tlet digits = get_digits right in\n\t\t\tlet num_digit = Array.length digits in\n\t\t\t\n\t\t\tlet init_1d: int -> int64 = fun _ -> Int64.zero in\n\t\t\tlet init_2d: int -> int64 array = fun _ -> Array.init 2 init_1d in\n\t\t\tlet init_3d: int -> int64 array array = fun _ -> Array.init 4 init_2d in\n\t\t\tlet f: int64 array array array = Array.init (num_digit + 1) init_3d in\n\t\t\tf.(0).(0).(1) <- Int64.one;\n\t\t\t\n\t\t\tlet pos_range = range num_digit in\n\t\t\tlet used_range = range 4 in\n\t\t\tlet comp_range = range 2 in\n\t\t\tlet next_range = range 10 in\n\t\t\t\n\t\t\tList.iter (fun pos -> \n\t\t\t\tList.iter (fun used ->\n\t\t\t\t\tList.iter (fun comp -> \n\t\t\t\t\t\tlet cur = f.(pos).(used).(comp) in\n\t\t\t\t\t\tif cur > Int64.zero then\n\t\t\t\t\t\t\tList.iter (fun next ->\n\t\t\t\t\t\t\t\tlet used' = if next = 0 then used else used + 1 in\n\t\t\t\t\t\t\t\tlet comp' = if next = digits.(pos) then comp else \n\t\t\t\t\t\t\t\t\tif next < digits.(pos) then 1 else 0\n\t\t\t\t\t\t\t\tin\n\t\t\t\t\t\t\t\tif used' <= 3 then\n\t\t\t\t\t\t\t\t\tf.(pos + 1).(used').(comp') <- f.(pos + 1).(used').(comp') +. cur\n\t\t\t\t\t\t\t\t) next_range\n\t\t\t\t\t\t) comp_range\n\t\t\t\t\t) used_range\n\t\t\t\t) pos_range;\n\t\t\t\n\t\t\tList.fold_left (fun sum used -> sum +. f.(num_digit).(used).(1) ) Int64.zero used_range\n\t\t\t\t\nlet () =\n\tlet q = reader#next_int () in\n\tlet q = Int64.to_int q in\n\tfor i = 1 to q do\n\t\tlet l = reader#next_int () in\n\t\tlet r = reader#next_int () in\n\t\tlet res = count_number l r in\n\t\tprint_endline (Int64.to_string res)\n\tdone"}], "negative_code": [], "src_uid": "993f96a62a2ba75a12684b75a5b2f1ed"} {"nl": {"description": "There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i\u2009+\u20091 are neighbours for all i from 1 to n\u2009-\u20091. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product si\u00b7sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.", "input_spec": "The first line of the input contains two space-separated integers n and p (3\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20092\u2009\u2264\u2009p\u2009\u2264\u2009109)\u00a0\u2014 the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime. The i-th of the following n lines contains information about i-th shark\u00a0\u2014 two space-separated integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.", "output_spec": "Print a single real number \u2014 the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["3 2\n1 2\n420 421\n420420 420421", "3 5\n1 4\n2 3\n11 14"], "sample_outputs": ["4500.0", "0.0"], "notes": "NoteA prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0,\u2009s1,\u2009s2) each shark grows: (1,\u2009420,\u2009420420): note that s0\u00b7s1\u2009=\u2009420, s1\u00b7s2\u2009=\u2009176576400, and s2\u00b7s0\u2009=\u2009420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars. (1,\u2009420,\u2009420421): now, the product s2\u00b7s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000. (1,\u2009421,\u2009420420): total is 4000 (1,\u2009421,\u2009420421): total is 0. (2,\u2009420,\u2009420420): total is 6000. (2,\u2009420,\u2009420421): total is 6000. (2,\u2009421,\u2009420420): total is 6000. (2,\u2009421,\u2009420421): total is 4000.The expected value is .In the second sample, no combination of quantities will garner the sharks any money."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac +. (f i))\n\nlet ceil a b = (a ++ b -- 1L) // b\nlet floor a b = a // b\nlet float = Int64.to_float\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %Ld %Ld \" (fun x y -> (x,y))\n\nlet () = \n let n = read_int () in\n let p = long(read_int()) in\n let range = Array.init n (fun _ -> read_pair()) in\n\n let prob_p_divides i =\n let (l,r) = range.(i) in\n let len = r -- l ++ 1L in\n let first = (ceil l p) ** p in\n let last = (floor r p) ** p in\n if last < first then 0.0 else (\n (float ((last -- first)//p ++ 1L)) /. (float len)\n )\n in\n\n let exp2 i = \n let j = (i+1) mod n in \n let pri = prob_p_divides i in\n let prj = prob_p_divides j in\n 2000.0 *. pri *. prj +.\n 2000.0 *. pri *. (1.0 -. prj) +. \n 2000.0 *. (1.0 -. pri) *. prj\n in\n \n printf \"%.8f\\n\" (sum 0 (n-1) exp2 0.0)\n"}], "negative_code": [], "src_uid": "5aad0a82748d931338140ae81fed301d"} {"nl": {"description": "In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression ma\u2009-\u2009mb, where a is the most loaded server and b is the least loaded one.In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.Write a program to find the minimum number of seconds needed to balance the load of servers.", "input_spec": "The first line contains positive number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of the servers. The second line contains the sequence of non-negative integers m1,\u2009m2,\u2009...,\u2009mn (0\u2009\u2264\u2009mi\u2009\u2264\u20092\u00b7104), where mi is the number of tasks assigned to the i-th server.", "output_spec": "Print the minimum number of seconds required to balance the load.", "sample_inputs": ["2\n1 6", "7\n10 11 10 11 10 11 11", "5\n1 2 3 4 5"], "sample_outputs": ["2", "0", "3"], "notes": "NoteIn the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.In the second example the load is already balanced.A possible sequence of task movements for the third example is: move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5); then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4); then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0L in\n let s = ref 0L in\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s);\n s := !s +| a.(i);\n done;\n Array.sort compare a;\n let ma = !s /| Int64.of_int n in\n let mb =\n ma +| if ma *| Int64.of_int n = !s then 0L else 1L\n in\n let x = ref 0L in\n let y = ref 0L in\n for i = 0 to n - 1 do\n\tif a.(i) < ma\n\tthen x := !x +| ma -| a.(i)\n\telse if a.(i) > mb\n\tthen y := !y +| a.(i) -| mb\n done;\n let res = max !x !y in\n Printf.printf \"%Ld\\n\" res\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet ( ++ ) a b = Int64.add a b\nlet ( ** ) a b = Int64.mul a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\n\nlet () = \n\n let n = read_int() in\n let nn = long n in\n let m = Array.init n (fun _ -> long (read_int())) in\n let s = sum 0 (n-1) (fun i -> m.(i)) 0L in\n\n let p = s//nn in\n let q = (s++(nn--1L)) // nn in\n\n let total_above_q = sum 0 (n-1) (fun i -> max 0L (m.(i) -- q)) 0L in\n let total_below_p = sum 0 (n-1) (fun i -> max 0L (p -- m.(i))) 0L in\n\n printf \"%Ld\\n\" (max total_above_q total_below_p)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet ( ++ ) a b = Int64.add a b\nlet ( ** ) a b = Int64.mul a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\n\nlet () = \n\n let n = read_int() in\n let nn = long n in\n let m = Array.init n (fun _ -> long (read_int())) in\n let s = sum 0 (n-1) (fun i -> m.(i)) 0L in\n\n let p = s//nn in\n let q = (s++(nn--1L)) // nn in\n\n let total_above_q = sum 0 (n-1) (fun i -> max 0L (m.(i) -- q)) 0L in\n let total_below_p = sum 0 (n-1) (fun i -> min 0L (p -- m.(i))) 0L in\n\n printf \"%Ld\\n\" (max total_above_q total_below_p)\n"}], "src_uid": "c0c29565e465840103a4af884f951cda"} {"nl": {"description": "Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak\u2009+\u20091 and ak\u2009-\u20091 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105).", "output_spec": "Print a single integer \u2014 the maximum number of points that Alex can earn.", "sample_inputs": ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"], "sample_outputs": ["2", "4", "10"], "notes": "NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,\u20092,\u20092,\u20092]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points."}, "positive_code": [{"source_code": "let ( + ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( * ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( - ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( / ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( ~- ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet pf = Printf.printf\n \nlet epf = Printf.eprintf\n \nlet sf = Scanf.scanf\n \nlet ( |> ) x f = f x\n \nlet ( @@ ) f x = f x\n \nmodule Array = ArrayLabels\n \nmodule List =\n struct\n include ListLabels\n \n let rec repeat n a =\n if n = 0 then [] else a :: (repeat (Pervasives.( - ) n 1) a)\n \n let rec drop n a =\n if n = 0\n then a\n else\n (match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (Pervasives.( - ) n 1) xs)\n \n end\n \nmodule H = Hashtbl\n \nlet solve n arr =\n (Array.sort ~cmp: compare arr;\n let prev = ref arr.(0) in\n let cnt = ref 1L in\n let ls = ref []\n in\n (for i = 1 to Pervasives.( - ) n 1 do\n if !prev = arr.(i)\n then cnt := Int64.add !cnt 1L\n else (ls := ((!prev), (!cnt)) :: !ls; prev := arr.(i); cnt := 1L)\n done;\n ls := ((!prev), (!cnt)) :: !ls;\n let arr = Array.of_list !ls in\n let n = Array.length arr\n in\n (Array.iter arr ~f: (fun (v, c) -> epf \"(%Ld, %Ld), \" v c);\n epf \"\\n\";\n let mul (x, y) = Int64.mul (x : int64) y in\n let memo = H.create 10 in\n let rec iter i =\n if i = n\n then 0L\n else\n if i = (Pervasives.( - ) n 1)\n then mul arr.(i)\n else\n if H.mem memo i\n then H.find memo i\n else\n if\n (Int64.sub (fst arr.(i)) 1L) =\n (fst arr.(Pervasives.( + ) i 1))\n then\n (let v =\n max\n (Int64.add (iter (Pervasives.( + ) i 2))\n (mul arr.(i)))\n (iter (Pervasives.( + ) i 1))\n in (H.add memo i v; v))\n else\n (let v =\n Int64.add (mul arr.(i)) (iter (Pervasives.( + ) i 1))\n in (H.add memo i v; v))\n in (pf \"%Ld\\n\") @@ (iter 0))))\n \nlet () =\n sf \"%d \"\n (fun n ->\n let arr = Array.init n ~f: (fun _ -> sf \"%Ld \" (fun x -> x))\n in solve n arr)\n \n\n"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\nlet print score = Printf.printf \"%Ld\\n\" score\n\nlet list_init n f =\n let rec loop i list = \n if i < n\n then\n let element = f(i) in\n loop (i + 1) (element :: list)\n else\n List.rev list\n in loop 0 []\n\nlet count list =\n let rec loop count acc = function\n | a :: (b :: _ as tl) -> if a = b then loop (count + 1) acc tl\n else loop 0 ((a, count + 1) :: acc) tl\n | [x] -> (x, count + 1) :: acc\n | [] -> []\n in List.rev (loop 0 [] list)\n\nlet multiply list = List.map (fun (x, n) -> (x, Int64.mul (Int64.of_int x) (Int64.of_int n))) list\n\nlet score list = \n let rec loop prev sum_if_prev_taken sum_if_prev_skipped rest =\n let sum_if_unconstrained = Pervasives.max sum_if_prev_taken sum_if_prev_skipped in\n match rest with\n | [] -> sum_if_unconstrained\n | (a, v) :: tl -> \n let sum_if_a_taken = \n if a - 1 = prev\n then\n Int64.add v sum_if_prev_skipped\n else\n Int64.add v sum_if_unconstrained\n in\n let sum_if_a_skipped = sum_if_unconstrained in\n loop a sum_if_a_taken sum_if_a_skipped tl\n in loop (-1) 0L 0L list\n\nlet input () = \n let n = read () in\n let numbers = List.sort (Pervasives.compare) (list_init n (fun i -> read ())) in\n (numbers, n)\n\nlet solve (numbers, n) = \n let score = score (multiply (count numbers)) in\n score\n\nlet () = print (solve (input ()))"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Num;;\n\nlet n = bscanf Scanning.stdin \"%d \" (fun x -> x);;\n\nlet nn = 100000 + 5;;\nlet count = Array.make nn (num_of_int 0);;\nlet indx = Array.make nn 0;;\nlet score = Array.make nn (num_of_int 0);;\n\nlet p = Array.init n (fun x -> 0);;\n\nfor i=0 to n-1 do\n let f = bscanf Scanning.stdin \"%d \" (fun x -> x) in\n count.(f) <- count.(f) +/ (num_of_int f)\ndone;;\n\nlet l = ref 1;;\n\nfor i=1 to nn-1 do\n if count.(i) >/ num_of_int 0 then\n begin\n indx.(!l) <- i;\n l := !l + 1\n end\ndone;;\n\n(*For testing\nfor i=1 to !l-1 do\n printf \"%d %d\\n\" indx.(i) count.(indx.(i));\ndone;;*)\n\nscore.(0) <- num_of_int 0;;\nscore.(1) <- count.(indx.(1));;\nlet cur_indx = ref indx.(1) in\nfor i=2 to !l-1 do\n let x1 = !cur_indx in\n let x2 = indx.(i) in\n if x2 > x1 + 1 then\n begin\n score.(i)<-score.(i-1) +/ count.(x2);\n cur_indx := indx.(i)\n end\n else\n begin\n let tscore = score.(i-2) +/ count.(x2) in\n if tscore >/ score.(i-1) then\n begin\n score.(i) <- tscore;\n cur_indx := x2\n end\n else\n begin\n score.(i) <- score.(i-1);\n cur_indx := indx.(i-1)\n end\n end\ndone;;\n\nprint_endline (string_of_num (score.(!l-1)));; \n\n"}], "negative_code": [{"source_code": "let ( + ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( * ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( - ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( / ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( ~- ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet pf = Printf.printf\n \nlet epf = Printf.eprintf\n \nlet sf = Scanf.scanf\n \nlet ( |> ) x f = f x\n \nlet ( @@ ) f x = f x\n \nmodule Array = ArrayLabels\n \nmodule List =\n struct\n include ListLabels\n \n let rec repeat n a =\n if n = 0 then [] else a :: (repeat (Pervasives.( - ) n 1) a)\n \n let rec drop n a =\n if n = 0\n then a\n else\n (match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (Pervasives.( - ) n 1) xs)\n \n end\n \nmodule H = Hashtbl\n \nlet solve n arr =\n (Array.sort ~cmp: compare arr;\n let prev = ref arr.(0) in\n let cnt = ref 1L in\n let ls = ref []\n in\n (for i = 1 to Pervasives.( - ) n 1 do\n if !prev = arr.(i)\n then cnt := Int64.add !cnt 1L\n else (ls := ((!prev), (!cnt)) :: !ls; prev := arr.(i); cnt := 1L)\n done;\n ls := ((!prev), (!cnt)) :: !ls;\n let arr = Array.of_list !ls in\n let n = Array.length arr\n in\n (Array.iter arr ~f: (fun (v, c) -> epf \"(%Ld, %Ld), \" v c);\n epf \"\\n\";\n let mul (x, y) = Int64.mul (x : int64) y in\n let memo = H.create 10 in\n let rec iter i =\n if i = n\n then 0L\n else\n if i = (Pervasives.( - ) n 1)\n then mul arr.(i)\n else\n if H.mem memo i\n then H.find memo i\n else\n if\n (Int64.sub (fst arr.(i)) 1L) =\n (fst arr.(Pervasives.( + ) i 1))\n then\n (let v =\n max\n (Int64.add (iter (Pervasives.( + ) i 2))\n (mul arr.(i)))\n (iter (Pervasives.( + ) i 1))\n in (H.add memo i v; v))\n else\n (let v =\n Int64.add (mul arr.(i)) (iter (Pervasives.( + ) i 2))\n in (H.add memo i v; v))\n in (pf \"%Ld\\n\") @@ (iter 0))))\n \nlet () =\n sf \"%d \"\n (fun n ->\n let arr = Array.init n ~f: (fun _ -> sf \"%Ld \" (fun x -> x))\n in solve n arr)\n \n"}, {"source_code": "let ( + ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( * ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( - ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( / ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet ( ~- ) : 'a -> 'a -> 'a = fun x y -> assert false\n \nlet pf = Printf.printf\n \nlet epf = Printf.eprintf\n \nlet sf = Scanf.scanf\n \nlet ( |> ) x f = f x\n \nlet ( @@ ) f x = f x\n \nmodule Array = ArrayLabels\n \nmodule List =\n struct\n include ListLabels\n \n let rec repeat n a =\n if n = 0 then [] else a :: (repeat (Pervasives.( - ) n 1) a)\n \n let rec drop n a =\n if n = 0\n then a\n else\n (match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (Pervasives.( - ) n 1) xs)\n \n end\n \nmodule H = Hashtbl\n \nlet solve n arr =\n (Array.sort ~cmp: compare arr;\n let prev = ref arr.(0) in\n let cnt = ref 1L in\n let ls = ref []\n in\n (for i = 1 to Pervasives.( - ) n 1 do\n if !prev = arr.(i)\n then cnt := Int64.add !cnt 1L\n else (ls := ((!prev), (!cnt)) :: !ls; prev := arr.(i); cnt := 1L)\n done;\n ls := ((!prev), (!cnt)) :: !ls;\n let arr = Array.of_list !ls in\n let n = Array.length arr\n in\n (Array.iter arr ~f: (fun (v, c) -> epf \"(%Ld, %Ld), \" v c);\n epf \"\\n\";\n let mul (x, y) = Int64.mul (x : int64) y in\n let memo = H.create 10 in\n let rec iter i =\n if i = n\n then 0L\n else\n if i = (Pervasives.( - ) n 1)\n then mul arr.(i)\n else\n if H.mem memo i\n then H.find memo i\n else\n if\n (Int64.sub (fst arr.(i)) 1L) =\n (fst arr.(Pervasives.( + ) i 1))\n then\n (let v =\n max\n (Int64.add (iter (Pervasives.( + ) i 2))\n (mul arr.(i)))\n (iter (Pervasives.( + ) i 1))\n in (H.add memo i v; v))\n else\n (let v =\n Int64.add\n (Int64.add (mul arr.(i))\n (mul arr.(Pervasives.( + ) i 1)))\n (iter (Pervasives.( + ) i 2))\n in (H.add memo i v; v))\n in (pf \"%Ld\\n\") @@ (iter 0))))\n \nlet () =\n sf \"%d \"\n (fun n ->\n let arr = Array.init n ~f: (fun _ -> sf \"%Ld \" (fun x -> x))\n in solve n arr)\n \n"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\nlet print score = Printf.printf \"%d\\n\" score\n\nlet list_init n f =\n let rec loop i list = \n if i < n\n then\n let element = f(i) in\n loop (i + 1) (element :: list)\n else\n List.rev list\n in loop 0 []\n\nlet count list =\n let rec loop count acc = function\n | a :: (b :: _ as tl) -> if a = b then loop (count + 1) acc tl\n else loop 0 ((a, count + 1) :: acc) tl\n | [x] -> (x, count + 1) :: acc\n | [] -> []\n in List.rev (loop 0 [] list)\n\nlet multiply list = List.map (fun (x, n) -> (x, x * n)) list\n\nlet score list = \n let rec loop prev sum_if_prev_taken sum_if_prev_skipped rest =\n let sum_if_unconstrained = Pervasives.max sum_if_prev_taken sum_if_prev_skipped in\n match rest with\n | [] -> sum_if_unconstrained\n | (a, v) :: tl -> \n let sum_if_a_taken = \n if a - 1 = prev\n then\n v + sum_if_prev_skipped\n else\n v + sum_if_unconstrained\n in\n let sum_if_a_skipped = sum_if_unconstrained in\n loop a sum_if_a_taken sum_if_a_skipped tl\n in loop (-1) 0 0 list\n\nlet input () = \n let n = read () in\n let numbers = List.sort (Pervasives.compare) (list_init n (fun i -> read ())) in\n (numbers, n)\n\nlet solve (numbers, n) = \n let score = score (multiply (count numbers)) in\n score\n\nlet () = print (solve (input ()))"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\n\nlet n = bscanf Scanning.stdin \"%d \" (fun x -> x);;\n\nlet nn = 100000 + 2;;\nlet count = Array.make nn 0;;\nlet indx = Array.make nn 0;;\nlet score = Array.make nn 0;;\n\nlet p = Array.init n (fun x -> 0);;\n\nfor i=0 to n-1 do\n let f = bscanf Scanning.stdin \"%d \" (fun x -> x) in\n count.(f) <- count.(f) + f\ndone;;\n\nlet l = ref 1;;\n\nfor i=1 to nn-1 do\n if count.(i) > 0 then\n begin\n indx.(!l) <- i;\n l := !l + 1\n end\ndone;;\n\n(* For testing\nfor i=1 to !l-1 do\n printf \"%d %d\\n\" indx.(i) count.(indx.(i));\ndone;;\n*)\n\nscore.(0) <- 0;;\nscore.(1) <- count.(indx.(1));;\nfor i=2 to !l-1 do\n let x1 = indx.(i-1) in\n let x2 = indx.(i) in\n if x2 > x1 + 1 then\n begin\n score.(i)<-score.(i+1)+count.(x2)\n end\n else\n begin\n let tscore = score.(i-2) + count.(x2) in\n if tscore > score.(i-1) then\n score.(i) <- tscore\n else\n score.(i) <- score.(i-1)\n end\ndone;;\n\nprint_int score.(!l-1); print_endline \"\";;\n\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\nopen Num;;\n\nlet n = bscanf Scanning.stdin \"%d \" (fun x -> x);;\n\nlet nn = 100000 + 2;;\nlet count = Array.make nn 0;;\nlet indx = Array.make nn 0;;\nlet score = Array.make nn (num_of_int 0);;\n\nlet p = Array.init n (fun x -> 0);;\n\nfor i=0 to n-1 do\n let f = bscanf Scanning.stdin \"%d \" (fun x -> x) in\n count.(f) <- count.(f) + f\ndone;;\n\nlet l = ref 1;;\n\nfor i=1 to nn-1 do\n if count.(i) > 0 then\n begin\n indx.(!l) <- i;\n l := !l + 1\n end\ndone;;\n\n(*For testing\nfor i=1 to !l-1 do\n printf \"%d %d\\n\" indx.(i) count.(indx.(i));\ndone;;*)\n\nscore.(0) <- num_of_int 0;;\nscore.(1) <- num_of_int count.(indx.(1));;\nlet cur_indx = ref indx.(1) in\nfor i=2 to !l-1 do\n let x1 = !cur_indx in\n let x2 = indx.(i) in\n if x2 > x1 + 1 then\n begin\n score.(i)<-score.(i-1)+/ (num_of_int count.(x2));\n cur_indx := indx.(i)\n end\n else\n begin\n let tscore = score.(i-2) +/ num_of_int (count.(x2)) in\n if tscore >/ score.(i-1) then\n begin\n score.(i) <- tscore;\n cur_indx := x2\n end\n else\n begin\n score.(i) <- score.(i-1);\n cur_indx := indx.(i-1)\n end\n end\ndone;;\n\nprint_endline (string_of_num (score.(!l-1)));; \n\n"}, {"source_code": "open Scanf;;\nopen String;;\nopen Printf;;\n\nlet n = bscanf Scanning.stdin \"%d \" (fun x -> x);;\n\nlet nn = 100000 + 2;;\nlet count = Array.make nn 0;;\nlet indx = Array.make nn 0;;\nlet score = Array.make nn 0;;\n\nlet p = Array.init n (fun x -> 0);;\n\nfor i=0 to n-1 do\n let f = bscanf Scanning.stdin \"%d \" (fun x -> x) in\n count.(f) <- count.(f) + f\ndone;;\n\nlet l = ref 1;;\n\nfor i=1 to nn-1 do\n if count.(i) > 0 then\n begin\n indx.(!l) <- i;\n l := !l + 1\n end\ndone;;\n\n(*For testing\nfor i=1 to !l-1 do\n printf \"%d %d\\n\" indx.(i) count.(indx.(i));\ndone;;*)\n\nscore.(0) <- 0;;\nscore.(1) <- count.(indx.(1));;\nlet cur_indx = ref indx.(1) in\nfor i=2 to !l-1 do\n let x1 = !cur_indx in\n let x2 = indx.(i) in\n if x2 > x1 + 1 then\n begin\n score.(i)<-score.(i-1)+count.(x2);\n cur_indx := indx.(i)\n end\n else\n begin\n let tscore = score.(i-2) + count.(x2) in\n if tscore > score.(i-1) then\n begin\n score.(i) <- tscore;\n cur_indx := x2\n end\n else\n begin\n score.(i) <- score.(i-1);\n cur_indx := indx.(i-1)\n end\n end\ndone;;\n\nprint_int score.(!l-1); print_endline \"\";;\n\n"}], "src_uid": "41b3e726b8146dc733244ee8415383c0"} {"nl": {"description": "Polycarp is playing a new computer game. This game has $$$n$$$ stones in a row. The stone on the position $$$i$$$ has integer power $$$a_i$$$. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if $$$n = 5$$$ and $$$a = [1, 5, 4, 3, 2]$$$, then Polycarp could make the following moves: Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$; Destroy the rightmost stone. After this move $$$a = [5, 4, 3]$$$; Destroy the leftmost stone. After this move $$$a = [4, 3]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example: Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$; Destroy the leftmost stone. After this move $$$a = [4, 3, 2]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \\le n \\le 100$$$)\u00a0\u2014 the number of stones. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the power of the stones.", "output_spec": "For each test case, output the minimum number of moves required to destroy the stones with the greatest and the lowest power.", "sample_inputs": ["5\n5\n1 5 4 3 2\n8\n2 1 3 4 5 6 8 7\n8\n4 2 3 1 8 6 7 5\n4\n3 4 2 1\n4\n2 3 1 4"], "sample_outputs": ["2\n4\n5\n3\n2"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int () in\n let a = Array.init n read_int in\n\n let (_,max_loc) = maxf 0 (n-1) (fun i -> (a.(i), i)) in\n let (_,min_loc) = minf 0 (n-1) (fun i -> (a.(i), i)) in\n\n let ltor = 1 + max max_loc min_loc in\n let rtol = max (n-max_loc) (n-min_loc) in\n let both_ends = (1 + min max_loc min_loc) + (min (n-max_loc) (n-min_loc)) in\n\n printf \"%d\\n\" (min ltor (min rtol both_ends))\n done\n\n \n\n\n"}], "negative_code": [], "src_uid": "d5fc2bc618dd9d453a5e7ae30ccb73f3"} {"nl": {"description": "Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1,\u2009a2,\u2009...,\u2009an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1,\u2009b2,\u2009...,\u2009bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.", "input_spec": "The first line contains two numbers n and m\u00a0(2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the dimensions of the matrix. The second line contains n numbers a1,\u2009a2,\u2009...,\u2009an\u00a0(0\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the xor of all elements in row i. The third line contains m numbers b1,\u2009b2,\u2009...,\u2009bm\u00a0(0\u2009\u2264\u2009bi\u2009\u2264\u2009109), where bi is the xor of all elements in column i.", "output_spec": "If there is no matrix satisfying the given constraints in the first line, output \"NO\". Otherwise, on the first line output \"YES\", and then n rows of m numbers in each ci1,\u2009ci2,\u2009... ,\u2009cim\u00a0(0\u2009\u2264\u2009cij\u2009\u2264\u20092\u00b7109) \u2014 the description of the matrix. If there are several suitable matrices, it is allowed to print any of them.", "sample_inputs": ["2 3\n2 9\n5 3 13", "3 3\n1 7 6\n2 15 12"], "sample_outputs": ["YES\n3 4 5\n6 7 8", "NO"], "notes": null}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0L in\n let b = Array.make m 0L in\n let c = Array.make_matrix n m 0L in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s)\n done;\n for j = 0 to m - 1 do\n b.(j) <- Scanf.bscanf sb \"%Ld \" (fun s -> s)\n done;\n in\n let x = ref 0L in\n let y = ref 0L in\n for i = 0 to n - 1 do\n x := Int64.logxor !x a.(i)\n done;\n for i = 0 to m - 1 do\n y := Int64.logxor !y b.(i)\n done;\n if !x <> !y\n then Printf.printf \"NO\\n\"\n else (\n c.(0).(0) <- Int64.logxor !x (Int64.logxor a.(0) b.(0));\n for i = 1 to n - 1 do\n\tc.(i).(0) <- a.(i)\n done;\n for j = 1 to m - 1 do\n\tc.(0).(j) <- b.(j)\n done;\n Printf.printf \"YES\\n\";\n for i = 0 to n - 1 do\n\tfor j = 0 to m - 1 do\n\t Printf.printf \"%Ld \" c.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done;\n )\n"}], "negative_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0L in\n let b = Array.make m 0L in\n let c = Array.make_matrix n m 0L in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s)\n done;\n for j = 0 to m - 1 do\n b.(j) <- Scanf.bscanf sb \"%Ld \" (fun s -> s)\n done;\n in\n let x = ref 0L in\n let y = ref 0L in\n for i = 0 to n - 1 do\n x := Int64.logxor !x a.(i)\n done;\n for i = 0 to m - 1 do\n y := Int64.logxor !y b.(i)\n done;\n if !x <> !y\n then Printf.printf \"NO\\n\"\n else (\n c.(0).(0) <- Int64.logxor !x (Int64.logxor a.(0) b.(0));\n for i = 1 to n - 1 do\n\tc.(i).(0) <- a.(i)\n done;\n for j = 1 to m - 1 do\n\tc.(0).(j) <- b.(j)\n done;\n for i = 0 to n - 1 do\n\tfor j = 0 to m - 1 do\n\t Printf.printf \"%Ld \" c.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done;\n )\n"}], "src_uid": "3815d18843dbd15a73383d69eb6880dd"} {"nl": {"description": "The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be ai teams on the i-th day.There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.Sereja wants to order exactly ai pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of training sessions. The second line contains n integers a1, a2, ..., an (0\u2009\u2264\u2009ai\u2009\u2264\u200910\u2009000)\u00a0\u2014 the number of teams that will be present on each of the days.", "output_spec": "If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print \"YES\" (without quotes) in the only line of output. Otherwise, print \"NO\" (without quotes).", "sample_inputs": ["4\n1 2 1 2", "3\n1 0 1"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample.In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days."}, "positive_code": [{"source_code": "\nlet read_nums () = \n let s = read_line () in\n let nums = List.map int_of_string (Str.split (Str.regexp \" \") s) in\n nums\n\n;;\n\nlet rec is_possible lst =\n match lst with\n | [] -> true\n | [a] -> (a mod 2 = 0)\n | a :: b :: tl -> if a < 0 then\n false\n else if a mod 2 = 0 then\n is_possible (b::tl)\n else\n is_possible ((b-1)::tl)\n;;\n\nlet main () =\n let _n = read_int () in\n let lst = read_nums () in\n if is_possible lst then\n print_string \"YES\\n\"\n else\n print_string \"NO\\n\"\n;;\n\nmain () ;;\n\n\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let data = Array.init n (fun i ->\n if i = 0 then read_int () mod 2\n else read_int ()\n )\n in\n let possible = ref \"YES\" in\n let reminder = ref 0 in\n for i = 0 to n - 1 do\n let r = data.(i) - !reminder in\n if r < 0 || i = n - 1 && r mod 2 != 0\n then possible := \"NO\"\n else reminder := r mod 2\n done;\n print_endline !possible\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let data = Array.init n (fun i ->\n if i = 0 then read_int () mod 2\n else read_int ()\n )\n in\n let possible = ref \"YES\" in\n let init = data.(0) in\n let reminder = ref init in\n for i = 1 to n - 1 do\n let r = data.(i) - !reminder in\n if r < 0 || i = n - 1 && data.(i) mod 2 != 0\n then possible := \"NO\"\n else reminder := data.(i) mod 2\n done;\n print_endline !possible\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let data = Array.init n (fun i ->\n if i = 0 then read_int () mod 2\n else read_int ()\n )\n in\n let possible = ref \"YES\" in\n let init = data.(0) in\n let reminder = ref init in\n for i = 1 to n - 1 do\n let r = data.(i) - !reminder in\n if r < 0 || i = n - 1 && data.(i) != 0\n then possible := \"NO\"\n else reminder := data.(i) mod 2\n done;\n print_endline !possible\n"}], "src_uid": "97697eba87bd21ae5c979a5ea7a81cb7"} {"nl": {"description": "This problem differs from one which was on the online contest.The sequence a1,\u2009a2,\u2009...,\u2009an is called increasing, if ai\u2009<\u2009ai\u2009+\u20091 for i\u2009<\u2009n.The sequence s1,\u2009s2,\u2009...,\u2009sk is called the subsequence of the sequence a1,\u2009a2,\u2009...,\u2009an, if there exist such a set of indexes 1\u2009\u2264\u2009i1\u2009<\u2009i2\u2009<\u2009...\u2009<\u2009ik\u2009\u2264\u2009n that aij\u2009=\u2009sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009500) \u2014 the length of the first sequence. The second line contains n space-separated integers from the range [0,\u2009109] \u2014 elements of the first sequence. The third line contains an integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009500) \u2014 the length of the second sequence. The fourth line contains m space-separated integers from the range [0,\u2009109] \u2014 elements of the second sequence.", "output_spec": "In the first line output k \u2014 the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.", "sample_inputs": ["7\n2 3 1 6 5 4 6\n4\n1 3 5 6", "5\n1 2 0 2 1\n3\n1 0 1"], "sample_outputs": ["3\n3 5 6", "2\n0 1"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let m = read_int 0 in\n let b = Array.init m read_int in\n let s = Array.make_matrix n m 0 in\n let p = Array.make_matrix n m m in\n let rec go i j optl opti optx =\n if i >= 0 then\n if j < 0 then\n go (i-1) (m-1) 0 m (-1)\n else (\n if i+1 < n then (\n s.(i).(j) <- s.(i+1).(j);\n p.(i).(j) <- p.(i+1).(j);\n );\n if a.(i) = b.(j) && optl+1 > s.(i).(j) then (\n s.(i).(j) <- optl+1;\n p.(i).(j) <- opti;\n );\n let optl',opti',optx' = if i+1 < n && a.(i) < b.(j) && (s.(i).(j) > optl || s.(i).(j) = optl && b.(j) <= optx) then\n s.(i).(j),j,b.(j)\n else\n optl,opti,optx in\n go i (j-1) optl' opti' optx'\n )\n in\n go (n-1) (m-1) 0 m (-1);\n\n let rec plan i j =\n if i < n && j < m then\n if a.(i) <> b.(j) then\n plan (i+1) j\n else (\n Printf.printf \"%d \" a.(i);\n plan (i+1) p.(i).(j)\n )\n in\n let rec find i opt opti =\n if i >= m then (\n Printf.printf \"%d\\n\" opt;\n plan 0 opti\n ) else if s.(0).(i) > opt then\n find (i+1) s.(0).(i) i\n else\n find (i+1) opt opti\n in\n find 0 0 m\n"}], "negative_code": [], "src_uid": "dca6eee27f002413d5e2eaf28fd60750"} {"nl": {"description": "While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i,\u2009j) such that ai\u2009\u2264\u2009aj and there are exactly k integers y such that ai\u2009\u2264\u2009y\u2009\u2264\u2009aj and y is divisible by x.In this problem it is meant that pair (i,\u2009j) is equal to (j,\u2009i) only if i is equal to j. For example pair (1,\u20092) is not the same as (2,\u20091).", "input_spec": "The first line contains 3 integers n,\u2009x,\u2009k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009x\u2009\u2264\u2009109,\u20090\u2009\u2264\u2009k\u2009\u2264\u2009109), where n is the size of the array a and x and k are numbers from the statement. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the elements of the array a.", "output_spec": "Print one integer\u00a0\u2014 the answer to the problem.", "sample_inputs": ["4 2 1\n1 3 5 7", "4 2 0\n5 3 1 7", "5 3 1\n3 3 3 3 3"], "sample_outputs": ["3", "4", "25"], "notes": "NoteIn first sample there are only three suitable pairs of indexes\u00a0\u2014 (1,\u20092),\u2009(2,\u20093),\u2009(3,\u20094).In second sample there are four suitable pairs of indexes(1,\u20091),\u2009(2,\u20092),\u2009(3,\u20093),\u2009(4,\u20094).In third sample every pair (i,\u2009j) is suitable, so the answer is 5\u2009*\u20095\u2009=\u200925."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet () = \n let n = read_int () in\n let x = read_int () in\n let k = read_int () in \n let a = Array.init n read_int in\n\n let increment h t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n let divisors_up_to ai = ai/x in\n\n if k=0 then (\n let h0 = Hashtbl.create 10 in\n let h1 = Hashtbl.create 10 in\n \n for i=0 to n-1 do\n if a.(i) mod x <> 0 then (\n\tincrement h0 (divisors_up_to a.(i));\n\tincrement h1 a.(i);\n )\n done;\n\n let ordered = Hashtbl.fold (fun _ count0 ac ->\n ac ++ ((long count0) ** (long (count0 - 1))) // 2L\n ) h0 0L in\n\n let correction = Hashtbl.fold (fun _ c2 ac ->\n let c2 = long c2 in\n ac ++ c2 ** c2 -- (c2 ** (c2 -- 1L))//2L\n ) h1 0L in\n\n printf \"%Ld\\n\" (ordered ++ correction)\n \n ) else (\n let h0 = Hashtbl.create 10 in\n let h1 = Hashtbl.create 10 in \n \n (* let d(a.(i)) be the number of numbers in 1, 2, ..., a.(i) divisible by x.\n This table stores key value pairs (k,v) where v = the number of a.(i) such\n that d.(a.(i)) = k.\n *)\n \n \n for i=0 to n-1 do\n increment h0 (divisors_up_to a.(i));\n increment h1 (divisors_up_to (a.(i)-1))\n done; \n \n (* think k >= 2 and solve it and then check k=0 or 1 later *)\n \n let answer = Hashtbl.fold (fun d0 count0 ac ->\n let count1 = try Hashtbl.find h1 (d0-k) with Not_found -> 0 in\n ac ++ ((long count0) ** (long count1))\n ) h0 0L in\n \n printf \"%Ld\\n\" answer\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet () = \n let n = read_int () in\n let x = read_int () in\n let k = read_int () in \n let a = Array.init n read_int in\n\n Array.sort compare a;\n\n let same_as_previous i =\n (* i > 0 *)\n a.(i-1) = a.(i) || (a.(i-1) mod x <> 0 && a.(i) mod x <> 0 && a.(i-1)/x = a.(i)/x)\n in\n \n let rec compress i c ac = if i=n then (a.(i-1),c)::ac else (\n if same_as_previous i then compress (i+1) (c+1) ac\n else compress (i+1) 1 ((a.(i-1),c)::ac)\n )\n in\n\n let clist = List.rev (compress 1 1 []) in\n let nn = List.length clist in\n let b = Array.make nn 0 in\n let bcount = Array.make nn 0L in\n List.iteri (fun i (v,c) -> b.(i) <- v; bcount.(i) <- long c) clist;\n\n (*\n for i=0 to nn-1 do\n printf \"b.(%d) = %d bcount.(%d) = %Ld\\n\" i b.(i) i bcount.(i)\n done;\n *)\n \n let count_divisible_by a b x =\n (* number of a <= y <=b divisible by x *)\n let a' = a + (x - (a mod x)) mod x in (* next number >= a to be divisible by x *)\n let b' = b - (b mod x) in (* first number <= b to be divisible by x *)\n if b' < a' then 0 else (b'+x-a') / x\n in\n\n let rec scan i j ac = if j = nn then ac else (\n (* i <= j *)\n let c = count_divisible_by b.(i) b.(j) x in\n if c = k then (\n(* printf \"i=%d j=%d\\n\" i j; *)\n let blah = bcount.(i) ** bcount.(j) in\n let ac = if i = j then ac ++ blah else ac ++ blah in\n scan i (j+1) ac\n ) else if c < k then scan i (j+1) ac\n else scan (i+1) (max j (i+1)) ac\n ) in\n\n let answer = scan 0 0 0L in\n\n printf \"%Ld\\n\" answer\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet () = \n let n = read_int () in\n let x = read_int () in\n let k = read_int () in \n let a = Array.init n read_int in\n\n let increment h t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n let divisors_up_to ai = ai/x in\n\n if k=0 then (\n let h0 = Hashtbl.create 10 in\n let h1 = Hashtbl.create 10 in\n \n for i=0 to n-1 do\n if a.(i) mod x <> 0 then (\n\tincrement h0 (divisors_up_to a.(i));\n\tincrement h1 a.(i);\n )\n done;\n\n let ordered = Hashtbl.fold (fun _ count0 ac ->\n ac ++ ((long count0) ** (long (count0 - 1))) // 2L\n ) h0 0L in\n\n let correction = Hashtbl.fold (fun _ c2 ac ->\n let c2 = long c2 in\n c2 ** c2 -- (c2 ** (c2 -- 1L))//2L\n ) h1 0L in\n \n printf \"%Ld\\n\" (ordered ++ correction)\n \n ) else (\n let h0 = Hashtbl.create 10 in\n let h1 = Hashtbl.create 10 in \n \n (* let d(a.(i)) be the number of numbers in 1, 2, ..., a.(i) divisible by x.\n This table stores key value pairs (k,v) where v = the number of a.(i) such\n that d.(a.(i)) = k.\n *)\n \n \n for i=0 to n-1 do\n increment h0 (divisors_up_to a.(i));\n increment h1 (divisors_up_to (a.(i)-1))\n done; \n \n (* think k >= 2 and solve it and then check k=0 or 1 later *)\n \n let answer = Hashtbl.fold (fun d0 count0 ac ->\n let count1 = try Hashtbl.find h1 (d0-k) with Not_found -> 0 in\n ac ++ ((long count0) ** (long count1))\n ) h0 0L in\n \n printf \"%Ld\\n\" answer\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet () = \n let n = read_int () in\n let x = read_int () in\n let k = read_int () in \n let a = Array.init n read_int in\n\n let h0 = Hashtbl.create 10 in\n let h1 = Hashtbl.create 10 in \n\n (* let d(a.(i)) be the number of numbers in 1, 2, ..., a.(i) divisible by x.\n This table stores key value pairs (k,v) where v = the number of a.(i) such\n that d.(a.(i)) = k.\n *)\n\n let increment h t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n let divisors_up_to ai = ai/x in\n\n for i=0 to n-1 do\n increment h0 (divisors_up_to a.(i));\n increment h1 (divisors_up_to (a.(i)-1))\n done; \n\n (* think k >= 2 and solve it and then check k=0 or 1 later *)\n\n let answer = Hashtbl.fold (fun d0 count0 ac ->\n let count1 = try Hashtbl.find h1 (d0-k) with Not_found -> 0 in\n ac ++ ((long count0) ** (long count1))\n ) h0 0L in\n\n printf \"%Ld\\n\" answer\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet () = \n let n = read_int () in\n let x = read_int () in\n let k = read_int () in \n let a = Array.init n read_int in\n\n let increment h t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n let divisors_up_to ai = ai/x in\n\n if k=0 then (\n let h0 = Hashtbl.create 10 in\n let h1 = Hashtbl.create 10 in\n \n for i=0 to n-1 do\n if a.(i) mod x <> 0 then (\n\tincrement h0 (divisors_up_to a.(i));\n\tincrement h1 a.(i);\n )\n done;\n\n let ordered = Hashtbl.fold (fun _ count0 ac ->\n ac ++ ((long count0) ** (long (count0 - 1))) // 2L\n ) h0 0L in\n\n let correction = sum 0 (n-1) (fun i ->\n if a.(i) mod x = 0 then 0L else\n\tlet c2 = long (Hashtbl.find h1 a.(i)) in\n\tc2 ** c2 -- (c2 ** (c2 -- 1L))//2L\n ) in\n\n printf \"%Ld\\n\" (ordered ++ correction)\n \n ) else (\n let h0 = Hashtbl.create 10 in\n let h1 = Hashtbl.create 10 in \n \n (* let d(a.(i)) be the number of numbers in 1, 2, ..., a.(i) divisible by x.\n This table stores key value pairs (k,v) where v = the number of a.(i) such\n that d.(a.(i)) = k.\n *)\n \n \n for i=0 to n-1 do\n increment h0 (divisors_up_to a.(i));\n increment h1 (divisors_up_to (a.(i)-1))\n done; \n \n (* think k >= 2 and solve it and then check k=0 or 1 later *)\n \n let answer = Hashtbl.fold (fun d0 count0 ac ->\n let count1 = try Hashtbl.find h1 (d0-k) with Not_found -> 0 in\n ac ++ ((long count0) ** (long count1))\n ) h0 0L in\n \n printf \"%Ld\\n\" answer\n )\n"}], "src_uid": "6fbcc92541705a63666701238778a04a"} {"nl": {"description": "A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1,\u2009y1), and the distress signal came from the point (x2,\u2009y2).Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed meters per second.Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx,\u2009vy) for the nearest t seconds, and then will change to (wx,\u2009wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x,\u2009y), while its own velocity relative to the air is equal to zero and the wind (ux,\u2009uy) is blowing, then after seconds the new position of the dirigible will be .Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.", "input_spec": "The first line of the input contains four integers x1, y1, x2, y2 (|x1|,\u2009\u2009|y1|,\u2009\u2009|x2|,\u2009\u2009|y2|\u2009\u2264\u200910\u2009000)\u00a0\u2014 the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively. The second line contains two integers and t (0\u2009<\u2009v,\u2009t\u2009\u2264\u20091000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively. Next follow one per line two pairs of integer (vx,\u2009vy) and (wx,\u2009wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that and .", "output_spec": "Print a single real value\u00a0\u2014 the minimum time the rescuers need to get to point (x2,\u2009y2). You answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["0 0 5 5\n3 2\n-1 -1\n-1 0", "0 0 0 1000\n100 1000\n-50 0\n50 0"], "sample_outputs": ["3.729935587093555327", "11.547005383792516398"], "notes": null}, "positive_code": [{"source_code": "(* 1st observation is that you're going to be flying in a constant\n direction for each part of the flight. You can see this as\n follows. If you're going to be flying for t units of time from\n point a to point b with the wind pushing you at velocity w, then we\n can split the components of the final displacement vector as\n follows. We first fly for t units with the wind. Then fly at your\n favorite velocity (no wind) for t units of time in some direction.\n Clearly in this case you'll want to fly in a constant direction to\n minimize your time.\n\n So one thing you need is to know how long it will take to get from\n point a to point b with wind vector w and your own maximum velocity\n v. To do this involves computing the intersection point of a\n circle and a line. I did this using binary search cause I didn't\n have the geometric primitives handy.\n\n Now we see if we can get there before the wind changes. If\n possible we just do it. Otherwise we do a ternary search over the\n angles of the first part of the flight that lasts time t. We can\n compute its cost by flying t in that direction and then use the\n previous function to see how long it will take to get home from\n there.\n*)\nopen Printf\nopen Scanf\n\nlet pi = 2.0 *. asin 1.0\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n \nlet read2_float () = bscanf Scanning.stdib \" %f %f \" (fun x y -> (x,y))\n\nlet sq x = x *. x\nlet len2 (x,y) = (sq x) +. (sq y)\nlet len pt = sqrt (len2 pt)\n \nlet ( ++ ) (a,b) (c,d) = (a+.c, b+.d)\nlet ( -- ) (a,b) (c,d) = (a-.c, b-.d) \nlet ( ** ) c (x,y) = (c*.x, c*.y)\n\nlet () = \n let (x1,y1) = read2_float () in\n let (x2,y2) = read2_float () in\n let (v,t) = read2_float () in\n let (vx,vy) = read2_float () in\n let (wx,wy) = read2_float () in\n\n let time_to_reach v w g =\n (* assuming we're at the origin and have a max velocity v\n offset by velocity w how long does it take for us\n to get to point g ? *)\n\n let toofar m = \n len2 (w -- (m ** g)) > sq v\n in\n \n let rec bsearch lo hi i =\n let m = (lo +. hi) /. 2.0 in\n if i=70 then m else\n\tif toofar m then bsearch lo m (i+1) else bsearch m hi (i+1)\n in\n\n let rec findhi hi = if toofar hi then hi else findhi (2.0 *. hi) in\n let s = bsearch 0.0 (findhi 1.0) 0 in\n let vel = len (s ** g) in\n (len g) /. vel\n in\n\n let answer =\n if (x1,y1) = (x2,y2) then 0.0 else\n let t0 = time_to_reach v (vx,vy) ((x2,y2) -- (x1,y1)) in\n if t0 <= t then t0 else (\n\tlet (x1,y1) = (x1,y1) ++ (t ** (vx,vy)) in\n\tlet angle i = (2.0 *. pi) *. ((float i) /. 10.0)in\n\tlet angle_time alpha =\n\t let p1 = (x1,y1) ++ ((t *. v) ** (cos alpha, sin alpha)) in\n\t time_to_reach v (wx,wy) ((x2,y2)--p1)\n\tin\n\tlet (_,i) = minf 0 9 (fun i -> (angle_time (angle i), i)) in\n\tlet alpha_lo = angle (i-1) in\n\tlet alpha_hi = angle (i+1) in\n\t\n\tlet rec tsearch lo tlo hi thi i = if i=100 then (tlo +.thi) /. 2.0 else\n\t let m1 = (2.0 *. lo +. hi) /. 3.0 in\n\t let m2 = (lo +. 2.0 *. hi) /. 3.0 in\n\t let tm1 = angle_time m1 in\n\t let tm2 = angle_time m2 in\n\t if tm1 < tm2\n\t then tsearch lo tlo m2 tm2 (i+1)\n\t else tsearch m1 tm1 hi thi (i+1)\n\tin\n\tt +. tsearch alpha_lo (angle_time alpha_lo) alpha_hi (angle_time alpha_hi) 0\n )\n in\n\n printf \"%.8f\\n\" answer\n"}], "negative_code": [], "src_uid": "b44c6836ee3d597a78d4b6b16ef1d4b3"} {"nl": {"description": "Let's assume that we are given a matrix b of size x\u2009\u00d7\u2009y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x\u2009\u00d7\u2009y matrix c which has the following properties: the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; the lower half of matrix c (rows with numbers from x\u2009+\u20091 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x\u2009+\u20091). Sereja has an n\u2009\u00d7\u2009m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?", "input_spec": "The first line contains two integers, n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). Each of the next n lines contains m integers \u2014 the elements of matrix a. The i-th line contains integers ai1,\u2009ai2,\u2009...,\u2009aim (0\u2009\u2264\u2009aij\u2009\u2264\u20091) \u2014 the i-th row of the matrix a.", "output_spec": "In the single line, print the answer to the problem \u2014 the minimum number of rows of matrix b.", "sample_inputs": ["4 3\n0 0 1\n1 1 0\n1 1 0\n0 0 1", "3 3\n0 0 0\n0 0 0\n0 0 0", "8 1\n0\n1\n1\n0\n0\n1\n1\n0"], "sample_outputs": ["2", "3", "2"], "notes": "NoteIn the first test sample the answer is a 2\u2009\u00d7\u20093 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001"}, "positive_code": [{"source_code": "let (n,m)=Scanf.scanf \"%d %d\" (fun x y->(x,y));;\n\nlet is_mirror mat i j=\n if i mod 2=1 then false\n else\n begin\n let b=ref true in\n for k=1 to i/2 do\n for l=1 to j do\n b:= !b&&(mat.(k).(l)=mat.(i+1-k).(l))\n done\n done;\n !b\n end;;\n \nlet mat=Array.make_matrix (n+1) (m+1) 0;;\n\nfor i=1 to n do\n for j=1 to m do\n mat.(i).(j)<-Scanf.scanf \" %d\" (fun x->x)\n done\ndone;;\n\nlet sol=ref n;;\n\nwhile is_mirror mat !sol m do\n sol:= !sol/2\ndone;;\n\nprint_int !sol;;\n"}], "negative_code": [], "src_uid": "90125e9d42c6dcb0bf3b2b5e4d0f845e"} {"nl": {"description": "Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e. or (or both).Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).", "input_spec": "The first line of the input contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers ui and vi (1\u2009\u2009\u2264\u2009\u2009ui,\u2009\u2009vi\u2009\u2009\u2264\u2009\u2009n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.", "output_spec": "If it's impossible to split the graph between Pari and Arya as they expect, print \"-1\" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers\u00a0\u2014 the indices of vertices. Note that because of m\u2009\u2265\u20091, vertex cover cannot be empty.", "sample_inputs": ["4 2\n1 2\n2 3", "3 3\n1 2\n2 3\n1 3"], "sample_outputs": ["1\n2 \n2\n1 3", "-1"], "notes": "NoteIn the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish).In the second sample, there is no way to satisfy both Pari and Arya."}, "positive_code": [{"source_code": "exception GameOver\n\ntype owner = Nobody | Pari | Arya\n\nlet () =\n match read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string with\n | [n; m] -> (\n let adj = Array.make n [] in\n for i = 1 to m do\n match read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string with\n | [u; v] ->\n let u = u-1\n and v = v-1 in\n adj.(u) <- v :: adj.(u);\n adj.(v) <- u :: adj.(v)\n | _ -> assert false\n done;\n \n let own = Array.make n Nobody in\n let rec give who v =\n let other =\n match who with\n | Pari -> Arya\n | Arya -> Pari\n | Nobody -> assert false\n in\n if own.(v) == Nobody then (\n own.(v) <- who;\n List.iter (give other) adj.(v)\n )\n else if own.(v) == other then (\n raise GameOver\n )\n and print who =\n print_int (Array.fold_left (fun count x -> if x == who then count + 1 else count) 0 own);\n print_newline ();\n for i = 0 to n - 1 do\n if own.(i) == who then (\n print_int (i+1);\n print_char ' ';\n )\n done;\n print_newline ();\n in\n try\n for v = 0 to n - 1 do\n if own.(v) == Nobody then\n give Pari v;\n done;\n print Pari;\n print Arya\n with\n GameOver -> print_endline \"-1\"\n )\n | _ -> assert false\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n \nlet () = \n let (n,m) = read_pair () in\n\n let g = Array.make n [] in\n\n let add_edge u v =\n g.(u) <- v::g.(u);\n g.(v) <- u::g.(v)\n in\n\n for i=1 to m do\n let (u,v) = read_pair() in\n add_edge (u-1) (v-1)\n done;\n\n let color = Array.make n 0 in\n let bipartite = ref true in\n let visited = Array.make n false in\n \n let rec dfs u c =\n if visited.(u) then (\n if color.(u) <> c then bipartite := false\n ) else (\n visited.(u) <- true;\n color.(u) <- c;\n List.iter (fun v ->\n\tdfs v (1-c)\n ) g.(u)\n )\n in\n\n for u=0 to n-1 do\n if not visited.(u) then dfs u 0\n done;\n\n let color1 = sum 0 (n-1) (fun u -> color.(u)) in\n let color0 = n-color1 in\n\n if !bipartite then (\n \n printf \"%d\\n\" color0;\n for i=0 to n-1 do\n if color.(i) = 0 then printf \"%d \" (i+1)\n done;\n print_newline();\n \n printf \"%d\\n\" color1;\n for i=0 to n-1 do\n if color.(i) = 1 then printf \"%d \" (i+1)\n done;\n print_newline()\n ) else (\n printf \"-1\\n\"\n )\n \n"}], "negative_code": [{"source_code": "exception GameOver\n\ntype owner = Nobody | Pari | Arya\n\nlet () =\n match read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string with\n | [n; m] -> (\n let adj = Array.make n [] in\n for i = 1 to m do\n match read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string with\n | [u; v] ->\n let u = u-1\n and v = v-1 in\n adj.(u) <- v :: adj.(u);\n adj.(v) <- u :: adj.(v)\n | _ -> assert false\n done;\n \n let own = Array.make n Nobody in\n let rec give who v =\n let other =\n match who with\n | Pari -> Arya\n | Arya -> Pari\n | Nobody -> assert false\n in\n if own.(v) == Nobody then (\n own.(v) <- who;\n List.iter (give other) adj.(v)\n )\n else if own.(v) == other then (\n raise GameOver\n )\n and print who =\n print_int (Array.fold_left (fun count x -> if x == who then count + 1 else count) 0 own);\n print_newline ();\n for i = 0 to n - 1 do\n if own.(i) == who then (\n print_int (i+1);\n print_char ' ';\n )\n done;\n print_newline ();\n in\n try\n give Pari 0;\n print Pari;\n print Arya\n with\n | GameOver -> print_endline \"-1\"\n )\n | _ -> assert false\n"}], "src_uid": "810f267655da0ad14538c275fd13821d"} {"nl": {"description": "There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n\u2009+\u2009m. Then the number of integers i (1\u2009\u2264\u2009i\u2009<\u2009n\u2009+\u2009m) such that positions with indexes i and i\u2009+\u20091 contain children of different genders (position i has a girl and position i\u2009+\u20091 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.", "input_spec": "The single line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100), separated by a space.", "output_spec": "Print a line of n\u2009+\u2009m characters. Print on the i-th position of the line character \"B\", if the i-th position of your arrangement should have a boy and \"G\", if it should have a girl. Of course, the number of characters \"B\" should equal n and the number of characters \"G\" should equal m. If there are multiple optimal solutions, print any of them.", "sample_inputs": ["3 3", "4 2"], "sample_outputs": ["GBGBGB", "BGBGBB"], "notes": "NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal."}, "positive_code": [{"source_code": "(* it said I submitted this before, so I will change it *)\n\nlet chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n let (g1,g2) = if n>m then (\"B\",\"G\") else (\"G\",\"B\") in\n let (n,m) = (max n m, min n m) in\n let rec loop i j = if (i,j) = (0,0) then () else\n if i>j then (print_string g1; loop (i-1) j)\n else (print_string g2; loop i (j-1))\n in\n loop n m;\n print_string \"\\n\"\n"}], "negative_code": [{"source_code": "let chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet print_stirng s = Printf.fprintf (open_out \"output.txt\") \"%s\\n\" s\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n let (g1,g2) = if n>m then (\"B\",\"G\") else (\"G\",\"B\") in\n let (n,m) = (max n m, min n m) in\n let rec loop i j = if (i,j) = (0,0) then () else\n if i>j then (print_string g1; loop (i-1) j)\n else (print_string g2; loop i (j-1))\n in\n loop n m;\n print_string \"\\n\"\n"}], "src_uid": "5392996bd06bf52b48fe30b64493f8f5"} {"nl": {"description": "Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements.Right now he has a map of some imaginary city with $$$n$$$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once.One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them.Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $$$u$$$ and $$$v$$$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $$$w$$$ that the original map has a tunnel between $$$u$$$ and $$$w$$$ and a tunnel between $$$w$$$ and $$$v$$$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map.", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 200\\,000$$$)\u00a0\u2014 the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $$$n - 1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \\leq u_i, v_i \\leq n$$$, $$$u_i \\ne v_i$$$), meaning the station with these indices are connected with a direct tunnel. It is guaranteed that these $$$n$$$ stations and $$$n - 1$$$ tunnels form a tree.", "output_spec": "Print one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map.", "sample_inputs": ["4\n1 2\n1 3\n1 4", "4\n1 2\n2 3\n3 4"], "sample_outputs": ["6", "7"], "notes": "NoteIn the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is $$$6$$$.In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair $$$(1, 4)$$$. For these two stations the distance is $$$2$$$."}, "positive_code": [{"source_code": "let ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( ** ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet read_int _ = Scanf.scanf \" %d \" (fun n -> n)\nlet read_int64 _ = Scanf.scanf \" %Ld \" (fun n -> n)\n\nlet rec dfs g v p =\n let neighbors = List.filter (fun x -> x <> p) g.(v) in\n let dp = List.map (fun w -> dfs g w v) neighbors in\n let evens = List.fold_left (fun a (b,_,_,_) -> a ++ b) 0L dp in\n let odds = List.fold_left (fun a (_,b,_,_) -> a ++ b) 0L dp in\n let sz = evens ++ odds in\n let sd = sz ++ List.fold_left (fun a (_,_,b,_) -> a ++ b) 0L dp in\n let ans = List.fold_left (fun x (e,o,s,a) -> x ++ a ++ (e++o++s)**(sz ++ 1L --e--o)) 0L dp in\n (* Printf.printf \"v = %d\\nEvens:%Ld Odds:%Ld Sd:%Ld Ans:%Ld\\n\" v (odds++1L) evens sd ans; *)\n (odds ++ 1L, evens, sd, ans)\n\nlet () =\n let n = read_int () in\n let edges = Array.init (n-1)\n (fun _ -> let v = read_int () and w = read_int () in (v,w)) in\n let add_edge graph (v,w) = (graph.(v) <- w :: graph.(v);\n graph.(w) <- v :: graph.(w);) in\n let graph = Array.make (n+1) [] in\n Array.iter (add_edge graph) edges;\n let (evens, odds, _, ans) = dfs graph 1 0 in\n let res = (ans ++ evens**odds) // 2L in\n Printf.printf \"%Ld\\n\" res\n\n"}], "negative_code": [], "src_uid": "274ae43b10bb15e270788d36590713c7"} {"nl": {"description": "Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one. To be more clear, consider all integer sequence with length k (a1,\u2009a2,\u2009...,\u2009ak) with . Give a value to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest.For definitions of powers and lexicographical order see notes.", "input_spec": "The first line consists of two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20091018,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009105)\u00a0\u2014 the required sum and the length of the sequence.", "output_spec": "Output \"No\" (without quotes) in a single line if there does not exist such sequence. Otherwise, output \"Yes\" (without quotes) in the first line, and k numbers separated by space in the second line\u00a0\u2014 the required sequence. It is guaranteed that the integers in the answer sequence fit the range [\u2009-\u20091018,\u20091018].", "sample_inputs": ["23 5", "13 2", "1 2"], "sample_outputs": ["Yes\n3 3 2 1 0", "No", "Yes\n-1 -1"], "notes": "NoteSample 1:23\u2009+\u200923\u2009+\u200922\u2009+\u200921\u2009+\u200920\u2009=\u20098\u2009+\u20098\u2009+\u20094\u2009+\u20092\u2009+\u20091\u2009=\u200923Answers like (3,\u20093,\u20092,\u20090,\u20091) or (0,\u20091,\u20092,\u20093,\u20093) are not lexicographically largest.Answers like (4,\u20091,\u20091,\u20091,\u20090) do not have the minimum y value.Sample 2:It can be shown there does not exist a sequence with length 2.Sample 3:Powers of 2:If x\u2009>\u20090, then 2x\u2009=\u20092\u00b72\u00b72\u00b7...\u00b72 (x times).If x\u2009=\u20090, then 2x\u2009=\u20091.If x\u2009<\u20090, then .Lexicographical order:Given two different sequences of the same length, (a1,\u2009a2,\u2009... ,\u2009ak) and (b1,\u2009b2,\u2009... ,\u2009bk), the first one is smaller than the second one for the lexicographical order, if and only if ai\u2009<\u2009bi, for the first i where ai and bi differ."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( land ) a b = Int64.logand a b\nlet ( lsr ) a b = Int64.shift_right_logical a b \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdib \" %Ld \" (fun x -> x) \n\nlet () =\n let n = read_long() in\n let k = read_int() in\n\n let rec make_list n c ac = if n=0L then ac else\n let ac = if n land 1L = 1L then ((1,c)::ac) else ac in\n make_list (n lsr 1) (c+1) ac\n in\n\n (* the list nl is (count, value) pairs, where count is the number of\n copies of the value. Initially all counts are 1. Values are\n always in strictly decreasing order *)\n\n let nl = make_list n 0 [] in\n let len = List.length nl in\n\n if k < len then printf \"No\\n\" else (\n printf \"Yes\\n\";\n\n let d = k - len in\n\n let compress nl =\n match nl with\n\t| [] -> failwith \"can't happen\"\n\t| [_] -> nl\n\t| (c1,v1)::((c2,v2)::tail) ->\n\t if v1 = v2 then (c1+c2,v1)::tail else nl\n in\n\n let rec expand_smallest nl d =\n if d = 0 then nl else (\n\tlet (c,v) = List.hd nl in\n\tif c <> 1 then failwith \"c should be 1\";\n\texpand_smallest ((1,v-1)::((1,v-1)::(List.tl nl))) (d-1)\n )\n in\n\n let rec pass nl d =\n if d=0 then nl else (\n\tlet (c,v) = List.hd nl in\n\tif d >= c then (\n\t let nl = (2*c, v-1)::(List.tl nl) in\n\t let nl = compress nl in\n\t let d = d-c in\n\t pass nl d\n\t) else (\n\t(* now we grow the last one as much as possible *)\n\t let nl = List.rev nl in\n\t let nl = if List.length nl = 1 then (\n\t (* special case for the list has one element *)\n\t let (c,v) = List.hd nl in\n\t (1,v)::[((c-1),v)]\n\t ) else nl\n\t in\n\t List.rev (expand_smallest nl d)\n\t)\n )\n in\n\n let nl = pass nl d in\n List.iter (fun (c,v) ->\n for i=1 to c do printf \"%d \" v done\n ) nl;\n print_newline()\n )\n"}], "negative_code": [], "src_uid": "39e4bae5abbc0efac5316bec0d540665"} {"nl": {"description": "According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower. However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.Write a program that models the behavior of Ankh-Morpork residents.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the total number of snacks. The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n. ", "output_spec": "Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.", "sample_inputs": ["3\n3 1 2", "5\n4 5 1 2 3"], "sample_outputs": ["3\n\u00a0\n2 1", "5 4\n\u00a0\n\u00a0\n3 2 1"], "notes": "NoteIn the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before."}, "positive_code": [{"source_code": "module IntSet = Set.Make(\n struct\n let compare = Pervasives.compare\n type t = int\n end) ;;\n\nlet n = Scanf.scanf \"%d\\n\" (fun x -> x) ;;\nlet x = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) ;;\n\n(* the smallest item on the tower *)\nlet smallest = ref (n + 1)\n(* the rest of the items *)\nand queue = ref IntSet.empty ;;\n\n(* loop over items/days\n * if this is the next item in the tower, place it on\n * and place all additional items in the remaining queue\n * otherwise, insert this item into the remaining queue *)\nfor i = 0 to n - 1 do\n if x.(i) == !smallest - 1 then begin\n (* place this item on the tower *)\n print_int x.(i);\n (* update smallest *)\n smallest := x.(i);\n (* use up remaining *)\n while not (IntSet.is_empty !queue) && IntSet.max_elt !queue == !smallest - 1 do\n print_char ' ';\n let e = IntSet.max_elt !queue in\n print_int e;\n queue := IntSet.remove e !queue;\n smallest := e\n done\n end\n else queue := IntSet.add x.(i) !queue;\n\n print_newline ()\ndone ;;\n"}], "negative_code": [], "src_uid": "3d648acee2abbf834f865b582aa9b7bc"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by $$$2$$$) or determine that there is no such subset.Both the given array and required subset may contain equal values.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$), number of test cases to solve. Descriptions of $$$t$$$ test cases follow. A description of each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$), length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 100$$$), elements of $$$a$$$. The given array $$$a$$$ can contain equal values (duplicates).", "output_spec": "For each test case output $$$-1$$$ if there is no such subset of elements. Otherwise output positive integer $$$k$$$, number of elements in the required subset. Then output $$$k$$$ distinct integers ($$$1 \\leq p_i \\leq n$$$), indexes of the chosen elements. If there are multiple solutions output any of them.", "sample_inputs": ["3\n3\n1 4 3\n1\n15\n2\n3 5"], "sample_outputs": ["1\n2\n-1\n2\n1 2"], "notes": "NoteThere are three test cases in the example.In the first test case, you can choose the subset consisting of only the second element. Its sum is $$$4$$$ and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_int_array_of_size n = Array.init n (fun _ -> scan_int());;\n\nlet t = scan_int ();;\nfor x = 1 to t do\n\tlet n = scan_int () in\n\tlet tab = scan_int_array_of_size n in\n\tlet p = ref (-1) and i1 = ref (-1) and i2 = ref (-1) in\n\tfor i = 0 to n-1 do\n\t\tif tab.(i) mod 2 = 0 then p := i+1\n\t\telse if !i1 = -1 then i1 := i+1 else i2 := i+1\n\tdone;\n\tif !p <> -1 then (print_int 1; print_newline (); print_int !p; print_newline ())\n\telse if !i2 <> -1 then (print_int 2; print_newline (); print_int !i1; print_string \" \"; print_int !i2; print_newline ())\n\telse (print_int (-1); print_newline ())\ndone;;\n"}], "negative_code": [], "src_uid": "3fe51d644621962fe41c32a2d90c7f94"} {"nl": {"description": "The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding\u00a0\u2014 an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the length of the initial name and the number of designers hired, respectively. The second line consists of n lowercase English letters and represents the original name of the corporation. Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi.", "output_spec": "Print the new name of the corporation.", "sample_inputs": ["6 1\npolice\np m", "11 6\nabacabadaba\na b\nb c\na d\ne g\nf a\nb b"], "sample_outputs": ["molice", "cdcbcdcfcdc"], "notes": "NoteIn the second sample the name of the corporation consecutively changes as follows: "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\nlet n2l n = char_of_int ((int_of_char 'a') + n)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let m = read_int () in\n\n let s = read_string () in\n let s = Array.init n (fun i -> l2n s.[i]) in\n \n let p = Array.init 26 (fun i -> i) in\n\n let swaps = Array.init m (fun _ ->\n let i = l2n (read_string()).[0] in\n let j = l2n (read_string()).[0] in\n (i,j)\n ) in\n \n for i=m-1 downto 0 do\n let (i,j) = swaps.(i) in\n let (a,b) = (p.(i), p.(j)) in\n p.(i) <- b;\n p.(j) <- a;\n done;\n\n for i=0 to n-1 do\n printf \"%c\" (n2l p.(s.(i)))\n done;\n print_newline()\n"}], "negative_code": [], "src_uid": "67a70d58415dc381afaa74de1fee7215"} {"nl": {"description": "In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n\u2009=\u20094 the sum is equal to \u2009-\u20091\u2009-\u20092\u2009+\u20093\u2009-\u20094\u2009=\u2009\u2009-\u20094, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.", "input_spec": "The first line of the input contains a single integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009100) \u2014 the number of values of n to be processed. Each of next t lines contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009109).", "output_spec": "Print the requested sum for each of t integers n given in the input.", "sample_inputs": ["2\n4\n1000000000"], "sample_outputs": ["-4\n499999998352516354"], "notes": "NoteThe answer for the first sample is explained in the statement."}, "positive_code": [{"source_code": "open Big_int;;\n\nlet (|) = gt_big_int\nlet (<|) = lt_big_int\nlet (>=|) = ge_big_int\nlet (<=|) = le_big_int\n\nlet n0 = zero_big_int\nlet n1 = unit_big_int\nlet n2 = big_int_of_int 2\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for ca = 1 to t do\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p =\n\tlet p = ref 0 in\n\tlet n = ref n in\n\t while !n > 1 do\n\t incr p;\n\t n := !n / 2;\n\t done;\n\t !p\n in\n let nn = big_int_of_int n in\n let res = nn *| (nn +| n1) /| n2 in\n let res = res -| power_int_positive_int 2 (p + 2) +| n2 in\n\tPrintf.printf \"%s\\n\" (string_of_big_int res)\n done\n"}], "negative_code": [{"source_code": "let rec potegi a x n = \nif n < x then a\nelse potegi (a+x) (2*x) n;;\n\nlet wynik n = n*(n+1)/2 - (potegi 0 1 n);;\nlet rec licz n =\nif n > 0 then licz (n-1)\nelse Printf.printf \"\\n\";\nPrintf.printf \"%d\\n\" ( Scanf.bscanf Scanf.Scanning.stdin \"%d\" wynik );;"}, {"source_code": "let rec potegi a x n = \nif n < x then a\nelse potegi (a+x) (2*x) n;;\n\nlet wynik n = n*(n+1)/2 - (potegi 0 1 n);;\nlet rec licz n =\nif n = 0 then Printf.printf \"\\n\"\nelse \nPrintf.printf \"%d\\n\" ( Scanf.bscanf Scanf.Scanning.stdin \"%d\" wynik ); licz(n-1);;"}, {"source_code": "let rec potegi a x n = \nif n < x then a\nelse potegi (a+x) (2*x) n;;\n\nlet wynik n = Printf.printf \"%d\\n\" ( n*(n+1)/2 - (potegi 0 1 n) );;\n\nlet rec licz n a =\nif n = 1 then a\nelse licz (n-1) ( wynik ( read_int () ) );;\n\nlet funkcja x = licz x (Printf.printf \"\");;\n\nlet test x = licz 0 (Printf.printf \" 5\");;\n\n funkcja ( read_int () );;"}, {"source_code": "let rec potegi a x n = \nif n < x then a\nelse potegi (a+x) (2*x) n;;\n\nlet wynik n = Printf.printf \"%d\\n\" ( n*(n+1)/2 - (potegi 0 1 n) );;\n\nlet rec licz n a =\nif n = 0 then a\nelse licz (n-1)\n(Scanf.bscanf Scanf.Scanning.stdin \"%d\" wynik );;"}, {"source_code": "let rec potegi a x n = \nif n < x then a\nelse potegi (a+x) (2*x) n;;\n\nlet wynik n = n*(n+1)/2 - (potegi 0 1 n);;\n\nPrintf.printf \"%d\" ( Scanf.bscanf Scanf.Scanning.stdin \"%d\" wynik );;"}, {"source_code": "let rec potegi a x n = \nif n < x then a\nelse potegi (a+x) (2*x) n;;\n\nlet wynik n = Printf.printf \"%d\\n\" ( n*(n+1)/2 - (potegi 0 1 n) );;\n\nlet rec licz n a =\nif n = 0 then a\nelse licz (n-1)\n(Scanf.bscanf Scanf.Scanning.stdin \"%d\\n\" wynik );;\n\nlet funkcja x = licz x (Printf.printf \"\");;\n\nlet test x = licz 0 (Printf.printf \" 5\");;\n\n test ( read_int () );;"}, {"source_code": "let rec potegi a x n = \nif n < x then a\nelse potegi (a+x) (2*x) n;;\n\nlet wynik n = Printf.printf \"%d\\n\" ( n*(n+1)/2 - (potegi 0 1 n) );;\n\nlet rec licz n a =\nif n = 0 then a\nelse licz (n-1)\n(Scanf.bscanf Scanf.Scanning.stdin \"%d\" wynik );;\n\nlet funkcja x = licz x (Printf.printf \"\");;\n\nScanf.bscanf Scanf.Scanning.stdin \"%d\" licz;;"}, {"source_code": "let rec potegi a x n = \nif n < x then a\nelse potegi (a+x) (2*x) n;;\n\nlet wynik n = Printf.printf \"%d\\n\" ( n*(n+1)/2 - (potegi 0 1 n) );;\n\nlet rec licz n a =\nif n <= 0 then a\nelse licz (n-1)\n(Scanf.bscanf Scanf.Scanning.stdin \"%d\" wynik );;\n\nlet funkcja x = licz x (Printf.printf \"5\");;\n\nlet test x = licz 0 (Printf.printf \" 5\");;\n\nScanf.bscanf Scanf.Scanning.stdin \"%d\" test;;"}], "src_uid": "a3705f29b9a8be97a9e9e54b6eccba09"} {"nl": {"description": "The Little Elephant loves trees very much, he especially loves root trees.He's got a tree consisting of n nodes (the nodes are numbered from 1 to n), with root at node number 1. Each node of the tree contains some list of numbers which initially is empty. The Little Elephant wants to apply m operations. On the i-th operation (1\u2009\u2264\u2009i\u2009\u2264\u2009m) he first adds number i to lists of all nodes of a subtree with the root in node number ai, and then he adds number i to lists of all nodes of the subtree with root in node bi.After applying all operations the Little Elephant wants to count for each node i number ci \u2014 the number of integers j (1\u2009\u2264\u2009j\u2009\u2264\u2009n;\u00a0j\u2009\u2260\u2009i), such that the lists of the i-th and the j-th nodes contain at least one common number.Help the Little Elephant, count numbers ci for him.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of the tree nodes and the number of operations. Each of the following n\u2009-\u20091 lines contains two space-separated integers, ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n,\u2009ui\u2009\u2260\u2009vi), that mean that there is an edge between nodes number ui and vi. Each of the following m lines contains two space-separated integers, ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n,\u2009ai\u2009\u2260\u2009bi), that stand for the indexes of the nodes in the i-th operation. It is guaranteed that the given graph is an undirected tree.", "output_spec": "In a single line print n space-separated integers \u2014 c1,\u2009c2,\u2009...,\u2009cn.", "sample_inputs": ["5 1\n1 2\n1 3\n3 5\n3 4\n2 3", "11 3\n1 2\n2 3\n2 4\n1 5\n5 6\n5 7\n5 8\n6 9\n8 10\n8 11\n2 9\n3 6\n2 8"], "sample_outputs": ["0 3 3 3 3", "0 6 7 6 0 2 0 5 4 5 5"], "notes": null}, "positive_code": [{"source_code": "(* this is customized splay tree code for storing a set of disjoint intervals *)\n\ntype tree = Empty \n | Node of tree * (int * int) * tree * (int * int)\n(* left item right (total length * depth *)\ntype direction = Left | Right\ntype path = Item of tree * direction\n \nlet size tree = match tree with Empty -> 0 | Node(_, _, _, (size,_)) -> size\nlet depth tree = match tree with Empty -> 0 | Node(_, _, _, (_,depth)) -> depth\n\nlet getroot = function \n | Node(left, k, right, _) -> (left, k, right)\n | _ -> failwith \"called getroot on Empty\"\n\nlet newNode (l, (lo,hi), r) = Node(l, (lo,hi), r, \n\t\t\t\t ((size l) + (size r) + (hi-lo+1),\n\t\t\t\t 1 + max (depth l) (depth r)))\n\nlet splay t p = \n (* The following splay function takes as input the currently splayed\n tree (so far) t, and a path list. It takes two steps up, and calls\n itself recursively. *)\n let rec rsplay = function\n | (t,[]) -> t\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->\n\trsplay (newNode(tL,tK,newNode(tR,bK,newNode(bR,cK,cR))), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->\n rsplay (newNode(newNode(newNode(cL,cK,bL), bK, tL),tK,tR), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->\n\trsplay (newNode(tL,tK,newNode(tR,bK,bR)), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->\n\trsplay (newNode(newNode(bL,bK,tL),tK,tR), tail)\n\t \n | (_,_) -> failwith \"Splay_failed (Should not happen)\"\n in\n\n let rec build_path t path = \n match t with \n | Empty -> failwith \"failed build_path\"\n | Node(left, (lo,hi), right, _) ->\n\t if p < lo && left<>Empty then build_path left (Item(t, Left)::path)\n\t else if p > hi && right<>Empty then build_path right (Item(t, Right)::path)\n\t else (t,path)\n in\n\n if t=Empty then Empty else\n rsplay (build_path t [])\n\nlet splaydeep t = \n let rec find_deepest = function\n | Node(Empty, (lo,_), Empty, _) -> lo\n | Node(left, _, right, _) ->\n\tfind_deepest (if depth left >= depth right then left else right)\n | Empty -> failwith \"find_deepest called with Empty\"\n\t\n in\n if t=Empty then t else splay t (find_deepest t)\n\nlet split_l t l = \n (* split the list of segments in two. Find the leftmost segment\n whose left endpoint is >= l. That is the right part of my split. *)\n if t=Empty then (Empty,Empty) else\n let (left, (lo,hi), right) = getroot (splay t l) in\n let put_on_left = \n if lo <= l && l <= hi then lo < l\n else if l < lo then false else true\n in\n if put_on_left \n then (newNode(left, (lo,hi), Empty), right)\n else (left, newNode(Empty,(lo,hi),right)) \n\nlet split_r t r = \n (* split the list of segments in two. Find the rightmost segment\n whose right endpoint is <= r. That is the left part of my split. *)\n if t=Empty then (Empty,Empty) else\n let (left, (lo,hi), right) = getroot (splay t r) in\n let put_on_left = \n if lo <= r && r <= hi then r = hi\n else if r < lo then false else true\n in\n if put_on_left \n then (newNode(left, (lo,hi), Empty), right)\n else (left, newNode(Empty,(lo,hi),right)) \n\t\nlet insert t (l,r) =\n (* Insert a new interval that is either contained in,\n is disjoint from, or fully contains some other intervals *)\n if t=Empty then newNode (Empty,(l,r),Empty) else\n let t = splay t l in\n let (left, (lo,hi), right) = getroot t in\n if lo <= l && r <= hi then t else (* new interval contained *)\n\tlet (s1,s23) = split_l t l in\n\tlet (s2,s3) = split_r s23 r in\n\t newNode(s1,(l,r),s3)\n\n\n(**************************************************************************)\n\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int()-1 in (u, read_int()-1)\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n let edges = Array.make n [] in\n let () = for i=0 to n-2 do\n let (u,v) = read_pair() in\n edges.(u) <- v::edges.(u);\n edges.(v) <- u::edges.(v)\n done in\n let update = Array.make n [] in\n let () = for i=0 to m-1 do\n let (u,v) = read_pair() in\n update.(u) <- v::update.(u);\n update.(v) <- u::update.(v)\n done in\n\n let pre = Array.make n (-1) in\n\n let rec dfspre c u = if pre.(u) >= 0 then c else (\n pre.(u) <- c;\n List.fold_left dfspre (c+1) edges.(u)\n ) in\n\n let _ = dfspre 0 0 in\n\n let () = for i=0 to n-1 do\n edges.(i) <- List.filter (fun e -> pre.(e) > pre.(i)) edges.(i)\n (* Edge from parent to child increases pre.()\n\t keep edges from parent to child *)\n done in\n\n let mpre = Array.make n (-1) in (* max preorder number in the subtree rooted here *)\n\n let rec dfsmpre c u = \n let c = List.fold_left dfsmpre c edges.(u) in\n mpre.(u) <- max c pre.(u);\n mpre.(u)\n in\n\n let _ = dfsmpre 0 0 in\n\n let count = Array.make n 0 in (* our answer *)\n\n let rec solve u t = (* u is a node, t is a tree of intervals inherited from the parent of u *)\n let nt = if update.(u) = [] then t else insert t (pre.(u), mpre.(u)) in\n let nt = List.fold_left (\n fun t v -> insert t (pre.(v), mpre.(v))\n ) nt update.(u)\n in\n\n(*\n let rec logint i ac = if i=0 then ac else logint (i/2) (1::ac) in\n let nt = List.fold_left (fun t _ -> splaydeep t) nt (logint (List.length edges.(u)) []) in\n*)\n\n let nt = List.fold_left (fun t _ -> splaydeep t) nt edges.(u) in\n List.iter (fun v -> solve v nt) edges.(u);\n count.(u) <- size nt;\n in\n\n solve 0 Empty;\n \n for i=0 to n-1 do\n Printf.printf \"%d \" (if count.(i)>0 then count.(i)-1 else 0)\n done;\n print_newline()\n"}, {"source_code": "(* this is customized splay tree code for storing a set of disjoint intervals *)\n\ntype tree = Empty \n | Node of tree * (int * int) * tree * (int * int)\n(* left item right (total length * depth *)\ntype direction = Left | Right\ntype path = Item of tree * direction\n \nlet size tree = match tree with Empty -> 0 | Node(_, _, _, (size,_)) -> size\nlet depth tree = match tree with Empty -> 0 | Node(_, _, _, (_,depth)) -> depth\n\nlet getroot = function \n | Node(left, k, right, _) -> (left, k, right)\n | _ -> failwith \"called getroot on Empty\"\n\nlet newNode (l, (lo,hi), r) = Node(l, (lo,hi), r, \n\t\t\t\t ((size l) + (size r) + (hi-lo+1),\n\t\t\t\t 1 + max (depth l) (depth r)))\n\nlet splay t p = \n (* The following splay function takes as input the currently splayed\n tree (so far) t, and a path list. It takes two steps up, and calls\n itself recursively. *)\n let rec rsplay = function\n | (t,[]) -> t\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->\n\trsplay (newNode(tL,tK,newNode(tR,bK,newNode(bR,cK,cR))), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->\n rsplay (newNode(newNode(newNode(cL,cK,bL), bK, tL),tK,tR), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->\n\trsplay (newNode(tL,tK,newNode(tR,bK,bR)), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->\n\trsplay (newNode(newNode(bL,bK,tL),tK,tR), tail)\n\t \n | (_,_) -> failwith \"Splay_failed (Should not happen)\"\n in\n\n let rec build_path t path = \n match t with \n | Empty -> failwith \"failed build_path\"\n | Node(left, (lo,hi), right, _) ->\n\t if p < lo && left<>Empty then build_path left (Item(t, Left)::path)\n\t else if p > hi && right<>Empty then build_path right (Item(t, Right)::path)\n\t else (t,path)\n in\n\n if t=Empty then Empty else\n rsplay (build_path t [])\n\nlet splaydeep t = \n let rec find_deepest = function\n | Node(Empty, (lo,_), Empty, _) -> lo\n | Node(left, _, right, _) ->\n\tfind_deepest (if depth left >= depth right then left else right)\n | Empty -> failwith \"find_deepest called with Empty\"\n\t\n in\n if t=Empty then t else splay t (find_deepest t)\n\nlet split_l t l = \n (* split the list of segments in two. Find the leftmost segment\n whose left endpoint is >= l. That is the right part of my split. *)\n if t=Empty then (Empty,Empty) else\n let (left, (lo,hi), right) = getroot (splay t l) in\n let put_on_left = \n if lo <= l && l <= hi then lo < l\n else if l < lo then false else true\n in\n if put_on_left \n then (newNode(left, (lo,hi), Empty), right)\n else (left, newNode(Empty,(lo,hi),right)) \n\nlet split_r t r = \n (* split the list of segments in two. Find the rightmost segment\n whose right endpoint is <= r. That is the left part of my split. *)\n if t=Empty then (Empty,Empty) else\n let (left, (lo,hi), right) = getroot (splay t r) in\n let put_on_left = \n if lo <= r && r <= hi then r = hi\n else if r < lo then false else true\n in\n if put_on_left \n then (newNode(left, (lo,hi), Empty), right)\n else (left, newNode(Empty,(lo,hi),right)) \n\t\nlet insert t (l,r) =\n (* Insert a new interval that is either contained in,\n is disjoint from, or fully contains some other intervals *)\n if t=Empty then newNode (Empty,(l,r),Empty) else\n let t = splay t l in\n let (left, (lo,hi), right) = getroot t in\n if lo <= l && r <= hi then t else (* new interval contained *)\n\tlet (s1,s23) = split_l t l in\n\tlet (s2,s3) = split_r s23 r in\n\t newNode(s1,(l,r),s3)\n\n\n(**************************************************************************)\n\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int()-1 in (u, read_int()-1)\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n let edges = Array.make n [] in\n let () = for i=0 to n-2 do\n let (u,v) = read_pair() in\n edges.(u) <- v::edges.(u);\n edges.(v) <- u::edges.(v)\n done in\n let update = Array.make n [] in\n let () = for i=0 to m-1 do\n let (u,v) = read_pair() in\n update.(u) <- v::update.(u);\n update.(v) <- u::update.(v)\n done in\n\n let pre = Array.make n (-1) in\n\n let rec dfspre c u = if pre.(u) >= 0 then c else (\n pre.(u) <- c;\n List.fold_left dfspre (c+1) edges.(u)\n ) in\n\n let _ = dfspre 0 0 in\n\n let () = for i=0 to n-1 do\n edges.(i) <- List.filter (fun e -> pre.(e) > pre.(i)) edges.(i)\n (* Edge from parent to child increases pre.()\n\t keep edges from parent to child *)\n done in\n\n let mpre = Array.make n (-1) in (* max preorder number in the subtree rooted here *)\n\n let rec dfsmpre c u = \n let c = List.fold_left dfsmpre c edges.(u) in\n mpre.(u) <- max c pre.(u);\n mpre.(u)\n in\n\n let _ = dfsmpre 0 0 in\n\n let count = Array.make n 0 in (* our answer *)\n\n let rec solve u t = (* u is a node, t is a tree of intervals inherited from the parent of u *)\n let nt = if update.(u) = [] then t else insert t (pre.(u), mpre.(u)) in\n let nt = List.fold_left (\n fun t v -> insert t (pre.(v), mpre.(v))\n ) nt update.(u)\n in\n\n let rec logint i ac = if i=0 then ac else logint (i/2) (1::ac) in\n let nt = List.fold_left (fun t _ -> splaydeep t) nt (logint (List.length edges.(u)) []) in\n\n(* let nt = List.fold_left (fun t _ -> splaydeep t) nt edges.(u) in *)\n List.iter (fun v -> solve v nt) edges.(u);\n count.(u) <- size nt;\n in\n\n solve 0 Empty;\n \n for i=0 to n-1 do\n Printf.printf \"%d \" (if count.(i)>0 then count.(i)-1 else 0)\n done;\n print_newline()\n"}], "negative_code": [], "src_uid": "1cdbf1984e359e48d6675fb4ed4c97c5"} {"nl": {"description": "Little X has met the following problem recently. Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234)\u2009=\u20091\u2009+\u20092\u2009+\u20093\u2009+\u20094). You are to calculate Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the following C++ code: ans = solve(l, r) % a; if (ans <= 0) ans += a; This code will fail only on the test with . You are given number a, help Little X to find a proper test for hack.", "input_spec": "The first line contains a single integer a\u00a0(1\u2009\u2264\u2009a\u2009\u2264\u20091018).", "output_spec": "Print two integers: l,\u2009r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009<\u200910200) \u2014 the required test data. Leading zeros aren't allowed. It's guaranteed that the solution exists.", "sample_inputs": ["46", "126444381000032"], "sample_outputs": ["1 10", "2333333 2333333333333"], "notes": null}, "positive_code": [{"source_code": "\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i++1L) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet rec dig n = if n>0L then (n %% 10L)::(dig (n//10L)) else [] \n(* produces a list of the digits of n, from lowest to highest *)\nlet f n = List.fold_left (++) 0L (dig n)\n\nopen Printf\nopen Scanf\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet solve m =\n\n let compute_sum n =\n (* compute the sum of the digits of all the numbers from 1 to n. *)\n let sumd d = d ** (d++1L) // 2L in\n let rec loop n ac digs = \n match digs with []-> ac\n\t| d::digs -> \n\t let ac = (ac ++ m -- (f n)) %% m in\n\t let ac = (((ac ** 2L) %% m) ** 5L) %% m in (* multiply by 10 modulo m *)\n\t let ac = (ac ++ n ** 45L ++ (d++1L) ** (f n) ++ (sumd d)) %% m in (* n is not as big as m *)\n\t loop ((10L ** n) ++ d) ac digs\n in\n if n=0L then 0L else loop 0L 0L (List.rev (dig n))\n in \n\n let dig_of_m = long (List.length (dig m)) in\n let delta = max (m // (dig_of_m ** 9L)) 1L in\n\n let rec find_hi cur v = \n let cur = cur++delta in\n let v' = compute_sum cur in\n if v' < v then cur else find_hi cur v'\n in\n\n let rec bsearch lo vlo hi vhi = \n (* compute_sum lo = vlo > compute_sum hi = vhi *)\n if lo ++ 1L = hi then hi else\n let mid = (lo ++ hi) // 2L in\n let vmid = compute_sum mid in\n if vmid > vlo then bsearch mid vmid hi vhi\n else if vmid < vlo then bsearch lo vlo mid vmid\n else failwith \"binary search failed\"\n in\n let hi = find_hi 1L 1L in\n let lo = hi -- delta in\n let st = bsearch lo (compute_sum lo) hi (compute_sum hi) in\n\n let rec find_match i sumi j sumj = \n if i >= j then find_match i sumi (j++1L) ((sumj ++ (f (j++1L))) %% m) (* neede for small values of m *)\n else if sumi = sumj then (i,j)\n else if sumi < sumj \n then find_match (i++1L) ((sumi ++ (f (i++1L))) %% m) j sumj\n else find_match i sumi (j++1L) ((sumj ++ (f (j++1L))) %% m)\n in\n\n find_match 0L 0L st (compute_sum st)\n\nlet () = \n let (i,j) = solve (read_long()) in\n printf \"%Ld %Ld\\n\" (i++1L) j\n"}], "negative_code": [], "src_uid": "52b8d97f216ea22693bc16fadcd46dae"} {"nl": {"description": "You are given an n\u2009\u00d7\u2009m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijk\u00a0we obtain the table:acdefghjk\u00a0A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.", "input_spec": "The first line contains two integers \u00a0\u2014 n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). Next n lines contain m small English letters each\u00a0\u2014 the characters of the table.", "output_spec": "Print a single number\u00a0\u2014 the minimum number of columns that you need to remove in order to make the table good.", "sample_inputs": ["1 10\ncodeforces", "4 4\ncase\ncare\ntest\ncode", "5 4\ncode\nforc\nesco\ndefo\nrces"], "sample_outputs": ["0", "2", "4"], "notes": "NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t."}, "positive_code": [{"source_code": "let s = read_line ();;\nlet sx = List.map int_of_string (Str.split (Str.regexp \" +\") s);;\nlet n = List.hd sx;;\nlet m = List.hd (List.tl sx);;\n\n\nlet a = Array.make n \"\";;\n\nfor i = 0 to (n - 1) do\n\ta.(i) <- read_line ();\ndone;;\n\n\nlet rec proc (e: bool array) = function\n| j when j = m -> 0\n| j ->\n\tlet e' = Array.copy e in\n\t(*print_newline(Array.iter (fun x -> print_string (if x then \"true \" else \"false \")) e);*)\n\tlet rec aux = function\n\t| i when i = n -> proc e' (j+1)\n\t| i ->\n\t\tif (e.(i) && a.(i).[j] < a.(i-1).[j]) then\n\t\t\t1 + proc e (j+1)\n\t\telse\n\t\t\t(e'.(i) <- e'.(i) && a.(i).[j] = a.(i-1).[j];\n\t\t\taux (i+1)) in\n\taux 1;;\n\n\n\n\n\nprint_newline (print_int (proc (Array.make n true) 0));;\n(*print_newline (print_int (Array.fold_left (fun a x -> if x then 0 else 1) 0 e));;*)"}, {"source_code": "exception Invalid_input\n\ntype status =\n | Stable\n | Safe\n\nlet (|>) x f = f x\n\nlet rec make_list = fun len f ->\n if len = 0 then\n []\n else\n f () :: make_list (len - 1) f\n\nlet rec prepend_list_to_list_of_list = fun li acc ->\n match li, acc with\n | h1 :: t1, h2 :: t2 -> (h1 :: h2) :: (prepend_list_to_list_of_list t1 t2)\n | _ -> acc\n\nlet string_to_list = fun s ->\n let len = String.length s in\n let rec do_string_to_list = fun s i ->\n if i < len then\n s.[i] :: do_string_to_list s (i + 1)\n else\n []\n in\n do_string_to_list s 0\n\nlet read_input = fun n m ->\n let rec do_read_input = fun i acc ->\n if i < n then\n let current_line =\n read_line ()\n |> string_to_list\n in\n prepend_list_to_list_of_list current_line acc\n |> do_read_input (i + 1)\n else\n acc\n in\n make_list m (fun () -> [])\n |> do_read_input 0\n\nlet process_one_column = fun status chars ->\n let rec need_to_remove = fun s_list c_list ->\n match s_list, c_list with\n | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->\n if h1 = Stable && h2 < m2 then\n true\n else\n need_to_remove p1 p2\n | _ ->\n false\n in\n if need_to_remove status chars then\n status, true\n else\n let rec get_new_status = fun s_list c_list ->\n match s_list, c_list with\n | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->\n let new_s =\n if h1 = Safe || m2 < h2 then\n Safe\n else\n Stable\n in\n new_s :: get_new_status p1 p2\n | hd :: [], _ ->\n [hd]\n | _ ->\n raise Invalid_input\n in\n (get_new_status status chars), false\n\nlet process_all_columns = fun n input ->\n let initial = make_list n (fun () -> Stable) in\n let rec do_process = fun status count input ->\n match input with\n | hd :: tl ->\n let new_status, removed = process_one_column status hd in\n let new_count = if removed then count + 1 else count in\n do_process new_status new_count tl\n | _ ->\n count\n in\n do_process initial 0 input\n\nlet () =\n let (n, m) =\n read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map int_of_string\n |> fun li ->\n match li with\n | a :: [b] -> (a, b)\n | _ -> raise Invalid_input\n in\n let input = read_input n m in\n process_all_columns n input\n |> print_int\n |> print_newline\n"}], "negative_code": [{"source_code": "let s = read_line ();;\nlet sx = List.map int_of_string (Str.split (Str.regexp \" +\") s);;\nlet n = List.hd sx;;\nlet m = List.hd (List.tl sx);;\n\n\nlet a = Array.make n \"\";;\n\nfor i = 0 to (n - 1) do\n\ta.(i) <- read_line ();\ndone;;\n\n\nlet rec proc (e: bool array) = function\n| j when j = m -> 0\n| j ->\n\tlet e' = Array.copy e in\n\n\tlet rec aux = function\n\t| i when i = n -> proc e' (j+1)\n\t| i ->\n\t\tif (e.(i) && a.(i).[j] < a.(i-1).[j]) then\n\t\t\t1 + proc e (j+1)\n\t\telse\n\t\t\t(e'.(i) <- a.(i).[j] = a.(i-1).[j];\n\t\t\taux (i+1)) in\n\taux 1;;\n\n\n\n\n\nprint_newline (print_int (proc (Array.make n true) 0));;\n(*print_newline (print_int (Array.fold_left (fun a x -> if x then 0 else 1) 0 e));;*)"}, {"source_code": "exception Invalid_input\n\ntype status =\n | Stable\n | Safe\n\nlet (|>) x f = f x\n\nlet rec make_list = fun len f ->\n if len = 0 then\n []\n else\n f () :: make_list (len - 1) f\n\nlet rec prepend_list_to_list_of_list = fun li acc ->\n match li, acc with\n | h1 :: t1, h2 :: t2 -> (h1 :: h2) :: (prepend_list_to_list_of_list t1 t2)\n | _ -> acc\n\nlet string_to_list = fun s ->\n let len = String.length s in\n let rec do_string_to_list = fun s i ->\n if i < len then\n s.[i] :: do_string_to_list s (i + 1)\n else\n []\n in\n do_string_to_list s 0\n\nlet read_input = fun n m ->\n let rec do_read_input = fun i acc ->\n if i < n then\n let current_line =\n read_line ()\n |> string_to_list\n in\n prepend_list_to_list_of_list current_line acc\n |> do_read_input (i + 1)\n else\n acc\n in\n make_list m (fun () -> [])\n |> do_read_input 0\n\nlet process_one_column = fun status chars ->\n let rec need_to_remove = fun s_list c_list ->\n match s_list, c_list with\n | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->\n if h1 = Stable && h2 < m2 then\n true\n else\n need_to_remove p1 p2\n | _ ->\n false\n in\n if need_to_remove status chars then\n status, true\n else\n let rec get_new_status = fun s_list c_list ->\n match s_list, c_list with\n | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->\n let new_s =\n if h1 = Safe || m2 < h2 then\n Safe\n else\n Stable\n in\n new_s :: get_new_status p1 p2\n | _ ->\n []\n in\n (get_new_status status chars), false\n\nlet process_all_columns = fun n input ->\n let initial = make_list n (fun () -> Stable) in\n let rec do_process = fun status count input ->\n match input with\n | hd :: tl ->\n let new_status, removed = process_one_column status hd in\n let new_count = if removed then count + 1 else count in\n do_process new_status new_count tl\n | _ ->\n count\n in\n do_process initial 0 input\n\nlet () =\n let (n, m) =\n read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map int_of_string\n |> fun li ->\n match li with\n | a :: [b] -> (a, b)\n | _ -> raise Invalid_input\n in\n let input = read_input n m in\n process_all_columns n input\n |> print_int\n |> print_newline\n"}, {"source_code": "exception Invalid_input\n\ntype status =\n | Stable\n | Safe\n\nlet (|>) x f = f x\n\nlet rec make_list = fun len f ->\n if len = 0 then\n []\n else\n f () :: make_list (len - 1) f\n\nlet rec prepend_list_to_list_of_list = fun li acc ->\n match li, acc with\n | h1 :: t1, h2 :: t2 -> (h1 :: h2) :: (prepend_list_to_list_of_list t1 t2)\n | _ -> acc\n\nlet string_to_list = fun s ->\n let len = String.length s in\n let rec do_string_to_list = fun s i ->\n if i < len then\n s.[i] :: do_string_to_list s (i + 1)\n else\n []\n in\n do_string_to_list s 0\n\nlet read_input = fun n m ->\n let rec do_read_input = fun i acc ->\n if i < n then\n let current_line =\n read_line ()\n |> string_to_list\n in\n prepend_list_to_list_of_list current_line acc\n |> do_read_input (i + 1)\n else\n acc\n in\n make_list m (fun () -> [])\n |> do_read_input 0\n\nlet process_one_column = fun status chars ->\n let rec need_to_remove = fun s_list c_list ->\n match s_list, c_list with\n | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->\n if h1 = Stable && h2 < m2 then\n true\n else\n need_to_remove p1 p2\n | _ ->\n false\n in\n if need_to_remove status chars then\n status, true\n else\n let rec get_new_status = fun s_list c_list ->\n match s_list, c_list with\n | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->\n let new_s =\n if h1 = Stable && m2 < h2 then\n Safe\n else\n Stable\n in\n new_s :: get_new_status p1 p2\n | _ ->\n []\n in\n (get_new_status status chars), false\n\nlet process_all_columns = fun n input ->\n let initial = make_list n (fun () -> Stable) in\n let rec do_process = fun status count input ->\n match input with\n | hd :: tl ->\n let new_status, removed = process_one_column status hd in\n let new_count = if removed then count + 1 else count in\n do_process new_status new_count tl\n | _ ->\n count\n in\n do_process initial 0 input\n\nlet () =\n let (n, m) =\n read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map int_of_string\n |> fun li ->\n match li with\n | a :: [b] -> (a, b)\n | _ -> raise Invalid_input\n in\n let input = read_input n m in\n process_all_columns n input\n |> print_int\n |> print_newline\n"}], "src_uid": "a45cfc2855f82f162133930d9834a9f0"} {"nl": {"description": "Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?", "input_spec": "The first line contains two integers n, l (1\u2009\u2264\u2009n\u2009\u2264\u20091000, 1\u2009\u2264\u2009l\u2009\u2264\u2009109)\u00a0\u2014 the number of lanterns and the length of the street respectively. The next line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009l). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street.", "output_spec": "Print the minimum light radius d, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10\u2009-\u20099.", "sample_inputs": ["7 15\n15 5 3 7 9 14 0", "2 5\n2 5"], "sample_outputs": ["2.5000000000", "2.0000000000"], "notes": "NoteConsider the second sample. At d\u2009=\u20092 the first lantern will light the segment [0,\u20094] of the street, and the second lantern will light segment [3,\u20095]. Thus, the whole street will be lit."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let n = read () in\n let length = float (read ()) in\n let rec loop list i =\n if i < n\n then\n let var = float (read ()) in\n loop (var :: list) (i + 1)\n else\n (length, list)\n in loop [] 0\n\nlet get_max head prev max = \n if prev = float (-1)\n then\n Pervasives.max head max\n else\n Pervasives.max ((head -. prev) /. (float 2)) max\n\nlet solve (length, list) =\n let lampposts = List.sort (Pervasives.compare) list in \n let d_start = 0.0 -. List.hd lampposts in\n let d_end = length -. List.hd (List.rev lampposts) in\n let d_min = Pervasives.max d_start d_end in\n\n let rec loop rest prev max = \n match rest with\n | (head :: tail) -> loop tail head (get_max head prev max)\n | [] -> Pervasives.max d_min max\n in loop lampposts (float (-1)) (float 0)\n\nlet print result = Printf.printf \"%.10f\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "(* Codeforces 349 A Cinema Line done *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet rec minrad l d len = match l with\n| [] -> d\n| h :: [] -> max d (float_of_int (len - h))\n| h :: t ->\n\tlet dd = (float_of_int ((List.hd t) - h)) /. 2.0 in\n\tlet dd = max dd d in\n\tminrad t dd len;;\n\nlet main() =\n\tlet n = gr() in\n\tlet len = gr() in\n\tlet ll = readlist n [] in\n\tlet li = List.rev ll in\n\tlet sol = List.sort_uniq compare li in\n\tlet dinit = float_of_int (List.hd sol) in\n\tlet rad = minrad sol dinit len in\n\tbegin\n\t\tPrintf.printf \"%.2f\\n\" rad\n\tend;;\n\nmain();;"}, {"source_code": "(* Codeforces 492B VaniaFonari *)\n\nopen List;;\nopen String;;\nopen Array;;\nopen Int64;;\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet printarri64 ai = Array.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) ai;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n - 1) (gr() :: acc);;\n\nlet miscomp a b = a - b;;\n\nlet rec maxdif dif l = match l with \n| a :: b :: tl -> \n\tlet d = b - a in\n\tlet dd = if d>dif then d else dif in\n\tmaxdif dd (b :: tl)\t\t\t\t\t\t\t\t\n| _ -> dif;;\n\nlet main () = \n\tlet n = gr () in\n\tlet l = gr () in\n\tlet aal : int list = readlist n [] in\n\tlet aso : int list = List.sort miscomp (l :: aal) in\n\tlet d0 = maxdif 0 (0 :: aso) in\n\tlet f0 = ((float_of_int d0) /. 2.0) in \n\tlet d1 = float_of_int (List.nth aso 0) in\n\tlet d2 = float_of_int (l - (List.nth aso (n-1))) in\n\tlet d = max f0 (max d1 d2) in\n\tbegin\n\t print_float d\n\tend;;\n\nmain();;\n"}, {"source_code": "open Str\n\nlet print_tuple = fun tuple ->\n let (x, y) = tuple in\n Printf.printf \"%d %d\\n\" x y\n\nlet rec print_list = fun l ->\n match l with\n | hd :: tl ->\n print_int hd;\n print_char ' ';\n print_list tl;\n | _ -> ()\n\nlet rec find_max_gap = fun l cur_max ->\n match l with\n | hd :: mid :: tl ->\n let diff = mid - hd in\n if diff < cur_max then\n find_max_gap (mid :: tl) cur_max\n else\n find_max_gap (mid :: tl) diff\n | _ -> cur_max\n\nlet rec get_last = fun l ->\n match l with\n | [x] ->\n Some x\n | _ :: tl ->\n get_last tl\n | _ -> None\n\nexception Invalid_input\n\nlet find_max_gap_including_head_and_tail = fun l e ->\n match get_last l with\n | Some last ->\n List.hd (List.fast_sort (fun i j ->\n if i < j then\n 1\n else\n -1\n ) ([(float_of_int (List.hd l)); (float_of_int (e - last)); (float_of_int (find_max_gap l 0)) /. 2.0])\n )\n | None -> raise Invalid_input\n\nlet () =\n let (num_of_lanterns, len_of_street) = (fun line ->\n match line with\n | hd :: tl -> (int_of_string hd, int_of_string (List.hd tl))\n | _ -> raise Invalid_input\n ) (Str.split (Str.regexp \" +\") (read_line ()))\n in\n let lanterns = List.fast_sort (fun i j ->\n i - j\n ) (List.map int_of_string (Str.split (Str.regexp \" +\") (read_line ())))\n in\n print_float (find_max_gap_including_head_and_tail lanterns len_of_street);\n print_newline ()\n"}], "negative_code": [{"source_code": "(* Codeforces 492B VaniaFonari *)\n\nopen List;;\nopen String;;\nopen Array;;\nopen Int64;;\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet printarri64 ai = Array.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) ai;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n - 1) (gr() :: acc);;\n\nlet miscomp a b = a - b;;\n\nlet rec maxdif dif l = match l with \n| a :: b :: tl -> \n\tlet d = b - a in\n\tlet dd = if d>dif then d else dif in\n\tmaxdif dd (b :: tl)\t\t\t\t\t\t\t\t\n| _ -> dif;;\n\nlet main () = \n\tlet n = gr () in\n\tlet l = gr () in\n\tlet aal : int list = readlist n [] in\n\tlet aso : int list = List.sort miscomp (l :: aal) in\n\tlet df = maxdif 0 (0 :: aso) in\n\tbegin\n\t print_float ((float_of_int df) /. 2.0)\n\tend;;\n\nmain();;\n"}], "src_uid": "d79166497eb61d81fdfa4ef80ec1c8e8"} {"nl": {"description": "You are given four integers $$$n$$$, $$$c_0$$$, $$$c_1$$$ and $$$h$$$ and a binary string $$$s$$$ of length $$$n$$$.A binary string is a string consisting of characters $$$0$$$ and $$$1$$$.You can change any character of the string $$$s$$$ (the string should be still binary after the change). You should pay $$$h$$$ coins for each change.After some changes (possibly zero) you want to buy the string. To buy the string you should buy all its characters. To buy the character $$$0$$$ you should pay $$$c_0$$$ coins, to buy the character $$$1$$$ you should pay $$$c_1$$$ coins.Find the minimum number of coins needed to buy the string.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10$$$)\u00a0\u2014 the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of the description of each test case contains four integers $$$n$$$, $$$c_{0}$$$, $$$c_{1}$$$, $$$h$$$ ($$$1 \\leq n, c_{0}, c_{1}, h \\leq 1000$$$). The second line of the description of each test case contains the binary string $$$s$$$ of length $$$n$$$.", "output_spec": "For each test case print a single integer\u00a0\u2014 the minimum number of coins needed to buy the string.", "sample_inputs": ["6\n3 1 1 1\n100\n5 10 100 1\n01010\n5 10 1 1\n11111\n5 1 10 1\n11111\n12 2 1 10\n101110110101\n2 100 1 10\n00"], "sample_outputs": ["3\n52\n5\n10\n16\n22"], "notes": "NoteIn the first test case, you can buy all characters and pay $$$3$$$ coins, because both characters $$$0$$$ and $$$1$$$ costs $$$1$$$ coin.In the second test case, you can firstly change $$$2$$$-nd and $$$4$$$-th symbols of the string from $$$1$$$ to $$$0$$$ and pay $$$2$$$ coins for that. Your string will be $$$00000$$$. After that, you can buy the string and pay $$$5 \\cdot 10 = 50$$$ coins for that. The total number of coins paid will be $$$2 + 50 = 52$$$."}, "positive_code": [{"source_code": "let line_of_ints () =\n ()\n |> read_line\n |> Str.split (Str.regexp \" \")\n |> List.map (fun s -> s |> String.trim |> int_of_string)\n\nlet () =\n let [t] = line_of_ints () in\n for _ = 1 to t do\n let [n; c0; c1; h] = line_of_ints () in\n let s = read_line () in\n let (s0, s1) =\n let s0 = ref 0 in\n let s1 = ref 0 in\n String.iter\n (function\n | '0' -> incr s0\n | '1' -> incr s1)\n s;\n (!s0, !s1)\n in\n let answer =\n let c = ref max_int in\n for a0 = 0 to s0 do\n for a1 = 0 to s1 do\n c := min !c ((s0 - a0 + a1) * c0 + (s1 - a1 + a0) * c1 + (a0 + a1) * h)\n done\n done;\n !c\n in\n answer\n |> string_of_int\n |> print_endline\n done\n"}], "negative_code": [], "src_uid": "7cc0a6df601e3dcf4e1d9578dd599a36"} {"nl": {"description": "The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti \u2014 the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that: the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n), the sum of the ti values of the remaining sculptures is maximized. Help the Vice Rector to analyze the criticism \u2014 find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.", "input_spec": "The first input line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u200920000) \u2014 the initial number of sculptures. The second line contains a sequence of integers t1,\u2009t2,\u2009...,\u2009tn, ti \u2014 the degree of the i-th sculpture's attractiveness (\u2009-\u20091000\u2009\u2264\u2009ti\u2009\u2264\u20091000). The numbers on the line are separated by spaces.", "output_spec": "Print the required maximum sum of the sculptures' attractiveness.", "sample_inputs": ["8\n1 2 -3 4 -5 5 2 3", "6\n1 -2 3 -4 5 -6", "6\n1 2 3 4 5 6"], "sample_outputs": ["14", "9", "21"], "notes": "NoteIn the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 \u0438 3."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\nlet (|>) x f = f x\nlet id = fun x -> x\n(* zd4 *)\nlet n = scanf \"%d\\n\" (fun n -> n)\n\nlet arr = Array.make n 0\n\nlet () = \n for i=0 to n-1 do\n arr.(i) <- scanf \"%d \" (fun x -> x)\n done\nlet ans = ref min_int\n\nlet eval1 vn len =\n for i=0 to len-1 do\n let old,new_sum = ref i,ref 0 in \n for j=1 to vn do\n new_sum := !new_sum + arr.(!old);\n old := !old+len\n done;\n if !new_sum > !ans then ans := !new_sum\n done\n\nlet iter = \n for vn = 3 to n do\n if n mod vn = 0 then\n eval1 vn (n/vn)\n else ()\n done\n\n\nlet () = printf \"%d\\n\" !ans\n(*\nlet () = Array.iter (print_int) arr \nlet () = print_newline ()\n *)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "0ff4ac859403db4e29554ca7870f5490"} {"nl": {"description": "You are given a string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters.A substring of a string is a contiguous subsequence of that string. So, string \"forces\" is substring of string \"codeforces\", but string \"coder\" is not.Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one).It is guaranteed that there is at least two different characters in $$$s$$$.Note that you can remove the whole string and it is correct. Also note that you should remove at least one character.Since the answer can be rather large (not very large though) print it modulo $$$998244353$$$.If you are Python programmer, consider using PyPy instead of Python when you submit your code.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of the string $$$s$$$. The second line of the input contains the string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. It is guaranteed that there is at least two different characters in $$$s$$$.", "output_spec": "Print one integer \u2014 the number of ways modulo $$$998244353$$$ to remove exactly one substring from $$$s$$$ in such way that all remaining characters are equal.", "sample_inputs": ["4\nabaa", "7\naacdeee", "2\naz"], "sample_outputs": ["6", "6", "3"], "notes": "NoteLet $$$s[l; r]$$$ be the substring of $$$s$$$ from the position $$$l$$$ to the position $$$r$$$ inclusive.Then in the first example you can remove the following substrings: $$$s[1; 2]$$$; $$$s[1; 3]$$$; $$$s[1; 4]$$$; $$$s[2; 2]$$$; $$$s[2; 3]$$$; $$$s[2; 4]$$$. In the second example you can remove the following substrings: $$$s[1; 4]$$$; $$$s[1; 5]$$$; $$$s[1; 6]$$$; $$$s[1; 7]$$$; $$$s[2; 7]$$$; $$$s[3; 7]$$$. In the third example you can remove the following substrings: $$$s[1; 1]$$$; $$$s[1; 2]$$$; $$$s[2; 2]$$$. "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet md = 998244353L\nlet () =\n let n = gi 0 in let n = i32 n in\n let s = scanf \" %s\" @@ id in\n if s.[0] = s.[n-$1] then (\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let p = i64 !c mod md in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let q = i64 !c mod md in\n printf \"%Ld\\n\" @@ (((p+1L)*(q+1L)) mod md);\n ) else (\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\\n\" !c; *)\n let p = i64 !c in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\\n\" !c; *)\n let q = i64 !c in\n printf \"%Ld\\n\" @@ ((p+1L)+(q+1L)-1L) mod md;\n )\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "let rec fix f x = f (fix f) x\nlet i64,i32 = Int64.(of_int,to_int)\nlet md = 998244353L\nlet ( **% ) p q = Int64.(rem (mul p q) md);;\nScanf.(Array.(\n let n = scanf \" %d\" @@ fun v -> v in\n let s = scanf \" %s\" @@ fun v -> v in\n let p = fix (fun f i a ->\n if s.[i] = s.[0] then f (i+1) (i::a)\n else a\n ) 0 [] |> List.length in\n let q = fix (fun f i a ->\n if s.[i] = s.[n-1] then f (i-1) (i::a)\n else a\n ) (n-1) [] |> List.length in\n if s.[0] = s.[n-1] then (\n print_int @@ i32 @@ (i64 @@ p+1) **% (i64 @@ q+1)\n ) else (\n print_int @@ i32 @@ (i64 ((p+1) + (q+1) - 1) **% 1L)\n )\n))"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet md = 998244353\nlet () =\n let n = gi 0 in let n = i32 n in\n let s = scanf \" %s\" @@ id in\n if s.[0] = s.[n-$1] then (\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let p = !c %$ md in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let q = !c %$ md in\n printf \"%d\\n\" @@ (((p+$1)*$(q+$1)) %$ md);\n ) else (\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let p = !c in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let q = !c in\n printf \"%d\\n\" @@ ((p+$1)+$(q+$1)-$1) %$ md;\n )\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet md = 998244353\nlet () =\n let n = gi 0 in let n = i32 n in\n let s = scanf \" %s\" @@ id in\n if s.[0] = s.[n-$1] then (\n (* let f,c = ref true,ref s.[0] in\n repi 0 (n-$1) (fun i -> f := !f && !c = s.[i]);\n if !f then (\n fail 0\n ) else (\n\n ) *)\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let p = !c in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let q = !c in\n printf \"%d\" @@ (((p+$1) %$ md)*$((q+$1) %$ md) %$ md);\n ) else (\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let p = !c in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let q = !c in\n printf \"%d\\n\" @@ (p+$q+$1) %$ md;\n )\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nlet allsame s =\n let f = ref true in\n String.iter (fun v -> if v <> s.[0] then f := false) s; !f\nlet () =\n let n = gi 0 in let n = i32 n in\n let s = scanf \" %s\" @@ id in\n let c = ref 0L in\n repi 0 (n) (fun i ->\n repi i (n) (fun j ->\n let p = String.sub s 0 i in\n let q = String.sub s j (n-$j) in\n let f = allsame @@ p ^ q in\n if f then\n printf \"%s ^ %s = %s :: %b\\n\"\n p q (p^q) f\n ;\n if f then c+=1L\n )\n ); printf \"%Ld\\n\" !c\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in let n = i32 n in\n let s = scanf \" %s\" @@ id in\n if s.[0] = s.[n-$1] then (\n (* let f,c = ref true,ref s.[0] in\n repi 0 (n-$1) (fun i -> f := !f && !c = s.[i]);\n if !f then (\n fail 0\n ) else (\n\n ) *)\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let p = !c in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let q = !c in\n printf \"%d\" @@ p*$q;\n ) else (\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let p = !c in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let q = !c in\n printf \"%d\\n\" @@ p+$q+$1;\n )\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in let n = i32 n in\n let s = scanf \" %s\" @@ id in\n if s.[0] = s.[n-$1] then (\n (* let f,c = ref true,ref s.[0] in\n repi 0 (n-$1) (fun i -> f := !f && !c = s.[i]);\n if !f then (\n fail 0\n ) else (\n\n ) *)\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let p = !c in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let q = !c in\n printf \"%d\" @@ (p+$1)*$(q+$1);\n ) else (\n let f,c = ref true,ref 0 in\n repi 0 (n-$1) (fun i ->\n if !f && s.[i] = s.[0] then (\n c := i+$1\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let p = !c in\n let f,c = ref true,ref 0 in\n repi_rev (n-$1) 0 (fun i ->\n if !f && s.[i] = s.[n-$1] then (\n c := n-$i\n ) else f := false;\n );\n (* printf \"%d\" !c; *)\n let q = !c in\n printf \"%d\\n\" @@ p+$q+$1;\n )\n\n\n\n\n\n\n\n\n\n"}], "src_uid": "9693f60fc65065d00a1899df999405fe"} {"nl": {"description": "Wilbur the pig is tinkering with arrays again. He has the array a1,\u2009a2,\u2009...,\u2009an initially consisting of n zeros. At one step, he can choose any index i and either add 1 to all elements ai,\u2009ai\u2009+\u20091,\u2009... ,\u2009an or subtract 1 from all elements ai,\u2009ai\u2009+\u20091,\u2009...,\u2009an. His goal is to end up with the array b1,\u2009b2,\u2009...,\u2009bn. Of course, Wilbur wants to achieve this goal in the minimum number of steps and asks you to compute this value.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the length of the array ai. Initially ai\u2009=\u20090 for every position i, so this array is not given in the input. The second line of the input contains n integers b1,\u2009b2,\u2009...,\u2009bn (\u2009-\u2009109\u2009\u2264\u2009bi\u2009\u2264\u2009109).", "output_spec": "Print the minimum number of steps that Wilbur needs to make in order to achieve ai\u2009=\u2009bi for all i.", "sample_inputs": ["5\n1 2 3 4 5", "4\n1 2 2 1"], "sample_outputs": ["5", "3"], "notes": "NoteIn the first sample, Wilbur may successively choose indices 1, 2, 3, 4, and 5, and add 1 to corresponding suffixes.In the second sample, Wilbur first chooses indices 1 and 2 and adds 1 to corresponding suffixes, then he chooses index 4 and subtract 1."}, "positive_code": [{"source_code": "let n = read_int ();;\nlet a = Array.of_list (List.map (Int64.of_string) (Str.split (Str.regexp \" \") (read_line ())));;\nlet x = ref 0L and ans = ref 0L;;\nfor i = 0 to n - 1 do\n\tans :=\n\t\tInt64.add !ans (Int64.abs (Int64.sub !x a.(i)));\n\t\tx := a.(i);\ndone;;\nprint_string (Int64.to_string !ans);;\n"}, {"source_code": "open Big_int\n\nlet rec yolo now = function\n\t|t::q\t-> Big_int.add_big_int (Big_int.abs_big_int (Big_int.sub_big_int now t)) (yolo t q)\n\t| []\t-> Big_int.big_int_of_int 0\n\nlet main () =\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) and l = ref [] in\n\t\tfor j=1 to n do\n\t\t\tScanf.scanf \" %d\" (fun i -> l := (Big_int.big_int_of_int i):: !l);\n\t\tdone;\n\tPrintf.printf \"%s\" (Big_int.string_of_big_int (yolo (Big_int.big_int_of_int 0) (List.rev !l)));;\n\nmain ();;\n"}, {"source_code": "open Printf\nopen Scanf\n\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n\n let b = Array.init n (fun _ -> long (read_int())) in\n\n let rec loop i running_total total_ops =\n if i=n then total_ops else (\n let x = running_total -- b.(i) in\n let total_ops = total_ops ++ (Int64.abs x) in\n let running_total = running_total -- x in\n loop (i+1) running_total total_ops\n )\n in\n\n let answer = loop 0 0L 0L in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "97a226f47973fcb39c40e16f66654b5f"} {"nl": {"description": "Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). Ivan has beads of n colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.", "input_spec": "The first line of the input contains a single number n (1\u2009\u2264\u2009n\u2009\u2264\u200926) \u2014 the number of colors of beads. The second line contains after n positive integers ai \u00a0 \u2014 the quantity of beads of i-th color. It is guaranteed that the sum of ai is at least 2 and does not exceed 100\u2009000.", "output_spec": "In the first line print a single number\u00a0\u2014 the maximum number of beautiful cuts that a necklace composed from given beads may have. In the second line print any example of such necklace. Each color of the beads should be represented by the corresponding lowercase English letter (starting with a). As the necklace is cyclic, print it starting from any point.", "sample_inputs": ["3\n4 2 1", "1\n4", "2\n1 1"], "sample_outputs": ["1\nabacaba", "4\naaaa", "0\nab"], "notes": "NoteIn the first sample a necklace can have at most one beautiful cut. The example of such a necklace is shown on the picture.In the second sample there is only one way to compose a necklace."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a\n\nlet n2l n = char_of_int ((int_of_char 'a') + n)\n\nlet reverse s = String.init (String.length s) (fun i -> s.[(String.length s) - 1 - i])\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let oddcount = sum 0 (n-1) (fun i -> a.(i) land 1) in\n let m =\n let rec loop i ac = if i=n then ac else\n\tif a.(i) land 1 = 1 then loop (i+1) ac\n\telse loop (i+1) (gcd ac a.(i))\n in\n loop 0 0\n in\n\n match oddcount with\n | 0 ->\n printf \"%d\\n\" m;\n\n let slist = fold 0 (n-1) (fun i ac ->\n\t(String.make (a.(i)/m) (n2l i))::ac\n ) [] in\n \n let s = String.concat \"\" slist in\n let sr = reverse s in\n\n for i=1 to m/2 do\n\tprintf \"%s%s\" s sr;\n done;\n print_newline()\n | 1 ->\n let oddindex = sum 0 (n-1) (fun i -> i * (a.(i) land 1)) in\n let oddone = a.(oddindex) in\n\n let rec loop q =\n\tlet m' = gcd (oddone-q) m in\n\tif (m'/2) mod q = 0 then q else loop (q-2)\n in\n\t \n let q = loop oddone in\n\n printf \"%d\\n\" q;\n a.(oddindex) <- oddone-q;\n\n let slist = fold 0 (n-1) (fun i ac ->\n\t(String.make (a.(i)/(2*q)) (n2l i))::ac\n ) [] in\n let s = String.concat \"\" slist in\n let s' = sprintf \"%s%c%s\" s (n2l oddindex) (reverse s) in\n\n for i=1 to q do\n\tprintf \"%s\" s'\n done;\n print_newline()\n | _ ->\n let slist = fold 0 (n-1) (fun i ac ->\n\t(String.make a.(i) (n2l i))::ac\n ) [] in\n\n printf \"0\\n%s\\n\" (String.concat \"\" slist)\n"}], "negative_code": [], "src_uid": "d467f457a462c83a1a0a6320494da811"} {"nl": {"description": "Vasya had two arrays consisting of non-negative integers: a of size n and b of size m. Vasya chose a positive integer k and created an n\u2009\u00d7\u2009m matrix v using the following formula:Vasya wrote down matrix v on a piece of paper and put it in the table.A year later Vasya was cleaning his table when he found a piece of paper containing an n\u2009\u00d7\u2009m matrix w. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix v from those days. Your task is to find out if the matrix w that you've found could have been obtained by following these rules and if it could, then for what numbers k,\u2009a1,\u2009a2,\u2009...,\u2009an,\u2009b1,\u2009b2,\u2009...,\u2009bm it is possible.", "input_spec": "The first line contains integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100), separated by a space \u2014 the number of rows and columns in the found matrix, respectively. The i-th of the following lines contains numbers wi,\u20091,\u2009wi,\u20092,\u2009...,\u2009wi,\u2009m (0\u2009\u2264\u2009wi,\u2009j\u2009\u2264\u2009109), separated by spaces \u2014 the elements of the i-th row of matrix w.", "output_spec": "If the matrix w could not have been obtained in the manner described above, print \"NO\" (without quotes) in the single line of output. Otherwise, print four lines. In the first line print \"YES\" (without quotes). In the second line print an integer k (1\u2009\u2264\u2009k\u2009\u2264\u20091018). Note that each element of table w should be in range between 0 and k\u2009-\u20091 inclusively. In the third line print n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u20091018), separated by spaces. In the fourth line print m integers b1,\u2009b2,\u2009...,\u2009bm (0\u2009\u2264\u2009bi\u2009\u2264\u20091018), separated by spaces.", "sample_inputs": ["2 3\n1 2 3\n2 3 4", "2 2\n1 2\n2 0", "2 2\n1 2\n2 1"], "sample_outputs": ["YES\n1000000007\n0 1 \n1 2 3", "YES\n3\n0 1 \n1 2", "NO"], "notes": "NoteBy we denote the remainder of integer division of b by c.It is guaranteed that if there exists some set of numbers k,\u2009a1,\u2009...,\u2009an,\u2009b1,\u2009...,\u2009bm, that you could use to make matrix w, then there also exists a set of numbers that meets the limits 1\u2009\u2264\u2009k\u2009\u2264\u20091018, 1\u2009\u2264\u2009ai\u2009\u2264\u20091018, 1\u2009\u2264\u2009bi\u2009\u2264\u20091018 in the output format. In other words, these upper bounds are introduced only for checking convenience purposes."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet rec gcd a b = if a=0L then b else gcd (b %% a) a\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n\n let w = Array.make_matrix n m 0L in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n w.(i).(j) <- long (read_int())\n done\n done;\n\n let mink = 1L ++ maxf 0 (n-1) (fun i-> maxf 0 (m-1) (fun j -> w.(i).(j))) in\n\n let g = ref 0L in\n\n for i=0 to 0 do\n for i'=1 to n-1 do\n for j=0 to 0 do\n\tfor j'=j+1 to m-1 do\n\t let d1 = w.(i).(j) -- w.(i').(j) in\n\t let d2 = w.(i).(j') -- w.(i').(j') in\n\t let d3 = Int64.abs (d1 -- d2) in\n\t g := gcd !g d3;\n\n\t let d1 = w.(i).(j) -- w.(i).(j') in\n\t let d2 = w.(i').(j) -- w.(i').(j') in\n\t let d3 = Int64.abs (d1 -- d2) in\n\t g := gcd !g d3;\n\n\tdone\n done\n done\n done;\n\n let k = if !g = 0L then mink else !g in\n\n if k < mink then printf \"NO\\n\" else (\n printf \"YES\\n\";\n \n let a = Array.make n 0L in\n let b = Array.make m 0L in\n\n for i=1 to n-1 do\n a.(i) <- (w.(i).(0) -- w.(0).(0)) %% k;\n if a.(i) < 0L then a.(i) <- a.(i) ++ k;\n done;\n \n for j=0 to m-1 do\n b.(j) <- w.(0).(j) %% k;\n done;\n\n printf \"%Ld\\n\" k;\n \n for i=0 to n-1 do\n printf \"%Ld \" a.(i)\n done;\n\n print_newline();\n\n for j=0 to m-1 do\n printf \"%Ld \" b.(j)\n done;\n print_newline();\n )\n"}], "negative_code": [], "src_uid": "ddd246cbbd038ae3fc54af1dcb9065c3"} {"nl": {"description": "Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are three or more consonants in a row in the word. The only exception is that if the block of consonants has all letters the same, then this block (even if its length is greater than three) is not considered a typo. Formally, a word is typed with a typo if there is a block of not less that three consonants in a row, and there are at least two different letters in this block.For example: the following words have typos: \"hellno\", \"hackcerrs\" and \"backtothefutttture\"; the following words don't have typos: \"helllllooooo\", \"tobeornottobe\" and \"oooooo\". When Beroffice editor finds a word with a typo, it inserts as little as possible number of spaces in this word (dividing it into several words) in such a way that each of the resulting words is typed without any typos.Implement this feature of Beroffice editor. Consider the following letters as the only vowels: 'a', 'e', 'i', 'o' and 'u'. All the other letters are consonants in this problem.", "input_spec": "The only line contains a non-empty word consisting of small English letters. The length of the word is between 1 and 3000 letters.", "output_spec": "Print the given word without any changes if there are no typos. If there is at least one typo in the word, insert the minimum number of spaces into the word so that each of the resulting words doesn't have any typos. If there are multiple solutions, print any of them.", "sample_inputs": ["hellno", "abacaba", "asdfasdf"], "sample_outputs": ["hell no", "abacaba", "asd fasd f"], "notes": null}, "positive_code": [{"source_code": "let rec splitstr s i pc1 pc2 cnt = \nif (i < String.length s) then\n(\n\tmatch s.[i] with\n\t|'a'|'e'|'i'|'o'|'u' as ch -> (* Printf.printf \"vowel: %c\\n\" ch; flush(stdout); *)(String.make 1 ch)^(splitstr s (i+1) pc2 ch 0)\n\t|ch when (cnt < 2) -> (* Printf.printf \"Conscnt<3: %c %d\\n\" ch cnt; flush(stdout); *)(String.make 1 ch)^(splitstr s (i+1) pc2 ch (cnt+1))\n\t|ch when ((ch = pc1)&&(ch=pc2)) -> (* Printf.printf \"series: %c %d\\n\" ch cnt; flush(stdout); *)(String.make 1 ch)^(splitstr s (i+1) pc2 ch (cnt+1))\n\t|ch when (cnt>=2) -> (* Printf.printf \"Overconso: %c %d\\n\" ch cnt; flush(stdout); *)(\" \"^(String.make 1 ch))^(splitstr s (i+1) pc2 ch 1)\n\t|_ -> failwith \"Redundancy\"\n)\nelse \"\";;\n\nlet st = read_line();;\n\nlet _ = \n\tPrintf.printf \"%s\\n\" (splitstr st 0 '-' '-' (0));\n\tflush(stdout);;"}], "negative_code": [{"source_code": "let rec splitstr s i pc1 pc2 cnt = \nif (i < String.length s) then\n(\n\tmatch s.[i] with\n\t|'a'|'e'|'i'|'o'|'u' as ch -> (* Printf.printf \"vowel: %c\\n\" ch; flush(stdout); *)(String.make 1 ch)^(splitstr s (i+1) pc2 ch 0)\n\t|ch when (cnt < 2) -> (* Printf.printf \"Conscnt<3: %c %d\\n\" ch cnt; flush(stdout); *)(String.make 1 ch)^(splitstr s (i+1) pc2 ch (cnt+1))\n\t|ch when ((ch = pc1)&&(ch=pc2)) -> (* Printf.printf \"series: %c %d\\n\" ch cnt; flush(stdout); *)(String.make 1 ch)^(splitstr s (i+1) pc2 ch (cnt+1))\n\t|ch when (cnt>=2) -> (* Printf.printf \"Overconso: %c %d\\n\" ch cnt; flush(stdout); *)(\" \"^(String.make 1 ch))^(splitstr s (i+1) pc2 ch 0)\n\t|_ -> failwith \"Redundancy\"\n)\nelse \"\";;\n\nlet st = read_line();;\n\nlet _ = \n\tPrintf.printf \"%s\\n\" (splitstr st 0 '-' '-' (0));\n\tflush(stdout);;"}, {"source_code": "let rec splitstr s i pc1 pc2 cnt = \nif (i < String.length s) then\n(\n\tmatch s.[i] with\n\t|'a'|'e'|'i'|'o'|'u' as ch -> (* Printf.printf \"vowel: %c\\n\" ch; flush(stdout); *)(String.make 1 ch)^(splitstr s (i+1) pc2 ch 0)\n\t|ch when (cnt < 2) -> (* Printf.printf \"Conscnt<3: %c %d\\n\" ch cnt; flush(stdout); *)(String.make 1 ch)^(splitstr s (i+1) pc2 ch (cnt+1))\n\t|ch when ((ch = pc1)&&(ch=pc2)) -> (* Printf.printf \"series: %c %d\\n\" ch cnt; flush(stdout); *)(String.make 1 ch)^(splitstr s (i+1) pc2 ch (cnt+1))\n\t|ch when (cnt>=2) -> (* Printf.printf \"Overconso: %c %d\\n\" ch cnt; flush(stdout); *)(\" \"^(String.make 1 ch))^(splitstr s (i+1) pc2 ch 0)\n\t|_ -> failwith \"Redundancy\"\n)\nelse \"\";;\n\nlet st = read_line();;\n\nlet _ = \n\tPrintf.printf \"%s\\n\" (splitstr st 0 '-' '-' (0));\n\tflush(stdout);;"}], "src_uid": "436c00c832de8df739fc391f2ed6dac4"} {"nl": {"description": "Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house.Your house has $$$n$$$ rooms. In the $$$i$$$-th room you can install at most $$$c_i$$$ heating radiators. Each radiator can have several sections, but the cost of the radiator with $$$k$$$ sections is equal to $$$k^2$$$ burles.Since rooms can have different sizes, you calculated that you need at least $$$sum_i$$$ sections in total in the $$$i$$$-th room. For each room calculate the minimum cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.", "input_spec": "The first line contains single integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the number of rooms. Each of the next $$$n$$$ lines contains the description of some room. The $$$i$$$-th line contains two integers $$$c_i$$$ and $$$sum_i$$$ ($$$1 \\le c_i, sum_i \\le 10^4$$$) \u2014 the maximum number of radiators and the minimum total number of sections in the $$$i$$$-th room, respectively.", "output_spec": "For each room print one integer \u2014 the minimum possible cost to install at most $$$c_i$$$ radiators with total number of sections not less than $$$sum_i$$$.", "sample_inputs": ["4\n1 10000\n10000 1\n2 6\n4 6"], "sample_outputs": ["100000000\n1\n18\n10"], "notes": "NoteIn the first room, you can install only one radiator, so it's optimal to use the radiator with $$$sum_1$$$ sections. The cost of the radiator is equal to $$$(10^4)^2 = 10^8$$$.In the second room, you can install up to $$$10^4$$$ radiators, but since you need only one section in total, it's optimal to buy one radiator with one section.In the third room, there $$$7$$$ variants to install radiators: $$$[6, 0]$$$, $$$[5, 1]$$$, $$$[4, 2]$$$, $$$[3, 3]$$$, $$$[2, 4]$$$, $$$[1, 5]$$$, $$$[0, 6]$$$. The optimal variant is $$$[3, 3]$$$ and it costs $$$3^2+ 3^2 = 18$$$."}, "positive_code": [{"source_code": "let rep f n = let rec iter i = if i < n then (f ();iter (i+1)) in iter 0\n\nlet () =\n read_int () |> rep (fun () ->\n let (a, b) = Scanf.scanf \"%d %d \" (fun a b -> (a,b)) in\n let k = b/a and l = b mod a in\n print_int (k*k*(a-l) + (k+1)*(k+1)*l);\n print_newline ()\n )\n"}], "negative_code": [], "src_uid": "0ec973bf4ad209de9731818c75469541"} {"nl": {"description": "You have written on a piece of paper an array of n positive integers a[1],\u2009a[2],\u2009...,\u2009a[n] and m good pairs of integers (i1,\u2009j1),\u2009(i2,\u2009j2),\u2009...,\u2009(im,\u2009jm). Each good pair (ik,\u2009jk) meets the following conditions: ik\u2009+\u2009jk is an odd number and 1\u2009\u2264\u2009ik\u2009<\u2009jk\u2009\u2264\u2009n.In one operation you can perform a sequence of actions: take one of the good pairs (ik,\u2009jk) and some integer v (v\u2009>\u20091), which divides both numbers a[ik] and a[jk]; divide both numbers by v, i. e. perform the assignments: and . Determine the maximum number of operations you can sequentially perform on the given array. Note that one pair may be used several times in the described operations.", "input_spec": "The first line contains two space-separated integers n, m (2\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009m\u2009\u2264\u2009100). The second line contains n space-separated integers a[1],\u2009a[2],\u2009...,\u2009a[n] (1\u2009\u2264\u2009a[i]\u2009\u2264\u2009109) \u2014 the description of the array. The following m lines contain the description of good pairs. The k-th line contains two space-separated integers ik, jk (1\u2009\u2264\u2009ik\u2009<\u2009jk\u2009\u2264\u2009n, ik\u2009+\u2009jk is an odd number). It is guaranteed that all the good pairs are distinct.", "output_spec": "Output the answer for the problem.", "sample_inputs": ["3 2\n8 3 8\n1 2\n2 3", "3 2\n8 12 8\n1 2\n2 3"], "sample_outputs": ["0", "2"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\n(* Implementation of Dinic's algorithm for max flow. See ../spoj/PROFIT/\n for additional algorithms. *)\n\nlet infinite_c = 10000 (* \"infinite\" capacity *)\n\nlet maxflow s t adj cap =\n (* s and t are nodes (numbers). g is a graph (represented via an\n array of adjacency lists). c is a 1-d array of capacities. The\n adjacency list on node v stores pairs like (w,i) where w is the\n other node, and i is the index into the capacity array for where\n this capacity is stored. It's set up so that i lxor 1 is where the\n capacity of edge (w,v) is stored. We compute the maximum flow in\n the same representation as the capacities. *)\n\n let c = Array.copy cap in\n let n = Array.length adj in\n let alive = Array.make n [] in\n let level = Array.make n 0 in\n let queue = Array.make n 0 in\n let front = ref 0 in\n let back = ref 0 in\n\n let push w = queue.(!back) <- w; back := !back+1 in\n let eject() = let x = queue.(!front) in front := !front + 1; x; in\n\n let rec bfs () = \n let rec loop () = \n if !front = !back then false else\n\tlet v = eject() in\n\t if level.(v) = level.(t) then true else (\n\t List.iter ( \n\t fun (w,i) -> if level.(w) < 0 && c.(i) > 0 then (\n\t\tlevel.(w) <- level.(v) + 1;\n\t\tpush w\n\t )\n\t ) adj.(v);\n\t loop ()\n\t )\n in\n level.(s) <- 0;\n back := 0; front := 0;\n push s;\n loop ();\n in\n \n let rec dfs v cap = \n (* Does a DFS from v looking for a path to t. It tries to push cap units\n of flow to t. It returns the amount of flow actually pushed *)\n if v=t then cap else\n let rec loop total remaining li = \n\t match li with \n\t | [] -> \n\t\talive.(v) <- [];\n\t\ttotal\n\t | (w,i)::tail -> \n\t\tif level.(w) = level.(v)+1 && c.(i) > 0 then (\n\t\t let p = dfs w (min c.(i) remaining) in\n\t\t c.(i) <- c.(i) - p;\n\t\t c.(i lxor 1) <- c.(i lxor 1) + p;\n\t\t if remaining-p = 0 then (\n\t\t alive.(v) <- li;\n\t\t total+p\n\t\t ) else loop (total+p) (remaining-p) tail\n\t\t) else loop total remaining tail\n in loop 0 cap alive.(v)\n in\n \n let rec main_loop flow_so_far = \n for i=0 to n-1 do level.(i) <- -1; done;\n Array.blit adj 0 alive 0 n;\n if bfs () then main_loop (flow_so_far + (dfs s infinite_c)) else flow_so_far\n in\n main_loop 0\n\nlet factor n = \n let rec loop n p ac = \n if n=1 then ac\n else if p*p > n then (n::ac)\n else if n mod p = 0 then loop (n/p) p (p::ac)\n else loop n (p+1) ac\n in\n List.rev (loop n 2 [])\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let pair = Array.init m (fun _ ->\n let i = read_int() -1 in\n let j = read_int() -1 in\n if i land 1 = 0 then (i,j) else (j,i)\n ) in\n\n let fact = Array.init n (fun i -> factor a.(i)) in\n \n let primeset = Hashtbl.create 10 in (* the set of primes that occur *)\n for i=0 to n-1 do\n List.iter (fun p -> Hashtbl.replace primeset p true) fact.(i)\n done;\n\n let build_graph p = \n (* build the graph for a specific prime p *)\n let s = n in\n let t = n+1 in\n let adj = Array.make (n+2) [] in\n let cap = Array.make (2*m + 2*n) 0 in\n\n let add_edge u v c cr ind indr =\n adj.(u) <- (v,ind)::adj.(u);\n adj.(v) <- (u,indr)::adj.(v);\n cap.(ind) <- c;\n cap.(indr) <- cr\n in\n\n for k = 0 to m-1 do\n let (i,j) = pair.(k) in\n add_edge i j infinite_c 0 (2*k) (2*k+1)\n done;\n\n for v = 0 to n-1 do\n let capacity = List.length (List.filter (fun e -> e = p) fact.(v)) in\n let edgeno = 2*m + 2*v in\n if v land 1 = 0 then (\n\tadd_edge s v capacity 0 edgeno (edgeno+1);\n ) else (\n\tadd_edge v t capacity 0 edgeno (edgeno+1);\n )\n done;\n (s,t,adj,cap)\n in\n\n let flowsum = ref 0 in\n \n Hashtbl.iter (fun p _ -> \n let (s,t,adj,cap) = build_graph p in\n let f = maxflow s t adj cap in\n flowsum := !flowsum + f\n ) primeset;\n\n printf \"%d\\n\" !flowsum\n"}, {"source_code": "open Printf\nopen Scanf\n\n(* Implementation of Dinic's algorithm for max flow. See ../spoj/PROFIT/\n for additional algorithms. *)\n\nlet infinite_c = 10000 (* \"infinite\" capacity *)\n\nlet maxflow s t adj cap =\n (* s and t are nodes (numbers). g is a graph (represented via an\n array of adjacency lists). c is a 1-d array of capacities. The\n adjacency list on node v stores pairs like (w,i) where w is the\n other node, and i is the index into the capacity array for where\n this capacity is stored. It's set up so that i lxor 1 is where the\n capacity of edge (w,v) is stored. We compute the maximum flow in\n the same representation as the capacities. *)\n\n let c = Array.copy cap in\n let n = Array.length adj in\n let alive = Array.make n [] in\n let level = Array.make n 0 in\n let queue = Array.make n 0 in\n let front = ref 0 in\n let back = ref 0 in\n\n let push w = queue.(!back) <- w; back := !back+1 in\n let eject() = let x = queue.(!front) in front := !front + 1; x; in\n\n let rec bfs () = \n let rec loop () = \n if !front = !back then false else\n\tlet v = eject() in\n\t if level.(v) = level.(t) then true else (\n\t List.iter ( \n\t fun (w,i) -> if level.(w) < 0 && c.(i) > 0 then (\n\t\tlevel.(w) <- level.(v) + 1;\n\t\tpush w\n\t )\n\t ) adj.(v);\n\t loop ()\n\t )\n in\n level.(s) <- 0;\n back := 0; front := 0;\n push s;\n loop ();\n in\n \n let rec dfs v cap = \n (* Does a DFS from v looking for a path to t. It tries to push cap units\n of flow to t. It returns the amount of flow actually pushed *)\n if v=t then cap else\n let rec loop total remaining li = \n\t match li with \n\t | [] -> \n\t\talive.(v) <- [];\n\t\ttotal\n\t | (w,i)::tail -> \n\t\tif level.(w) = level.(v)+1 && c.(i) > 0 then (\n\t\t let p = dfs w (min c.(i) remaining) in\n\t\t c.(i) <- c.(i) - p;\n\t\t c.(i lxor 1) <- c.(i lxor 1) + p;\n\t\t if remaining-p = 0 then (\n\t\t alive.(v) <- li;\n\t\t total+p\n\t\t ) else loop (total+p) (remaining-p) tail\n\t\t) else loop total remaining tail\n in loop 0 cap alive.(v)\n in\n \n let rec main_loop flow_so_far = \n for i=0 to n-1 do level.(i) <- -1; done;\n Array.blit adj 0 alive 0 n;\n if bfs () then main_loop (flow_so_far + (dfs s infinite_c)) else flow_so_far\n in\n main_loop 0\n\nlet factor n = \n let rec loop n p ac = \n if n=1 then ac\n else if p*p > n then (n::ac)\n else if n mod p = 0 then loop (n/p) p (p::ac)\n else loop n (p+1) ac\n in\n List.rev (loop n 2 [])\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let pair = Array.init m (fun _ ->\n let i = read_int() -1 in\n let j = read_int() -1 in\n if i land 1 = 0 then (i,j) else (j,i)\n ) in\n\n let fact = Array.init n (fun i -> factor a.(i)) in\n \n let primeset = Hashtbl.create 10 in (* the set of primes that occur *)\n for i=0 to n-1 do\n List.iter (fun p -> Hashtbl.replace primeset p true) fact.(i)\n done;\n\n let build_graph p = \n (* build the graph for a specific prime p *)\n let s = n in\n let t = n+1 in\n let adj = Array.make (n+2) [] in\n let cap = Array.make (2*m + 2*n) 0 in\n\n let add_edge u v c cr ind indr =\n adj.(u) <- (v,ind)::adj.(u);\n adj.(v) <- (u,indr)::adj.(v);\n cap.(ind) <- c;\n cap.(indr) <- cr\n in\n\n for k = 0 to m-1 do\n let (i,j) = pair.(k) in\n add_edge i j infinite_c 0 (2*k) (2*k+1)\n done;\n\n for v = 0 to n-1 do\n let capacity = List.length (List.filter (fun e -> e = p) fact.(v)) in\n let edgeno = 2*m + 2*v in\n if v land 1 = 0 then (\n\tadd_edge s v capacity 0 edgeno (edgeno+1);\n ) else (\n\tadd_edge v t capacity 0 edgeno (edgeno+1);\n )\n done;\n (s,t,adj,cap)\n in\n\n let flowsum = ref 0 in\n \n Hashtbl.iter (fun p _ -> \n let (s,t,adj,cap) = build_graph p in\n let f = maxflow s t adj cap in\n flowsum := !flowsum + f\n ) primeset;\n\n printf \"%d\\n\" !flowsum\n"}], "negative_code": [], "src_uid": "10efa17a66af684dbc13c456ddef1b1b"} {"nl": {"description": "Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally: There is no road between a and b. There exists a sequence (path) of n distinct cities v1,\u2009v2,\u2009...,\u2009vn that v1\u2009=\u2009a, vn\u2009=\u2009b and there is a road between vi and vi\u2009+\u20091 for . On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1,\u2009u2,\u2009...,\u2009un that u1\u2009=\u2009c, un\u2009=\u2009d and there is a road between ui and ui\u2009+\u20091 for .Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1,\u2009...,\u2009vn) and (u1,\u2009...,\u2009un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.", "input_spec": "The first line of the input contains two integers n and k (4\u2009\u2264\u2009n\u2009\u2264\u20091000, n\u2009-\u20091\u2009\u2264\u2009k\u2009\u2264\u20092n\u2009-\u20092)\u00a0\u2014 the number of cities and the maximum allowed number of roads, respectively. The second line contains four distinct integers a, b, c and d (1\u2009\u2264\u2009a,\u2009b,\u2009c,\u2009d\u2009\u2264\u2009n).", "output_spec": "Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1,\u2009v2,\u2009...,\u2009vn where v1\u2009=\u2009a and vn\u2009=\u2009b. The second line should contain n distinct integers u1,\u2009u2,\u2009...,\u2009un where u1\u2009=\u2009c and un\u2009=\u2009d. Two paths generate at most 2n\u2009-\u20092 roads: (v1,\u2009v2),\u2009(v2,\u2009v3),\u2009...,\u2009(vn\u2009-\u20091,\u2009vn),\u2009(u1,\u2009u2),\u2009(u2,\u2009u3),\u2009...,\u2009(un\u2009-\u20091,\u2009un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x,\u2009y) and (y,\u2009x) are the same road.", "sample_inputs": ["7 11\n2 4 7 3", "1000 999\n10 20 30 40"], "sample_outputs": ["2 7 1 3 6 5 4\n7 1 5 4 6 2 3", "-1"], "notes": "NoteIn the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let (n,k) = read_pair() in\n let (a,b) = read_pair() in\n let (c,d) = read_pair() in\n\n if n <= 4 || k < n+1 then\n printf \"-1\\n\"\n else (\n let perm = Array.make (n+1) 0 in\n let used = Array.make (n+1) false in\n perm.(1) <- a;\n perm.(2) <- c;\n perm.(n) <- b;\n perm.(n-1) <- d;\n used.(a) <- true;\n used.(b) <- true;\n used.(c) <- true;\n used.(d) <- true;\n let lowused = ref 0 in\n for i=1 to n do\n if perm.(i) = 0 then (\n\tlet rec loop j = if used.(j) then loop (j+1) else j in\n\tlet next = loop (!lowused + 1) in\n\tlowused := next;\n\tused.(next) <- true;\n\tperm.(i) <- next\n )\n done;\n\n for i=1 to n do\n printf \"%d \" perm.(i)\n done;\n print_newline();\n for i=1 to n do\n let j =\n\tif i=1 then 2\n\telse if i=2 then 1\n\telse if i=n-1 then n\n\telse if i=n then n-1 else i\n in\n printf \"%d \" perm.(j)\n done;\n print_newline();\n )\n"}], "negative_code": [], "src_uid": "6b398790adbd26dd9af64e9086e38f7f"} {"nl": {"description": "Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.", "input_spec": "In first line there is one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 number of cafes indices written by Vlad. In second line, n numbers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u20092\u00b7105) are written\u00a0\u2014 indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.", "output_spec": "Print one integer\u00a0\u2014 index of the cafe that Vlad hasn't visited for as long as possible.", "sample_inputs": ["5\n1 3 2 1 2", "6\n2 1 2 2 4 1"], "sample_outputs": ["3", "2"], "notes": "NoteIn first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer. In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes."}, "positive_code": [{"source_code": "let n = read_int () in \nlet h = Hashtbl.create n in\nfor i = 0 to n-1 do Hashtbl.replace h (Scanf.scanf \" %d\" (fun x -> x)) i done;\nprint_int @@ fst @@ Hashtbl.fold (fun a b c -> if b < snd c then (a,b) else c) h (min_int, max_int);\n"}, {"source_code": "module IntSet = Set.Make(struct \n let compare = Pervasives.compare\n type t = int\nend);;\nlet n = read_int () in \nlet a = Array.make n 0 and\ns = ref IntSet.empty in\nfor i = 0 to n-1 do begin\n a.(i) <- Scanf.scanf \" %d\" (fun x -> x);\n s := IntSet.add a.(i) !s\nend done;\nlet p = ref 0 in\nfor i = n-1 downto 0 do begin\n if IntSet.mem a.(i) !s then begin\n p := a.(i) ;\n s := IntSet.remove a.(i) !s\n end\nend done;\nprint_int !p;\n\n"}, {"source_code": "(* 7:22 *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let n = read_int () in\n let a = Array.init n read_int in\n\n let m = 200_001 in\n let vtime = Array.make (m+1) (2*m) in\n\n for i=0 to n-1 do\n vtime.(a.(i)) <- i\n done;\n\n let cafe = minf 0 m (fun cafe -> vtime.(cafe)) in\n \n printf \"%d\\n\" a.(cafe)\n"}], "negative_code": [], "src_uid": "bdea209c7b628e4cc90ebc2572826485"} {"nl": {"description": "Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $$$(0,0)$$$ to $$$(x,0)$$$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $$$n$$$ favorite numbers: $$$a_1, a_2, \\ldots, a_n$$$. What is the minimum number of hops Rabbit needs to get from $$$(0,0)$$$ to $$$(x,0)$$$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points $$$(x_i, y_i)$$$ and $$$(x_j, y_j)$$$ is $$$\\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$$$.For example, if Rabbit has favorite numbers $$$1$$$ and $$$3$$$ he could hop from $$$(0,0)$$$ to $$$(4,0)$$$ in two hops as shown below. Note that there also exists other valid ways to hop to $$$(4,0)$$$ in $$$2$$$ hops (e.g. $$$(0,0)$$$ $$$\\rightarrow$$$ $$$(2,-\\sqrt{5})$$$ $$$\\rightarrow$$$ $$$(4,0)$$$). Here is a graphic for the first example. Both hops have distance $$$3$$$, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number $$$a_i$$$ and hops with distance equal to $$$a_i$$$ in any direction he wants. The same number can be used multiple times.", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u00a0\u2014 the number of test cases. Next $$$2t$$$ lines contain test cases \u2014 two lines per test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 10^5$$$, $$$1 \\le x \\le 10^9$$$) \u00a0\u2014 the number of favorite numbers and the distance Rabbit wants to travel, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u00a0\u2014 Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the minimum number of hops needed.", "sample_inputs": ["4\n\n2 4\n\n1 3\n\n3 12\n\n3 4 5\n\n1 5\n\n5\n\n2 10\n\n15 4"], "sample_outputs": ["2\n3\n1\n2"], "notes": "NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to $$$(2,\\sqrt{5})$$$, then to $$$(4,0)$$$ for a total of two hops. Each hop has a distance of $$$3$$$, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop $$$3$$$ times is: $$$(0,0)$$$ $$$\\rightarrow$$$ $$$(4,0)$$$ $$$\\rightarrow$$$ $$$(8,0)$$$ $$$\\rightarrow$$$ $$$(12,0)$$$.In the third test case of the sample, Rabbit can hop from $$$(0,0)$$$ to $$$(5,0)$$$.In the fourth test case of the sample, Rabbit can hop: $$$(0,0)$$$ $$$\\rightarrow$$$ $$$(5,10\\sqrt{2})$$$ $$$\\rightarrow$$$ $$$(10,0)$$$."}, "positive_code": [{"source_code": "let get_int () =\n Scanf.scanf \"%d \" (fun x -> x)\n;;\n\nlet rec read_int_seq n =\n match n with\n 0 -> []\n | _ -> (get_int ()) :: (read_int_seq (n-1))\n;;\n\nlet read_case () =\n let n = get_int () in\n let x = get_int () in\n let a = read_int_seq n in\n (n, x, a)\n;;\n\nlet rec max xs =\n match xs with \n [x] -> x\n | x :: xs' -> let y = max xs' in\n if x > y then x else y\n;;\n\nlet rec contains xs y =\n match xs with\n [] -> false\n | x :: xs' -> (x=y) || (contains xs' y)\n;;\n\nlet solve (n, x, a) =\n let m = max a in\n if (x mod m)=0 then x/m else\n if x > m then (x/m)+1 else\n if (contains a x) then 1 else 2\n;;\n\nlet rec solve_cases t =\n if t=0 then () else\n let case = read_case () in\n let _ = (solve case) |> string_of_int |> print_endline in\n solve_cases (t-1)\n;;\n\nlet t = read_int () in\n solve_cases t\n"}], "negative_code": [{"source_code": "let get_int () =\n Scanf.scanf \"%d \" (fun x -> x)\n;;\n\nlet rec read_int_seq n =\n match n with\n 0 -> []\n | _ -> (get_int ()) :: (read_int_seq (n-1))\n;;\n\nlet read_case () =\n let n = get_int () in\n let x = get_int () in\n let a = read_int_seq n in\n (n, x, a)\n;;\n\nlet rec max xs =\n match xs with \n [x] -> x\n | x :: xs' -> let y = max xs' in\n if x > y then x else y\n;;\n\nlet solve (n, x, a) =\n let m = max a in\n if (x mod m)=0 then x/m else\n if (x/m)=0 then 2 else (x/m)+1\n;;\n\nlet rec solve_cases t =\n if t=0 then () else\n let case = read_case () in\n let _ = (solve case) |> string_of_int |> print_endline in\n solve_cases (t-1)\n;;\n\nlet t = read_int () in\n solve_cases t\n"}], "src_uid": "b6a7e8abc747bdcee74653817085002c"} {"nl": {"description": "Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \\in E$$$ \u00a0$$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output \"Impossible\".If there are multiple answers then print any of them.", "input_spec": "The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^5$$$) \u2014 the number of vertices and the number of edges.", "output_spec": "If there exists no valid graph with the given number of vertices and edges then output \"Impossible\". Otherwise print the answer in the following format: The first line should contain the word \"Possible\". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \\le v_i, u_i \\le n, v_i \\neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them.", "sample_inputs": ["5 6", "6 12"], "sample_outputs": ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"], "notes": "NoteHere is the representation of the graph from the first example: "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt64 = struct \n\t(* include Int64 *)\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\tlet (~~|) p = Int64.of_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\n\t\n\tlet (mod) m n = m - (m/n) * n\n\tlet rec gcd m n = match m,n with\n\t\t| m,0L -> m\n\t\t| m,n -> gcd n (m mod n)\n\nend open MyInt64\n\nexception Hoge\nexception Fuga\n\nlet () =\n\tlet n,m = get_2_i64 ()\n\tin\n\tlet ls = ref []\n\tin let rest = ref m\n\tin\n\tif m < n - 1L then printf \"Impossible\\n\"\n\telse\n\ttry\n\t\tfor i=1 to ~|n do\n\t\t\tfor j=i+$1 to ~|n do\n\t\t\t\t(* printf \"gcd %Ld %Ld = %Ld; %b\\n\" ~~|i ~~|j (gcd ~~|i ~~|j) (gcd ~~|i ~~|j = 1L); *)\n\t\t\t\tif gcd ~~|i ~~|j = 1L then (\n\t\t\t\t\tls := (i,j)::!ls;\n\t\t\t\t\trest -= 1L;\n\t\t\t\t\tif !rest <= 0L then raise Hoge\n\t\t\t\t)\n\t\t\tdone;\n\t\tdone;\n\t\traise Fuga\n\twith\n\t| Hoge -> (\n\t\tprintf \"Possible\\n\";\n\t\tList.iter (fun (u,v) -> printf \"%d %d\\n\" u v) !ls;\n\t)\n\t| Fuga -> \n\t\tprintf \"Impossible\\n\";"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt64 = struct \n\t(* include Int64 *)\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\tlet (~~|) p = Int64.of_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\n\t\n\tlet (mod) m n = m - (m/n) * n\n\tlet rec gcd m n = match m,n with\n\t\t| m,0L -> m\n\t\t| m,n -> gcd n (m mod n)\n\nend open MyInt64\n\nexception Hoge\nexception Fuga\n\nlet () =\n\tlet n,m = get_2_i64 ()\n\tin\n\tlet ls = ref []\n\tin let rest = ref m\n\tin\n\ttry\n\t\tfor i=1 to ~|n do\n\t\t\tfor j=i+$1 to ~|n do\n\t\t\t\t(* printf \"gcd %Ld %Ld = %Ld; %b\\n\" ~~|i ~~|j (gcd ~~|i ~~|j) (gcd ~~|i ~~|j = 1L); *)\n\t\t\t\tif gcd ~~|i ~~|j = 1L then (\n\t\t\t\t\tls := (i,j)::!ls;\n\t\t\t\t\trest -= 1L;\n\t\t\t\t\tif !rest <= 0L then raise Hoge\n\t\t\t\t)\n\t\t\tdone;\n\t\tdone;\n\t\traise Fuga\n\twith\n\t| Hoge -> (\n\t\tprintf \"Possible\\n\";\n\t\tList.iter (fun (u,v) -> printf \"%d %d\\n\" u v) !ls;\n\t)\n\t| Fuga -> \n\t\tprintf \"Impossible\\n\";"}], "src_uid": "0ab1b97a8d2e0290cda31a3918ff86a4"} {"nl": {"description": "Of course, many of you can calculate \u03c6(n) \u2014 the number of positive integers that are less than or equal to n, that are coprime with n. But what if we need to calculate \u03c6(\u03c6(...\u03c6(n))), where function \u03c6 is taken k times and n is given in the canonical decomposition into prime factors? You are given n and k, calculate the value of \u03c6(\u03c6(...\u03c6(n))). Print the result in the canonical decomposition into prime factors.", "input_spec": "The first line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of distinct prime divisors in the canonical representaion of n. Each of the next m lines contains a pair of space-separated integers pi,\u2009ai (2\u2009\u2264\u2009pi\u2009\u2264\u2009106;\u00a01\u2009\u2264\u2009ai\u2009\u2264\u20091017) \u2014 another prime divisor of number n and its power in the canonical representation. The sum of all ai doesn't exceed 1017. Prime divisors in the input follow in the strictly increasing order. The last line contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u20091018).", "output_spec": "In the first line, print integer w \u2014 the number of distinct prime divisors of number \u03c6(\u03c6(...\u03c6(n))), where function \u03c6 is taken k times. Each of the next w lines must contain two space-separated integers qi,\u2009bi (bi\u2009\u2265\u20091) \u2014 another prime divisor and its power in the canonical representaion of the result. Numbers qi must go in the strictly increasing order.", "sample_inputs": ["1\n7 1\n1", "1\n7 1\n2", "1\n2 100000000000000000\n10000000000000000"], "sample_outputs": ["2\n2 1\n3 1", "1\n2 1", "1\n2 90000000000000000"], "notes": "NoteYou can read about canonical representation of a positive integer here: http://en.wikipedia.org/wiki/Fundamental_theorem_of_arithmetic.You can read about function \u03c6(n) here: http://en.wikipedia.org/wiki/Euler's_totient_function."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let m = read_int () in\n let p = Array.make m 0 in\n let a = Array.make m 0L in\n for i=0 to m-1 do\n p.(i) <- read_int();\n a.(i) <- read_long()\n done;\n \n let k = read_long () in\n\n let max_p = p.(m-1) in\n\n let sieve = Array.make (max_p+1) 0 in\n(* sieve.(n) is the smallest prime that divides n. \n sieve.(n) = n iff n is prime. *)\n \n for i=2 to max_p do\n if sieve.(i) = 0 then\n let rec loop j = if j <= max_p then (\n\tsieve.(j) <- i;\n\tloop (j+i);\n ) in\n loop (i)\n done;\n\n let e = Array.make (max_p+1) 0L in\n\n for i=0 to m-1 do\n e.(p.(i)) <- a.(i)\n done;\n\n let is_normal () = \n(* let process p = \n let rec loop r = r=1 || (e.(sieve.(r)) <> 0L && loop (r/sieve.(r))) in\n loop (p-1);\n in *)\n\n let process p = \n let rec loop r = if r=1 then true \n\telse if e.(sieve.(r)) = 0L then false else loop (r/sieve.(r))\n in\n loop (p-1);\n in\n\n let rec loop p = if p > max_p then true \n else if (sieve.(p) <> p || e.(p) = 0L) then loop (p+1)\n else process p && loop (p+1)\n in\n loop 2\n in\n\n let step () = \n let process p = \n let rec loop r = if r>1 then\n\t let s = sieve.(r) in\n\t e.(s) <- e.(s) ++ 1L;\n\t loop (r/s)\n in\n loop (p-1);\n e.(p) <- e.(p) -- 1L;\n in\n\n for p=2 to max_p do\n if sieve.(p) = p && e.(p) > 0L then process p\n done;\n in\n \n let rec steploop k = if k=0L || is_normal() then k else (\n step();\n steploop (k--1L)\n )\n in \n\n let k = steploop k in\n\n let elim p = \n let d = min e.(p) k in\n e.(p) <- e.(p) -- d;\n (* now add d to the exponents of all the prime factors of p-1 *)\n let rec loop r = if r=1 then () else\n\tlet s = sieve.(r) in\n\te.(s) <- e.(s) ++ d;\n\tloop (r/s)\n in\n loop (p-1);\n in\n\n for p=max_p downto 2 do\n if sieve.(p) = p then elim p\n done;\n\n let np = sum 2 max_p (fun i -> if e.(i) <> 0L then 1 else 0) in\n \n printf \"%d\\n\" np;\n\n for i=2 to max_p do\n if e.(i) <> 0L then printf \"%d %Ld\\n\" i e.(i)\n done\n"}, {"source_code": "(* \n Imagine the following graph. There's a node for every prime, and in\n the node an exponent of that prime is stored. There is an edge from\n prime p to each of the prime factors of p-1. EG from 13 there are two\n edges to 2 and one edge to 3. (2*2*3=12).\n\n To compute Phi of a number represented in this way, you do the following.\n For each non-zero exponent (simultaneously) decrement its exponentent\n by 1. Then for each successor of those that you decremented, you increment\n the exponent by 1.\n\n The problem here is to be able to iterate the Phi operator a huge\n number of times efficiently.\n\n Call a state \"normal\" if there is no pair of nodes p-->q such that\n p is non-zero while q is zero. The beauty of a normal state is\n that if you apply the Phi operator to it, it remains normal.\n\n Consider what happens to some node when you hit it with the Phi\n operator in a normal state. Exactly the same thing happens every\n time locally to it until all of its sources dry up.\n\n This means we can apply the Phi operator to various different nodes\n in any order we want. So we apply it in topological order\n (i.e. largest first). It's easy to apply the operator all k times\n to a node in O(number successors of it).\n\n It remains to explain how to get the system into a normal state.\n We simply iterate the Phi operator on it until it becomes normal.\n Then we reduce k by the number of times we had to apply the\n operator. The number of times we have to do this is the length of\n the longest path in the graph. This is at most logarithmic in the\n largest prime (a pessimistic estimate).\n\n (There is also an alternative algorithm that \"protects\" some amount\n of the exponent from being depleted. You are effectively computing\n the number of iterations until a node becomes non-zero. That's the\n amount of protection it gets. This can be computed as you go along.\n Some of the other shorter solutions do it this way.)\n\n Danny Sleator, March 2014\n*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let m = read_int () in\n let p = Array.make m 0 in\n let a = Array.make m 0L in\n for i=0 to m-1 do\n p.(i) <- read_int();\n a.(i) <- read_long()\n done;\n \n let k = read_long () in\n\n let max_p = p.(m-1) in\n\n let sieve = Array.make (max_p+1) 0 in\n(* sieve.(n) is the smallest prime that divides n. \n sieve.(n) = n iff n is prime. *)\n \n for i=2 to max_p do\n if sieve.(i) = 0 then\n let rec loop j = if j <= max_p then (\n\tsieve.(j) <- i;\n\tloop (j+i);\n ) in\n loop (i)\n done;\n\n let e = Array.make (max_p+1) 0L in\n\n for i=0 to m-1 do\n e.(p.(i)) <- a.(i)\n done;\n\n let is_normal () = \n(* let process p = \n let rec loop r = r=1 || (e.(sieve.(r)) <> 0L && loop (r/sieve.(r))) in\n loop (p-1);\n in *)\n\n let process p = \n let rec loop r = if r=1 then true \n\telse if e.(sieve.(r)) = 0L then false else loop (r/sieve.(r))\n in\n loop (p-1);\n in\n\n let rec loop p = if p > max_p then true \n else if (sieve.(p) <> p || e.(p) = 0L) then loop (p+1)\n else process p && loop (p+1)\n in\n loop 2\n in\n\n let step () = \n let process p = \n let rec loop r = if r>1 then\n\t let s = sieve.(r) in\n\t e.(s) <- e.(s) ++ 1L;\n\t loop (r/s)\n in\n loop (p-1);\n e.(p) <- e.(p) -- 1L;\n in\n\n for p=2 to max_p do\n if sieve.(p) = p && e.(p) > 0L then process p\n done;\n in\n \n let rec steploop k = if k=0L || is_normal() then k else (\n step();\n steploop (k--1L)\n )\n in \n\n let k = steploop k in\n\n let elim p = \n let d = min e.(p) k in\n e.(p) <- e.(p) -- d;\n (* now add d to the exponents of all the prime factors of p-1 *)\n let rec loop r = if r=1 then () else\n\tlet s = sieve.(r) in\n\te.(s) <- e.(s) ++ d;\n\tloop (r/s)\n in\n loop (p-1);\n in\n\n for p=max_p downto 2 do\n if sieve.(p) = p then elim p\n done;\n\n let np = sum 2 max_p (fun i -> if e.(i) <> 0L then 1 else 0) in\n \n printf \"%d\\n\" np;\n\n for i=2 to max_p do\n if e.(i) <> 0L then printf \"%d %Ld\\n\" i e.(i)\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let m = read_int () in\n let p = Array.make m 0 in\n let a = Array.make m 0L in\n for i=0 to m-1 do\n p.(i) <- read_int();\n a.(i) <- read_long()\n done;\n \n let k = read_long () in\n\n let max_p = p.(m-1) in\n\n let sieve = Array.make (max_p+1) 0 in\n(* sieve.(n) is the smallest prime that divides n. \n sieve.(n) = n iff n is prime. *)\n \n for i=2 to max_p do\n if sieve.(i) = 0 then\n let rec loop j = if j <= max_p then (\n\tsieve.(j) <- i;\n\tloop (j+i);\n ) in\n loop (i)\n done;\n\n let e = Array.make (max_p+1) 0L in\n\n for i=0 to m-1 do\n e.(p.(i)) <- a.(i)\n done;\n\n let is_normal () = \n let process p = \n let rec loop r = r=1 || (e.(sieve.(r)) <> 0L && loop (r/sieve.(r))) in\n loop (p-1);\n in\n\n let rec loop p = if p = max_p then true \n else if (sieve.(p) <> p || e.(p) = 0L) then loop (p+1)\n else process p && loop (p+1)\n in\n loop 2\n in\n\n let step () = \n let process p = \n let rec loop r = if r>1 then\n\t let s = sieve.(r) in\n\t e.(s) <- e.(s) ++ 1L;\n\t loop (r/s)\n in\n loop (p-1);\n e.(p) <- e.(p) -- 1L;\n in\n\n for p=2 to max_p do\n if sieve.(p) = p && e.(p) > 0L then process p\n done;\n in\n \n let rec steploop k = if k=0L || is_normal() then k else (\n step();\n steploop (k--1L)\n )\n in \n\n let k = steploop k in\n\n let elim p = \n let d = min e.(p) k in\n e.(p) <- e.(p) -- d;\n (* now add d to the exponents of all the prime factors of p-1 *)\n let rec loop r = if r=1 then () else\n\tlet s = sieve.(r) in\n\te.(s) <- e.(s) ++ d;\n\tloop (r/s)\n in\n loop (p-1);\n in\n\n for p=max_p downto 2 do\n if sieve.(p) = p then elim p\n done;\n\n let np = sum 2 max_p (fun i -> if e.(i) <> 0L then 1 else 0) in\n \n printf \"%d\\n\" np;\n\n for i=2 to max_p do\n if e.(i) <> 0L then printf \"%d %Ld\\n\" i e.(i)\n done\n"}], "src_uid": "6a52ad07f04498498d8ddd63caddbce6"} {"nl": {"description": "There are $$$n$$$ candies put from left to right on a table. The candies are numbered from left to right. The $$$i$$$-th candy has weight $$$w_i$$$. Alice and Bob eat candies. Alice can eat any number of candies from the left (she can't skip candies, she eats them in a row). Bob can eat any number of candies from the right (he can't skip candies, he eats them in a row). Of course, if Alice ate a candy, Bob can't eat it (and vice versa).They want to be fair. Their goal is to eat the same total weight of candies. What is the most number of candies they can eat in total?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2\\cdot10^5$$$)\u00a0\u2014 the number of candies on the table. The second line of each test case contains $$$n$$$ integers $$$w_1, w_2, \\dots, w_n$$$ ($$$1 \\leq w_i \\leq 10^4$$$)\u00a0\u2014 the weights of candies from left to right. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot10^5$$$.", "output_spec": "For each test case, print a single integer\u00a0\u2014 the maximum number of candies Alice and Bob can eat in total while satisfying the condition.", "sample_inputs": ["4\n3\n10 20 10\n6\n2 1 4 2 4 1\n5\n1 2 4 8 16\n9\n7 3 20 5 15 1 11 8 10"], "sample_outputs": ["2\n6\n0\n7"], "notes": "NoteFor the first test case, Alice will eat one candy from the left and Bob will eat one candy from the right. There is no better way for them to eat the same total amount of weight. The answer is $$$2$$$ because they eat two candies in total.For the second test case, Alice will eat the first three candies from the left (with total weight $$$7$$$) and Bob will eat the first three candies from the right (with total weight $$$7$$$). They cannot eat more candies since all the candies have been eaten, so the answer is $$$6$$$ (because they eat six candies in total).For the third test case, there is no way Alice and Bob will eat the same non-zero weight so the answer is $$$0$$$.For the fourth test case, Alice will eat candies with weights $$$[7, 3, 20]$$$ and Bob will eat candies with weights $$$[10, 8, 11, 1]$$$, they each eat $$$30$$$ weight. There is no better partition so the answer is $$$7$$$."}, "positive_code": [{"source_code": "let getInt () = Scanf.scanf \" %d\" (fun i -> i);;\r\n\r\n\r\nlet getList(n): int list = \r\n let rec getList2 ((n: int), (acc: int list)) = match n with\r\n\t | 0 -> List.rev acc\r\n\t | _ -> getList2 (n-1, getInt() :: acc)\r\n in getList2(n, [])\r\n\r\nlet getLine() = Scanf.scanf \" %s\" (fun i -> i);;\r\n\r\nlet prefix((arr: int list)) = \r\n let rec p2((arr: int list), (acc: int list), (s: int)) = \r\n match arr with\r\n | [] -> List.rev(acc)\r\n | x::xs -> p2(xs, (s + x)::acc, s + x)\r\n in p2(arr, [0], 0);;\r\n \r\nlet rec solve((p1: int list), (p2: int list), (ct: int), (n: int), (ret: int)) = \r\n if ct = n then ret else\r\n if (List.hd(List.tl(p2)) < List.hd(p1)) then solve(p1, List.tl(p2), ct + 1, n, ret)\r\n else if (List.hd(List.tl(p2)) = List.hd(p1))then solve(p1, List.tl(p2), ct + 1, n, ct + 1)\r\n else solve(List.tl(p1), p2, ct + 1, n, ret);;\r\n\r\nlet main() = \r\n let t = getInt() in\r\n for i = 1 to t do \r\n let n = getInt() in let arr = getList(n) in let arr2 = List.rev(arr) in\r\n let p1 = prefix(arr) in let p2 = prefix(arr2) in\r\n print_endline(string_of_int(solve(p1, p2, 0, n, 0)))\r\n\r\n done;;\r\n\r\nmain();;\r\n\r\n\r\n"}], "negative_code": [], "src_uid": "90e448ed43ba9a0533ac7dc24f92a7f8"} {"nl": {"description": "To stay woke and attentive during classes, Karen needs some coffee! Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed \"The Art of the Covfefe\".She knows n coffee recipes. The i-th recipe suggests that coffee should be brewed between li and ri degrees, inclusive, to achieve the optimal taste.Karen thinks that a temperature is admissible if at least k recipes recommend it.Karen has a rather fickle mind, and so she asks q questions. In each question, given that she only wants to prepare coffee with a temperature between a and b, inclusive, can you tell her how many admissible integer temperatures fall within the range?", "input_spec": "The first line of input contains three integers, n, k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009200000), and q (1\u2009\u2264\u2009q\u2009\u2264\u2009200000), the number of recipes, the minimum number of recipes a certain temperature must be recommended by to be admissible, and the number of questions Karen has, respectively. The next n lines describe the recipes. Specifically, the i-th line among these contains two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009200000), describing that the i-th recipe suggests that the coffee be brewed between li and ri degrees, inclusive. The next q lines describe the questions. Each of these lines contains a and b, (1\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009\u2264\u2009200000), describing that she wants to know the number of admissible integer temperatures between a and b degrees, inclusive.", "output_spec": "For each question, output a single integer on a line by itself, the number of admissible integer temperatures between a and b degrees, inclusive.", "sample_inputs": ["3 2 4\n91 94\n92 97\n97 99\n92 94\n93 97\n95 96\n90 100", "2 1 1\n1 1\n200000 200000\n90 100"], "sample_outputs": ["3\n3\n0\n4", "0"], "notes": "NoteIn the first test case, Karen knows 3 recipes. The first one recommends brewing the coffee between 91 and 94 degrees, inclusive. The second one recommends brewing the coffee between 92 and 97 degrees, inclusive. The third one recommends brewing the coffee between 97 and 99 degrees, inclusive. A temperature is admissible if at least 2 recipes recommend it.She asks 4 questions.In her first question, she wants to know the number of admissible integer temperatures between 92 and 94 degrees, inclusive. There are 3: 92, 93 and 94 degrees are all admissible.In her second question, she wants to know the number of admissible integer temperatures between 93 and 97 degrees, inclusive. There are 3: 93, 94 and 97 degrees are all admissible.In her third question, she wants to know the number of admissible integer temperatures between 95 and 96 degrees, inclusive. There are none.In her final question, she wants to know the number of admissible integer temperatures between 90 and 100 degrees, inclusive. There are 4: 92, 93, 94 and 97 degrees are all admissible.In the second test case, Karen knows 2 recipes. The first one, \"wikiHow to make Cold Brew Coffee\", recommends brewing the coffee at exactly 1 degree. The second one, \"What good is coffee that isn't brewed at at least 36.3306 times the temperature of the surface of the sun?\", recommends brewing the coffee at exactly 200000 degrees. A temperature is admissible if at least 1 recipe recommends it.In her first and only question, she wants to know the number of admissible integer temperatures that are actually reasonable. There are none."}, "positive_code": [{"source_code": "Scanf.scanf \"%d %d %d\" (fun n k q ->\nlet maxn=200001 in\nlet add,sub = (Array.make maxn 0) ,(Array.make maxn 0) in \nlet presum=Array.make 211111 0 in\nlet cnt = ref 0 in\n for i = 0 to n-1 do\n Scanf.scanf \"\\n%d %d\" (fun x y ->\n add.(x) <- add.(x) + 1 ;\n sub.(y) <- sub.(y) + 1 )\n done;\n for i = 1 to maxn-1 do\n cnt:=!cnt+add.(i)-sub.(i-1);\n presum.(i) <- (if !cnt>=k then 1 else 0) +presum.(i-1)\n done;\n for i= 1 to q do\n Scanf.scanf \"\\n%d %d\" (fun l r ->\n Printf.printf \"%d\\n\" (presum.(r)-presum.(l-1))\n )\n done)\n"}, {"source_code": "Scanf.scanf \"%d %d %d\" (fun n k q ->\nlet qs,qt = Queue.create(), Queue.create() in\nlet dat = Array.make n (0,0) in \nlet presum=Array.make 211111 0 in\nlet cnt = ref 0 in\n for i = 0 to n-1 do\n Scanf.scanf \"\\n%d %d\" (fun x y ->dat.(i) <-(x,y))\n done;\n Array.sort (fun (xh,_) (yh,_) -> xh-yh) dat;\n Array.iter (fun (h,_) -> Queue.push h qs) dat;\n Array.sort (fun (_,xt) (_,yt) -> xt-yt) dat;\n Array.iter (fun (_,t) -> Queue.push t qt) dat;\n for i = 1 to 200000 do\n (*Printf.printf \"i=%d\\n\" i;*)\n while not (Queue.is_empty qs) && Queue.top qs <= i do\n \n (*Printf.printf \"qs:%d\\n\"*) ( Queue.pop qs );\n cnt:= !cnt +1\n done;\n while not (Queue.is_empty qt) && Queue.top qt < i do\n (*Printf.printf \"qt:%d\\n\"*) ( Queue.pop qt );\n cnt:= !cnt -1\n done;\n presum.(i) <- (if !cnt>=k then 1 else 0) +presum.(i-1)\n done;\n for i= 1 to q do\n Scanf.scanf \"\\n%d %d\" (fun l r ->\n Printf.printf \"%d\\n\" (presum.(r)-presum.(l-1))\n )\n done)\n"}], "negative_code": [], "src_uid": "4bdf819b73ffb708ad571accf3b8c23d"} {"nl": {"description": "Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately. Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe. Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), that is the number of cafe visitors. Each of the following n lines has two space-separated integers hi and mi (0\u2009\u2264\u2009hi\u2009\u2264\u200923;\u00a00\u2009\u2264\u2009mi\u2009\u2264\u200959), representing the time when the i-th person comes into the cafe. Note that the time is given in the chronological order. All time is given within one 24-hour period.", "output_spec": "Print a single integer \u2014 the minimum number of cashes, needed to serve all clients next day.", "sample_inputs": ["4\n8 0\n8 10\n8 10\n8 45", "3\n0 12\n10 11\n22 22"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.In the second sample all visitors will come in different times, so it will be enough one cash."}, "positive_code": [{"source_code": "let input () = \n let n = Scanf.scanf \"%d \" (fun n -> n) in\n let rec loop i list = \n if i < n\n then\n let str = Scanf.scanf \"%s %s \" (fun a b -> String.concat \"\" [a; b]) in\n loop (i + 1) (str :: list)\n else\n List.rev list\n in loop 0 []\n \n\nlet print int = Printf.printf \"%d\\n\" int\n\nlet solve list = \n let rec loop rest prev count max = \n match rest with\n | (head :: tail) -> \n if String.compare head prev = 0\n then\n let max_upd = Pervasives.max (count + 1) max in\n loop tail head (count + 1) max_upd\n else\n loop tail head 1 max\n | [] -> max\n in loop list \"start\" 1 1\n\nlet () = print (solve (input ()))"}, {"source_code": "let print int = Printf.printf \"%d\\n\" int\n\nlet same time prev =\n match time, prev with\n | (h, m), (hh, mm) -> \n if h = hh && m = mm\n then\n true\n else\n false\n\nlet () = \n let n = Scanf.scanf \"%d \" (fun n -> n) in\n let rec loop i prev count max = \n if i < n\n then\n let time = Scanf.scanf \"%d %d \" (fun h m -> (h, m)) in \n if same time prev\n then \n let max_upd = Pervasives.max (count + 1) max in\n loop (i + 1) time (count + 1) max_upd\n else\n loop (i + 1) time 1 max\n else\n print max\n in loop 0 (99, 99) 1 1"}, {"source_code": "let input () = \n let n = Scanf.scanf \"%d \" (fun n -> n) in\n let rec loop i list = \n if i < n\n then\n let time = Scanf.scanf \"%d %d \" (fun h m -> (h, m)) in\n loop (i + 1) (time :: list)\n else\n list\n in loop 0 []\n \nlet print int = Printf.printf \"%d\\n\" int\n\nlet solve list = \n let rec loop rest prev count max = \n match rest, prev with\n | ((h, m) as head :: tail), (hh, mm) -> \n if h = hh && m = mm\n then\n let max_upd = Pervasives.max (count + 1) max in\n loop tail head (count + 1) max_upd\n else\n loop tail head 1 max\n | [], _ -> max\n in loop list (99, 99) 1 1\n\nlet () = print (solve (input ()))"}, {"source_code": "\n(* Codeforces 237A *)\n\nlet read_time() = Scanf.scanf \"%d %d\\n\" (fun x y -> x, y)\n\nlet solve n =\n let rec inner n prev_time count max_count =\n if (n == 0) then max count max_count\n else \n begin\n\tlet time = read_time() in\n\tif (time = prev_time)\n\tthen inner (n-1) time (count+1) max_count\n\telse\n\t if (count > max_count)\n\t then inner (n-1) time 1 count\n\t else inner (n-1) time 1 max_count\n end\n in\n inner n (-1, -1) 0 0\n\nlet _ =\n Printf.printf \"%d\\n\" (Scanf.scanf \"%d\\n\" solve)\n"}], "negative_code": [{"source_code": "\n(* Codeforces 237A *)\n\nlet read_time() = Scanf.scanf \"%d %d\\n\" (fun x y -> x, y)\n\nlet solve n =\n let rec inner n prev_time count max_count =\n if (n == 0) then max_count\n else\n begin\n\tlet time = read_time() in\n\tlet max_count =\n\t if (max_count < count)\n\t then count\n\t else max_count\n\tin\n\tlet count =\n\t if (time = prev_time)\n\t then count+1\n\t else 1\n\tin\n\tinner (n-1) time count max_count\n end\n in\n inner n (-1, -1) 0 0\n\nlet _ =\n Printf.printf \"%d\\n\" (Scanf.scanf \"%d\\n\" solve)\n"}], "src_uid": "cfad2cb472e662e037f3415a84daca57"} {"nl": {"description": "Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti. As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.It's time for Susie to go to bed, help her find such string p or state that it is impossible.", "input_spec": "The first line contains string s of length n. The second line contains string t of length n. The length of string n is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.", "output_spec": "Print a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line \"impossible\" (without the quotes). If there are multiple possible answers, print any of them.", "sample_inputs": ["0001\n1011", "000\n111"], "sample_outputs": ["0011", "impossible"], "notes": "NoteIn the first sample different answers are possible, namely \u2014 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101."}, "positive_code": [{"source_code": "\nlet list_of_string s =\n let rec loc i acc =\n if i < 0\n then acc\n else loc (i - 1) (String.get s i :: acc)\n in\n loc (String.length s - 1) []\n\nlet combine s t =\n let rec loc acc s t =\n match s, t with\n | [], [] -> acc\n | x :: rs, y :: rt -> loc ((x, y) :: acc) rs rt\n | _, _ -> invalid_arg \"\"\n in\n List.rev (loc [] s t)\n\nexception Impossible\n\nlet solve a b =\n\n let la = list_of_string a\n and lb = list_of_string b in\n let l = combine la lb in\n let n = List.length l in\n\n let diff =\n List.fold_left\n (fun acc (ca, cb) -> if ca <> cb then acc + 1 else acc)\n 0\n l\n in\n if diff mod 2 <> 0 then raise Impossible;\n\n let ans = String.create n in\n let rec loc i j = function\n | [] -> ()\n | (ca, cb) :: rest ->\n if ca = cb\n then (String.set ans i ca; loc (i + 1) j rest)\n else\n begin\n if j < diff / 2\n then (String.set ans i ca; loc (i + 1) (j + 1) rest)\n else (String.set ans i cb; loc (i + 1) (j + 1) rest)\n end\n in\n loc 0 0 l;\n ans\n\n(* let mk n = String.init n (fun _ -> if Random.bool () then '0' else '1') *)\n\nlet _ =\n (* print_endline (mk 100000); *)\n (* print_endline (mk 100000); *)\n \n let a = read_line ()\n and b = read_line () in\n let ans =\n try solve a b\n with Impossible -> \"impossible\"\n in\n print_endline ans\n"}, {"source_code": "let _ =\n\tlet (s1,s2) = Scanf.scanf \"%s %s\" (fun i j -> (i,j)) in\n\tlet res = String.copy s1 and flg = ref true in\n\tfor i=0 to String.length res - 1 do\n\t\tif res.[i] <> s2.[i]\n\t\t\tthen begin\n\t\t\t\tflg := not !flg;\n\t\t\t\tif !flg\n\t\t\t\t\tthen res.[i] <- s2.[i]\n\t\t\t end;\n\tdone;\n\tPrintf.printf \"%s\" (if !flg then res else \"impossible\")\n"}], "negative_code": [{"source_code": "\nlet list_of_string s =\n let rec loc i acc =\n if i < 0\n then acc\n else loc (i - 1) (String.get s i :: acc)\n in\n loc (String.length s - 1) []\n\nlet combine s t =\n let rec loc acc s t =\n match s, t with\n | [], [] -> acc\n | x :: rs, y :: rt -> loc ((x, y) :: acc) rs rt\n | _, _ -> invalid_arg \"\"\n in\n List.rev (loc [] s t)\n\nexception Impossible\n\nlet solve a b =\n\n let la = list_of_string a\n and lb = list_of_string b in\n let l = combine la lb in\n let n = List.length l in\n\n let diff =\n List.fold_left\n (fun acc (ca, cb) -> if ca <> cb then acc + 1 else acc)\n 0\n l\n in\n if diff mod 2 <> 0 then raise Impossible;\n\n let ans = String.create n in\n List.iteri\n (fun i (ca, cb) ->\n if i < n / 2\n then String.set ans i ca\n else String.set ans i cb)\n l;\n ans\n\n(* let mk n = String.init n (fun _ -> if Random.bool () then '0' else '1') *)\n\nlet _ =\n (* print_endline (mk 100000); *)\n (* print_endline (mk 100000); *)\n \n let a = read_line ()\n and b = read_line () in\n let ans =\n try solve a b\n with Impossible -> \"impossible\"\n in\n print_endline ans\n"}], "src_uid": "2df181f2d1f4063a22fd2fa2d47eef92"} {"nl": {"description": "You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where ai,\u2009j\u2009=\u20091 if the i-th switch turns on the j-th lamp and ai,\u2009j\u2009=\u20090 if the i-th switch is not connected to the j-th lamp.Initially all m lamps are turned off.Switches change state only from \"off\" to \"on\". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.It is guaranteed that if you push all n switches then all m lamps will be turned on.Your think that you have too many switches and you would like to ignore one of them. Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other n\u2009-\u20091 switches then all the m lamps will be turned on.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092000) \u2014 the number of the switches and the number of the lamps. The following n lines contain m characters each. The character ai,\u2009j is equal to '1' if the i-th switch turns on the j-th lamp and '0' otherwise. It is guaranteed that if you press all n switches all m lamps will be turned on.", "output_spec": "Print \"YES\" if there is a switch that if you will ignore it and press all the other n\u2009-\u20091 switches then all m lamps will be turned on. Print \"NO\" if there is no such switch.", "sample_inputs": ["4 5\n10101\n01000\n00111\n10000", "4 5\n10100\n01000\n00110\n00101"], "sample_outputs": ["YES", "NO"], "notes": null}, "positive_code": [{"source_code": "\nlet _ =\n let n, m = Scanf.scanf \" %u %u\" (fun i j -> i, j) in\n (* n - #switch, m - #lamp *)\n let switches_of_lamp: (int list) array =\n Array.init m (fun _ -> [])\n in\n \n for i = 0 to n - 1 do\n let s = Scanf.scanf \" %s\" (fun i -> i) in\n for j = 0 to m - 1 do\n match String.get s j with\n | '1' -> switches_of_lamp.(j) <- i :: switches_of_lamp.(j)\n | _ -> ()\n done\n done;\n \n let rec f (switch: int): unit =\n if switch >= n\n then print_endline \"NO\"\n else\n let rec g (lamp: int): bool =\n let rec k (switch_inner: int list): bool =\n match switch_inner with\n | [] -> false\n | x :: xs when x = switch -> k xs\n | _ -> true\n in\n if lamp >= m\n then true\n else if k switches_of_lamp.(lamp)\n then g (lamp + 1)\n else false\n in\n if g 0 then print_endline \"YES\" else f (switch + 1)\n in\n f 0\n"}], "negative_code": [], "src_uid": "5ce39a83d27253f039f0e26045249d99"} {"nl": {"description": "Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second. ", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105) \u2014 the quantity of the numbers in the both given permutations. Next line contains n space-separated integers \u2014 the first permutation. Each number between 1 to n will appear in the permutation exactly once. Next line describe the second permutation in the same format.", "output_spec": "Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.", "sample_inputs": ["3\n3 2 1\n1 2 3", "5\n1 2 3 4 5\n1 5 2 3 4", "5\n1 5 2 3 4\n1 2 3 4 5"], "sample_outputs": ["2", "1", "3"], "notes": "NoteIn the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.In the second sample, he removes number 5 and inserts it after 1.In the third sample, the sequence of changes are like this: 1 5 2 3 4 1 4 5 2 3 1 3 4 5 2 1 2 3 4 5 So he needs three moves."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\ta.(k) <- i\n done;\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tb.(a.(k)) <- i\n done;\n in\n let res = ref (n - 1) in\n (try\n for i = 1 to n - 1 do\n\t if b.(i - 1) < b.(i) then (\n\t decr res;\n\t ) else raise Not_found\n done;\n with\n | Not_found -> ()\n );\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\ta.(k) <- i\n done;\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tb.(a.(k)) <- i\n done;\n in\n let res = ref 0 in\n let d = Array.make n false in\n let c = ref (n - 1) in\n for i = n - 1 downto 0 do\n if b.(i) <> !c then (\n\tincr res;\n\td.(b.(i)) <- true;\n ) else (\n\tdecr c\n );\n while !c >= 0 && d.(!c) do\n\tdecr c\n done;\n done;\n Printf.printf \"%d\\n\" !res\n"}], "src_uid": "a26e048eb9b18f87f1703d42e172f318"} {"nl": {"description": "A permutation p of length n is a sequence of distinct integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n). A permutation is an identity permutation, if for any i the following equation holds pi\u2009=\u2009i. A swap (i,\u2009j) is the operation that swaps elements pi and pj in the permutation. Let's assume that f(p) is the minimum number of swaps that you need to make the permutation p an identity permutation. Valera wonders, how he can transform permutation p into any permutation q, such that f(q)\u2009=\u2009m, using the minimum number of swaps. Help him do that.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093000) \u2014 the length of permutation p. The second line contains n distinct integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) \u2014 Valera's initial permutation. The last line contains integer m (0\u2009\u2264\u2009m\u2009<\u2009n).", "output_spec": "In the first line, print integer k \u2014 the minimum number of swaps. In the second line, print 2k integers x1,\u2009x2,\u2009...,\u2009x2k \u2014 the description of the swap sequence. The printed numbers show that you need to consecutively make swaps (x1,\u2009x2), (x3,\u2009x4), ..., (x2k\u2009-\u20091,\u2009x2k). If there are multiple sequence swaps of the minimum length, print the lexicographically minimum one.", "sample_inputs": ["5\n1 2 3 4 5\n2", "5\n2 1 4 5 3\n2"], "sample_outputs": ["2\n1 2 1 3", "1\n1 2"], "notes": "NoteSequence x1,\u2009x2,\u2009...,\u2009xs is lexicographically smaller than sequence y1,\u2009y2,\u2009...,\u2009ys, if there is such integer r (1\u2009\u2264\u2009r\u2009\u2264\u2009s), that x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009...,\u2009xr\u2009-\u20091\u2009=\u2009yr\u2009-\u20091 and xr\u2009<\u2009yr. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet split_cycles n m ncycles p mark =\n failwith \"split_cycles called\"\n\nlet merge_cycles n goal ncycles p mark =\n (* The algorithm is to find the smallest element not in\n cycle 0 and swap it with 0, thus putting it in cycle 0.\n The mark array already has 0s in it at cycle 0. This is O(n).\n *)\n let rec build_swaps i ncyc ac = if ncyc=goal then List.rev ac else\n if mark.(i) = 0 then build_swaps (i+1) ncyc ac else\n\tlet rec loop j = if j=i then () else (\n\t mark.(j) <- 0;\n\t loop p.(j)\n\t)\n\tin\n\tloop p.(i);\n\tbuild_swaps (i+1) (ncyc-1) ((0,i)::ac)\n in\n\n build_swaps 1 ncycles []\n\nlet split_cycles n goal ncycles p mark =\n let rec build_swaps i ncyc ac = if ncyc=goal then List.rev ac else\n if p.(i) = i then build_swaps (i+1) ncyc ac else\n\tlet rec find_smallest j ac = if j=i then ac else\n\t find_smallest p.(j) (min ac j)\n\tin\n\tlet j = find_smallest p.(i) p.(i) in\n\tlet (oi, oj) = (p.(i), p.(j)) in\n\tp.(i) <- oj;\n\tp.(j) <- oi;\n\tbuild_swaps i (ncyc+1) ((i,j)::ac)\n in\n build_swaps 0 ncycles []\n \nlet () = \n let n = read_int () in\n let p = Array.init n (fun _ -> read_int()-1) in\n let m = read_int () in\n let goal = n-m in (* number of cycles of the goal *)\n\n let mark = Array.make n (-1) in\n\n let rec dfs i c = if mark.(i) < 0 then (\n mark.(i) <- c;\n dfs p.(i) c\n ) in\n\n let rec count_cycles c i = \n if i=n then c \n else if mark.(i) >= 0 then count_cycles c (i+1) else (\n dfs i c;\n count_cycles (c+1) (i+1)\n )\n in\n\n let ncycles = count_cycles 0 0 in\n\n printf \"%d\\n\" (abs (ncycles-goal));\n\n let answer = \n (if ncycles >= goal then merge_cycles else split_cycles) n goal ncycles p mark\n in\n\n List.iter (fun (i,j) -> printf \"%d %d \" (i+1) (j+1)) answer;\n print_newline();\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet merge_cycles n goal ncycles p mark =\n let rec build_swaps i ncyc ac = if ncyc=goal then List.rev ac else\n if mark.(i) = 0 then build_swaps (i+1) ncyc ac else\n\tlet rec loop j = if j<>i then (\n\t mark.(j) <- 0;\n\t loop p.(j)\n\t)\n\tin\n\tloop p.(i);\n\tbuild_swaps (i+1) (ncyc-1) ((0,i)::ac)\n in\n build_swaps 1 ncycles []\n\nlet split_cycles n goal ncycles p mark =\n let rec build_swaps i ncyc ac = if ncyc=goal then List.rev ac else\n if p.(i) = i then build_swaps (i+1) ncyc ac else\n\tlet rec find_smallest j ac = if j=i then ac else\n\t find_smallest p.(j) (min ac j)\n\tin\n\tlet j = find_smallest p.(i) p.(i) in\n\tlet (oi, oj) = (p.(i), p.(j)) in\n\tp.(i) <- oj;\n\tp.(j) <- oi;\n\tbuild_swaps i (ncyc+1) ((i,j)::ac)\n in\n build_swaps 0 ncycles []\n \nlet () = \n let n = read_int () in\n let p = Array.init n (fun _ -> read_int()-1) in\n let goal = n - (read_int ()) in\n\n let mark = Array.make n (-1) in\n\n let rec dfs i c = if mark.(i) < 0 then (\n mark.(i) <- c;\n dfs p.(i) c\n ) in\n\n let rec count_cycles c i = \n if i=n then c \n else if mark.(i) >= 0 then count_cycles c (i+1) else (\n dfs i c;\n count_cycles (c+1) (i+1)\n )\n in\n\n let ncycles = count_cycles 0 0 in\n\n printf \"%d\\n\" (abs (ncycles-goal));\n\n let answer = \n (if ncycles >= goal then merge_cycles else split_cycles) n goal ncycles p mark\n in\n\n List.iter (fun (i,j) -> printf \"%d %d \" (i+1) (j+1)) answer;\n print_newline();\n"}], "negative_code": [], "src_uid": "e7517e32caa1b044ebf1d39276560b47"} {"nl": {"description": "A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.", "input_spec": "The first line contains a pair of integer numbers n and v (1\u2009\u2264\u2009n\u2009\u2264\u2009105; 1\u2009\u2264\u2009v\u2009\u2264\u2009109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti,\u2009pi (1\u2009\u2264\u2009ti\u2009\u2264\u20092; 1\u2009\u2264\u2009pi\u2009\u2264\u2009104), where ti is the vehicle type (1 \u2013 a kayak, 2 \u2013 a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.", "output_spec": "In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.", "sample_inputs": ["3 2\n1 2\n2 7\n1 3"], "sample_outputs": ["7\n2"], "notes": null}, "positive_code": [{"source_code": "let (|>) x f = f x\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let v = read_int 0 in\n let one = Array.make n (0,0)\n and two = Array.make n (0,0) in\n let rec input i none ntwo =\n if i >= n then\n none,ntwo\n else (\n let t = read_int 0 in\n let c = read_int 0 in\n if t = 1 then (\n one.(none) <- (c,i);\n input (i+1) (none+1) ntwo\n ) else (\n two.(ntwo) <- (c,i);\n input (i+1) none (ntwo+1)\n )\n ) in\n let none,ntwo = input 0 0 0 in\n Array.sort (fun x y -> compare y x) one;\n Array.sort (fun x y -> compare y x) two;\n\n let ans = ref 0\n and ansp = ref 0\n and ansq = ref 0\n and qs = ref 0\n and ps = Array.make (none+1) 0 in\n for i = 0 to none-1 do\n ps.(i+1) <- ps.(i)+fst one.(i)\n done;\n for i = 0 to min (v/2) ntwo do\n let rest = min (v-2*i) none in\n if ps.(rest) + !qs > !ans then (\n ans := ps.(rest) + !qs;\n ansp := rest;\n ansq := i\n );\n if i < ntwo then\n qs := !qs+fst two.(i)\n done;\n\n Printf.printf \"%d\\n\" !ans;\n for i = 0 to !ansp-1 do\n Printf.printf \"%d \" (snd one.(i)+1)\n done;\n for i = 0 to !ansq-1 do\n Printf.printf \"%d \" (snd two.(i)+1)\n done\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\ntype container = {\n cap : int;\n id: int\n};;\n\nlet comp contA contB =\n - (contA.cap - contB.cap);;\n\nlet rec get_best tab1 tab2 size = match (tab1,tab2) with\n | ([],[])\n -> []\n | ([], _) when size < 2\n -> []\n | (_, _) when size = 0\n -> []\n | (first :: tail, _) when size = 1\n -> [first]\n | ([], first :: tail)\n -> first :: get_best [] tail (size - 2)\n | (first :: tail, [])\n -> first :: get_best tail [] (size - 1)\n | (first1 :: [], first2 :: tail2)\n -> if first1.cap >= first2.cap then\n first1 :: get_best [] tab2 (size - 1)\n else\n first2 :: get_best tab1 tail2 (size - 2)\n | (first1 :: second1 :: tail1, first2 :: tail2)\n -> if first1.cap + second1.cap >= first2.cap then\n first1 :: get_best (second1::tail1) tab2 (size - 1)\n else\n first2 :: get_best tab1 tail2 (size - 2);;\n\n(*#trace get_best;;*)\n\nlet rec read_input index left = match left with\n | 0 -> [],[]\n | n ->\n let size = read_int () in\n let cap = read_int () in\n let cont = {cap = cap; id = index} in\n let size1,size2 = read_input (index + 1) (left - 1) in\n if size = 1 then\n (cont :: size1, size2)\n else\n (size1, cont :: size2);;\n\n\n\nlet nbVehi = read_int () in\nlet maxV = read_int () in\nlet unsort1,unsort2 = (read_input 1 nbVehi) in\nlet tab1 = List.sort comp unsort1 in\nlet tab2 = List.sort comp unsort2 in\nlet res = get_best tab1 tab2 maxV in\nbegin\n let maxC = List.fold_left (fun sum cont -> sum + cont.cap) 0 res in\n Printf.printf \"%d\\n\" maxC;\n List.iter (fun cont -> Printf.printf \"%d\\n\" cont.id) res\nend;;"}], "negative_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\ntype container = {\n cap : int;\n id: int\n};;\n\nlet comp contA contB =\n - (contA.cap - contB.cap);;\n\nlet rec get_best tab1 tab2 size = match (tab1,tab2) with\n | ([],[])\n -> []\n | ([], _) when size < 2\n -> []\n | (_, _) when size = 0\n -> []\n | (first :: tail, _) when size = 1\n -> [first]\n | ([], first :: tail)\n -> first :: get_best [] tail (size - 2)\n | (first :: tail, [])\n -> first :: get_best tail [] (size - 1)\n | (first1 :: second1 :: [], first2 :: tail2) when size > 2\n -> first2 :: get_best tab1 tail2 (size - 2)\n | (first1 :: [], first2 :: tail2)\n -> if first1.cap >= first2.cap then\n first1 :: get_best [] tab2 (size - 1)\n else\n first2 :: get_best tab1 tail2 (size - 2)\n | (first1 :: second1 :: tail1, first2 :: tail2)\n -> if first1.cap + second1.cap >= first2.cap then\n first1 :: second1 :: get_best tail1 tab2 (size - 2)\n else\n first2 :: get_best tab1 tail2 (size - 2);;\n\n(*#trace get_best;;*)\n\nlet rec read_input index left = match left with\n | 0 -> [],[]\n | n ->\n let size = read_int () in\n let cap = read_int () in\n let cont = {cap = cap; id = index} in\n let size1,size2 = read_input (index + 1) (left - 1) in\n if size = 1 then\n (cont :: size1, size2)\n else\n (size1, cont :: size2);;\n\n\n\nlet nbVehi = read_int () in\nlet maxV = read_int () in\nlet unsort1,unsort2 = (read_input 1 nbVehi) in\nlet tab1 = List.sort comp unsort1 in\nlet tab2 = List.sort comp unsort2 in\nlet res = get_best tab1 tab2 maxV in\nbegin\n let maxC = List.fold_left (fun sum cont -> sum + cont.cap) 0 res in\n Printf.printf \"%d\\n\" maxC;\n List.iter (fun cont -> Printf.printf \"%d\\n\" cont.id) res\nend;;"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\ntype container = {\n cap : int;\n id: int\n};;\n\nlet comp contA contB =\n - (contA.cap - contB.cap);;\n\nlet rec get_best tab1 tab2 size = match (tab1,tab2) with\n | ([],[])\n -> []\n | ([], _) when size < 2\n -> []\n | (_, _) when size = 0\n -> []\n | (first :: [], _) when size = 1\n -> [first]\n | ([], first :: tail)\n -> first :: get_best [] tail (size - 2)\n | (first :: tail, [])\n -> first :: get_best tail [] (size - 1)\n | (first1 :: [], first2 :: tail2)\n -> if first1.cap >= first2.cap then\n first1 :: get_best [] tab2 (size - 1)\n else\n first2 :: get_best tab1 tail2 (size - 2)\n | (first1 :: second1 :: tail1, first2 :: tail2)\n -> if first1.cap + second1.cap >= first2.cap then\n first1 :: second1 :: get_best tail1 tab2 (size - 2)\n else\n first2 :: get_best tab1 tail2 (size - 2);;\n\n(*#trace get_best;;*)\n\nlet rec read_input index left = match left with\n | 0 -> [],[]\n | n ->\n let size = read_int () in\n let cap = read_int () in\n let cont = {cap = cap; id = index} in\n let size1,size2 = read_input (index + 1) (left - 1) in\n if size = 1 then\n (cont :: size1, size2)\n else\n (size1, cont :: size2);;\n\n\n\nlet nbVehi = read_int () in\nlet maxV = read_int () in\nlet unsort1,unsort2 = (read_input 1 nbVehi) in\nlet tab1 = List.sort comp unsort1 in\nlet tab2 = List.sort comp unsort2 in\nlet res = get_best tab1 tab2 maxV in\nbegin\n let maxC = List.fold_left (fun sum cont -> sum + cont.cap) 0 res in\n Printf.printf \"%d\\n\" maxC;\n List.iter (fun cont -> Printf.printf \"%d\\n\" cont.id) res\nend;;"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\ntype container = {\n vol : int;\n size: int;\n id: int\n};;\n\nlet comp contA contB =\n - (contA.vol * contB.size - contB.vol * contA.size);;\n\nlet rec get_best tab size = match tab with\n | [] -> []\n | curr_best :: suite ->\n match size with\n | 0 -> []\n | 1 -> \n if curr_best.size == 1 then\n [curr_best]\n else\n get_best suite size\n | n ->\n curr_best :: get_best suite (size - curr_best.size);;\n\nlet rec read_input index left = match left with\n | 0 -> []\n | n ->\n let size = read_int () in\n let cap = read_int () in\n let cont = {\n size = size;\n vol = cap;\n id = index;\n } in\n cont :: read_input (index + 1) (left - 1);;\n\n\nlet nbVehi = read_int () in\nlet maxV = read_int () in\nlet tableau = read_input 1 nbVehi \n |> List.sort comp in\nlet res = get_best tableau maxV in\nbegin\n let maxC = List.fold_left (fun sum cont -> sum + cont.vol) 0 res in\n Printf.printf \"%d\\n\" maxC;\n List.iter (fun cont -> Printf.printf \"%d\\n\" cont.id) res\nend;;"}], "src_uid": "a1f98b06650a5755e784cd6ec6f3b211"} {"nl": {"description": "There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C\u00b7k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.", "input_spec": "The first line contains five integers n, A, B, C and T (1\u2009\u2264\u2009n,\u2009A,\u2009B,\u2009C,\u2009T\u2009\u2264\u20091000). The second string contains n integers ti (1\u2009\u2264\u2009ti\u2009\u2264\u2009T).", "output_spec": "Output one integer \u00a0\u2014 the answer to the problem.", "sample_inputs": ["4 5 5 3 5\n1 5 5 4", "5 3 1 1 3\n2 2 2 1 1", "5 5 3 4 5\n1 2 3 4 5"], "sample_outputs": ["20", "15", "35"], "notes": "NoteIn the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n\u00b7A\u2009=\u200920 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5\u2009-\u20094\u00b73)\u2009+\u2009(5\u2009-\u20093\u00b73)\u2009+\u2009(5\u2009-\u20092\u00b73)\u2009+\u2009(5\u2009-\u20091\u00b73)\u2009+\u20095\u2009=\u2009\u2009-\u20095 points. This is 35 in total."}, "positive_code": [{"source_code": "\nlet compute n a b c t ts: int =\n Array.sort compare ts;\n if b >= c\n then n * a\n else\n let diffs = Array.map (fun v -> t - v) ts in\n let incomes = Array.map (fun v -> (c - b) * v) diffs in\n let total_income = Array.fold_left (+) 0 incomes in\n total_income + n * a\n \n\nlet _ =\n let n, a, b, c, t = Scanf.scanf \" %d %d %d %d %d\" (fun a b c d e -> a, b, c, d, e) in\n let ts = Array.init n (fun i -> Scanf.scanf \" %d\" (fun a -> a)) in\n compute n a b c t ts |> string_of_int |> print_endline\n"}], "negative_code": [], "src_uid": "281b95c3686c94ae1c1e4e2a18b7fcc4"} {"nl": {"description": "Polycarp remembered the $$$2020$$$-th year, and he is happy with the arrival of the new $$$2021$$$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $$$n$$$ as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$.For example, if: $$$n=4041$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2021$$$; $$$n=4042$$$, then the number $$$n$$$ can be represented as the sum $$$2021 + 2021$$$; $$$n=8081$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2020 + 2020 + 2021$$$; $$$n=8079$$$, then the number $$$n$$$ cannot be represented as the sum of the numbers $$$2020$$$ and $$$2021$$$. Help Polycarp to find out whether the number $$$n$$$ can be represented as the sum of a certain number of numbers $$$2020$$$ and a certain number of numbers $$$2021$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^6$$$)\u00a0\u2014 the number that Polycarp wants to represent as the sum of the numbers $$$2020$$$ and $$$2021$$$.", "output_spec": "For each test case, output on a separate line: \"YES\" if the number $$$n$$$ is representable as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$; \"NO\" otherwise. You can output \"YES\" and \"NO\" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).", "sample_inputs": ["5\n1\n4041\n4042\n8081\n8079"], "sample_outputs": ["NO\nYES\nYES\nYES\nNO"], "notes": null}, "positive_code": [{"source_code": "let calculate_table () =\n let table = Hashtbl.create 1000000 in\n for a = 0 to 500 do\n for b = 0 to 500 do\n let new_value = (a*2020 + b*2021) in\n Hashtbl.add table new_value (a, b)\n done\n done;\n table;;\n\nlet find_opt tbl n =\n try\n Some (Hashtbl.find tbl n)\n with Not_found -> None\n\nlet solution_exists n solutions =\n let maybe_sol = find_opt solutions n in\n match maybe_sol with\n | Some _ -> true\n | None -> false;;\n\nlet cases = read_int () in\nlet solutions = calculate_table () in\nfor i = 1 to cases do\n let test = read_int () in\n if solution_exists test solutions then\n print_endline \"YES\"\n else\n print_endline \"NO\"\ndone"}, {"source_code": "module Stdlib = Pervasives\r\nlet std_inp = Stdlib.stdin;;\r\n(* let std_inp = Stdlib.open_in \"input.txt\";; *)\r\nlet std_outp = Stdlib.stdout;;\r\n\r\nlet identity x = x;;\r\n\r\nlet rec repeat ((f, f_in, f_out) as call) = function\r\n| 0 -> ()\r\n| n ->\r\n let _ = f f_in f_out in\r\n repeat call (n - 1);;\r\n\r\nlet flags =\r\n let sum_limit = 1_000_000 in\r\n let flags = Array.make (1 + sum_limit) false in\r\n let safe_get pos =\r\n if pos < 0 then false\r\n else flags.(pos)\r\n in\r\n let rec fill n =\r\n if n > sum_limit then ()\r\n else\r\n let _ = flags.(n) <- ((safe_get (n - 2020)) || (safe_get(n - 2021))) in\r\n fill (n + 1)\r\n in\r\n let _ = flags.(0) <- true in\r\n let _ = fill 1 in\r\n flags;;\r\n\r\nlet run_test inp outp =\r\n let value = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let result = if flags.(value) then \"YES\" else \"NO\" in\r\n let _ = Printf.fprintf outp \"%s\\n\" result in\r\n ();;\r\n\r\nlet (_:unit) =\r\n let inp = std_inp and outp = std_outp in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let _ = repeat (run_test, inp, outp) tests_count in\r\n ();;"}], "negative_code": [], "src_uid": "3ec1b7027f487181dbdfb12f295f11ae"} {"nl": {"description": "Santa Claus likes palindromes very much. There was his birthday recently. k of his friends came to him to congratulate him, and each of them presented to him a string si having the same length n. We denote the beauty of the i-th string by ai. It can happen that ai is negative\u00a0\u2014 that means that Santa doesn't find this string beautiful at all.Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have the same length n.Recall that a palindrome is a string that doesn't change after one reverses it.Since the empty string is a palindrome too, the answer can't be negative. Even if all ai's are negative, Santa can obtain the empty string.", "input_spec": "The first line contains two positive integers k and n divided by space and denoting the number of Santa friends and the length of every string they've presented, respectively (1\u2009\u2264\u2009k,\u2009n\u2009\u2264\u2009100\u2009000; n\u00b7k\u00a0\u2009\u2264\u2009100\u2009000). k lines follow. The i-th of them contains the string si and its beauty ai (\u2009-\u200910\u2009000\u2009\u2264\u2009ai\u2009\u2264\u200910\u2009000). The string consists of n lowercase English letters, and its beauty is integer. Some of strings may coincide. Also, equal strings can have different beauties.", "output_spec": "In the only line print the required maximum possible beauty.", "sample_inputs": ["7 3\nabb 2\naaa -3\nbba -1\nzyz -4\nabb 5\naaa 7\nxyx 4", "3 1\na 1\na 2\na 3", "2 5\nabcde 10000\nabcde 10000"], "sample_outputs": ["12", "6", "0"], "notes": "NoteIn the first example Santa can obtain abbaaaxyxaaabba by concatenating strings 5, 2, 7, 6 and 3 (in this order)."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet () =\n let k = read_int() in\n let n = read_int() in\n\n let s = Array.init k (fun _ ->\n let str = read_string() in\n let cost = read_int() in\n (str,cost)\n ) in\n\n let h = Hashtbl.create 10 in\n\n let insert (str,cost) = \n let (li,index) = try Hashtbl.find h str with Not_found -> ([], Hashtbl.length h) in\n Hashtbl.replace h str ((cost::li),index)\n in\n\n for i=0 to k-1 do insert s.(i) done;\n\n let rev_string s = String.init n (fun i -> s.[n-i-1]) in\n \n let nstrings = Hashtbl.length h in\n\n let pair = Array.make nstrings (-1) in\n let clist = Array.make nstrings [] in\n\n Hashtbl.iter (fun str (li,index) ->\n clist.(index) <- List.sort (fun a b -> compare b a) li; \n let rstr = rev_string str in\n let (_,rindex) = try Hashtbl.find h rstr with Not_found -> ([], -1) in\n if rindex >= 0 then pair.(index) <- rindex\n ) h;\n\n let best_correction = ref 0 in\n\n let score = sum 0 (nstrings-1) (fun i ->\n let j = pair.(i) in\n if j = -1 then 0\n else if j < i then 0\n else if j > i then ( (* a non-palindrome with a pair *)\n let rec loop l1 l2 ac =\n\tmatch (l1,l2) with\n\t | ([],_) | (_,[]) -> ac\n\t | (c1::t1, c2::t2) ->\n\t if c1+c2 <= 0 then ac\n\t else loop t1 t2 (ac + c1 + c2)\n in\n loop clist.(i) clist.(j) 0\n ) else ( (* a palindrome *)\n let rec loop li rem ac =\n\tmatch li with\n\t | [] -> (rem,ac)\n\t | [c] -> (max rem c, ac)\n\t | c1::(c2::t) ->\n\t if c1+c2 <= 0 then (max rem c1, ac) else\n\t let rem = max rem (-c2) in \n\t loop t rem (ac + c1 + c2)\n in\n let (rem,ac) = loop clist.(i) 0 0 in\n best_correction := max !best_correction rem;\n ac\n )\n )\n in\n\n printf \"%d\\n\" (score + !best_correction)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet () =\n let k = read_int() in\n let n = read_int() in\n\n let s = Array.init k (fun _ ->\n let str = read_string() in\n let cost = read_int() in\n (str,cost)\n ) in\n\n let h = Hashtbl.create 10 in\n\n let insert (str,cost) = \n let (li,index) = try Hashtbl.find h str with Not_found -> ([], Hashtbl.length h) in\n Hashtbl.replace h str ((cost::li),index)\n in\n\n for i=0 to k-1 do insert s.(i) done;\n\n let rev_string s = String.init n (fun i -> s.[n-i-1]) in\n \n let nstrings = Hashtbl.length h in\n\n let pair = Array.make nstrings (-1) in\n let clist = Array.make nstrings [] in\n\n Hashtbl.iter (fun str (li,index) ->\n clist.(index) <- List.sort (fun a b -> compare b a) li; \n let rstr = rev_string str in\n let (_,rindex) = try Hashtbl.find h rstr with Not_found -> ([], -1) in\n if rindex >= 0 then pair.(index) <- rindex\n ) h;\n\n let best_correction = ref 0 in\n\n let score = sum 0 (nstrings-1) (fun i ->\n let j = pair.(i) in\n if j = -1 then 0\n else if j < i then 0\n else if j > i then ( (* a non-palindrome with a pair *)\n let rec loop l1 l2 ac =\n\tmatch (l1,l2) with\n\t | ([],_) | (_,[]) -> ac\n\t | (c1::t1, c2::t2) ->\n\t if c1+c2 <= 0 then ac\n\t else loop t1 t2 (ac + c1 + c2)\n in\n loop clist.(i) clist.(j) 0\n ) else ( (* a palindrome *)\n let rec loop li rem ac =\n\tmatch li with\n\t | [] -> (ac,rem)\n\t | [c] -> (ac, max rem c)\n\t | c1::(c2::t) ->\n\t if c1+c2 <= 0 then (ac,rem) else\n\t let rem = max rem (-c2) in \n\t loop t rem (ac + c1 + c2)\n in\n let (ac,rem) = loop clist.(i) 0 0 in\n best_correction := max !best_correction rem;\n ac\n )\n )\n in\n\n printf \"%d\\n\" (score + !best_correction)\n"}], "src_uid": "71fbc176f2022365fc10d934807651ab"} {"nl": {"description": "A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.", "input_spec": "The first input line contains the only integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) which represents the number of soldiers in the line. The second line contains integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1,\u2009a2,\u2009...,\u2009an are not necessarily different.", "output_spec": "Print the only integer \u2014 the minimum number of seconds the colonel will need to form a line-up the general will like.", "sample_inputs": ["4\n33 44 11 22", "7\n10 10 58 31 63 40 76"], "sample_outputs": ["2", "10"], "notes": "NoteIn the first sample the colonel will need to swap the first and second soldier and then the third and fourth soldier. That will take 2 seconds. The resulting position of the soldiers is (44, 33, 22, 11).In the second sample the colonel may swap the soldiers in the following sequence: (10, 10, 58, 31, 63, 40, 76) (10, 58, 10, 31, 63, 40, 76) (10, 58, 10, 31, 63, 76, 40) (10, 58, 10, 31, 76, 63, 40) (10, 58, 31, 10, 76, 63, 40) (10, 58, 31, 76, 10, 63, 40) (10, 58, 31, 76, 63, 10, 40) (10, 58, 76, 31, 63, 10, 40) (10, 76, 58, 31, 63, 10, 40) (76, 10, 58, 31, 63, 10, 40) (76, 10, 58, 31, 63, 40, 10) "}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet find_min array l = \n let rec loop min position i =\n if i < l \n then\n let current = array.(i) in\n if current <= min\n then\n loop current i (i + 1)\n else\n loop min position (i + 1)\n else\n position\n in loop array.(0) 0 0\n\nlet find_max array l = \n let rec loop max position i =\n if i < l \n then\n let current = array.(i) in\n if current > max\n then\n loop current i (i + 1)\n else\n loop max position (i + 1)\n else\n position\n in loop array.(0) 0 0\n\nlet solve () = \n let l = read () in\n let line = Array.init l (fun x -> read ()) in\n let min_i = find_min line l in\n let max_i = find_max line l in\n if max_i > min_i\n then\n (l - 1 - min_i) + (max_i - 1)\n else\n (l - 1 - min_i) + max_i\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve ())"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet find_best f array l =\n let rec loop best position i =\n if i < l \n then\n let current = array.(i) in\n if f current best\n then\n loop current i (i + 1)\n else\n loop best position (i + 1)\n else\n position\n in loop array.(0) 0 0\n\nlet find_min = find_best (fun x y -> x <= y)\nlet find_max = find_best (fun x y -> x > y)\n\nlet solve () = \n let l = read () in\n let line = Array.init l (fun x -> read ()) in\n let min_i = find_min line l in\n let max_i = find_max line l in\n if max_i > min_i\n then\n (l - 1 - min_i) + (max_i - 1)\n else\n (l - 1 - min_i) + max_i\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve ())"}, {"source_code": "let rec split s i acc =\nbegin\n if i > String.length s \n then List.rev acc\n else \n let first = \n if String.contains_from s i ' ' \n then String.index_from s i ' ' \n else String.length s \n in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc) \nend in \nlet n = int_of_string(read_line ()) and \n vals = split (read_line ()) 0 [] in \nif n == List.length vals\n then \n let maxval = List.fold_right max (List.tl vals) (List.hd vals) and\n minval = List.fold_right min (List.tl vals) (List.hd vals) in\n if (List.nth vals 0) == maxval && (List.nth vals (n-1)) == minval \n then print_int 0 \n else \n let maxpos = ref (n-1) and \n minpos = ref 0 in begin\n List.iteri (fun a b -> if b ==maxval then maxpos := min !maxpos a \n else if b == minval then minpos := max !minpos a\n else ()) vals;\n print_int (!maxpos + n - 1 - !minpos - (if !maxpos > !minpos then 1 else 0))\n end\n else ()\n\n"}, {"source_code": "let ( |> ) x f = f x\nlet () =\n\tlet n = read_int ()\n\tin let a =\n\t\tread_line ()\n\t\t|> Str.split (Str.regexp \"\\ \")\n\t\t|> List.map int_of_string\n\tin let ((max, left_most_pos), (min, right_most_pos)) =\n\t\tlet rec search sublist_of_a pos =\n\t\t\tmatch sublist_of_a with\n\t\t\t\t| [] -> invalid_arg \"\"\n\t\t\t\t| hd :: [] -> ((hd, pos), (hd, pos))\n\t\t\t\t| hd :: tl ->\n\t\t\t\t\t let ((max, left_most_pos), (min, right_most_pos)) = (search tl (pos + 1))\n\t\t\t\t\t in let (new_max, new_left_most_pos) =\n\t\t\t\t\t\t if hd >= max then\n\t\t\t\t\t\t\t (hd, pos)\n\t\t\t\t\t\t else\n\t\t\t\t\t\t\t (max, left_most_pos)\n\t\t\t\t\t in let (new_min, new_right_most_pos) =\n\t\t\t\t\t\t if hd < min then\n\t\t\t\t\t\t\t (hd, pos)\n\t\t\t\t\t\t else\n\t\t\t\t\t\t\t (min, right_most_pos)\n\t\t\t\t\t in ((new_max, new_left_most_pos), (new_min, new_right_most_pos))\n\t\tin search a 0\n\tin begin\n\t\tif left_most_pos > right_most_pos then\n\t\t\t(left_most_pos + (n - right_most_pos - 2))\n\t\telse\n\t\t\t(left_most_pos + (n - right_most_pos - 1))\n\tend |> print_int; print_newline ()\n"}, {"source_code": "let n = read_int () in\n\nlet arr = Array.init n (fun i ->\n\tScanf.scanf \" %d\" (fun i->i)\n) in\n\nlet maxi = ref 0 in\nlet mini = ref 0 in\nlet _ = Array.iteri (fun i r ->\n\tif r <= arr.(!mini) then mini := i;\n\tif r > arr.(!maxi) then maxi := i\n) arr in\nprint_int (!maxi + (n-1- !mini) - (if !maxi > !mini then 1 else 0)) \n\n"}, {"source_code": "(* codeforces 103. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let n = read_int() in\n let a = Array.make n 0 in\n let () = for i=0 to n-1 do a.(i) <- read_int() done in\n let rec find_max i ac = if i=n then ac else find_max (i+1) (if ac < 0 || a.(i) > a.(ac) then i else ac) in\n let rec find_min i ac = if i=n then ac else find_min (i+1) (if ac < 0 || a.(i) <= a.(ac) then i else ac) in\n let mx = find_max 0 (-1) in\n let mi = find_min 0 (-1) in\n let guess = mx + (n-1-mi) in\n let answer = if mx < mi then guess else guess-1 in\n Printf.printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "let rec split s i acc =\nbegin\n if i > String.length s \n then List.rev acc\n else \n let first = \n if String.contains_from s i ' ' \n then String.index_from s i ' ' \n else String.length s \n in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc) \nend in \nlet n = int_of_string(read_line ()) and \n vals = split (read_line ()) 0 [] in \nif n == List.length vals\n then begin\n let maxval = List.fold_right max (List.tl vals) (List.hd vals) and\n minval = List.fold_right min (List.tl vals) (List.hd vals) in\n let maxpos = ref (n-1) and \n minpos = ref 0 in\n List.iteri (fun a b -> if b ==maxval then maxpos := min !maxpos a \n else if b == minval then minpos := max !minpos a\n else ()) vals;\n print_int (!maxpos + n - 1 - !minpos - (if !maxpos > !minpos then 1 else 0))\n end\n else ()\n\n"}, {"source_code": "let ( |> ) x f = f x\nlet () =\n\tlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d\" (fun x -> x)\n\tin let a =\n\t\tread_line ()\n\t\t|> Str.split (Str.regexp \"\\ \")\n\t\t|> List.map int_of_string\n\tin let ((max, left_most_pos), (min, right_most_pos)) =\n\t\tlet rec search sublist_of_a pos =\n\t\t\tmatch sublist_of_a with\n\t\t\t\t| [] -> invalid_arg \"\"\n\t\t\t\t| hd :: [] -> ((hd, pos), (hd, pos))\n\t\t\t\t| hd :: tl ->\n\t\t\t\t\t let ((max, left_most_pos), (min, right_most_pos)) = (search tl (pos + 1))\n\t\t\t\t\t in let (new_max, new_left_most_pos) =\n\t\t\t\t\t\t if hd >= max then\n\t\t\t\t\t\t\t (hd, pos)\n\t\t\t\t\t\t else\n\t\t\t\t\t\t\t (max, left_most_pos)\n\t\t\t\t\t in let (new_min, new_right_most_pos) =\n\t\t\t\t\t\t if hd < min then\n\t\t\t\t\t\t\t (hd, pos)\n\t\t\t\t\t\t else\n\t\t\t\t\t\t\t (min, right_most_pos)\n\t\t\t\t\t in ((new_max, new_left_most_pos), (new_min, new_right_most_pos))\n\t\tin search a 0\n\tin begin\n\t\tif left_most_pos > right_most_pos then\n\t\t\t(left_most_pos + (n - right_most_pos - 2))\n\t\telse\n\t\t\t(left_most_pos + (n - right_most_pos - 1))\n\tend |> Printf.printf \"%d\\n\"\n"}], "src_uid": "ef9ff63d225811868e786e800ce49c92"} {"nl": {"description": "One day Ms Swan bought an orange in a shop. The orange consisted of n\u00b7k segments, numbered with integers from 1 to n\u00b7k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009k) child wrote the number ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009n\u00b7k). All numbers ai accidentally turned out to be different.Now the children wonder, how to divide the orange so as to meet these conditions: each child gets exactly n orange segments; the i-th child gets the segment with number ai for sure; no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u200930). The second line contains k space-separated integers a1,\u2009a2,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u2009n\u00b7k), where ai is the number of the orange segment that the i-th child would like to get. It is guaranteed that all numbers ai are distinct.", "output_spec": "Print exactly n\u00b7k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces. You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.", "sample_inputs": ["2 2\n4 1", "3 1\n2"], "sample_outputs": ["2 4 \n1 3", "3 2 1"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let k = read_int() in\n let a = Array.init k (fun _ -> -1 + read_int()) in\n\n let b = Array.make (n*k) (-1) in\n\n let ans = Array.make k [] in\n \n for i=0 to k-1 do\n b.(a.(i)) <- i;\n ans.(i) <- [a.(i)]\n done;\n \n let rec loop child count seg = \n if child=k then () \n else if count=n then loop (child+1) 1 seg\n else if b.(seg) >= 0 then loop child count (seg+1)\n else (\n\tb.(seg) <- child;\n\tans.(child) <- seg::(ans.(child));\n\tloop child (count+1) (seg+1)\n )\n in\n \n loop 0 1 0;\n\n for i=0 to k-1 do\n\tList.iter (fun e -> Printf.printf \"%d \" (e+1)) ans.(i);\n\tprint_newline()\n done\n"}], "negative_code": [], "src_uid": "928f18ee5dbf44364c0d578f4317944c"} {"nl": {"description": "Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?", "input_spec": "The first line of input contains an integer t (0\u2009<\u2009t\u2009<\u2009180) \u2014 the number of tests. Each of the following t lines contains a single integer a (0\u2009<\u2009a\u2009<\u2009180) \u2014 the angle the robot can make corners at measured in degrees.", "output_spec": "For each test, output on a single line \"YES\" (without quotes), if the robot can build a fence Emuskald wants, and \"NO\" (without quotes), if it is impossible.", "sample_inputs": ["3\n30\n60\n90"], "sample_outputs": ["NO\nYES\nYES"], "notes": "NoteIn the first test case, it is impossible to build the fence, since there is no regular polygon with angle .In the second test case, the fence is a regular triangle, and in the last test case \u2014 a square."}, "positive_code": [{"source_code": "let read () = Pervasives.read_int ()\nlet print string = Pervasives.print_endline string\n\nlet () =\n let n = read () in\n let rec loop i =\n if i < n\n then\n let angle = read () in\n if 360 mod (180 - angle) = 0\n then\n print \"YES\"\n else\n print \"NO\";\n loop (i + 1)\n else\n ()\n in loop 0"}, {"source_code": "let can x = if 360 mod (180 - x) = 0 then \"YES\\n\" else \"NO\\n\" in\nlet n = read_line () |> int_of_string in\nfor i = 1 to n do\n print_string (read_line () |> int_of_string |> can) \ndone\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\nlet a = Array.make n (-1);;\nlet b = Array.make n (-1);;\n\nlet nd=181\nlet c = Array.make nd 0;; \n\nfor i = 3 to 360 do\n if (360 mod i) = 0 then\n c.(180 - 360/i) <- 1\ndone\n\nfor i = 1 to n do\n let deg = Scanf.scanf \"%d \" ( fun x -> x ) in\n if c.(deg) = 0 then print_endline \"NO\" else print_endline \"YES\"\ndone\n"}, {"source_code": "let ok x =\n let an = 180 - x in\n let n = 360 / an\n in an * n = 360 ;;\n\nlet test_num = read_int()\nin\nfor i = 1 to test_num do\n let x = read_int()\n in\n if (ok x) then\n Printf.printf \"YES\\n\"\n else\n Printf.printf \"NO\\n\"\ndone\n"}], "negative_code": [{"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\nlet a = Array.make n (-1);;\nlet b = Array.make n (-1);;\n\nlet nd=181\nlet c = Array.make nd 0;; \n\nfor i = 3 to 360 do\n c.(180 - 360/i) <- 1\ndone\n\nfor i = 1 to n do\n let deg = Scanf.scanf \"%d \" ( fun x -> x ) in\n if c.(deg) = 0 then print_endline \"NO\" else print_endline \"YES\"\ndone\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet (a,b) = Scanf.scanf \"%d %d \" ( fun x y -> (x,y))\n\n\nlet aa = ref a in\nlet tt = ref a in\nlet () =\n while ( !aa /b > 0 ) do\n tt := !tt + (!aa)/b; aa := (!aa/b) + (!aa mod b)\n done\nin printf \"%d\\n\" !tt\n\n\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\nlet a = Array.make n (-1);;\nlet b = Array.make n (-1);;\n\nlet nd=181\nlet c = Array.make nd 0;; \n\nfor i = 3 to 360 do\n if (360 mod 5) = 0 then\n c.(180 - 360/i) <- 1\ndone\n\nfor i = 1 to n do\n let deg = Scanf.scanf \"%d \" ( fun x -> x ) in\n if c.(deg) = 0 then print_endline \"NO\" else print_endline \"YES\"\ndone\n"}], "src_uid": "9037f487a426ead347baa803955b2c00"} {"nl": {"description": "You are given $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i.\u00a0e. change $$$x \\to (-x)$$$). What is the maximum number of different values in the array you can achieve?", "input_spec": "The first line of input contains one integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$): the number of test cases. The next lines contain the description of the $$$t$$$ test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-100 \\leq a_i \\leq 100$$$).", "output_spec": "For each test case, print one integer: the maximum number of different elements in the array that you can achieve negating numbers in the array.", "sample_inputs": ["3\n4\n1 1 2 2\n3\n1 2 3\n2\n0 0"], "sample_outputs": ["4\n3\n1"], "notes": "NoteIn the first example we can, for example, negate the first and the last numbers, achieving the array $$$[-1, 1, 2, -2]$$$ with four different values.In the second example all three numbers are already different.In the third example negation does not change anything."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet bound = 100\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let a = Array.init n read_int in\n let count = Array.make (bound+1) 0 in\n for i=0 to n-1 do\n let x = abs a.(i) in\n count.(x) <- 1 + count.(x)\n done;\n let answer = sum 1 bound (fun i -> min 2 count.(i)) in\n let answer = answer + (if count.(0) > 0 then 1 else 0) in\n printf \"%d\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "23ef311011b381d0ca2e84bc861f0a31"} {"nl": {"description": "While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1,\u2009a2,\u2009...,\u2009am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1,\u2009f2,\u2009...,\u2009fn of length n and for each number ai got number bi\u2009=\u2009fai. To finish the prank he erased the initial sequence ai.It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the lengths of sequences fi and bi respectively. The second line contains n integers, determining sequence f1,\u2009f2,\u2009...,\u2009fn (1\u2009\u2264\u2009fi\u2009\u2264\u2009n). The last line contains m integers, determining sequence b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009n).", "output_spec": "Print \"Possible\" if there is exactly one sequence ai, such that bi\u2009=\u2009fai for all i from 1 to m. Then print m integers a1,\u2009a2,\u2009...,\u2009am. If there are multiple suitable sequences ai, print \"Ambiguity\". If Spongebob has made a mistake in his calculations and no suitable sequence ai exists, print \"Impossible\".", "sample_inputs": ["3 3\n3 2 1\n1 2 3", "3 3\n1 1 1\n1 1 1", "3 3\n1 2 1\n3 3 3"], "sample_outputs": ["Possible\n3 2 1", "Ambiguity", "Impossible"], "notes": "NoteIn the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique.In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence.In the third sample fi\u2009\u2260\u20093 for all i, so no sequence ai transforms into such bi and we can say for sure that Spongebob has made a mistake."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f) \n\nlet () = \n let n = read_int () in\n let m = read_int () in\n\n let lv = Array.make (n+1) [] in\n for j=1 to n do\n let f = read_int () in\n lv.(f) <- j::lv.(f)\n done;\n\n let b = Array.init m (fun i -> read_int()) in\n\n if exists 0 (m-1) (fun i -> lv.(b.(i)) = []) then printf \"Impossible\\n\" else (\n if maxf 0 (m-1) (fun i -> List.length lv.(b.(i))) > 1 then printf \"Ambiguity\\n\" else (\n printf \"Possible\\n\";\n for i=0 to m-1 do\n\tprintf \"%d \" (List.hd (lv.(b.(i))))\n done;\n print_newline()\n )\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f) \n\nlet () = \n let n = read_int () in\n let m = read_int () in\n\n let lv = Array.make (n+1) [] in\n for j=1 to n do\n let f = read_int () in\n lv.(f) <- j::lv.(f)\n done;\n\n let b = Array.init m (fun i -> read_int()) in\n\n if exists 0 (m-1) (fun i -> lv.(b.(i)) = []) then printf \"Impossible\\n\" else (\n if maxf 0 (m-1) (fun i -> List.length lv.(b.(i))) > 1 then printf \"Ambiguous\\n\" else (\n printf \"Possible\\n\";\n for i=0 to m-1 do\n\tprintf \"%d \" (List.hd (lv.(b.(i))))\n done;\n print_newline()\n )\n )\n"}], "src_uid": "468e8a14dbdca471f143f59b945508d0"} {"nl": {"description": "One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?He needs your help to check it.A Minesweeper field is a rectangle $$$n \\times m$$$, where each cell is either empty, or contains a digit from $$$1$$$ to $$$8$$$, or a bomb. The field is valid if for each cell: if there is a digit $$$k$$$ in the cell, then exactly $$$k$$$ neighboring cells have bombs. if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i.\u00a0e. a cell has at most $$$8$$$ neighboring cells).", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 100$$$) \u2014 the sizes of the field. The next $$$n$$$ lines contain the description of the field. Each line contains $$$m$$$ characters, each of them is \".\" (if this cell is empty), \"*\" (if there is bomb in this cell), or a digit from $$$1$$$ to $$$8$$$, inclusive.", "output_spec": "Print \"YES\", if the field is valid and \"NO\" otherwise. You can choose the case (lower or upper) for each letter arbitrarily.", "sample_inputs": ["3 3\n111\n1*1\n111", "2 4\n*.*.\n1211"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the second example the answer is \"NO\" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.You can read more about Minesweeper in Wikipedia's article."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f) \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet () = \n let n = read_int () in\n let m = read_int () in\n \n let board = Array.init n read_string in\n\n let get i j =\n let x = (board.(i)).[j] in\n if x = '.' then '0' else x\n in\n\n let count_neighbors (i,j) =\n sum (max (i-1) 0) (min (i+1) (n-1)) (fun i ->\n sum (max (j-1) 0) (min (j+1) (m-1)) (fun j ->\n\tif get i j = '*' then 1 else 0\n )\n )\n in\n\n let l2n c = (int_of_char c) - (int_of_char '0') in\n \n let answer = forall 0 (n-1) (fun i ->\n forall 0 (m-1) (fun j ->\n get i j = '*' || count_neighbors (i,j) = l2n (get i j)\n )\n ) in\n\n if answer then printf \"YES\\n\" else printf \"NO\\n\"\n"}], "negative_code": [], "src_uid": "0d586ba7d304902caaeb7cd9e6917cd6"} {"nl": {"description": "Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the imagined circles.Yesterday Ruslan tried to solve this problem for the case when the set of points is considered beautiful if it is given as (xt\u2009=\u2009f(t),\u2009yt\u2009=\u2009g(t)), where argument t takes all integer values from 0 to 50. Moreover, f(t) and g(t) should be correct functions.Assume that w(t) and h(t) are some correct functions, and c is an integer ranging from 0 to 50. The function s(t) is correct if it's obtained by one of the following rules: s(t)\u2009=\u2009abs(w(t)), where abs(x) means taking the absolute value of a number x, i.e. |x|; s(t)\u2009=\u2009(w(t)\u2009+\u2009h(t)); s(t)\u2009=\u2009(w(t)\u2009-\u2009h(t)); s(t)\u2009=\u2009(w(t)\u2009*\u2009h(t)), where \u2009*\u2009 means multiplication, i.e. (w(t)\u00b7h(t)); s(t)\u2009=\u2009c; s(t)\u2009=\u2009t;Yesterday Ruslan thought on and on, but he could not cope with the task. Now he asks you to write a program that computes the appropriate f(t) and g(t) for any set of at most 50 circles.In each of the functions f(t) and g(t) you are allowed to use no more than 50 multiplications. The length of any function should not exceed 100\u00b7n characters. The function should not contain spaces.Ruslan can't keep big numbers in his memory, so you should choose f(t) and g(t), such that for all integer t from 0 to 50 value of f(t) and g(t) and all the intermediate calculations won't exceed 109 by their absolute value.", "input_spec": "The first line of the input contains number n (1\u2009\u2264\u2009n\u2009\u2264\u200950)\u00a0\u2014 the number of circles Ruslan thinks of. Next follow n lines, each of them containing three integers xi, yi and ri (0\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u200950, 2\u2009\u2264\u2009ri\u2009\u2264\u200950)\u00a0\u2014 the coordinates of the center and the raduis of the i-th circle.", "output_spec": "In the first line print a correct function f(t). In the second line print a correct function g(t). The set of the points (xt\u2009=\u2009f(t),\u2009yt\u2009=\u2009g(t)) (0\u2009\u2264\u2009t\u2009\u2264\u200950) must satisfy the condition, that there is at least one point inside or on the border of each of the circles, Ruslan thinks of at the beginning.", "sample_inputs": ["3\n0 10 4\n10 0 4\n20 10 4"], "sample_outputs": ["t \nabs((t-10))"], "notes": "NoteCorrect functions: 10 (1+2) ((t-3)+(t*4)) abs((t-10)) (abs((((23-t)*(t*t))+((45+12)*(t*t))))*((5*t)+((12*t)-13))) abs((t-(abs((t*31))+14))))Incorrect functions: 3+5+7 (not enough brackets, it should be ((3+5)+7) or (3+(5+7))) abs(t-3) (not enough brackets, it should be abs((t-3)) 2+(2-3 (one bracket too many) 1(t+5) (no arithmetic operation between 1 and the bracket) 5000*5000 (the number exceeds the maximum) The picture shows one of the possible solutions"}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let x = Array.make n 0 in\n let y = Array.make n 0 in \n\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n x.(i) <- x.(i) + (x.(i) land 1);\n y.(i) <- y.(i) + (y.(i) land 1); \n ignore (read_int())\n done;\n\n let abs f =\n sprintf \"abs(%s)\" f\n in\n\n let comb f op g =\n sprintf \"(%s%s%s)\" f op g\n in\n\n let rec const k =\n if k < 0 then comb (const 0) \"-\" (const (-k)) else sprintf \"%d\" k\n in\n\n let absdif k =\n abs (comb \"t\" \"-\" (const k))\n in\n\n let basis k =\n let p1 = comb (absdif (k+1)) \"+\" (absdif (k-1)) in\n let p2 = comb (absdif k) \"+\" (absdif k) in\n comb p1 \"-\" p2\n in\n\n let build_function n x =\n let rec loop i ac = if i=n then ac else\n\tlet v = x.(i) in\n\tloop (i+1) (comb ac \"+\" (comb (const (v/2)) \"*\" (basis i)))\n in\n loop 0 \"0\"\n in\n\n printf \"%s\\n\" (build_function n x);\n printf \"%s\\n\" (build_function n y); \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let x = Array.make n 0 in\n let y = Array.make n 0 in \n\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n ignore (read_int())\n done;\n\n let abs f =\n sprintf \"abs(%s)\" f\n in\n\n let comb f op g =\n sprintf \"(%s%s%s)\" f op g\n in\n\n let rec const k =\n sprintf \"%d\" k\n in\n\n let absdif k =\n if k>0 then abs (comb \"t\" \"-\" (const k)) else abs (comb \"t\" \"+\" (const (-k)))\n in\n\n let basis k =\n let p1 = comb (absdif (k+1)) \"-\" (absdif (k-1)) in\n comb \"2\" \"-\" (abs p1)\n in\n\n let build_function n x =\n let rec loop i ac = if i=n then ac else\n\tlet p1 = (comb (const ((x.(i)+1)/2)) \"*\" (basis i)) in\n\tlet ac = if ac=\"\" then p1 else comb p1 \"+\" ac in\n\tloop (i+1) ac\n in\n loop 0 \"\"\n in\n\n printf \"%s\\n\" (build_function n x);\n printf \"%s\\n\" (build_function n y); \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let x = Array.make n 0 in\n let y = Array.make n 0 in \n\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n x.(i) <- x.(i) + (x.(i) land 1);\n y.(i) <- y.(i) + (y.(i) land 1); \n ignore (read_int())\n done;\n\n let abs f =\n sprintf \"abs(%s)\" f\n in\n\n let comb f op g =\n sprintf \"(%s%s%s)\" f op g\n in\n\n let rec const k =\n if k < 0 then comb (const 0) \"-\" (const (-k)) else sprintf \"%d\" k\n in\n\n let absdif k =\n abs (comb \"t\" \"-\" (const k))\n in\n\n let basis k =\n let p1 = comb (absdif (k+1)) \"+\" (absdif (k-1)) in\n let p2 = comb (absdif k) \"+\" (absdif k) in\n comb p1 \"-\" p2\n in\n\n let build_function n x =\n let rec loop i ac = if i=n then ac else\n\tlet v = x.(i) in\n\tloop (i+1) (comb ac \"+\" (comb (const (v/2)) \"*\" (basis i)))\n in\n loop 0 \"0\"\n in\n\n printf \"%s\\n\" (build_function n x);\n printf \"%s\\n\" (build_function n y); \n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let x = Array.make n 0 in\n let y = Array.make n 0 in \n\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n x.(i) <- x.(i) + (x.(i) land 1);\n y.(i) <- y.(i) + (y.(i) land 1); \n ignore (read_int())\n done;\n\n let abs f =\n sprintf \"abs(%s)\" f\n in\n\n let comb f op g =\n sprintf \"(%s%s%s)\" f op g\n in\n\n let const k =\n sprintf \"%d\" k\n in\n\n let absdif k =\n abs (comb \"t\" \"-\" (const k))\n in\n\n let basis k =\n let p1 = comb (absdif (k+1)) \"+\" (absdif (k-1)) in\n let p2 = comb \"2\" \"*\" (absdif k) in\n comb p1 \"-\" p2\n in\n\n let build_function n x =\n let rec loop i ac = if i=n then ac else\n\tlet v = x.(i) in\n\tloop (i+1) (comb ac \"+\" (comb (const (v/2)) \"*\" (basis i)))\n in\n loop 0 \"0\"\n in\n\n printf \"%s\\n\" (build_function n x);\n printf \"%s\\n\" (build_function n y); \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let x = Array.make n 0 in\n let y = Array.make n 0 in \n\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n x.(i) <- x.(i) + (x.(i) land 1);\n y.(i) <- y.(i) + (y.(i) land 1); \n ignore (read_int())\n done;\n\n let abs f =\n sprintf \"abs(%s)\" f\n in\n\n let comb f op g =\n sprintf \"(%s%s%s)\" f op g\n in\n\n let const k =\n sprintf \"%d\" k\n in\n\n let absdif k =\n abs (comb \"t\" \"-\" (const k))\n in\n\n let basis k =\n let p1 = comb (absdif (k+1)) \"+\" (absdif (k-1)) in\n let p2 = comb (absdif k) \"+\" (absdif k) in\n comb p1 \"-\" p2\n in\n\n let build_function n x =\n let rec loop i ac = if i=n then ac else\n\tlet v = x.(i) in\n\tloop (i+1) (comb ac \"+\" (comb (const (v/2)) \"*\" (basis (i+1))))\n in\n loop 0 \"0\"\n in\n\n printf \"%s\\n\" (build_function n x);\n printf \"%s\\n\" (build_function n y); \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let x = Array.make n 0 in\n let y = Array.make n 0 in \n\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n x.(i) <- x.(i) + (x.(i) land 1);\n y.(i) <- y.(i) + (y.(i) land 1); \n ignore (read_int())\n done;\n\n let abs f =\n sprintf \"abs(%s)\" f\n in\n\n let comb f op g =\n sprintf \"(%s%s%s)\" f op g\n in\n\n let const k =\n sprintf \"%d\" k\n in\n\n let absdif k =\n abs (comb \"t\" \"-\" (const k))\n in\n\n let basis k =\n let p1 = comb (absdif (k+1)) \"-\" (absdif (k-1)) in\n let p2 = comb \"2\" \"*\" (absdif k) in\n comb p1 \"-\" p2\n in\n\n let build_function n x =\n let rec loop i ac = if i=n then ac else\n\tlet v = x.(i) in\n\tloop (i+1) (comb ac \"+\" (comb (const (v/2)) \"*\" (basis v)))\n in\n loop 0 \"0\"\n in\n\n printf \"%s\\n\" (build_function n x);\n printf \"%s\\n\" (build_function n y); \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let x = Array.make n 0 in\n let y = Array.make n 0 in \n\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n x.(i) <- x.(i) + (x.(i) land 1);\n y.(i) <- y.(i) + (y.(i) land 1); \n ignore (read_int())\n done;\n\n let abs f =\n sprintf \"abs(%s)\" f\n in\n\n let comb f op g =\n sprintf \"(%s%s%s)\" f op g\n in\n\n let const k =\n sprintf \"%d\" k\n in\n\n let absdif k =\n abs (comb \"t\" \"-\" (const k))\n in\n\n let basis k =\n let p1 = comb (absdif (k+1)) \"+\" (absdif (k-1)) in\n let p2 = comb \"2\" \"*\" (absdif k) in\n comb p1 \"-\" p2\n in\n\n let build_function n x =\n let rec loop i ac = if i=n then ac else\n\tlet v = x.(i) in\n\tloop (i+1) (comb ac \"+\" (comb (const (v/2)) \"*\" (basis v)))\n in\n loop 0 \"0\"\n in\n\n printf \"%s\\n\" (build_function n x);\n printf \"%s\\n\" (build_function n y); \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let x = Array.make n 0 in\n let y = Array.make n 0 in \n\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n x.(i) <- x.(i) + (x.(i) land 1);\n y.(i) <- y.(i) + (y.(i) land 1); \n ignore (read_int())\n done;\n\n let abs f =\n sprintf \"abs(%s)\" f\n in\n\n let comb f op g =\n sprintf \"(%s%s%s)\" f op g\n in\n\n let const k =\n sprintf \"%d\" k\n in\n\n let absdif k =\n abs (comb \"t\" \"-\" (const k))\n in\n\n let basis k =\n let p1 = comb (absdif (k+1)) \"+\" (absdif (k-1)) in\n let p2 = comb (absdif k) \"+\" (absdif k) in\n comb p1 \"-\" p2\n in\n\n let build_function n x =\n let rec loop i ac = if i=n then ac else\n\tlet v = x.(i) in\n\tloop (i+1) (comb ac \"+\" (comb (const (v/2)) \"*\" (basis i)))\n in\n loop 0 \"0\"\n in\n\n printf \"%s\\n\" (build_function n x);\n printf \"%s\\n\" (build_function n y); \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let x = Array.make n 0 in\n let y = Array.make n 0 in \n\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n x.(i) <- x.(i) + (x.(i) land 1);\n y.(i) <- y.(i) + (y.(i) land 1); \n ignore (read_int())\n done;\n\n let abs f =\n sprintf \"abs(%s)\" f\n in\n\n let comb f op g =\n sprintf \"(%s%s%s)\" f op g\n in\n\n let const k =\n sprintf \"%d\" k\n in\n\n let absdif k =\n abs (comb \"t\" \"-\" (const k))\n in\n\n let basis k =\n let p1 = comb (absdif (k+1)) \"+\" (absdif (k-1)) in\n let p2 = comb \"2\" \"*\" (absdif k) in\n comb p1 \"-\" p2\n in\n\n let build_function n x =\n let rec loop i ac = if i=n then ac else\n\tlet v = x.(i) in\n\tloop (i+1) (comb ac \"+\" (comb (const (v/2)) \"*\" (basis (i+1))))\n in\n loop 0 \"0\"\n in\n\n printf \"%s\\n\" (build_function n x);\n printf \"%s\\n\" (build_function n y); \n"}], "src_uid": "79c337ca7397eac500ca8e6693f83fb6"} {"nl": {"description": "Little Petya is now fond of data compression algorithms. He has already studied gz, bz, zip algorithms and many others. Inspired by the new knowledge, Petya is now developing the new compression algorithm which he wants to name dis.Petya decided to compress tables. He is given a table a consisting of n rows and m columns that is filled with positive integers. He wants to build the table a' consisting of positive integers such that the relative order of the elements in each row and each column remains the same. That is, if in some row i of the initial table ai,\u2009j\u2009<\u2009ai,\u2009k, then in the resulting table a'i,\u2009j\u2009<\u2009a'i,\u2009k, and if ai,\u2009j\u2009=\u2009ai,\u2009k then a'i,\u2009j\u2009=\u2009a'i,\u2009k. Similarly, if in some column j of the initial table ai,\u2009j\u2009<\u2009ap,\u2009j then in compressed table a'i,\u2009j\u2009<\u2009a'p,\u2009j and if ai,\u2009j\u2009=\u2009ap,\u2009j then a'i,\u2009j\u2009=\u2009a'p,\u2009j. Because large values require more space to store them, the maximum value in a' should be as small as possible.Petya is good in theory, however, he needs your help to implement the algorithm.", "input_spec": "The first line of the input contains two integers n and m (, the number of rows and the number of columns of the table respectively. Each of the following n rows contain m integers ai,\u2009j (1\u2009\u2264\u2009ai,\u2009j\u2009\u2264\u2009109) that are the values in the table.", "output_spec": "Output the compressed table in form of n lines each containing m integers. If there exist several answers such that the maximum number in the compressed table is minimum possible, you are allowed to output any of them.", "sample_inputs": ["2 2\n1 2\n3 4", "4 3\n20 10 30\n50 40 30\n50 60 70\n90 80 70"], "sample_outputs": ["1 2\n2 3", "2 1 3\n5 4 3\n5 6 7\n9 8 7"], "notes": "NoteIn the first sample test, despite the fact a1,\u20092\u2009\u2260\u2009a21, they are not located in the same row or column so they may become equal after the compression."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n let a = Array.make_matrix n m 0 in\n for i=0 to n-1 do\n for j=0 to m-1 do\n a.(i).(j) <- read_int()\n done\n done;\n\n let graph = Array.make_matrix n m [] in\n\n let add_edge x (i,j) h =\n try\n let (i',j') = Hashtbl.find h x in\n graph.(i').(j') <- (i,j)::graph.(i').(j');\n graph.(i).(j) <- (i',j')::graph.(i).(j);\n with Not_found ->\n Hashtbl.add h x (i,j)\n in\n \n for i=0 to n-1 do\n let row = Hashtbl.create 10 in\n for j=0 to m-1 do\n add_edge a.(i).(j) (i,j) row\n done\n done;\n\n for j=0 to m-1 do\n let col = Hashtbl.create 10 in\n for i=0 to n-1 do\n add_edge a.(i).(j) (i,j) col\n done\n done;\n\n let visited = Array.make_matrix n m false in\n let vis (i,j) = visited.(i).(j) in\n let mark (i,j) = visited.(i).(j) <- true in\n let gr (i,j) = graph.(i).(j) in\n let geta (i,j) = a.(i).(j) in\n \n let rec dfs ac v =\n if vis v then ac else (\n mark v;\n List.fold_left dfs (v::ac) (gr v)\n )\n in\n\n let next (i,j) = if j compare (geta (List.hd c1)) (geta (List.hd c2))\n ) comps\n in\n\n let row_max = Array.make n 0 in\n let col_max = Array.make m 0 in\n\n let answer = Array.make_matrix n m 0 in\n \n List.iter (fun li ->\n let mval = List.fold_left (fun ac (i,j) ->\n max ac (max row_max.(i) col_max.(j))\n ) 0 li in\n List.iter (fun (i,j) ->\n answer.(i).(j) <- mval+1; \n row_max.(i) <- mval+1;\n col_max.(j) <- mval+1; \n ) li\n ) comps;\n \n for i=0 to n-1 do\n for j=0 to m-1 do\n printf \"%d \" answer.(i).(j);\n done;\n print_newline()\n done;\n"}], "negative_code": [], "src_uid": "fffc745ca0fbbdb698520b0674beb22a"} {"nl": {"description": "A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values \u2014 the start time li and the finish time ri (li\u2009\u2264\u2009ri).Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept?No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.", "input_spec": "The first line contains integer number n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105) \u2014 number of orders. The following n lines contain integer values li and ri each (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109).", "output_spec": "Print the maximal number of orders that can be accepted.", "sample_inputs": ["2\n7 11\n4 7", "5\n1 2\n2 3\n3 4\n4 5\n5 6", "6\n4 8\n1 5\n4 7\n2 5\n1 3\n6 8"], "sample_outputs": ["1", "3", "2"], "notes": null}, "positive_code": [{"source_code": "open Array;;\nopen Str;;\nlet n = read_int () and ans = ref 0;; \nlet par = make n [|0; 0|] and right = ref (-1);;\nfor i = 1 to n do set par (i - 1) (of_list (List.map (int_of_string) (split (regexp \" \") (read_line ())))) done;;\nlet cmp [|a; b|] [|c; d|] = (if b < d then -1 else 1);;\nsort (cmp) par;;\nfor i = 0 to n - 1 do if par.(i).(0) > !right then begin\n\tright := par.(i).(1);\t\t\n\tans := !ans + 1;\nend done;;\nprint_int !ans\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make (2 * n) (0, 0, 0) in\n let ll = Array.make n 0 in\n for i = 0 to n - 1 do\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(2 * i) <- (l, 0, i);\n\ta.(2 * i + 1) <- (r, 1, i);\n\tll.(i) <- l;\n done;\n Array.sort compare a;\n let res = ref 0 in\n let s = ref [] in\n let tt = ref (-1) in\n for i = 0 to 2 * n - 1 do\n\tlet (t, k, x) = a.(i) in\n\t if k = 0\n\t then ()\n\t else (\n\t if ll.(x) > !tt then (\n\t incr res;\n\t tt := t;\n\t )\n\t )\n done;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [{"source_code": "open Array;;\nopen Str;;\nlet n = read_int () and ans = ref 0;; \nlet par = make n [|0; 0|] and right = ref (-1);;\nfor i = 1 to n do set par (i - 1) (of_list (List.map (int_of_string) (split (regexp \" \") (read_line ())))) done;;\nlet cmp [|a; b|] [|c; d|] = (if b < d then -1 else 1);;\nsort (cmp) par;;\nfor i = 0 to n - 1 do Printf.printf \"%d %d\\n\" par.(i).(0) par.(i).(1) done;;\nfor i = 0 to n - 1 do if par.(i).(0) > !right then begin\n\tright := par.(i).(1);\t\t\n\tans := !ans + 1;\nend done;;\nprint_int !ans\n"}], "src_uid": "73e8984cceded15027c4ab89c5624a92"} {"nl": {"description": "Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.", "input_spec": "The first line contains two integers, n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009m\u2009\u2264\u2009n) \u2014 the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n\u2009-\u20091 lines contains the edges of the tree in the format \"xi yi\" (without the quotes) (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, xi\u2009\u2260\u2009yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree.", "output_spec": "A single integer \u2014 the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.", "sample_inputs": ["4 1\n1 1 0 0\n1 2\n1 3\n1 4", "7 1\n1 0 1 1 0 0 0\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7"], "sample_outputs": ["2", "2"], "notes": "NoteLet us remind you that a tree is a connected graph on n vertices and n\u2009-\u20091 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7."}, "positive_code": [{"source_code": "let main () =\n\tlet (n,m) = Scanf.scanf \"%d %d\" (fun i j -> (i,j)) in\n\tlet grph = Array.make n [] and cats = Array.make n false \n\tand visited = Array.make n false in\n\t\tfor i=0 to n-1 do\n\t\t\tScanf.scanf \" %d\" (fun j -> if j = 1\n\t\t\t\t\t\tthen cats.(i) <- true);\n\t\tdone;\n\t\tfor k=1 to n-1 do\n\t\t\tScanf.scanf \" %d %d\" (fun i j ->\n\t\t\tlet (i',j') = (i-1,j-1) in\n\t\t\t\tgrph.(i') <- j'::grph.(i');\n\t\t\t\tgrph.(j') <- i'::grph.(j'));\n\t\tdone;\n\tlet rec construct cats_atm i =\n\t\tvisited.(i) <- true;\n\t\tif cats_atm = m && cats.(i)\n\t\t\tthen 0\n\t\t\telse let l = List.filter (fun i -> not (visited.(i))) (grph.(i)) in\n\t\t\t\tif List.length l = 0\n\t\t\t\t\tthen 1\n\t\t\t\t\telse let l' = List.map (construct (if cats.(i) then cats_atm + 1 else 0)) l in\n\t\t\t\t\t\tList.fold_left (+) 0 l'\n\tin Printf.printf \"%d\" (construct 0 0);;\n\nmain ();;\n"}], "negative_code": [], "src_uid": "875e7048b7a254992b9f62b9365fcf9b"} {"nl": {"description": "Eugeny has array a\u2009=\u2009a1,\u2009a2,\u2009...,\u2009an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries: Query number i is given as a pair of integers li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n). The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali\u2009+\u2009ali\u2009+\u20091\u2009+\u2009...\u2009+\u2009ari\u2009=\u20090, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries.", "input_spec": "The first line contains integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105). The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (ai\u2009=\u2009-1,\u20091). Next m lines contain Eugene's queries. The i-th line contains integers li,\u2009ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n).", "output_spec": "Print m integers \u2014 the responses to Eugene's queries in the order they occur in the input.", "sample_inputs": ["2 3\n1 -1\n1 1\n1 2\n2 2", "5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5"], "sample_outputs": ["0\n1\n0", "0\n1\n0\n1\n0"], "notes": null}, "positive_code": [{"source_code": "open List\nopen Printf\nopen Scanf\nopen String\n\nlet inf= 1070000000;;\n\nlet rec getlist n =\n\tif n=0 then []\n\telse scanf \" %d\" (fun x->x)::getlist (n-1);;\n\nlet rec getplist n =\n\tif n=0 then []\n\telse scanf \" %d %d\" (fun x y->(x,y))::getplist (n-1);;\n\nlet is1 x =\n\tif x=1 then 1\n\telse 0;;\n\nlet rec count1 a =\n\tif a=[] then 0\n\telse is1 (hd a) + count1 (tl a);;\n\nlet ans plus minus l r =\n\tlet len = r-l+1 in\n\tif len mod 2 = 0 && min plus minus >= len/2\n\t\tthen 1\n\telse 0;;\n\nlet rec solve plus minus lr =\n\tif lr <> [] then begin\n\t\tprintf \"%d\\n\" (ans plus minus (fst (hd lr)) (snd (hd lr)));\n\t\tsolve plus minus (tl lr)\n\tend;;\n\nlet n = scanf \" %d\" (fun x->x)\nin let m = scanf \" %d\" (fun x->x)\nin let a = getlist n\nin let plus = count1 a\nin let minus = n-plus\nin let lr = rev (getplist m)\nin solve plus minus lr;;\n\n"}], "negative_code": [{"source_code": "open List\nopen Printf\nopen Scanf\nopen String\n\nlet inf= 1070000000;;\n\nlet rec getlist n =\n\tif n=0 then []\n\telse scanf \" %d\" (fun x->x)::getlist (n-1);;\n\nlet rec getplist n =\n\tif n=0 then []\n\telse scanf \" %d %d\" (fun x y->(x,y))::getplist (n-1);;\n\nlet is1 x =\n\tif x=1 then 1\n\telse 0;;\n\nlet rec count1 a =\n\tif a=[] then 0\n\telse is1 (hd a) + count1 (tl a);;\n\nlet ans plus minus l r =\n\tlet len = r-l+1 in\n\tif len mod 2 = 0 && min plus minus >= len/2\n\t\tthen \"1\\n\"\n\t\telse \"0\\n\";;\n\nlet rec solve plus minus lr =\n\tif lr = [] then \"\"\n\telse\n\t\tans plus minus (fst (hd lr)) (snd (hd lr)) ^ solve plus minus (tl lr);;\t\t\n\nlet n = scanf \" %d\" (fun x->x)\nin let m = scanf \" %d\" (fun x->x)\nin let a = getlist n\nin let plus = count1 a\nin let minus = n-plus\nin let lr = getplist m\nin printf \"%s\" (solve plus minus lr);;\n\n"}], "src_uid": "deeb49969ac4bc4f1c7d76b89ac1402f"} {"nl": {"description": "Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place: A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars. Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it. Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally.", "input_spec": "The first input line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0\u2009\u2264\u2009x\u2009\u2264\u20092000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0\u2009\u2264\u2009x\u2009\u2264\u20092000).", "output_spec": "Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.", "sample_inputs": ["7\nwin 10\nwin 5\nwin 3\nsell 5\nsell 3\nwin 10\nsell 10", "3\nwin 5\nsell 6\nsell 4"], "sample_outputs": ["1056", "0"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\n\nlet base = 100000000\nlet base_digits = 8\n\nlet () =\n let n = read_int 0 in\n let a = Array.make (max n 700) (-1) in\n let b = ref [] in\n for i = 0 to n-1 do\n let op = read_str 0 in\n let x = read_int 0 in\n if op.[0] = 'w' then\n a.(i) <- x\n else (\n b := (x,i)::!b;\n )\n done;\n\n let mask = Array.make 2001 false in\n List.sort compare !b |> List.rev |> List.iter (fun (lv,x) ->\n let rec go j =\n if j >= 0 && a.(j) <> (-2) then\n if a.(j) = lv then (\n Array.fill a j (x-j+1) (-2);\n mask.(lv) <- true\n ) else\n go (j-1)\n in\n go x\n );\n\n let m = ref 1 in\n a.(0) <- 0;\n for i = 2001-1 downto 0 do\n let rec go c j =\n if j < !m then (\n let t = a.(j)*2+c in\n a.(j) <- t mod base;\n go (t/base) (j+1)\n ) else if c > 0 then (\n a.(j) <- c;\n !m+1\n ) else\n !m\n in\n m := go (if mask.(i) then 1 else 0) 0;\n done;\n\n Printf.printf \"%d\" a.(!m-1);\n for i = !m-2 downto 0 do\n Printf.printf \"%0*d\" base_digits a.(i)\n done;\n print_char '\\n'\n"}], "negative_code": [], "src_uid": "217a3a48b927213f4d5e0a19048e2a32"} {"nl": {"description": "ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b\u2009-\u2009a\u2009\u2264\u2009c, just the new word is appended to other words on the screen. If b\u2009-\u2009a\u2009>\u2009c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c\u2009=\u20095 and you typed words at seconds 1,\u20093,\u20098,\u200914,\u200919,\u200920 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.", "input_spec": "The first line contains two integers n and c (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009c\u2009\u2264\u2009109)\u00a0\u2014 the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009t1\u2009<\u2009t2\u2009<\u2009...\u2009<\u2009tn\u2009\u2264\u2009109), where ti denotes the second when ZS the Coder typed the i-th word.", "output_spec": "Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.", "sample_inputs": ["6 5\n1 3 8 14 19 20", "6 1\n1 3 5 7 9 10"], "sample_outputs": ["3", "2"], "notes": "NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3\u2009-\u20091\u2009>\u20091. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10\u2009-\u20099\u2009\u2264\u20091."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet make_list n =\n let rec loop i list =\n if i < n\n then\n let value = read () in\n loop (i + 1) (value :: list)\n else\n List.rev list\n in loop 0 []\n\nlet counter count max_delay diff =\n if diff <= max_delay\n then\n count + 1\n else\n 1\n\nlet input () = \n let n = read () in\n let delay = read () in\n let seconds = make_list n in\n (delay, seconds)\n\nlet solve (delay, seconds) =\n let rec loop prev rest count =\n match rest with\n | (head :: tail) -> loop head tail (counter count delay (head - prev))\n | [] -> count\n in loop 0 seconds 0\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "\n\nlet read_nums () = \n let s = read_line () in\n let nums = List.map int_of_string (Str.split (Str.regexp \" \") s) in\n nums\n\n;;\n\n\nlet rec get_ans c lst acc prev= \n match lst with\n | hd :: tl -> if (hd - prev <= c) then\n get_ans c tl (acc + 1) hd\n else\n get_ans c tl 1 hd\n | [] -> let () = print_int acc in print_string \"\\n\"\n\n\nlet main () =\n let l = read_nums () in\n match l with\n | [n; c] -> (get_ans c (read_nums ())) 0 0\n | _ -> ()\n;;\n\nmain () ;;\n\n\n\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let c = read_int () in\n let time_arr = Array.init n (fun _ ->\n read_int ()\n )\n in\n let counter = ref 1 in\n for i = 0 to n - 2 do\n if time_arr.(i+1) - time_arr.(i) <= c then\n counter := !counter + 1\n else counter := 1\n done;\n Printf.printf \"%d\" !counter\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet rec calc a i cur n c = if (i = n) then cur\nelse if (a.(i) - a.(i - 1) > c) then calc a (i + 1) 1 n c \nelse calc a (i + 1) (cur + 1) n c;;\n\nlet readInt () = scanf \" %d \" (fun x -> x)\n\nlet a = \nlet answer = \nlet n = readInt () in\nlet c = readInt () in \nlet a = Array.init n (fun y -> readInt ()) in\ncalc a 1 1 n c\nin printf \"%d\\n\" answer;;"}, {"source_code": "open Scanf\nopen Printf\n\nlet rec calc a i cur n c = if (i = n) then cur\nelse if (a.(i) - a.(i - 1) > c) then calc a (i + 1) 1 n c \nelse calc a (i + 1) (cur + 1) n c;;\n\nlet a = \nlet answer = \nlet n = scanf \" %d \" (fun x-> x) in\nlet c = scanf \" %d \" (fun x-> x) in \nlet a = Array.init n (fun y -> scanf \" %d \" (fun x -> x)) in\ncalc a 1 1 n c\nin printf \"%d\\n\" answer;;\n"}], "negative_code": [], "src_uid": "fb58bc3be4a7a78bdc001298d35c6b21"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\ldots, a_n$$$ consisting of $$$n$$$ positive integers and a positive integer $$$m$$$.You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.Let's call an array $$$m$$$-divisible if for each two adjacent numbers in the array (two numbers on the positions $$$i$$$ and $$$i+1$$$ are called adjacent for each $$$i$$$) their sum is divisible by $$$m$$$. An array of one element is $$$m$$$-divisible.Find the smallest number of $$$m$$$-divisible arrays that $$$a_1, a_2, \\ldots, a_n$$$ is possible to divide into.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 1000)$$$ \u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \\le n \\le 10^5, 1 \\le m \\le 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ $$$(1 \\le a_i \\le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.", "output_spec": "For each test case print the answer to the problem.", "sample_inputs": ["4\n6 4\n2 2 8 6 9 4\n10 8\n1 1 1 5 2 4 4 8 6 7\n1 1\n666\n2 2\n2 4"], "sample_outputs": ["3\n6\n1\n1"], "notes": "NoteIn the first test case we can divide the elements as follows: $$$[4, 8]$$$. It is a $$$4$$$-divisible array because $$$4+8$$$ is divisible by $$$4$$$. $$$[2, 6, 2]$$$. It is a $$$4$$$-divisible array because $$$2+6$$$ and $$$6+2$$$ are divisible by $$$4$$$. $$$[9]$$$. It is a $$$4$$$-divisible array because it consists of one element. "}, "positive_code": [{"source_code": "(* https://codeforces.com/contest/1497/problem/B *)\n\nlet make_hist modulo arr =\n let histo = Array.make modulo 0 in\n List.iter\n (fun e -> histo.(e) <- histo.(e) + 1)\n arr;\n histo\n\nlet marrays m l =\n let even = m mod 2 = 0 in\n let modulos = \n List.map (fun e -> Int64.rem e (Int64.of_int m) |> Int64.to_int)\n l in\n let histo = make_hist m modulos and\n last_i = (if even then m / 2 - 1 else m / 2) in\n let rec pair_modulos i nb_arrays =\n if i > last_i\n then nb_arrays\n else\n let min_amount = min histo.(i) histo.(m-i) and\n max_amount = max histo.(i) histo.(m-i) in\n if max_amount = min_amount && max_amount <> 0\n then pair_modulos (i+1) (nb_arrays+1)\n else pair_modulos (i+1) (nb_arrays+(max_amount-min_amount)) in\n let nb_arrays = ref 0 in\n nb_arrays := !nb_arrays + (if histo.(0) > 0 then 1 else 0);\n nb_arrays := !nb_arrays + (if even && histo.(m/2) > 0 then 1 else 0);\n nb_arrays := !nb_arrays + (pair_modulos 1 0);\n !nb_arrays\n\nlet read_case () =\n let [_; m] = \n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n let nums =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map Int64.of_string in\n m, nums\n\nlet rec solve_n n =\n if n <> 0\n then \n let m, nums = read_case () in\n let _ = marrays m nums\n |> Printf.printf \"%d\\n\" in\n solve_n (n-1)\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "negative_code": [{"source_code": "(* https://codeforces.com/contest/1497/problem/B *)\n\nlet make_hist modulo arr =\n let histo = Array.make modulo 0 in\n List.iter\n (fun e -> histo.(e) <- histo.(e) + 1)\n arr;\n histo\n\nlet marrays m l =\n let even = m mod 2 = 0 in\n let modulos = \n List.map (fun e -> Int64.rem e (Int64.of_int m) |> Int64.to_int)\n l in\n let histo = make_hist m modulos and\n last_i = (if even then m / 2 - 1 else m / 2) in\n let rec pair_modulos i nb_arrays =\n if i > last_i\n then nb_arrays\n else\n let min_amount = min histo.(i) histo.(m-i) in\n let _ = histo.(i) <- histo.(i) - (min_amount+1) and\n _ = histo.(m-i) <- histo.(m-i) - (min_amount+1) in\n pair_modulos (i+1) (nb_arrays+1) in\n let nb_arrays = ref 0 in\n nb_arrays := !nb_arrays + (if histo.(0) > 0 then 1 else 0);\n nb_arrays := !nb_arrays + (if even && histo.(m/2) > 0 then 1 else 0);\n nb_arrays := !nb_arrays + (pair_modulos 1 0);\n Array.iteri \n (fun i e ->\n if i = 0\n then ()\n else if even && i = m / 2\n then ()\n else if e > 0\n then nb_arrays := !nb_arrays + e)\n histo;\n !nb_arrays\n\nlet read_case () =\n let [_; m] = \n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n let nums =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map Int64.of_string in\n m, nums\n\nlet rec solve_n n =\n if n <> 0\n then \n let m, nums = read_case () in\n let _ = marrays m nums\n |> Printf.printf \"%d\\n\" in\n solve_n (n-1)\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "src_uid": "d107db1395ded62904d0adff164e5c1e"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$ both consisting of $$$n$$$ positive (greater than zero) integers. You are also given an integer $$$k$$$.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$) and swap $$$a_i$$$ and $$$b_j$$$ (i.e. $$$a_i$$$ becomes $$$b_j$$$ and vice versa). Note that $$$i$$$ and $$$j$$$ can be equal or different (in particular, swap $$$a_2$$$ with $$$b_2$$$ or swap $$$a_3$$$ and $$$b_9$$$ both are acceptable moves).Your task is to find the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ such moves (swaps).You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 30; 0 \\le k \\le n$$$) \u2014 the number of elements in $$$a$$$ and $$$b$$$ and the maximum number of moves you can do. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 30$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le 30$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$.", "output_spec": "For each test case, print the answer \u2014 the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ swaps.", "sample_inputs": ["5\n2 1\n1 2\n3 4\n5 5\n5 5 6 6 5\n1 2 5 4 3\n5 3\n1 2 3 4 5\n10 9 10 10 9\n4 0\n2 2 4 3\n2 4 2 3\n4 4\n1 2 2 1\n4 4 5 4"], "sample_outputs": ["6\n27\n39\n11\n17"], "notes": "NoteIn the first test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_2 = 4$$$, so $$$a=[4, 2]$$$ and $$$b=[3, 1]$$$.In the second test case of the example, you don't need to swap anything.In the third test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_1 = 10$$$, $$$a_3 = 3$$$ and $$$b_3 = 10$$$ and $$$a_2 = 2$$$ and $$$b_4 = 10$$$, so $$$a=[10, 10, 10, 4, 5]$$$ and $$$b=[1, 9, 3, 2, 9]$$$.In the fourth test case of the example, you cannot swap anything.In the fifth test case of the example, you can swap arrays $$$a$$$ and $$$b$$$, so $$$a=[4, 4, 5, 4]$$$ and $$$b=[1, 2, 2, 1]$$$."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet rec read_list = function\n| 0 -> []\n| n -> read() :: read_list (n - 1)\nin\n\nlet rec print_list = function\n| [] -> ()\n| x :: r -> print_int x; print_newline (); print_list r\nin\n\nlet rec biggest_sum a b nb = function\n| 0 -> 0\n| n -> if List.hd a < List.hd b && nb != 0 then\n (List.hd b) + (biggest_sum a (List.tl b) (nb - 1) (n - 1))\n else\n (List.hd a) + (biggest_sum (List.tl a) b nb (n - 1))\nin\n\nlet nbTests = read () in\nfor iTest = 1 to nbTests do\n let nbElems = read () in\n let nbEchanges = read () in\n let a = List.rev (List.sort (-) (read_list nbElems)) in\n let b = List.rev (List.sort (-) (read_list nbElems)) in\n \n print_int (biggest_sum a b nbEchanges nbElems);\n print_newline ()\ndone;"}], "negative_code": [], "src_uid": "7c2337c1575b4a62e062fc9990c0b098"} {"nl": {"description": "You are given two very long integers a,\u2009b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().", "input_spec": "The first line contains a non-negative integer a. The second line contains a non-negative integer b. The numbers a,\u2009b may contain leading zeroes. Each of them contains no more than 106 digits.", "output_spec": "Print the symbol \"<\" if a\u2009<\u2009b and the symbol \">\" if a\u2009>\u2009b. If the numbers are equal print the symbol \"=\".", "sample_inputs": ["9\n10", "11\n10", "00012345\n12345", "0123\n9", "0123\n111"], "sample_outputs": ["<", ">", "=", ">", ">"], "notes": null}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet sprawdz n a = (* czy jest jakis niezerowy *)\n let koniec = ref false in\n for i=0 to n do\n if a.[i] <> '0' then koniec := true\n done;\n !koniec;;\n\nlet rec porownaj ax bx a b =\n if ax = String.length a then '='\n else if a.[ax] = b.[bx] then porownaj (ax+1) (bx+1) a b\n else if a.[ax] < b.[bx] then '<'\n else '>';;\n\nlet check a b =\n let n = String.length a\n and m = String.length b in\n if sprawdz (n-m-1) a then '>'\n else if sprawdz (m-n-1) b then '<'\n else\n let ax = max 0 (n-m)\n and bx = max 0 (m-n) in\n porownaj ax bx a b;;\n\nlet _ = \n let (a,b) = Scanf.scanf \"%s\\n%s\\n\" (fun x y -> x, y) in\n Printf.printf \"%c\\n\" (check a b) ;;\n\n\n"}, {"source_code": "let xstr() = Scanf.scanf \"%s \" (fun x -> x)\n\nlet () = \n let s = xstr() and t = xstr() in\n let n = String.length s and m = String.length t in\n let i = ref 0 and j = ref 0 and res = ref 0 in\n while s.[!i] == '0' && !i + 1 < n do\n i := !i + 1;\n done;\n while t.[!j] == '0' && !j + 1 < m do\n j := !j + 1;\n done;\n res := (if n - !i < m - !j then -1 else (\n if n - !i > m - !j then 1 else 0\n ));\n if n - !i = m - !j then (\n res := 0;\n while !i < n && !j < m && !res = 0 do\n res := if s.[!i] < t.[!j] then -1 else (\n if s.[!i] > t.[!j] then 1 else 0\n );\n i := !i + 1;\n j := !j + 1;\n done;\n );\n if !res = 0 then (\n Printf.printf \"=\\n\";\n );\n if !res < 0 then (\n Printf.printf \"<\\n\";\n );\n if !res > 0 then (\n Printf.printf \">\\n\";\n );\n"}], "negative_code": [{"source_code": "let xstr() = Scanf.scanf \"%s \" (fun x -> x)\n\nlet () = \n let s = xstr() and t = xstr() in\n let n = String.length s and m = String.length t in\n let i = ref 0 and j = ref 0 and res = ref 0 in\n while s.[!i] == '0' && !i + 1 < n do\n i := !i + 1;\n done;\n while t.[!j] == '0' && !j + 1 < m do\n j := !j + 1;\n done;\n res := (if n - !i < m - !j then -1 else (\n if n - !i < m - !j then 1 else 0\n ));\n if n - !i = m - !j then (\n res := 0;\n while !i < n && !j < m && !res = 0 do\n res := if s.[!i] < t.[!j] then -1 else (\n if s.[!i] > t.[!j] then 1 else 0\n );\n i := !i + 1;\n j := !j + 1;\n done;\n );\n if !res = 0 then (\n Printf.printf \"=\\n\";\n );\n if !res < 0 then (\n Printf.printf \"<\\n\";\n );\n if !res > 0 then (\n Printf.printf \">\\n\";\n );\n"}], "src_uid": "fd63aeefba89bef7d16212a0d9e756cd"} {"nl": {"description": "This is the easier version of the problem. In this version, $$$1 \\le n \\le 10^5$$$ and $$$0 \\le a_i \\le 1$$$. You can hack this problem only if you solve and lock both problems.Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $$$n$$$ boxes of chocolate, numbered from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th box contains $$$a_i$$$ chocolate pieces.Since Bob is a typical nice guy, he will not send Alice $$$n$$$ empty boxes. In other words, at least one of $$$a_1, a_2, \\ldots, a_n$$$ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $$$k > 1$$$ such that the number of pieces in each box is divisible by $$$k$$$. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $$$i$$$ and put it into either box $$$i-1$$$ or box $$$i+1$$$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of chocolate boxes. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 1$$$)\u00a0\u2014 the number of chocolate pieces in the $$$i$$$-th box. It is guaranteed that at least one of $$$a_1, a_2, \\ldots, a_n$$$ is positive.", "output_spec": "If there is no way for Charlie to make Alice happy, print $$$-1$$$. Otherwise, print a single integer $$$x$$$\u00a0\u2014 the minimum number of seconds for Charlie to help Bob make Alice happy.", "sample_inputs": ["3\n1 0 1", "1\n1"], "sample_outputs": ["2", "-1"], "notes": null}, "positive_code": [{"source_code": "\nlet ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( ** ) = Int64.mul\nlet ( // ) = Int64.add\n\nlet cost arr k =\n let n = Array.length arr in\n let tar j = (j/k) * k + k/2 in\n Array.init n (fun i -> (Int64.abs (arr.(tar i) -- arr.(i)))) \n |> Array.fold_left ( ++ ) 0L\n\nlet () =\n let n = read_int () in\n let a = Array.init n (fun _ -> Scanf.scanf \" %d \" (fun x -> x)) in\n let rec iter j =\n if j = n then []\n else if a.(j)=1 then (Int64.of_int j)::(iter (j+1)) else iter (j+1) in\n let arr = Array.of_list (iter 0) in\n let n = Array.length arr in\n let rec iter acc n d =\n if d * d > n then (if n = 1 then acc else n::acc)\n else if n mod d > 0 then iter acc n (d+1)\n else let rec iter' n d = if n mod d = 0 then iter' (n/d) d else n in\n iter (d::acc) (iter' n d) (d+1) in\n let primes = iter [] n 2 in\n (* List.iter (Printf.printf \"%d\\n\") primes; *)\n if n = 1 then Printf.printf \"-1\\n\" else\n List.map (cost arr) primes\n (* |> List.iter (Printf.printf \" %Ld\") *)\n |> List.fold_left min 123412341234L\n |> Printf.printf \"%Ld\\n\"\n\n"}], "negative_code": [{"source_code": "\nlet ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( ** ) = Int64.mul\nlet ( // ) = Int64.add\n\nlet cost arr k =\n let n = Array.length arr in\n let tar j = (j/k) * k + k/2 in\n Array.init n (fun i -> (Int64.abs (arr.(tar i) -- arr.(i)))) \n |> Array.fold_left ( ++ ) 0L\n\nlet () =\n let n = read_int () in\n let a = Array.init n (fun _ -> Scanf.scanf \" %d \" (fun x -> x)) in\n let rec iter j =\n if j = n then []\n else if a.(j)=1 then (Int64.of_int j)::(iter (j+1)) else iter (j+1) in\n let arr = Array.of_list (iter 0) in\n let n = Array.length arr in\n let rec iter acc n d =\n if d * d > n then (if n = 1 then acc else n::acc)\n else if n mod d > 0 then iter acc n (d+1)\n else let rec iter' n d = if n mod d = 0 then iter' (n/d) d else n in\n iter (d::acc) (iter' n d) (d+1) in\n let primes = iter [] n 2 in\n (* List.iter (Printf.printf \"%d\\n\") primes; *)\n if n = 1 then Printf.printf \"-1\\n\" else\n List.map (cost arr) primes\n (* |> List.iter (Printf.printf \" %Ld\") *)\n |> List.fold_left min 0L\n |> Printf.printf \"%Ld\\n\"\n\n"}], "src_uid": "48494a73273cd8d999e94ba1a9581fdf"} {"nl": {"description": "It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.", "input_spec": "The first line of the input contains the number of countries n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000). The second line contains n non-negative integers ai without leading zeroes\u00a0\u2014 the number of tanks of the i-th country. It is guaranteed that the second line contains at least n\u2009-\u20091 beautiful numbers and the total length of all these number's representations doesn't exceed 100\u2009000.", "output_spec": "Print a single number without leading zeroes\u00a0\u2014 the product of the number of tanks presented by each country.", "sample_inputs": ["3\n5 10 1", "4\n1 1 10 11", "5\n0 3 1 100 1"], "sample_outputs": ["50", "110", "0"], "notes": "NoteIn sample 1 numbers 10 and 1 are beautiful, number 5 is not not.In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.In sample 3 number 3 is not beautiful, all others are beautiful."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet iszero s first last = forall first last (fun i -> s.[i] = '0')\n\nlet is_power10 s =\n let n = String.length s in\n s.[0] = '1' && iszero s 1 (n-1)\n\nlet rec log10 s = (* assuming it's a power of 10 *) -1+String.length s\n \nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_string()) in\n\n if exists 0 (n-1) (fun i -> iszero a.(i) 0 (-1 + String.length a.(i))) then (\n printf \"0\\n\"\n ) else (\n\n let rec find_bad_index i ac = if i=n then ac else\n\tif is_power10 a.(i) then find_bad_index (i+1) ac else i\n in\n\n let bad_index = find_bad_index 0 (-1) in\n\n let zeros = sum 0 (n-1) (fun i -> if i = bad_index then 0 else log10 a.(i)) in\n\n if bad_index < 0 then printf \"1\" else printf \"%s\" a.(bad_index);\n \n for i=1 to zeros do\n printf \"0\"\n done;\n\n print_newline()\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n\nlet rec is_power a b = if a=1 then true else a mod b = 0 && is_power (a/b) b\n\nlet rec log10 x = if x=1 then 0 else 1+(log10 (x/10))\n \nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n if exists 0 (n-1) (fun i -> a.(i) = 0) then (\n printf \"0\\n\"\n ) else (\n\n let rec find_bad i ac = if i=n then ac else\n\tif is_power a.(i) 10 then find_bad (i+1) ac else a.(i)\n in\n\n let bad = find_bad 0 1 in\n\n printf \"bad = %d\\n\" bad;\n\n let zeros = sum 0 (n-1) (fun i -> if a.(i) = bad then 0 else log10 a.(i)) in\n\n printf \"%d\" bad;\n\n for i=1 to zeros do\n printf \"0\"\n done;\n\n print_newline()\n )\n \n"}], "src_uid": "9b1b082319d045cf0ec6d124f97a8184"} {"nl": {"description": "Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:#define macro_name macro_valueAfter the macro has been declared, \"macro_name\" is replaced with \"macro_value\" each time it is met in the program (only the whole tokens can be replaced; i.e. \"macro_name\" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A \"macro_value\" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.One of the main problems arising while using macros \u2014 the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.Let's consider the following example. Say, we declared such a #define construction:#define sum x + yand further in the program the expression \"2 * sum\" is calculated. After macro substitution is performed we get \"2 * x + y\", instead of intuitively expected \"2 * (x + y)\".Let's call the situation \"suspicious\", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a \"safe\" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise \u2014 suspicious.Note that we consider the \"/\" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression \"a*(b/c)\" we can omit brackets to get the expression \"a*b/c\".", "input_spec": "The first line contains the only number n (0\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the amount of #define constructions in the given program. Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax: #define name expression where name \u2014 the macro name, expression \u2014 the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109. All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction. Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions. The input lines may contain any number of spaces anywhere, providing these spaces do not break the word \"define\" or the names of constructions and variables. In particular, there can be any number of spaces before and after the \"#\" symbol. The length of any line from the input file does not exceed 100 characters.", "output_spec": "Output \"OK\", if the expression is correct according to the above given criterion, otherwise output \"Suspicious\".", "sample_inputs": ["1\n#define sum x + y\n1 * sum", "1\n#define sum (x + y)\nsum - sum", "4\n#define sum x + y\n#define mul a * b\n#define div a / b\n#define expr sum + mul * div * mul\nexpr", "3\n#define SumSafe (a+b)\n#define DivUnsafe a/b\n#define DenominatorUnsafe a*b\n((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)"], "sample_outputs": ["Suspicious", "OK", "OK", "Suspicious"], "notes": null}, "positive_code": [{"source_code": "let (|>) x f = f x\n\nlet isalnum c =\n 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9'\n\nlet parse pri body =\n let isp = Hashtbl.create 10 in\n List.iter (fun (x,y) -> Hashtbl.add isp x y)\n ['\\000',0; '+',3; '-',3; '*',5; '/',5; '(',1; ')',6];\n let icp = Hashtbl.create 10 in\n List.iter (fun (x,y) -> Hashtbl.add icp x y)\n ['\\000',0; '+',2; '-',2; '*',4; '/',4; '(',6; ')',1];\n\n let len = String.length body in\n let rec go i (vs : int list) ops =\n (*Printf.printf \"== %d [ \" i;*)\n (*List.iter (fun x -> Printf.printf \"%c\" x) ops;*)\n (*Printf.printf \" ] [ \";*)\n (*List.iter (fun x -> Printf.printf \"%d\" x) vs;*)\n (*Printf.printf \" ]\";*)\n (*print_endline \"\";*)\n\n if i = len && List.hd ops = '\\000' then\n List.hd vs\n else\n let ic = if i = len then '\\000' else body.[i] in\n (* space *)\n if ic = ' ' then\n go (i+1) vs ops\n else\n try\n (* operator *)\n let ic_ = Hashtbl.find icp ic in\n let is = List.hd ops in\n let is_ = Hashtbl.find isp is in\n if is_ <= ic_ then\n go (i+1) vs (ic::ops)\n else\n match is with\n | '+' | '-' ->\n (match vs with | v::u::vs' ->\n let t = if u >= is_ && (v > is_ || v = is_ && is = '+') then is_ else 0 in\n go i (t::vs') (List.tl ops))\n | '*' | '/' ->\n (match vs with | v::u::vs' ->\n let t = if u >= is_ && (v > is_ || v = is_ && is = '*') then is_ else 0 in\n go i (t::vs') (List.tl ops))\n | ')' ->\n (match vs with | v::vs' ->\n let t = if v > 0 then 6 else 0 in\n go i (t::vs') (List.tl ops |> List.tl))\n with Not_found ->\n (* identifier/literal *)\n let rec go2 i =\n if i >= len || not (isalnum body.[i]) then\n i\n else\n go2 (i+1)\n in\n let j = go2 i in\n let ident = String.sub body i (j-i) in\n go j ((try Hashtbl.find pri ident with Not_found -> 7)::vs) ops\n in\n\n go 0 [] ['\\000']\n\nlet () =\n let n = read_int () in\n let pri = Hashtbl.create n in\n for i = 1 to n do\n let line = read_line () in\n Scanf.sscanf line \" # %s %s %[^\\n]\" (fun _ head body ->\n let r = parse pri body in\n Hashtbl.add pri head r\n );\n done;\n print_endline (if parse pri (read_line ()) = 0 then \"Suspicious\" else \"OK\")\n"}], "negative_code": [{"source_code": "let (|>) x f = f x\n\nlet isalnum c =\n 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9'\n\nlet parse pri body =\n let isp = Hashtbl.create 10 in\n List.iter (fun (x,y) -> Hashtbl.add isp x y)\n ['\\000',0; '+',3; '-',3; '*',5; '/',5; '(',1; ')',6];\n let icp = Hashtbl.create 10 in\n List.iter (fun (x,y) -> Hashtbl.add icp x y)\n ['\\000',0; '+',2; '-',2; '*',4; '/',4; '(',6; ')',1];\n\n let len = String.length body in\n let rec go i (vs : int list) ops =\n (*Printf.printf \"== %d [ \" i;*)\n (*List.iter (fun x -> Printf.printf \"%c\" x) ops;*)\n (*Printf.printf \" ] [ \";*)\n (*List.iter (fun x -> Printf.printf \"%d\" x) vs;*)\n (*Printf.printf \" ]\";*)\n (*print_endline \"\";*)\n\n if i = len && List.hd ops = '\\000' then\n List.hd vs\n else\n let ic = if i = len then '\\000' else body.[i] in\n (* space *)\n if ic = ' ' then\n go (i+1) vs ops\n else\n try\n (* operator *)\n let ic_ = Hashtbl.find icp ic in\n let is = List.hd ops in\n let is_ = Hashtbl.find isp is in\n if is_ <= ic_ then\n go (i+1) vs (ic::ops)\n else\n match is with\n | '+' | '-' ->\n (match vs with | v::u::vs' ->\n let t = if u >= is_ && (v > is_ || v = is_ && is = '+') then is_ else 0 in\n go i (t::vs') (List.tl ops))\n | '*' | '/' ->\n (match vs with | v::u::vs' ->\n let t = if u >= is_ && (v > is_ || v = is_ && is = '*') then is_ else 0 in\n go i (t::vs') (List.tl ops))\n | ')' ->\n (match vs with | v::vs' ->\n let t = if v > 0 then 6 else 0 in\n go i (t::vs') (List.tl ops |> List.tl))\n with Not_found ->\n (* identifier/literal *)\n let rec go2 i =\n if i >= len || not (isalnum body.[i]) then\n i\n else\n go2 (i+1)\n in\n let j = go2 i in\n let ident = String.sub body i (j-i) in\n go j ((try Hashtbl.find pri ident with Not_found -> 7)::vs) ops\n in\n\n go 0 [] ['\\000']\n\nlet () =\n let n = read_int () in\n let pri = Hashtbl.create n in\n for i = 1 to n do\n let line = read_line () in\n Scanf.sscanf line \"#define %s %[^\\n]\" (fun head body ->\n Printf.printf \"++ %s %s\\n\" head body;\n let r = parse pri body in\n Hashtbl.add pri head r;\n Printf.printf \"-- %s %s %d\\n\" head body r\n );\n done;\n print_endline (if parse pri (read_line ()) = 0 then \"Suspicious\" else \"OK\")\n"}], "src_uid": "c23d3ec2b9fb4b4d169bc8053bfd000e"} {"nl": {"description": "DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',\u2009E') of a graph G(V,\u2009E) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. ", "input_spec": "The first line contains two space-separated integers n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi\u00a0(1\u2009\u2264\u2009xi\u2009\u2264\u2009106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,\u2009bi,\u2009ci\u00a0(1\u2009\u2264\u2009ai\u2009<\u2009bi\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009ci\u2009\u2264\u2009103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.", "output_spec": "Output a real number denoting the answer, with an absolute or relative error of at most 10\u2009-\u20099.", "sample_inputs": ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"], "sample_outputs": ["0.000000000000000", "3.000000000000000", "2.965517241379311"], "notes": "NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let m = read_int () in\n let x = Array.init n (fun _ -> read_int()) in\n \n let best = ref 0.0 in\n \n for i=0 to m-1 do\n let vc = x.(-1+read_int()) + x.(-1+read_int()) in\n let ec = read_int () in\n best := max !best ((float vc) /. (float ec))\n done;\n\n printf \"%.10f\\n\" !best;\n"}], "negative_code": [], "src_uid": "ba4304e79d85d13c12233bcbcce6d0a6"} {"nl": {"description": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).If a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, then Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.", "input_spec": "The first line contains two space-separated integers n and x (1\u2009\u2264\u2009n\u2009\u2264\u20091000, 0\u2009\u2264\u2009x\u2009\u2264\u2009109). Each of the next n lines contains a character '+' or '-', and an integer di, separated by a space (1\u2009\u2264\u2009di\u2009\u2264\u2009109). Record \"+ di\" in i-th line means that a carrier with di ice cream packs occupies i-th place from the start of the queue, and record \"- di\" means that a child who wants to take di packs stands in i-th place.", "output_spec": "Print two space-separated integers\u00a0\u2014 number of ice cream packs left after all operations, and number of kids that left the house in distress.", "sample_inputs": ["5 7\n+ 5\n- 10\n- 20\n+ 40\n- 20", "5 17\n- 16\n- 2\n- 98\n+ 100\n- 98"], "sample_outputs": ["22 1", "3 2"], "notes": "NoteConsider the first sample. Initially Kay and Gerda have 7 packs of ice cream. Carrier brings 5 more, so now they have 12 packs. A kid asks for 10 packs and receives them. There are only 2 packs remaining. Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed. Carrier bring 40 packs, now Kay and Gerda have 42 packs. Kid asks for 20 packs and receives them. There are 22 packs remaining. "}, "positive_code": [{"source_code": "let [n; x] = read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string\n\nlet store = ref (Int64.of_int x)\nlet sad = ref 0\n\nlet step sign amount =\n let open Int64 in\n let amount = of_int amount in\n match sign with\n | '+' ->\n store := Int64.add !store amount\n | '-' ->\n if !store >= amount then\n store := Int64.sub !store amount\n else\n incr sad\n | _ -> assert false\n\nlet () =\n for i = 1 to n do\n Scanf.scanf \"%c %d\\n\" step\n done;\n Printf.printf \"%s %d\\n\" (Int64.to_string !store) !sad\n"}, {"source_code": "open Big_int\n\nlet (+.) = add_big_int\n\nlet rec f init dis = function\n | t::q when ge_big_int t zero_big_int -> f (init +. t) dis q\n | t::q -> if lt_big_int (init +. t) zero_big_int\n then f init (dis + 1) q\n else f (init +. t) dis q\n | _ -> (init,dis)\n\nlet _ =\n let (n,init) = Scanf.scanf \"%d %s\" (fun i j -> i,big_int_of_string j) in\n let l = ref [] in\n for i = 1 to n do Scanf.scanf \" %c %d\" (fun c x ->\n l := (big_int_of_int (x * if c = '+' then 1 else -1))::!l);\n done;\n let (a,b) = f init 0 (List.rev !l) in\n Printf.printf \"%s %d\" (string_of_big_int a) b \n"}, {"source_code": "(* Codeforces 686 A Free Ice Cream *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet x = ref (Int64.of_int 0);;\nlet ndistress = ref 0;;\n\n(* c - + or -, d - nuym of ice cream *)\nlet one_step c d = \n\t(* let _ = begin print_int !x; print_string \"\\n\" end in *)\n\tif c == '+' then \n\t\tbegin\n\t\t\tx := Int64.add !x d\n\t\tend\n\telse\n \t\tif !x < d then\n \t\t\tbegin\n \t\t\t\tndistress := !ndistress + 1\n \t\t\tend\n\t\t\telse \n\t\t\t\tbegin\n\t\t \t\tx := Int64.sub !x d\n\t\t\t\tend;;\n\nlet main() =\n\tlet n = gr() in\n\tlet xx = gr () in\n\tbegin\n\t\tx := Int64.of_int xx;\n\t\tfor i = 1 to n do\n\t\t\tlet c = grc () in\n\t\t\tlet d = Int64.of_int (gr ()) in\n\t\t\tone_step c d\n\t\tdone;\n\t\tprint_string (Int64.to_string !x);\n\t\tprint_string \" \";\t\t\n\t\tprint_int !ndistress;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let x = long (read_int ()) in\n\n let rec loop i packs distress = if i=n then (packs,distress) else (\n let s = read_string() in\n let q = long (read_int()) in\n match s with\n |\t\"+\" -> loop (i+1) (packs ++ q) distress\n | \"-\" ->\n\tif q > packs then loop (i+1) packs (distress+1)\n\telse loop (i+1) (packs -- q) distress\n | _ -> failwith \"bad input\"\n ) in \n \n let (packs, distress) = loop 0 x 0 in\n\n printf \"%Ld %d\\n\" packs distress\n"}], "negative_code": [{"source_code": "let [n; x] = read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string\n\nlet store = ref x\nlet sad = ref 0\n\nlet step sign amount =\n match sign with\n | '+' ->\n store := !store + amount\n | '-' ->\n if !store >= amount then\n store := !store - amount\n else\n incr sad\n | _ -> assert false\n\nlet () =\n for i = 1 to n do\n Scanf.scanf \"%c %d\\n\" step\n done;\n Printf.printf \"%d %d\\n\" !store !sad\n"}, {"source_code": "(* Codeforces 686 A Free Ice Cream *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet x = ref 0;;\nlet ndistress = ref 0;;\n\n(* c - + or -, d - nuym of ice cream *)\nlet one_step c d = \n\t(* let _ = begin print_int !x; print_string \"\\n\" end in *)\n\tif c == '+' then \n\t\tbegin\n\t\t\tx := !x + d\n\t\tend\n\telse\n \t\tif !x < d then\n \t\t\tbegin\n \t\t\t\tndistress := !ndistress + 1\n \t\t\tend\n\t\t\telse \n\t\t\t\tbegin\n\t\t \t\tx := !x-d\n\t\t\t\tend;;\n\nlet main() =\n\tlet n = gr() in\n\tlet xx = gr () in\n\tbegin\n\t\tx := xx;\n\t\tfor i = 1 to n do\n\t\t\tlet c = grc () in\n\t\t\tlet d = gr () in\n\t\t\tone_step c d\n\t\tdone;\n\t\tprint_int !x;\n\t\tprint_string \" \";\t\t\n\t\tprint_int !ndistress;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}], "src_uid": "0a9ee8cbfa9888caef39b024563b7dcd"} {"nl": {"description": "Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s\u2009=\u2009s1s2... sn, then the following inequality holds, si\u2009\u2260\u2009si\u2009+\u20091(1\u2009\u2264\u2009i\u2009<\u2009n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x\u2009=\u2009x1x2... xp is lexicographically less than string y\u2009=\u2009y1y2... yq, if either p\u2009<\u2009q and x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xp\u2009=\u2009yp, or there is such number r (r\u2009<\u2009p,\u2009r\u2009<\u2009q), that x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xr\u2009=\u2009yr and xr\u2009+\u20091\u2009<\u2009yr\u2009+\u20091. The characters of the strings are compared by their ASCII codes.", "input_spec": "A single line contains two positive integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009106,\u20091\u2009\u2264\u2009k\u2009\u2264\u200926) \u2014 the string's length and the number of distinct letters.", "output_spec": "In a single line print the required string. If there isn't such string, print \"-1\" (without the quotes).", "sample_inputs": ["7 4", "4 7"], "sample_outputs": ["ababacd", "-1"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet read_pair () = let a = read_int () in (a , read_int ());;\n\nlet n , k = read_pair ();;\n\nlet ans = String.create n;;\n\nfor i = 0 to (n-1) do\n if i mod 2 = 0 then ans.[i] <- 'a'\n else ans.[i] <- 'b'\ndone;;\n\nif n = 1 && k = 1 then Printf.printf \"a\\n\"\nelse if n != 1 && k = 1 then Printf.printf \"-1\\n\"\nelse if k > n then Printf.printf \"-1\\n\"\nelse begin\n for i = (n-k+2) to (n-1) do ans.[i] <- Char.chr ((Char.code 'c') + i - (n-k+2)) done;\n Printf.printf \"%s\\n\" ans\nend ;;\n \n\n"}, {"source_code": "(* Little penguin Polo adores strings. But most of all he adores strings of length n.\n\nOne day he wanted to find a string that meets the following conditions:\n\n The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.\n No two neighbouring letters of a string coincide; that is, if we represent a string as s\u2009=\u2009s1s2... sn, then the following inequality holds, si\u2009\u2260\u2009si\u2009+\u20091(1\u2009\u2264\u2009i\u2009<\u2009n).\n Among all strings that meet points 1 and 2, the required string is lexicographically smallest.\n Help him find such string or state that such string doesn't exist.\n\n Input\n A single line contains two positive integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009106,\u20091\u2009\u2264\u2009k\u2009\u2264\u200926) \u2014 the string's length and the number of distinct letters.\n\n string.length = n, string.distinct_letters = k, string.neighbouring_letters = false *)\n\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let k = read_int() in\n let s = String.create n in\n\n let answer =\n if n < k then \"-1\"\n else if n=1 then \"a\"\n else if k<2 then \"-1\"\n else (\n for i=0 to n-(k-2)-1 do\n s.[i] <- if i mod 2 = 0 then 'a' else 'b';\n done;\n for i=n-(k-2) to n-1 do\n let j = i-(n-(k-2)) in\n let c = char_of_int ((int_of_char 'c') + j) in\n s.[i] <- c;\n done;\n s\n )\n in\n print_string answer;\n print_newline();\n\n\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let k = read_int() in\n let s = String.create n in\n\n let answer = \n if n < k then \"-1\" \n else if n=1 then \"a\"\n else if k<2 then \"-1\"\n else (\n for i=0 to n-(k-2)-1 do\n\ts.[i] <- if i mod 2 = 0 then 'a' else 'b';\n done;\n for i=n-(k-2) to n-1 do\n\tlet j = i-(n-(k-2)) in\n\tlet c = char_of_int ((int_of_char 'c') + j) in\n\t s.[i] <- c;\n done;\n s\n )\n in\n print_string answer;\n print_newline();\n"}], "negative_code": [], "src_uid": "2f659be28674a81f58f5c587b6a0f465"} {"nl": {"description": "Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much. A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at volume v (1\u2009\u2264\u2009v\u2009\u2264\u2009ai; v is an integer) both on the piano and the guitar. They should retain harmony, so the total volume with which the i-th note was played on the guitar and the piano must equal bi. If Dima and Inna cannot play a note by the described rules, they skip it and Sereja's joy drops by 1. But if Inna and Dima play the i-th note at volumes xi and yi (xi\u2009+\u2009yi\u2009=\u2009bi) correspondingly, Sereja's joy rises by xi\u00b7yi. Sereja has just returned home from the university and his current joy is 0. Help Dima and Inna play the song so as to maximize Sereja's total joy after listening to the whole song!", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of notes in the song. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106). The third line contains n integers bi (1\u2009\u2264\u2009bi\u2009\u2264\u2009106).", "output_spec": "In a single line print an integer \u2014 the maximum possible joy Sereja feels after he listens to a song.", "sample_inputs": ["3\n1 1 2\n2 2 3", "1\n2\n5"], "sample_outputs": ["4", "-1"], "notes": "NoteIn the first sample, Dima and Inna play the first two notes at volume 1 (1\u2009+\u20091\u2009=\u20092, the condition holds), they should play the last note at volumes 1 and 2. Sereja's total joy equals: 1\u00b71\u2009+\u20091\u00b71\u2009+\u20091\u00b72\u2009=\u20094.In the second sample, there is no such pair (x,\u2009y), that 1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u20092, x\u2009+\u2009y\u2009=\u20095, so Dima and Inna skip a note. Sereja's total joy equals -1."}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet a=Array.init n (fun i->read_int());;\nlet b=Array.init n (fun i->read_int());;\nlet s=ref Int64.zero;;\nfor i=0 to n-1 do\n let m=b.(i)/2 in\n if b.(i)=2*m then (if m<=a.(i) then s:=Int64.add !s (Int64.mul (Int64.of_int(m)) (Int64.of_int(m))) else s:=Int64.pred !s)\n else (if (m+1<=a.(i))&&(m<>0) then s:=Int64.add !s (Int64.mul (Int64.of_int(m)) (Int64.of_int(m+1))) else s:=Int64.pred !s)\ndone;;\nprint_string (Int64.to_string !s);;"}], "negative_code": [{"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet a=Array.init n (fun i->read_int());;\nlet b=Array.init n (fun i->read_int());;\nlet s=ref Int64.zero;;\nfor i=0 to n-1 do\n let m=b.(i)/2 in\n if b.(i)=2*m then (if m<=a.(i) then s:=Int64.add !s (Int64.of_int (m*m)) else s:=Int64.pred !s)\n else (if (m+1<=a.(i))&&(m<>0) then s:=Int64.add !s (Int64.of_int (m*(m+1))) else s:=Int64.pred !s)\ndone;;\nprint_string (Int64.to_string !s);;"}, {"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet a=Array.init n (fun i->read_int());;\nlet b=Array.init n (fun i->read_int());;\nlet s=ref 0;;\nfor i=0 to n-1 do\n let m=b.(i)/2 in\n if b.(i)=2*m then (if m<=a.(i) then s:= !s+m*m else s:= !s-1)\n else (if m+1<=a.(i) then s:= !s+m*(m+1) else s:= !s-1)\ndone;;\nprint_int !s;;"}, {"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet a=Array.init n (fun i->read_int());;\nlet b=Array.init n (fun i->read_int());;\nlet s=ref 0;;\nfor i=0 to n-1 do\n let m=b.(i)/2 in\n if b.(i)=2*m then (if m<=a.(i) then s:= !s+m*m else s:= !s-1)\n else (if (m+1<=a.(i))&&(m<>0) then s:= !s+m*(m+1) else s:= !s-1)\ndone;;\nprint_int !s;;"}], "src_uid": "986a7d97e62856d5301d5a70ea01466a"} {"nl": {"description": "According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.", "output_spec": "Print a single number which is the number of people Vasya should check to guarantee the law enforcement.", "sample_inputs": ["5\n18\nVODKA\nCOKE\n19\n17"], "sample_outputs": ["2"], "notes": "NoteIn the sample test the second and fifth clients should be checked."}, "positive_code": [{"source_code": "let n = read_int ();;\nlet tests = ref 0;;\nlet drinks = [\"ABSINTH\";\"BEER\";\"BRANDY\";\"CHAMPAGNE\";\"GIN\";\"RUM\";\"SAKE\";\"TEQUILA\";\"VODKA\";\"WHISKEY\";\"WINE\"];;\n\nfor i = 1 to n do\n\tlet ln = read_line () in\n\ttry\n\t\tlet age = int_of_string ln in\n\t\tif age < 18 then incr(tests)\n\twith _ ->\n\t\tif List.mem ln drinks then incr(tests)\ndone;\n\nprint_int (!tests);;\n"}], "negative_code": [], "src_uid": "4b7b0fba7b0af78c3956c34c29785e7c"} {"nl": {"description": "The new generation external memory contains an array of integers $$$a[1 \\ldots n] = [a_1, a_2, \\ldots, a_n]$$$.This type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back into the same place.Technically, each cyclic shift consists of two consecutive actions: You may select arbitrary indices $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le n$$$) as the boundaries of the segment. Then you replace the segment $$$a[l \\ldots r]$$$ with it's cyclic shift to the left by an arbitrary offset $$$d$$$. The concept of a cyclic shift can be also explained by following relations: the sequence $$$[1, 4, 1, 3]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$1$$$ and the sequence $$$[4, 1, 3, 1]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$2$$$. For example, if $$$a = [1, \\color{blue}{3, 2, 8}, 5]$$$, then choosing $$$l = 2$$$, $$$r = 4$$$ and $$$d = 2$$$ yields a segment $$$a[2 \\ldots 4] = [3, 2, 8]$$$. This segment is then shifted by the offset $$$d = 2$$$ to the left, and you get a segment $$$[8, 3, 2]$$$ which then takes the place of of the original elements of the segment. In the end you get $$$a = [1, \\color{blue}{8, 3, 2}, 5]$$$.Sort the given array $$$a$$$ using no more than $$$n$$$ cyclic shifts of any of its segments. Note that you don't need to minimize the number of cyclic shifts. Any method that requires $$$n$$$ or less cyclic shifts will be accepted.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. The next $$$2t$$$ lines contain the descriptions of the test cases. The first line of each test case description contains an integer $$$n$$$ ($$$2 \\leq n \\leq 50$$$)\u00a0\u2014 the length of the array. The second line consists of space-separated elements of the array $$$a_i$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$). Elements of array $$$a$$$ may repeat and don't have to be unique.", "output_spec": "Print $$$t$$$ answers to all input test cases. The first line of the answer of each test case should contain an integer $$$k$$$ ($$$0 \\le k \\le n$$$)\u00a0\u2014 the number of actions to sort the array. The next $$$k$$$ lines should contain descriptions of the actions formatted as \"$$$l$$$\u00a0$$$r$$$\u00a0$$$d$$$\" (without quotes) where $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le n$$$) are the boundaries of the segment being shifted, while $$$d$$$ ($$$1 \\le d \\le r - l$$$) is the offset value. Please remember that only the cyclic shifts to the left are considered so the chosen segment will be shifted by the offset $$$d$$$ to the to the left. Note that you are not required to find the minimum number of cyclic shifts needed for sorting. Any sorting method where the number of shifts does not exceed $$$n$$$ will be accepted. If the given array $$$a$$$ is already sorted, one of the possible answers is $$$k = 0$$$ and an empty sequence of cyclic shifts. If there are several possible answers, you may print any of them.", "sample_inputs": ["4\n2\n2 1\n3\n1 2 1\n4\n2 4 1 3\n5\n2 5 1 4 3"], "sample_outputs": ["1\n1 2 1\n1\n1 3 2\n3\n2 4 1\n2 3 1\n1 3 2\n4\n2 4 2\n1 5 3\n1 2 1\n1 3 1"], "notes": "NoteExplanation of the fourth data set in the example: The segment $$$a[2 \\ldots 4]$$$ is selected and is shifted to the left by $$$2$$$: $$$[2, \\color{blue}{5, 1, 4}, 3] \\longrightarrow [2, \\color{blue}{4, 5, 1}, 3]$$$ The segment $$$a[1 \\ldots 5]$$$ is then selected and is shifted to the left by $$$3$$$: $$$[\\color{blue}{2, 4, 5, 1, 3}] \\longrightarrow [\\color{blue}{1, 3, 2, 4, 5}]$$$ After that the segment $$$a[1 \\ldots 2]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\\color{blue}{1, 3}, 2, 4, 5] \\longrightarrow [\\color{blue}{3, 1}, 2, 4, 5]$$$ And in the end the segment $$$a[1 \\ldots 3]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\\color{blue}{3, 1, 2}, 4, 5] \\longrightarrow [\\color{blue}{1, 2, 3}, 4, 5]$$$ "}, "positive_code": [{"source_code": "let left liste i =\n let liste = \" \" ^ liste in\n let rec aux j space =\n if liste.[j] = ' ' then\n if space = i then j\n else aux (j+1) (space+1)\n else\n aux (j+1) space in\n aux 0 0;;\n\nlet right liste i =\n let liste = liste ^ \" \" in\n let rec aux j space =\n if liste.[j] = ' ' then\n if space = i then j-1\n else aux (j+1) (space+1)\n else\n aux (j+1) space in\n aux 0 0;;\n\n\nlet ith liste i j n =\n let liste = liste ^ \" \" in\n let rec aux start j space =\n if liste.[j] = ' ' then\n if space = i then\n (int_of_string(String.sub liste (start+1) (j-start-1)), j+1)\n else aux j (j+1) (space+1)\n else\n aux start (j+1) space in\n aux (j-1) j n;;\n\nlet swipe liste l =\n let len = String.length liste in\n let r = right liste (l-2) in\n (String.sub liste (r+2) (len-r-2)) ^ \" \" ^ (String.sub liste 0 (r+1));;\n\nlet cut liste l r d p l2 =\n let len = String.length liste in\n let li = left liste l and ri = right liste r in\n let subliste = String.sub liste li (ri-li+1) in\n let subliste = swipe subliste (r-l+1) in\n if p then (print_int (l+1); print_string \" \"; print_int (r+1); print_string \" \"; print_int d; print_newline ());\n (String.sub liste 0 li) ^ subliste ^ (String.sub liste (ri+1) (len-ri-1));;\n\nlet posmin liste s l =\n let rec aux mini index i j =\n if i = l then index else\n let (elt, j) = ith liste i j i in\n if elt < mini then aux elt i (i+1) j else aux mini index (i+1) j in\n aux max_int (-1) s (left liste s);;\n\nlet solve liste p l =\n let rec aux liste i c =\n if i < l then\n let pos = posmin liste i l in\n if pos <> i then\n let liste = cut liste i pos (pos-i) p l in\n aux liste (i+1) (c+1)\n else aux liste (i+1) c\n else c in\n aux liste 0 0;;\n\nlet t = read_int ();;\n\nlet rec main i =\n if i < t then\n begin\n let l = read_int () in\n let liste = read_line () in\n let answer = solve liste false l in\n print_int answer;\n print_newline ();\n solve liste true l;\n main (i+1)\n end;;\n\nmain 0;;\n"}], "negative_code": [], "src_uid": "06c515c2d889edec8db784b2d5279edc"} {"nl": {"description": "Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as: a1\u2009=\u2009p, where p is some integer; ai\u2009=\u2009ai\u2009-\u20091\u2009+\u2009(\u2009-\u20091)i\u2009+\u20091\u00b7q (i\u2009>\u20091), where q is some integer. Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression.Sequence s1,\u2009\u2009s2,\u2009\u2009...,\u2009\u2009sk is a subsequence of sequence b1,\u2009\u2009b2,\u2009\u2009...,\u2009\u2009bn, if there is such increasing sequence of indexes i1,\u2009i2,\u2009...,\u2009ik (1\u2009\u2009\u2264\u2009\u2009i1\u2009\u2009<\u2009\u2009i2\u2009\u2009<\u2009... \u2009\u2009<\u2009\u2009ik\u2009\u2009\u2264\u2009\u2009n), that bij\u2009\u2009=\u2009\u2009sj. In other words, sequence s can be obtained from b by crossing out some elements.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20094000). The next line contains n integers b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009106).", "output_spec": "Print a single integer \u2014 the length of the required longest subsequence.", "sample_inputs": ["2\n3 5", "4\n10 20 10 30"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first test the sequence actually is the suitable subsequence. In the second test the following subsequence fits: 10,\u200920,\u200910."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet () = \n let n = read_int() in\n let b = Array.init n (fun _ -> read_int()) in\n\n let h = Hashtbl.create 100 in\n let c = ref 0 in\n for i=0 to n-1 do\n if not (Hashtbl.mem h b.(i)) then (\n\tHashtbl.add h b.(i) !c;\n\tc := !c + 1\n )\n done;\n\n for i=0 to n-1 do\n b.(i) <- Hashtbl.find h b.(i);\n(* Printf.printf \"b.(%d) = %d\\n\" i b.(i) *)\n done;\n\n let m = !c in\n\n let dp = Array.make_matrix n m 1 in\n \n for i=1 to n-1 do\n\tlet k = b.(i) in\n\t for j=0 to i-1 do\n\t let l = b.(j) in\n\t let c = dp.(j).(k) in\n\t dp.(i).(l) <- max (c+1) dp.(i).(l)\n\t done\n done;\n\n let mm = maxf 0 (n-1) (fun i -> maxf 0 (m-1) (fun k -> \n(*\t\t\t\t\t\t Printf.printf \"dp.(%d).(%d) = %d\\n\" k i dp.(i).(k); *)\n\t\t\t\t\t\t dp.(i).(k))) in\n\n\tPrintf.printf \"%d\\n\" mm\n"}], "negative_code": [], "src_uid": "86ded9e6336a14b43dda780ebd099b4f"} {"nl": {"description": "As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of snowballs. The next line contains n integers \u2014 the balls' radii r1, r2, ..., rn (1\u2009\u2264\u2009ri\u2009\u2264\u2009109). The balls' radii can coincide.", "output_spec": "Print on the first line a single number k \u2014 the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers \u2014 the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.", "sample_inputs": ["7\n1 2 3 4 5 6 7", "3\n2 2 3"], "sample_outputs": ["2\n3 2 1\n6 5 4", "0"], "notes": null}, "positive_code": [{"source_code": "type 'a heap = {mutable heap : (int * 'a) array;\n\t\tmutable heap_len : int;\n\t }\n\nlet heap_new size el = {heap = Array.make size (0, el);\n\t\t\theap_len = 0;\n\t\t }\n\nlet heap_reset heap =\n heap.heap_len <- 0\n\nlet heap_insert heap p el =\n if Array.length heap.heap = heap.heap_len then (\n let new_size = heap.heap_len * 2 in\n let new_heap = Array.make new_size heap.heap.(0) in\n Array.blit heap.heap 0 new_heap 0 heap.heap_len;\n heap.heap <- new_heap;\n );\n let h = heap.heap in\n let pos = ref heap.heap_len in\n while !pos > 0 && fst h.((!pos - 1) / 2) > p do\n let parent = (!pos - 1) / 2 in\n\th.(!pos) <- h.(parent);\n\tpos := parent\n done;\n h.(!pos) <- (p, el);\n heap.heap_len <- heap.heap_len + 1\n\nlet heap_get_min heap =\n if heap.heap_len > 0 then\n snd heap.heap.(0)\n else\n raise Not_found\n\nlet heap_extract_min heap =\n if heap.heap_len > 0 then\n let h = heap.heap in\n let res = h.(0) in\n let len = heap.heap_len - 1 in\n h.(0) <- h.(len);\n heap.heap_len <- len;\n if len > 0 then (\n\tlet p = fst h.(0) in\n\tlet i = ref 0 in\n\tlet b = ref true in\n\t while !b do\n\t let l = !i * 2 + 1 in\n\t let r = !i * 2 + 2 in\n\t let smallest =\n\t if l < len && p > fst h.(l)\n\t then l\n\t else !i\n\t in\n\t let smallest =\n\t if r < len && fst h.(smallest) > fst h.(r)\n\t then r\n\t else smallest\n\t in\n\t if smallest <> !i then (\n\t\tlet tmp = h.(!i) in\n\t\t h.(!i) <- h.(smallest);\n\t\t h.(smallest) <- tmp;\n\t\t i := smallest;\n\t ) else\n\t\tb := false\n\t done\n );\n res\n else\n raise Not_found\n\nlet heap_is_empty heap =\n heap.heap_len = 0\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let ht = Hashtbl.create n in\n let _ =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ttry\n\t Hashtbl.replace ht x (Hashtbl.find ht x + 1)\n\twith\n\t | Not_found ->\n\t Hashtbl.replace ht x 1\n done;\n in\n let heap = heap_new n (-1) in\n Hashtbl.iter\n (fun r c ->\n\t heap_insert heap (-c) r\n ) ht;\n let res = ref [] in\n (try\n while true do\n\t let (c1, r1) = heap_extract_min heap in\n\t let (c2, r2) = heap_extract_min heap in\n\t let (c3, r3) = heap_extract_min heap in\n\t let [r1'; r2'; r3'] = List.sort compare [r1; r2; r3] in\n\t res := (r3', r2', r1') :: !res;\n\t let c1 = c1 + 1 in\n\t let c2 = c2 + 1 in\n\t let c3 = c3 + 1 in\n\t if c1 <> 0 then heap_insert heap c1 r1;\n\t if c2 <> 0 then heap_insert heap c2 r2;\n\t if c3 <> 0 then heap_insert heap c3 r3;\n done\n with\n | Not_found -> ()\n );\n Printf.printf \"%d\\n\" (List.length !res);\n List.iter\n (fun (a, b, c) ->\n\t Printf.printf \"%d %d %d\\n\" a b c\n ) !res\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n r.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare r\n in\n let sr = Array.make 3 0 in\n let sc = Array.make 3 0 in\n let p = ref 0 in\n let rec clean i =\n if i < !p then (\n if sc.(i) = 0 then (\n\tfor j = i to !p - 2 do\n\t sc.(j) <- sc.(j + 1);\n\t sr.(j) <- sr.(j + 1);\n\tdone;\n\tdecr p;\n\tclean i\n ) else clean (i + 1)\n )\n in\n let res = ref [] in\n for i = 0 to n - 1 do\n if !p > 0 && sr.(!p - 1) = r.(i) then (\n\tsc.(!p - 1) <- sc.(!p - 1) + 1;\n ) else (\n\tsc.(!p) <- 1;\n\tsr.(!p) <- r.(i);\n\tincr p;\n );\n while !p = 3 do\n\tres := (sr.(2), sr.(1), sr.(0)) :: !res;\n\tfor i = 0 to 2 do\n\t sc.(i) <- sc.(i) - 1\n\tdone;\n\tclean 0\n done\n done;\n Printf.printf \"%d\\n\" (List.length !res);\n List.iter\n (fun (a, b, c) ->\n\t Printf.printf \"%d %d %d\\n\" a b c\n ) !res\n"}, {"source_code": "(*\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n r.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare r\n in\n let sr = Array.make 3 0 in\n let sc = Array.make 3 0 in\n let p = ref 0 in\n let rec clean i =\n if i < !p then (\n if sc.(i) = 0 then (\n\tfor j = i to !p - 2 do\n\t sc.(j) <- sc.(j + 1);\n\t sr.(j) <- sr.(j + 1);\n\tdone;\n\tdecr p;\n\tclean i\n ) else clean (i + 1)\n )\n in\n let res = ref [] in\n for i = 0 to n - 1 do\n if !p > 0 && sr.(!p - 1) = r.(i) then (\n\tsc.(!p - 1) <- sc.(!p - 1) + 1;\n ) else (\n\tsc.(!p) <- 1;\n\tsr.(!p) <- r.(i);\n\tincr p;\n );\n while !p = 3 do\n\tres := (sr.(2), sr.(1), sr.(0)) :: !res;\n\tfor i = 0 to 2 do\n\t sc.(i) <- sc.(i) - 1\n\tdone;\n\tclean 0\n done\n done;\n Printf.printf \"%d\\n\" (List.length !res);\n List.iter\n (fun (a, b, c) ->\n\t Printf.printf \"%d %d %d\\n\" a b c\n ) !res\n*)\n\ntype 'a heap = {mutable heap : (int * 'a) array;\n\t\tmutable heap_len : int;\n\t }\n\nlet heap_new size el = {heap = Array.make size (0, el);\n\t\t\theap_len = 0;\n\t\t }\n\nlet heap_reset heap =\n heap.heap_len <- 0\n\nlet heap_insert heap p el =\n if Array.length heap.heap = heap.heap_len then (\n let new_size = heap.heap_len * 2 in\n let new_heap = Array.make new_size heap.heap.(0) in\n Array.blit heap.heap 0 new_heap 0 heap.heap_len;\n heap.heap <- new_heap;\n );\n let h = heap.heap in\n let pos = ref heap.heap_len in\n while !pos > 0 && fst h.((!pos - 1) / 2) > p do\n let parent = (!pos - 1) / 2 in\n\th.(!pos) <- h.(parent);\n\tpos := parent\n done;\n h.(!pos) <- (p, el);\n heap.heap_len <- heap.heap_len + 1\n\nlet heap_get_min heap =\n if heap.heap_len > 0 then\n snd heap.heap.(0)\n else\n raise Not_found\n\nlet heap_extract_min heap =\n if heap.heap_len > 0 then\n let h = heap.heap in\n let res = h.(0) in\n let len = heap.heap_len - 1 in\n h.(0) <- h.(len);\n heap.heap_len <- len;\n if len > 0 then (\n\tlet p = fst h.(0) in\n\tlet i = ref 0 in\n\tlet b = ref true in\n\t while !b do\n\t let l = !i * 2 + 1 in\n\t let r = !i * 2 + 2 in\n\t let smallest =\n\t if l < len && p > fst h.(l)\n\t then l\n\t else !i\n\t in\n\t let smallest =\n\t if r < len && fst h.(smallest) > fst h.(r)\n\t then r\n\t else smallest\n\t in\n\t if smallest <> !i then (\n\t\tlet tmp = h.(!i) in\n\t\t h.(!i) <- h.(smallest);\n\t\t h.(smallest) <- tmp;\n\t\t i := smallest;\n\t ) else\n\t\tb := false\n\t done\n );\n res\n else\n raise Not_found\n\nlet heap_is_empty heap =\n heap.heap_len = 0\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let ht = Hashtbl.create n in\n let _ =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ttry\n\t Hashtbl.replace ht x (Hashtbl.find ht x + 1)\n\twith\n\t | Not_found ->\n\t Hashtbl.replace ht x 1\n done;\n in\n let heap = heap_new n (-1) in\n Hashtbl.iter\n (fun r c ->\n\t heap_insert heap (-c) r\n ) ht;\n let res = ref [] in\n (try\n while true do\n\t let (c1, r1) = heap_extract_min heap in\n\t let (c2, r2) = heap_extract_min heap in\n\t let (c3, r3) = heap_extract_min heap in\n\t let [r1; r2; r3] = List.sort compare [r1; r2; r3] in\n\t res := (r3, r2, r1) :: !res;\n\t let c1 = c1 + 1 in\n\t let c2 = c2 + 1 in\n\t let c3 = c3 + 1 in\n\t if c1 <> 0 then heap_insert heap c1 r1;\n\t if c2 <> 0 then heap_insert heap c2 r2;\n\t if c3 <> 0 then heap_insert heap c3 r3;\n done\n with\n | Not_found -> ()\n );\n Printf.printf \"%d\\n\" (List.length !res);\n List.iter\n (fun (a, b, c) ->\n\t Printf.printf \"%d %d %d\\n\" a b c\n ) !res\n"}], "src_uid": "551e66a4b3da71682652d84313adb8ab"} {"nl": {"description": "Alice has a grid with $$$2$$$ rows and $$$n$$$ columns. She fully covers the grid using $$$n$$$ dominoes of size $$$1 \\times 2$$$\u00a0\u2014 Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino.Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!", "input_spec": "The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 5000$$$)\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 100$$$)\u00a0\u2014 the width of the grid. The second line of each test case contains a string $$$s$$$ consisting of $$$n$$$ characters, each of which is either L, R, U, or D, representing the left, right, top, or bottom half of a domino, respectively (see notes for better understanding). This string represents one of the rows of the grid. Additional constraint on the input: each input corresponds to at least one valid tiling.", "output_spec": "For each test case, output one string\u00a0\u2014 the other row of the grid, using the same format as the input string. If there are multiple answers, print any.", "sample_inputs": ["4\n1\nU\n2\nLR\n5\nLRDLR\n6\nUUUUUU"], "sample_outputs": ["D\nLR\nLRULR\nDDDDDD"], "notes": "NoteIn the first test case, Alice shows Bob the top row, the whole grid may look like: In the second test case, Alice shows Bob the bottom row, the whole grid may look like: In the third test case, Alice shows Bob the bottom row, the whole grid may look like: In the fourth test case, Alice shows Bob the top row, the whole grid may look like: "}, "positive_code": [{"source_code": "(* OCaml template *)\n\n(* Utility functions *)\nlet sum = List.fold_left (+) 0;;\n\nlet aux = function\n\t| 'U' -> 'D'\n\t| 'D' -> 'U'\n\t| c -> c\n\n(* Main *)\nlet t = read_int ();;\n\nfor t' = 1 to t do\n\t(* Solve test case here *)\n\tlet n = read_int () in\n\t\tlet s = read_line () in\n\t\t\tprint_endline @@ String.map aux s\ndone\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int() in\n let s = read_string() in\n for i=0 to n-1 do\n let y = match s.[i] with\n\t| 'L' -> 'L'\n\t| 'R' -> 'R'\n\t| 'U' -> 'D'\n\t| 'D' -> 'U'\n\t| _ -> failwith \"bad input\"\n in\n printf \"%c\" y;\n done;\n print_newline()\n done\n"}], "negative_code": [], "src_uid": "b894e16e8c00f8d97fde4a104466b3ef"} {"nl": {"description": "There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.", "input_spec": "The first line of the input data contains two integer numbers separated by a space n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) and k (0\u2009\u2264\u2009k\u2009\u2264\u2009106) \u2014 the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1\u2009\u2264\u2009hi\u2009\u2264\u2009106) is the height of the i-th book in millimeters.", "output_spec": "In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b \u2014 the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space \u2014 indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.", "sample_inputs": ["3 3\n14 12 10", "2 0\n10 10", "4 5\n8 19 10 13"], "sample_outputs": ["2 2\n1 2\n2 3", "2 1\n1 2", "2 1\n3 4"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let th = read_int 0 in\n let a = Array.init n read_int in\n let h1 = ref 0 and t1 = ref 0 and h2 = ref 0 and t2 = ref 0\n and q1 = Array.make n 0 and q2 = Array.make n 0\n and j = ref (-1)\n and ans = ref 0 and ansl = ref [] in\n for i = 0 to n-1 do\n while !h1 < !t1 && a.(q1.(!t1-1)) > a.(i) do\n t1 := !t1-1;\n done;\n q1.(!t1) <- i;\n t1 := !t1+1;\n while !h2 < !t2 && a.(q2.(!t2-1)) < a.(i) do\n t2 := !t2-1;\n done;\n q2.(!t2) <- i;\n t2 := !t2+1;\n while a.(q2.(!h2))-a.(q1.(!h1)) > th do\n if q1.(!h1) < q2.(!h2) then (\n j := q1.(!h1);\n h1 := !h1+1\n ) else (\n j := q2.(!h2);\n h2 := !h2+1\n )\n done;\n if i- !j > !ans then (\n ans := i- !j;\n ansl := []\n );\n if i- !j = !ans then\n ansl := (!j+1)::!ansl\n done;\n Printf.printf \"%d %d\\n\" !ans (List.length !ansl);\n List.iter (fun x -> Printf.printf \"%d %d\\n\" (x+1) (x+ !ans)) (List.rev !ansl)"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let th = read_int 0 in\n let a = Array.init n read_int in\n let h1 = ref 0 and t1 = ref 0 and h2 = ref 0 and t2 = ref 0\n and q1 = Array.make n 0 and q2 = Array.make n 0\n and ans = ref 0 and ansl = ref [] in\n for i = 0 to n-1 do\n while !h1 < !t1 && a.(q1.(!t1-1)) > a.(i) do\n t1 := !t1-1;\n done;\n q1.(!t1) <- i;\n t1 := !t1+1;\n while !h2 < !t2 && a.(q2.(!t2-1)) < a.(i) do\n t2 := !t2-1;\n done;\n q2.(!t2) <- i;\n t2 := !t2+1;\n while a.(q2.(!h2))-a.(q1.(!h1)) > th do\n if q1.(!h1) < q2.(!h2) then\n h1 := !h1+1\n else\n h2 := !h2+1\n done;\n let j = min q1.(!h1) q2.(!h2) in\n if i-j > !ans then (\n ans := i-j;\n ansl := []\n );\n if i-j = !ans then\n ansl := j::!ansl\n done;\n Printf.printf \"%d %d\\n\" (!ans+1) (List.length !ansl);\n List.iter (fun x -> Printf.printf \"%d %d\\n\" (x+1) (x+1+ !ans)) (List.rev !ansl)\n"}], "src_uid": "bc8b4b74c2f2d486e2d2f03982ef1013"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots , a_n$$$, which is sorted in non-decreasing order ($$$a_i \\le a_{i + 1})$$$. Find three indices $$$i$$$, $$$j$$$, $$$k$$$ such that $$$1 \\le i < j < k \\le n$$$ and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$ (for example it is possible to construct a non-degenerate triangle with sides $$$3$$$, $$$4$$$ and $$$5$$$ but impossible with sides $$$3$$$, $$$4$$$ and $$$7$$$). If it is impossible to find such triple, report it.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \\le n \\le 5 \\cdot 10^4$$$)\u00a0\u2014 the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ ($$$1 \\le a_i \\le 10^9$$$; $$$a_{i - 1} \\le a_i$$$)\u00a0\u2014 the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print the answer to it in one line. If there is a triple of indices $$$i$$$, $$$j$$$, $$$k$$$ ($$$i < j < k$$$) such that it is impossible to construct a non-degenerate triangle having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1.", "sample_inputs": ["3\n7\n4 6 11 11 15 18 20\n4\n10 10 10 11\n3\n1 1 1000000000"], "sample_outputs": ["2 3 6\n-1\n1 2 3"], "notes": "NoteIn the first test case it is impossible with sides $$$6$$$, $$$11$$$ and $$$18$$$. Note, that this is not the only correct answer.In the second test case you always can construct a non-degenerate triangle."}, "positive_code": [{"source_code": "let main =\n let test_cases = Scanf.scanf \" %d\" (fun x -> x) in\n\n for i = 0 to test_cases - 1 do\n let len = Scanf.scanf \" %d\" (fun x -> x) in\n assert (len >= 3);\n\n let arr = Array.init len (fun _ -> 0L) in\n Array.iteri (fun idx _ -> arr.(idx) <- Scanf.scanf \" %Ld\" (fun x -> x)) arr;\n\n if Int64.add arr.(0) arr.(1) <= arr.(len - 1) then\n print_endline (Printf.sprintf \"%d %d %d\" 1 2 len)\n else print_endline \"-1\"\n done\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet main =\n let test_cases = read_int () in\n\n for i = 0 to test_cases - 1 do\n let len = read_int () in\n assert (len >= 3);\n\n let arr = Array.init len (fun _ -> 0) in\n Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;\n\n if arr.(0) + arr.(1) <= arr.(len - 1) then\n print_endline (Printf.sprintf \"%d %d %d\" 1 2 len)\n else print_endline \"-1\"\n done\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet main =\n let test_cases = read_int () in\n\n for i = 0 to test_cases - 1 do\n let len = read_int () in\n assert (len >= 3);\n\n let arr = Array.init len (fun _ -> 0) in\n Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;\n\n let rec h i =\n match (i <= 1, arr.(0) + arr.(1) <= arr.(i)) with\n | true, _ -> \"-1\"\n | false, true -> Printf.sprintf \"%d %d %d\" 0 1 i\n | false, false -> h (i - 1)\n in\n len - 1 |> h |> print_endline\n done\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet main =\n let test_cases = read_int () in\n\n for i = 0 to test_cases - 1 do\n let len = read_int () in\n\n let arr = Array.init len (fun _ -> 0) in\n Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;\n\n if arr.(0) + arr.(1) <= arr.(len - 1) then\n print_endline (Printf.sprintf \"%d %d %d\" 1 2 len)\n else print_endline \"-1\"\n done\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet main =\n let test_cases = read_int () in\n\n for i = 0 to test_cases - 1 do\n let len = read_int () in\n assert (len >= 3);\n\n let arr = Array.init len (fun _ -> 0) in\n Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;\n\n let rec h i =\n match (i <= 1, arr.(0) + arr.(1) <= arr.(i)) with\n | true, _ -> \"-1\"\n | false, true -> Printf.sprintf \"%d %d %d\" 1 2 (i + 1)\n | false, false -> h (i - 1)\n in\n len - 1 |> h |> print_endline\n done\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet test_cases = read_int ()\n\n;;\nfor i = 0 to test_cases - 1 do\n let len = read_int () in\n assert (len >= 3);\n\n let arr = Array.init len (fun _ -> 0) in\n Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;\n\n if arr.(0) + arr.(1) <= arr.(len - 1) then\n print_endline (Printf.sprintf \"%d %d %d\" 1 2 len)\n else print_endline \"-1\"\ndone\n"}], "src_uid": "341555349b0c1387334a0541730159ac"} {"nl": {"description": "Casimir has a string $$$s$$$ which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions: he can either erase exactly one letter 'A' and exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent); or he can erase exactly one letter 'B' and exactly one letter 'C' from arbitrary places in the string (these letters don't have to be adjacent). Therefore, each turn the length of the string is decreased exactly by $$$2$$$. All turns are independent so for each turn, Casimir can choose any of two possible actions.For example, with $$$s$$$\u00a0$$$=$$$\u00a0\"ABCABC\" he can obtain a string $$$s$$$\u00a0$$$=$$$\u00a0\"ACBC\" in one turn (by erasing the first occurrence of 'B' and the second occurrence of 'A'). There are also many other options for a turn aside from this particular example.For a given string $$$s$$$ determine whether there is a sequence of actions leading to an empty string. In other words, Casimir's goal is to erase all letters from the string. Is there a way to do this?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Each test case is described by one string $$$s$$$, for which you need to determine if it can be fully erased by some sequence of turns. The string $$$s$$$ consists of capital letters 'A', 'B', 'C' and has a length from $$$1$$$ to $$$50$$$ letters, inclusive.", "output_spec": "Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if there is a way to fully erase the corresponding string and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).", "sample_inputs": ["6\nABACAB\nABBA\nAC\nABC\nCABCBB\nBCBCBCBCBCBCBCBC"], "sample_outputs": ["NO\nYES\nNO\nNO\nYES\nYES"], "notes": null}, "positive_code": [{"source_code": "let count s =\r\n let l = String.length s in\r\n let rec iterate i a b c =\r\n if i >= l then (a, b, c) else\r\n match s.[i] with\r\n 'A' -> iterate (i+1) (a+1) b c\r\n |'B' -> iterate (i+1) a (b+1) c\r\n |'C' -> iterate (i+1) a b (c+1)\r\n | _ -> invalid_arg \"count: invalid character\"\r\n in iterate 0 0 0 0;;\r\n\r\nlet solve s =\r\n let (a, b, c) = count s in\r\n if a + c = b then\r\n begin\r\n print_string \"YES\"; print_newline ()\r\n end\r\n else\r\n begin\r\n print_string \"NO\"; print_newline () \r\n end;;\r\n\r\nlet t = read_int ();;\r\n\r\nlet rec main i =\r\n if i < t then\r\n let s = read_line () in\r\n begin\r\n solve s; main (i+1)\r\n end;;\r\n\r\nmain 0;;\r\n"}], "negative_code": [{"source_code": "let count s =\r\n let l = String.length s and (a, b, c) = (0,0,0) in\r\n let rec iterate i =\r\n if i >= l then (a, b, c) else\r\n match s.[i] with\r\n 'A' -> let a = a+1 in iterate (i+1)\r\n |'B' -> let b = b+1 in iterate (i+1)\r\n |'C' -> let c = c+1 in iterate (i+1)\r\n | _ -> invalid_arg \"count: invalid character\"\r\n in iterate 0;;\r\n\r\nlet solve s =\r\n let (a, b, c) = count s in\r\n if a + c = b then\r\n begin\r\n print_string \"YES\"; print_newline ()\r\n end\r\n else\r\n begin\r\n print_string \"NO\"; print_newline () \r\n end;;\r\n\r\nlet t = read_int ();;\r\n\r\nlet rec main i =\r\n if i < t then\r\n let s = read_line () in\r\n begin\r\n solve s; main (i+1)\r\n end;;\r\n\r\nmain 0;;\r\n"}], "src_uid": "ca6b162f945d4216055bf92d7263dbd5"} {"nl": {"description": "Are you going to Scarborough Fair?Parsley, sage, rosemary and thyme.Remember me to one who lives there.He once was the true love of mine.Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.Although the girl wants to help, Willem insists on doing it by himself.Grick gave Willem a string of length n.Willem needs to do m operations, each operation has four parameters l,\u2009r,\u2009c1,\u2009c2, which means that all symbols c1 in range [l,\u2009r] (from l-th to r-th, including l and r) are changed into c2. String is 1-indexed.Grick wants to know the final string after all the m operations.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). The second line contains a string s of length n, consisting of lowercase English letters. Each of the next m lines contains four parameters l,\u2009r,\u2009c1,\u2009c2 (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n, c1,\u2009c2 are lowercase English letters), separated by space.", "output_spec": "Output string s after performing m operations described above.", "sample_inputs": ["3 1\nioi\n1 1 i n", "5 3\nwxhak\n3 3 h x\n1 5 x a\n1 3 w g"], "sample_outputs": ["noi", "gaaak"], "notes": "NoteFor the second example:After the first operation, the string is wxxak.After the second operation, the string is waaak.After the third operation, the string is gaaak."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet string_replace s l r o t =\n let f i c =\n if i >= l && i <= r && c = o then\n t\n else\n c\n in\n String.mapi f s\n;;\n\nlet () =\n let (n, m) = bscanf Scanning.stdin \" %d %d\" (fun x y -> (x, y)) in\n let s = bscanf Scanning.stdin \" %s\" (fun x -> x) in\n let rec solve i result =\n if i = m\n then result\n else\n let (l, r, o, t) =\n bscanf Scanning.stdin \" %d %d %c %c\" (fun a b c d -> (a, b, c, d)) in\n let l = l-1 in\n let r = r-1 in\n let result = string_replace result l r o t in\n solve (i+1) result\n in\n printf \"%s\\n\" (solve 0 s);;\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet string_replace s l r o t =\n let f i c =\n if i >= l && i <= r && c = o then\n t\n else\n c\n in\n String.mapi f s\n;;\n\nlet () =\n let (n, m) = bscanf Scanning.stdin \" %d %d\" (fun x y -> (x, y)) in\n let s = bscanf Scanning.stdin \" %s\" (fun x -> x) in\n let rec solve i result =\n if i = m\n then result\n else\n let (l, r, o, t) =\n bscanf Scanning.stdin \" %d %d %c %c\" (fun a b c d -> (a, b, c, d)) in\n let ll = l-1 in\n let rr = r-1 in\n let tmp = string_replace result ll rr o t in\n solve (i+1) tmp\n in\n printf \"%s\\n\" (solve 0 s);;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let (n,m) = read_pair () in\n let s = read_string() in\n let rec loop i ac = if i=m then ac else (\n let (l,r) = read_pair() in\n let r = r-1 in\n let l = l-1 in\n let c1 = (read_string()).[0] in\n let c2 = (read_string()).[0] in\n let ac = String.init n (fun i -> if i < l || i > r then ac.[i]\n\telse if ac.[i] = c1 then c2 else ac.[i])\n in\n loop (i+1) ac\n )\n in\n\n printf \"%s\\n\" (loop 0 s)\n"}], "negative_code": [{"source_code": "open Scanf\nopen Printf\n\nlet string_replace s l r o t =\n let f i c =\n if i >= l && i <= r && c = o then\n t\n else\n s.[i] in\n String.mapi f s\n;;\n\nlet () =\n let (n, m) = bscanf Scanning.stdin \" %d %d\" (fun x y -> (x, y)) in\n let s = bscanf Scanning.stdin \" %s\" (fun x -> x) in\n let rec solve i result =\n if i = m\n then result\n else\n let (l, r, o, t) =\n bscanf Scanning.stdin \" %d %d %c %c\" (fun a b c d -> (a, b, c, d)) in\n let ll = l-1 in\n let rr = r-1 in\n let tmp = string_replace s ll rr o t in\n solve (i+1) tmp\n in\n printf \"%s\\n\" (solve 0 s);;\n"}], "src_uid": "3f97dc063286a7af4838b7cd1c01df69"} {"nl": {"description": "There are $$$n$$$ pieces of cake on a line. The $$$i$$$-th piece of cake has weight $$$a_i$$$ ($$$1 \\leq i \\leq n$$$).The tastiness of the cake is the maximum total weight of two adjacent pieces of cake (i.\u00a0e., $$$\\max(a_1+a_2,\\, a_2+a_3,\\, \\ldots,\\, a_{n-1} + a_{n})$$$).You want to maximize the tastiness of the cake. You are allowed to do the following operation at most once (doing more operations would ruin the cake): Choose a contiguous subsegment $$$a[l, r]$$$ of pieces of cake ($$$1 \\leq l \\leq r \\leq n$$$), and reverse it. The subsegment $$$a[l, r]$$$ of the array $$$a$$$ is the sequence $$$a_l, a_{l+1}, \\dots, a_r$$$.If you reverse it, the array will become $$$a_1, a_2, \\dots, a_{l-2}, a_{l-1}, \\underline{a_r}, \\underline{a_{r-1}}, \\underline{\\dots}, \\underline{a_{l+1}}, \\underline{a_l}, a_{r+1}, a_{r+2}, \\dots, a_{n-1}, a_n$$$.For example, if the weights are initially $$$[5, 2, 1, 4, 7, 3]$$$, you can reverse the subsegment $$$a[2, 5]$$$, getting $$$[5, \\underline{7}, \\underline{4}, \\underline{1}, \\underline{2}, 3]$$$. The tastiness of the cake is now $$$5 + 7 = 12$$$ (while before the operation the tastiness was $$$4+7=11$$$).Find the maximum tastiness of the cake after doing the operation at most once.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 50$$$) \u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 1000$$$) \u2014 the number of pieces of cake. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) \u2014 $$$a_i$$$ is the weight of the $$$i$$$-th piece of cake.", "output_spec": "For each test case, print a single integer: the maximum tastiness of the cake after doing the operation at most once.", "sample_inputs": ["5\n6\n5 2 1 4 7 3\n3\n32 78 78\n3\n69 54 91\n8\n999021 999021 999021 999021 999652 999021 999021 999021\n2\n1000000000 1000000000"], "sample_outputs": ["12\n156\n160\n1998673\n2000000000"], "notes": "NoteIn the first test case, after reversing the subsegment $$$a[2, 5]$$$, you get a cake with weights $$$[5, \\underline{7}, \\underline{4}, \\underline{1}, \\underline{2}, 3]$$$. The tastiness of the cake is now $$$\\max(5+7, 7+4, 4+1, 1+2, 2+3) = 12$$$. This is the maximum possible tastiness of the cake one can obtain by performing the operation at most once.In the second test case, it's optimal not to do any operation. The tastiness is $$$78+78 = 156$$$.In the third test case, after reversing the subsegment $$$a[1, 2]$$$, you get a cake with weights $$$[\\underline{54}, \\underline{69}, 91]$$$. The tastiness of the cake is now $$$\\max(54+69, 69+91) = 160$$$. There is no way to make the tastiness of the cake greater than $$$160$$$ by performing at most one operation."}, "positive_code": [{"source_code": "let parse len str = let rep = Array.make len (-1) in\r\n let temp = ref \"\" in\r\n let j = ref 0 in\r\n for i = 0 to String.length str -1 do\r\n if str.[i] = ' ' then \r\n (rep.(!j) <- (int_of_string !temp) ; incr j ; temp:=\"\" ) \r\n else \r\n (temp:= !temp ^ (String.make 1 str.[i]))\r\n done; rep.(!j) <- (int_of_string !temp) ;rep\r\n;; \r\n\r\nlet search2mmax t = let n = Array.length t in\r\n let min1 = ref (-1) in\r\n let min2 = ref (-2) in\r\n for i = 0 to n-1 do\r\n if (!min1 = -1 || (!min1 < !min2 && !min2 <> -2 && t.(i)> !min1 )) then\r\n min1 := t.(i)\r\n else (if (!min2 = -2 || (!min1 >= !min2 && t.(i)> !min2 )) then\r\n min2:= t.(i)\r\n );\r\n \r\n done; (Int64.add (Int64.of_int (!min1)) (Int64.of_int (!min2)) ) \r\n;;\r\n\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n -1 do\r\n let len = int_of_string(input_line stdin) in\r\n let str = input_line stdin in\r\n let toto = parse len str in \r\n print_endline (Int64.to_string (search2mmax toto)) ;\r\ndone;;\r\n\t"}], "negative_code": [{"source_code": "let parse len str = let rep = Array.make len (-1) in\r\n let temp = ref \"\" in\r\n let j = ref 0 in\r\n for i = 0 to String.length str -1 do\r\n if str.[i] = ' ' then \r\n (rep.(!j) <- (int_of_string !temp) ; incr j ; temp:=\"\" ) \r\n else \r\n (temp:= !temp ^ (String.make 1 str.[i]))\r\n done; rep.(!j) <- (int_of_string !temp) ;rep\r\n;; \r\n\r\nlet search2mmax t = let n = Array.length t in\r\n let min1 = ref (-1) in\r\n let min2 = ref (-2) in\r\n for i = 0 to n-1 do\r\n if (!min1 = -1 || (!min1 < !min2 && !min2 <> -2 && t.(i)> !min1 )) then\r\n min1 := t.(i)\r\n else (if (!min2 = -2 || (!min1 >= !min2 && t.(i)> !min2 )) then\r\n min2:= t.(i)\r\n );\r\n \r\n \r\n done; Int64.to_int (Int64.add (Int64.of_int (!min1)) (Int64.of_int (!min2)) ) \r\n;;\r\n\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n -1 do\r\n let len = int_of_string(input_line stdin) in\r\n let str = input_line stdin in\r\n let toto = parse len str in \r\n print_endline (string_of_int (search2mmax toto)) ;\r\ndone;;\r\n\t"}, {"source_code": "let parse len str = let rep = Array.make len (-1) in\r\n let temp = ref \"\" in\r\n let j = ref 0 in\r\n for i = 0 to String.length str -1 do\r\n if str.[i] = ' ' then \r\n (rep.(!j) <- (int_of_string !temp) ; incr j ; temp:=\"\" ) \r\n else \r\n (temp:= !temp ^ (String.make 1 str.[i]))\r\n done; rep.(!j) <- (int_of_string !temp) ;rep\r\n;; \r\n\r\nlet search2mmax t = let n = Array.length t in\r\n let min1 = ref (-1) in\r\n let min2 = ref (-2) in\r\n for i = 0 to n-1 do\r\n if (!min1 = -1 || (!min1 < !min2 && !min2 <> -2 && t.(i)> !min1 )) then\r\n min1 := t.(i)\r\n else (if (!min2 = -2 || (!min1 >= !min2 && t.(i)> !min2 )) then\r\n min2:= t.(i)\r\n );\r\n \r\n \r\n done; !min1 + !min2 \r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n -1 do\r\n let len = int_of_string(input_line stdin) in\r\n let str = input_line stdin in\r\n let toto = parse len str in \r\n print_endline (string_of_int (search2mmax toto)) ;\r\ndone;;\r\n"}, {"source_code": "let parse len str = let rep = Array.make len (-1) in\r\n let temp = ref \"\" in\r\n let j = ref 0 in\r\n for i = 0 to String.length str -1 do\r\n if str.[i] = ' ' then \r\n (rep.(!j) <- (int_of_string !temp) ; incr j ; temp:=\"\" ) \r\n else \r\n (temp:= !temp ^ (String.make 1 str.[i]))\r\n done; rep.(!j) <- (int_of_string !temp) ;rep\r\n;; \r\n\r\nlet search2min t = let n = Array.length t in\r\n let min1 = ref (-1) in\r\n let min2 = ref (-2) in\r\n for i = 0 to n-1 do\r\n if (!min1 = -1 || (!min1 > !min2 && !min2 <> -2 && t.(i)< !min1 )) then\r\n min1 := t.(i)\r\n else (if (!min2 = -2 || (!min1 <= !min2 && t.(i)< !min2 )) then\r\n min2:= t.(i)\r\n );\r\n \r\n \r\n done; !min1 + !min2 \r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n -1 do\r\n let len = int_of_string(input_line stdin) in\r\n let str = input_line stdin in\r\n let toto = parse len str in \r\n print_endline (string_of_int (search2min toto)) ;\r\ndone;;\r\n"}], "src_uid": "b856eafe350fccaabd39b97fb18d9c2f"} {"nl": {"description": "A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters \"-\".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format \"dd-mm-yyyy\". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy \"0012-10-2012-10-2012\" mentions date 12-10-2012 twice (first time as \"0012-10-2012-10-2012\", second time as \"0012-10-2012-10-2012\").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format \"dd-mm-yyyy\", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date \"1-1-2013\" isn't recorded in the format \"dd-mm-yyyy\", and date \"01-01-2013\" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.", "input_spec": "The first line contains the Prophesy: a non-empty string that only consists of digits and characters \"-\". The length of the Prophesy doesn't exceed 105 characters.", "output_spec": "In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.", "sample_inputs": ["777-444---21-12-2013-12-2013-12-2013---444-777"], "sample_outputs": ["13-12-2013"], "notes": null}, "positive_code": [{"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) ;;\n\nlet prophesy = read_string () ;;\n\nlet isdigit c = (c >= '0' && c <= '9') ;;\n\nlet months = [|0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31|] ;;\n\nlet parse_date date =\n Scanf.sscanf date \"%d-%d-%d\" (fun d m y -> (d, m, y))\n \nlet valid_date date = \n let rec loop i = \n if i >= 10 then true\n else if (i = 2 || i = 5) && date.[i] = '-' then loop (i + 1)\n else if i != 2 && i != 5 && isdigit date.[i] then loop (i + 1)\n else false\n in if (loop 0) = false then false \n else let (d, m, y) = parse_date date\n in y >= 2013 && y <= 2015 && m > 0 && m <= 12 && d > 0 && d <= months.(m) ;;\n\nlet freq = \n let matrix = Array.make 32 (Array.make_matrix 13 2016 0) in\n for i = 0 to 31 do\n matrix.(i) <- Array.make_matrix 13 2016 0\n done ;\n matrix ;;\n\nlet apocalypse = \n let rec loop i date count =\n if i > (String.length prophesy) - 10 then date\n else \n let cur_date = String.sub prophesy i 10 \n in if valid_date cur_date then let (d, m, y) = parse_date cur_date \n in \n (\n freq.(d).(m).(y) <- freq.(d).(m).(y) + 1 ;\n if freq.(d).(m).(y) > count then \n loop (i + 1) cur_date freq.(d).(m).(y)\n else\n loop (i + 1) date count\n ) \n else loop (i + 1) date count\n in loop 0 \"\" 0 ;;\n\nPrintf.printf \"%s\\n\" apocalypse ;;"}, {"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet days = [|31;28;31;30;31;30;31;31;30;31;30;31|]\n\nlet is_digit c = c >= '0' && c <= '9'\n\nlet valid_date s =\n (List.for_all (fun p -> is_digit s.[p]) [0;1;3;4;6;7;8;9]) &&\n (List.for_all (fun p -> s.[p] = '-') [2;5]) &&\n (\n let d = int_of_string (String.sub s 0 2) in\n let m = int_of_string (String.sub s 3 2) in\n let y = int_of_string (String.sub s 6 4) in\n\tm>=1 && m<=12 && d>=1 && d<=days.(m-1) && y>=2013 && y<=2015\n )\n \nlet () = \n let s = read_string () in\n let n = String.length s in\n\n let h = Hashtbl.create 10 in\n\n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n \n for i=0 to n-10 do\n let t = String.sub s i 10 in\n\tif valid_date t then increment t\n done;\n\n let m = Hashtbl.fold (fun _ c ac -> max c ac) h 0 in\n\n let t = Hashtbl.fold (fun s c ac -> if c = m then s else ac) h \"\" in\n\n Printf.printf \"%s\\n\" t\n"}], "negative_code": [{"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) ;;\n\nlet prophesy = read_string () ;;\n\nlet isdigit c = (c >= '0' && c <= '9') ;;\n\nlet months = [|0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31|] ;;\n\nlet parse_date date =\n Scanf.sscanf date \"%d-%d-%d\" (fun d m y -> (d, m, y))\n \nlet valid_date date = \n let rec loop i = \n if i >= 10 then true\n else if (i = 2 || i = 5) && date.[i] = '-' then loop (i + 1)\n else if i != 2 && i != 5 && isdigit date.[i] then loop (i + 1)\n else false\n in if (loop 0) = false then false \n else let (d, m, y) = parse_date date\n in y >= 2013 && y <= 2015 && m > 0 && m <= 12 && d > 0 && d <= months.(m) ;;\n\nlet freq = Array.make 32 (Array.make_matrix 13 2016 0) ;;\n\nlet apocalypse = \n let rec loop i date count =\n if i > (String.length prophesy) - 10 then date\n else \n let cur_date = String.sub prophesy i 10 \n in if valid_date cur_date then let (d, m, y) = parse_date cur_date \n in \n (\n freq.(d).(m).(y) <- freq.(d).(m).(y) + 1 ;\n if freq.(d).(m).(y) >= count then \n loop (i + 1) cur_date freq.(d).(m).(y)\n else\n loop (i + 1) date count\n ) \n else loop (i + 1) date count\n in loop 0 \"\" 0 ;;\n\nPrintf.printf \"%s\\n\" apocalypse ;;"}, {"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) ;;\n\nlet prophesy = read_string () ;;\n\nlet isdigit c = (c >= '0' && c <= '9') ;;\n\nlet months = [|0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31|] ;;\n\nlet parse_date date =\n Scanf.sscanf date \"%d-%d-%d\" (fun d m y -> (d, m, y))\n \nlet valid_date date = \n let rec loop i = \n if i >= 10 then true\n else if (i = 2 || i = 5) && date.[i] = '-' then loop (i + 1)\n else if i != 2 && i != 5 && isdigit date.[i] then loop (i + 1)\n else false\n in if (loop 0) = false then false \n else let (d, m, y) = parse_date date\n in y >= 2013 && y <= 2015 && m > 0 && m <= 12 && d > 0 && d <= months.(m) ;;\n\nlet freq = Array.make 32 (Array.make_matrix 13 2016 0) ;;\n\nlet apocalypse = \n let rec loop i date count =\n if i > (String.length prophesy) - 10 then date\n else \n let cur_date = String.sub prophesy i 10 \n in if valid_date cur_date then let (d, m, y) = parse_date cur_date \n in \n (\n freq.(d).(m).(y) <- freq.(d).(m).(y) + 1 ;\n if freq.(d).(m).(y) > count then \n loop (i + 1) cur_date freq.(d).(m).(y)\n else\n loop (i + 1) date count\n ) \n else loop (i + 1) date count\n in loop 0 \"\" 0 ;;\n\nPrintf.printf \"%s\\n\" apocalypse ;;"}, {"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet days = [|31;28;31;30;31;30;31;31;30;31;31;31|]\n\nlet is_digit c = c >= '0' && c <= '9'\n\nlet valid_date s =\n (List.for_all (fun p -> is_digit s.[p]) [0;1;3;4;6;7;8;9]) &&\n (List.for_all (fun p -> s.[p] = '-') [2;5]) &&\n (\n let d = int_of_string (String.sub s 0 2) in\n let m = int_of_string (String.sub s 3 2) in\n let y = int_of_string (String.sub s 6 4) in\n\tm>=1 && m<=12 && d>=1 && d<=days.(m-1) && y>=2013 && y<=2015\n )\n \nlet () = \n let s = read_string () in\n let n = String.length s in\n\n let h = Hashtbl.create 10 in\n\n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n \n for i=0 to n-10 do\n let t = String.sub s i 10 in\n\tif valid_date t then increment t\n done;\n\n let m = Hashtbl.fold (fun _ c ac -> max c ac) h 0 in\n\n let t = Hashtbl.fold (fun s c ac -> if c = m then s else ac) h \"\" in\n\n Printf.printf \"%s\\n\" t\n"}], "src_uid": "dd7fd84f7915ad57b0e21f416e2a3ea0"} {"nl": {"description": "Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive \"OR\", that is denoted as \"xor\" in Pascal and \"^\" in C/C++/Java.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.", "output_spec": "Print a single integer \u2014 the required maximal xor of a segment of consecutive elements.", "sample_inputs": ["5\n1 2 1 1 2", "3\n1 2 7", "4\n4 2 4 8"], "sample_outputs": ["3", "7", "14"], "notes": "NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three)."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun i -> read_int()) in\n let v = Array.make_matrix n n 0 in\n for i=0 to n-1 do\n v.(i).(i) <- a.(i);\n done;\n for i=0 to n-1 do\n for j=i+1 to n-1 do\n\tv.(i).(j) <- v.(i).(j-1) lxor a.(j)\n done\n done;\n\n let m = ref 0 in\n for i=0 to n-1 do\n\tfor j=i to n-1 do\n\t m := max v.(i).(j) !m\n\tdone\n done;\n \n Printf.printf \"%d\\n\" !m\n \n \n"}], "negative_code": [], "src_uid": "a33991c9d7fdb4a4e00c0d0e6902bee1"} {"nl": {"description": "In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second \u2014 number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 \u2014 AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.", "input_spec": "The first line of the input contains integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .", "output_spec": "Write n lines, each line should contain a cell coordinates in the other numeration system.", "sample_inputs": ["2\nR23C55\nBC23"], "sample_outputs": ["BC23\nR23C55"], "notes": null}, "positive_code": [{"source_code": "let rec base_26 a = \n if a = 0 then [0]\n else if a < 0 then []\n else (a mod 26) :: (base_26 (a / 26 - 1))\n\nlet inv26 a = \n let n = String.length a in\n let r = ref 0 in\n for i = 0 to (n-1) do \n r := !r * 26 + (Char.code a.[i] - 64)\n done;\n !r\n\nlet rec implode lc = \n match lc with\n |[] -> \"\"\n |c::t -> Printf.sprintf \"%c%s\" c (implode t)\n\nlet convert_nb n = \n let n = int_of_string n in\n let l = List.rev (base_26 (n - 1)) in\n implode (List.map (fun n -> Char.chr (n + 65)) l)\n\nlet () = \n let s = read_line () in \n let n = int_of_string s in\n for i = 0 to (n-1) do \n let s = read_line () in \n if Str.string_match (Str.regexp \"R[0-9]+C[0-9]+\") s 0 then begin\n let s = String.sub s 1 (String.length s - 1) in\n let [a;b] = Str.split (Str.regexp \"C\") s in\n Printf.printf \"%s%s\\n\" (convert_nb b) a\n end else begin\n ignore (Str.search_forward (Str.regexp \"[A-Z]+\") s 0);\n let a = Str.matched_string s in\n ignore (Str.search_forward (Str.regexp \"[0-9]+\") s 0);\n let b = Str.matched_string s in\n Printf.printf \"R%sC%i\\n\" b (inv26 a) \n end\n done;\n"}, {"source_code": "let (|>) x f = f x\n\nlet is_letter char =\n match char with\n 'A'..'Z' -> true\n | _ -> false\n\nlet is_digit char =\n match char with\n '0'..'9' -> true\n | _ -> false\n\nlet parse_pair s pos =\n let rec parse pred p =\n if p < String.length s && pred (String.get s p)\n then parse pred (p+1)\n else p\n in\n let pos1 = parse is_letter pos in\n let pos2 = parse is_digit pos1 in\n ((String.sub s pos (pos1 - pos), String.sub s pos1 (pos2 - pos1)), pos2)\n\nlet colrow_to_rowcol (col, row) =\n let int_of_letters letters =\n let res = ref 0 in\n String.iter (fun c -> res := !res * 26 + (int_of_char c) - 64) letters;\n !res\n in\n Printf.sprintf \"R%dC%d\" (int_of_string row) (int_of_letters col)\n\nlet rowcol_to_colrow (_, row) (_, col) =\n let rec letters_of_int n acc =\n if n = 0\n then acc\n else letters_of_int ((n-1) / 26) ((String.make 1 (char_of_int (65 + ((n-1) mod 26)))) ^ acc)\n in\n Printf.sprintf \"%s%s\" (letters_of_int (int_of_string col) \"\") row\n\nlet convert s =\n let pair1, pos = parse_pair s 0 in\n if pos = String.length s\n then colrow_to_rowcol pair1\n else let pair2, _ = (parse_pair s pos) in\n rowcol_to_colrow pair1 pair2\n\nlet iterate n =\n for i = 1 to n do\n read_line ()\n |> convert\n |> Printf.printf \"%s\\n\"\n done\n\nlet _= \n read_int ()\n |> iterate\n"}, {"source_code": "open Printf\nopen Scanf\n\ntype coord = \n | RC of int * int (* row, column *)\n | Concat of string * int (* column, row *)\n\nlet parse: string -> coord =\n fun s ->\n if (Str.string_match (Str.regexp \"R[0-9]+C[0-9]+\") s 0) then\n let sep = Str.search_forward (Str.regexp \"C[0-9]+\") s 0 in\n let a = int_of_string (Str.string_after (Str.string_before s sep) 1) in\n let b = int_of_string (Str.string_after s (sep + 1)) in\n RC (a, b) \n else\n let sep = Str.search_forward (Str.regexp \"[0-9]+\") s 0 in\n let a = Str.string_before s sep in\n let b = int_of_string (Str.string_after s sep) in\n Concat (a, b)\n\nlet pp: coord -> string =\n fun c ->\n match c with\n | RC(a, b) -> \"R\" ^ (string_of_int a) ^ \"C\" ^ (string_of_int b)\n | Concat(a, b) -> a ^ (string_of_int b)\n\nlet translate: coord -> coord =\n let char_to_num c = (Char.code c) - (Char.code 'A') + 1in\n let num_to_char n = Char.chr ((Char.code 'A') - 1 + n) in\n let num_to_str_system n =\n let rec inner i s =\n let d = i / 26\n and r = i mod 26 in\n if d > 0 then\n if r = 0 then\n if d > 1 then\n inner (d - 1) ((String.make 1 'Z') ^ s)\n else ((String.make 1 'Z') ^ s)\n else\n inner d ((String.make 1 (num_to_char r)) ^ s)\n else\n (String.make 1 (num_to_char r)) ^ s\n in\n inner n \"\"\n in\n let str_to_num_system s =\n let rec inner s = \n if (String.length s > 1) then\n (char_to_num s.[String.length s - 1]) + 26 * (inner (Str.string_before s (String.length s - 1)))\n else\n (char_to_num s.[String.length s - 1])\n in\n inner s\n in\n fun c ->\n match c with\n | RC(a, b) -> Concat(num_to_str_system b, a)\n | Concat(a, b) -> RC(b, str_to_num_system a)\n\nlet main () =\n let input = input_line stdin in\n let n = sscanf input \"%i\" (fun x -> x) in\n for i = 1 to n do\n let input = input_line stdin in\n let s = sscanf input \"%s\" (fun x -> x) in\n let c = parse s in\n let t = translate c in\n printf \"%s\\n\" (pp t);\n done\n\nlet _ = main ()\n"}, {"source_code": "let (|>) x f = f x\n\nlet rc2xls r c =\n let rec go c acc =\n if c = 0 then\n String.concat \"\" acc\n else\n let t = (c-1) mod 26 in\n go ((c-t-1)/26) (String.make 1 (Char.chr (t+65))::acc)\n in String.concat \"\" [go c []; string_of_int r]\n\nlet foldl f acc s =\n let n = String.length s in\n let rec go i acc =\n if i >= n then\n acc\n else\n go (i+1) (f acc s.[i])\n in go 0 acc\n\nlet xls2rc r c =\n String.concat \"\" [\"R\"; string_of_int c; \"C\"; string_of_int (foldl (fun acc x -> acc*26+(Char.code x-64)) 0 r)]\n\nlet () =\n for i = 1 to read_int () do\n let s = read_line () in\n try\n Scanf.sscanf s \"R%dC%d\" (fun r c ->\n rc2xls r c |> print_endline\n )\n with _ ->\n Scanf.sscanf s \"%[A-Z]%d\" (fun r c ->\n xls2rc r c |> print_endline\n )\n done\n"}, {"source_code": "let n = read_int () ;;\nlet r = Str.regexp \"R[0-9]+C[0-9]+\" ;;\nfor i = 1 to n do\n let coord = read_line () in\n let is_first = Str.string_match r coord 0 in\n if is_first then begin\n let coords = Str.split (Str.regexp \"[A-Z]\") coord in\n let col = int_of_string (List.nth coords 0) in\n let row = int_of_string (List.nth coords 1) in\n let buf1 = Buffer.create 1000 in\n let rec rstring num buf = \n let r = num mod 26 in\n if (num/26) = 0 then begin\n let _ = Buffer.add_char buf (Char.chr (r+64)) in\n Buffer.contents buf\n end\n else if r != 0 then begin\n let _ = Buffer.add_char buf (Char.chr (r+64)) in\n rstring (num/26) buf\n end\n else if ((num-1)/26) != 0 then begin\n let _ = Buffer.add_char buf 'Z' in\n rstring ((num-1)/26) buf\n end\n else begin\n let _ = Buffer.add_char buf 'Z' in\n Buffer.contents buf\n end in\n\n let rec rev s =\n let sl = String.length s in\n for j=0 to (sl-1)/2 do\n let c = s.[j] in\n s.[j] <- s.[sl-j-1];\n s.[sl-j-1] <- c;\n done;\n s in\n let row_s = rev (rstring (row) (Buffer.create 2)) in\n let _ = Printf.printf \"%s%d\\n\" row_s col in\n\n\n row\n end\n else begin\n let rec row str j runner = \n let fchar = Char.code str.[j] in\n let schar = Char.code str.[j+1] in\n if schar >= 65 then\n let runner = runner + fchar-64 in\n row str (j+1) (runner*26) \n else\n runner + fchar - 64 in\n let rnum = row coord 0 0 in\n let cpos = Str.search_forward (Str.regexp \"[0-9]+\") coord 0 in\n (*let cstring = String.sub coord cpos ((String.length coord)-cpos) in\n *)\n let cstring = Str.matched_string coord in\n let cint = int_of_string cstring in\n let _ = Printf.printf \"R%dC%d\\n\" cint rnum in\n 1\n end\ndone;\n"}, {"source_code": "open Scanf;;\nopen String;;\n\ntype cell = RC | NRC;;\n\nlet print_cell t = match t with\n RC -> print_endline \"RC\"\n |NRC -> print_endline \"NRC\"\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x);;\n\nlet ntostring=[|\"A\";\"B\";\"C\";\"D\";\"E\";\"F\";\"G\";\"H\";\"I\";\"J\";\"K\";\"L\";\"M\";\"N\";\"O\";\"P\";\"Q\";\"R\";\"S\";\"T\";\"U\";\"V\";\"W\";\"X\";\"Y\";\"Z\"|];;\n\nlet myindex s c = try index s c with Not_found -> -100;;\n\nlet is_digit = function\n '0'..'9' -> true\n |_ -> false;;\n\nlet rec digit_index x ind =\n let len = length x in\n match len with\n | 0 -> ind\n | _ -> match get x 0 with\n | '0' .. '9' -> ind\n |_ -> digit_index (sub x 1 (len - 1) ) (ind + 1)\n;;\nlet rec process_RC x = \n let (rown,coln) = get_num x in\n print_string (convert_to_AB coln); print_string (string_of_int rown); print_endline \"\";\nand get_num x = let m = index x 'C' in\n let tmp = (length x) - m -1 in\n let tmp1 = match tmp with\n | x when x <=0 -> 1\n |_ -> int_of_string (sub x (m+1) tmp)\n in\n (int_of_string (sub x 1 (m-1)), tmp1)\nand convert_to_AB x = \n let y = ref x in\n let ss = ref \"\" in\n let () = \n while !y > 0 do\n let tmp = ((!y-1) mod 26) in\n y := (!y - tmp - 1) / 26;\n ss := ntostring.(tmp) ^ !ss\n done in !ss;;\n\nlet rec process_NRC x = \n let (ab,row) = get_content x in\n print_char 'R'; print_string (string_of_int row); print_char 'C';\n print_string(string_of_int (convert_to_int ab)); \n print_endline \"\";\nand get_content x =\n let m = digit_index x 0 in\n let tmp=(length x) -m in\n let tmp2 = match tmp with\n |0 -> 1\n |_ -> int_of_string (sub x m tmp) in\n (sub x 0 m, tmp2)\nand convert_to_int x = \n let k = ref ((length x) - 1) in\n let mul = ref 1 in\n let acc = ref 0 in\n let nA = int_of_char 'A' in\n let () =\n while !k >=0 do\n let f = get x !k in\n let g = (int_of_char f) - nA + 1 in\n acc := !acc + g*(!mul); mul:= !mul* 26; k:=!k-1\n done in !acc\n;;\n\nlet process t s = match t with\n RC -> process_RC s\n |NRC -> process_NRC s\n;;\n\nfor i=1 to n do\n let ms = ref (String.make 32 'A') in\n let () = \n ms := Scanf.bscanf Scanf.Scanning.stdin \"%s \" (fun x -> x) \n in\n let t = match (myindex !ms 'R', myindex !ms 'C') with\n | (-100, _) -> NRC\n | (_,-100) -> NRC\n | (a, b) -> if b - a > 1 && (is_digit (get !ms (a+1))) then RC else NRC\n in (*print_string ! ms; print_string \" : \";*) process t !ms\ndone;; \n\n"}, {"source_code": "type mode =\n S0\n | S1 of string\n | S2 of string * int\n | S3\n | S4 of int\n | S5 of int\n | S6 of int * int\n\ntype ('a, 'b) either = Left of 'a | Right of 'b\n\nlet _ =\n let n = read_int () in\n let c2s c = String.make 1 c in\n let s2i s =\n let l = String.length s in\n let rec loop i acc =\n if i = l then acc else loop (i + 1) (acc * 26 + int_of_char s.[i] - 64)\n in\n loop 0 0\n in\n let i2s a =\n let rec loop i acc =\n if i = 0 then acc else loop ((i - 1) / 26) (c2s (char_of_int (((i - 1)mod 26) + 65)) ^ acc)\n in\n loop a \"\"\n in\n let conv s =\n let s = s ^ \".\" in\n let rec loop i mode =\n match mode, s.[i] with\n | S0, 'R' -> loop (i + 1) S3\n | S0, k -> loop (i + 1) (S1 (c2s k))\n | S1 a, ('0' .. '9' as k) -> loop (i + 1) (S2 (a, int_of_char k - 48))\n | S1 a, k -> loop (i + 1) (S1 (a ^ c2s k))\n | S2 (a, b), '.' -> Left (a, b)\n | S2 (a, b), ('0' .. '9' as k) -> loop (i + 1) (S2 (a, b * 10 + int_of_char k - 48))\n | S3, ('0' .. '9' as k) -> loop (i + 1) (S4 (int_of_char k - 48))\n | S3, k -> loop (i + 1) (S1 (\"R\" ^ c2s k))\n | S4 a, ('0' .. '9' as k) -> loop (i + 1) (S4 (a * 10 + int_of_char k - 48))\n | S4 a, '.' -> Left (\"R\", a)\n | S4 a, 'C' -> loop (i + 1) (S5 a)\n | S5 a, ('0' .. '9' as k) -> loop (i + 1) (S6 (a, int_of_char k - 48))\n | S6 (a, b), ('0' .. '9' as k) -> loop (i + 1) (S6 (a, b * 10 + int_of_char k - 48))\n | S6 (a, b), '.' -> Right (a, b)\n | _ -> failwith \"Illegal transition\"\n in\n match loop 0 S0 with\n | Left (a, b) -> Printf.sprintf \"R%dC%d\" b (s2i a)\n | Right (a, b) -> Printf.sprintf \"%s%d\" (i2s b) a\n in\n for i = 1 to n do\n let s = read_line () in\n print_endline (conv s)\n done\n"}, {"source_code": "let rec split num str =\n match str with\n | \"\" -> []\n | s -> \n let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnIntList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (int_of_string one):: (returnIntList t \"\")\n else returnIntList t (one^h)\n | _ -> (int_of_string one)::[]\n\nlet splitToList line =\n let lineList = split 1 line in\n returnIntList lineList \"\"\n\nlet rec checkInCHere str =\n match str with\n | \"\" -> false\n | s -> \n if (compare (String.sub s 0 1) \"C\" == 0)\n then true\n else if (Char.code(String.get s 0) > 64) then false\n else checkInCHere (String.sub s 1 (String.length s - 1))\n\nlet checkIsRC str =\n match str with\n | \"\" -> false\n | s ->\n if (compare (String.sub str 0 1) \"R\" == 0) && (Char.code(String.get s 1)<65)\n then checkInCHere (String.sub str 2 (String.length str - 2))\n else false\n\nlet rec reverseList li o =\n match li with \n | [] -> o\n | h :: t -> reverseList t (h :: o)\n\nlet returnConvertedCol k =\n let rec returnIt s =\n if (s > 0) then\n let n = s / 26 in\n let r = s mod 26 in\n (string_of_int r) :: returnIt n\n else [] in\n reverseList (returnIt (int_of_string k)) []\n\nlet returnConvertedRow n =\n let rec returnIt s =\n let k = s mod 26 in\n if (s > 0) then\n if (k == 0) then 'Z' :: (returnIt((s-26)/26))\n else\n (Char.chr (k+64)) :: (returnIt (s/26))\n else\n [] in\n reverseList (returnIt (int_of_string n)) []\n\nlet rec printList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_string h; printList t\n\nlet rec printCharList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_char h; printCharList t\n\nlet changeRCToAlph line =\n let rec newline l row col=\n if (compare (String.sub l 0 1) \"C\") == 0 then\n (row, String.sub l 1 (String.length l -1))\n else\n let newRow = row ^ (String.sub l 0 1) in\n newline (String.sub l 1 (String.length l -1))\n newRow col in\n let (r,c) = newline line \"\" \"\" in\n let rList = returnConvertedRow c in\n printCharList rList; print_string r; print_string \"\\n\"\n\nlet changeStringToAscii n =\n let rec returnStringToNum str num =\n match str with\n | \"\" -> num\n | s ->\n returnStringToNum (String.sub s 1 (String.length str - 1))\n ((Char.code(String.get s 0) - 64) + 26*num) in\n string_of_int (returnStringToNum n 0)\n\n\nlet changeAlphToRC line =\n let rec newline l row =\n if Char.code(String.get l 0) < 65 then\n (row, l)\n else \n newline (String.sub l 1 (String.length l -1)) (row^(String.sub l 0 1)) in\n let (r,c) = newline line \"\" in\n print_char 'R';print_string c;print_char 'C';\n print_string(changeStringToAscii r);print_string\"\\n\"\n\nlet n = read_int()\n\nlet check line =\n if (checkIsRC line) then\n changeRCToAlph(String.sub line 1 (String.length line -1))\n else\n changeAlphToRC line\n\nlet rec strList num =\n if (num > 0) then\n let k = read_line() in\n let _ = check k in\n strList (num-1)\n else\n print_string\"\"\nlet _ = strList n\n"}, {"source_code": "open Char;;\nopen String;;\n\nlet letters_of_num col =\n let rec letters_of_num' col =\n if col < 26 then Char.escaped (chr (col + code 'A'))\n else (letters_of_num' (col / 26 - 1)) ^ (letters_of_num' (col mod 26)) in\n letters_of_num' (col - 1);;\n\nlet solve_1 row col = letters_of_num (int_of_string col) ^ row;;\n\n\nlet rec pow a = function\n | 0 -> 1\n | 1 -> a\n | n ->\n let b = pow a (n / 2) in\n b * b * (if n mod 2 = 0 then 1 else a);;\n\nlet num_of_letters ls =\n let rec num_of_letters' ls =\n if length ls == 1 then code (get ls 0) - code 'A'\n else\n let hd = sub ls 0 1 in\n let tl = sub ls 1 ((length ls) - 1) in\n (pow 26 (length ls - 1)) * (1 + num_of_letters' hd) + (num_of_letters' tl) in\n num_of_letters' ls + 1;;\n\n\nlet solve_2 row col = \"R\" ^ row ^ \"C\" ^ (string_of_int (num_of_letters col));;\n\n\n\n\nlet solve: string -> string = fun s ->\n let open Str in\n let r_1 = regexp \"^R\\\\([0-9]+\\\\)C\\\\([0-9]+\\\\)$\" in\n let r_2 = regexp \"^\\\\([A-Z]+\\\\)\\\\([0-9]+\\\\)$\" in\n if (string_match r_1 s 0) then (solve_1 (Str.matched_group 1 s) (Str.matched_group 2 s))\n else if string_match r_2 s 0 then solve_2 (Str.matched_group 2 s) (Str.matched_group 1 s)\n else raise (Failure \"Unknown format\");;\n\n\n\nlet rec iter i max =\n if i < max then\n let s = input_line stdin in\n (print_string (solve s); print_newline (); iter (succ i) max)in\niter 0 (int_of_string (input_line stdin));;\n"}, {"source_code": "let get_int () = \nlet n = ref 0 in\nlet c = ref(input_char(stdin)) in\ntry\nwhile !c >= '0' && !c <= '9' do\n n := !n * 10 + (int_of_char !c - int_of_char '0');\n c := input_char(stdin)\ndone;\nn;\nwith End_of_file -> n;;\n\nlet int_of_column_header str =\nlet n = ref 0 in\nlet i = ref 0 in\ntry\nwhile str.[!i] >= 'A' && str.[!i] <= 'Z' do\n n := !n * 26 + (int_of_char str.[!i] - int_of_char 'A' + 1);\n i := !i + 1\ndone;\n(!n,!i);\nwith End_of_file -> (!n,!i);;\n\nlet column_header_of_int n =\n let s = ref \"\" in\n let nref = ref n in\n while !nref > 0 do\n s := Char.escaped(char_of_int((!nref-1) mod 26 + int_of_char 'A')) ^ !s;\n nref := (!nref-1)/26;\n done;\n !s;;\n\nlet n = get_int() in\n\nwhile !n > 0 do\n\nlet str = read_line() in\nlet cindex = try String.index str 'C' with Not_found -> -1 in\nlet alt_form = if str.[0] = 'R' && (str.[1] >= '0' && str.[1] <= '9') && (cindex >= 0) then column_header_of_int(int_of_string(String.sub str (cindex + 1) (String.length str - cindex - 1))) ^ (String.sub str 1 (cindex - 1)) else let (n,i) = int_of_column_header str in \"R\" ^ (String.sub str i (String.length str - i)) ^ \"C\" ^ string_of_int n in \nprint_endline(alt_form);\n\nn := !n - 1\n\ndone;;"}, {"source_code": "let rc_format coordinate = \n let pos = try String.index_from coordinate 2 'C' with Not_found -> -1 in\n if coordinate.[0] = 'R' && (coordinate.[1] >= '0' && coordinate.[1] <= '9') && (pos >= 2) then\n\t(true, int_of_string (String.sub coordinate 1 (pos - 1)), int_of_string (String.sub coordinate (pos + 1) (String.length coordinate - pos - 1)))\n else\n\t(false, -1, -1)\n\nlet excel_format coordinate =\n let rec decode_column c pos =\n\tif coordinate.[pos] < 'A' then\n\t (int_of_string (String.sub coordinate pos ((String.length coordinate) - pos)), c)\n\telse\n\t decode_column (c * 26 + (int_of_char coordinate.[pos]) - (int_of_char 'A') + 1) (pos + 1)\n in\n decode_column 0 0\n\nlet to_excel_format r c =\n let rec encode_column c = \n\tif c > 0 then\n\t (encode_column ((c - 1) / 26)) ^ (String.make 1 (char_of_int ((int_of_char 'A') + ((c - 1) mod 26))))\n\telse\n\t \"\"\n in\n (encode_column c) ^ (string_of_int r)\n\nlet to_rc_format r c =\n \"R\" ^ (string_of_int r) ^ \"C\" ^ (string_of_int c)\n\nlet () =\n for n = read_int () downto 1 do\n\tlet coordinate = read_line () in\n\tlet (is_rc_format, x, y) = rc_format coordinate in\n\tif is_rc_format then\n\t Printf.printf \"%s\" (to_excel_format x y)\n\telse (\n\t (* Printf.printf \"hooray!!!\"; *)\n\t let (x, y) = excel_format coordinate in\n\t Printf.printf \"%s\" (to_rc_format x y)\n\t);\n\tprint_newline()\n done\n"}, {"source_code": "\ntype numeration =\n | Excel of string * int\n | Coord of int * int\n\nlet string_to_numeration s =\n if Str.string_match (Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Excel (Str.matched_group 1 s, int_of_string (Str.matched_group 2 s)))\n else if Str.string_match (Str.regexp \"^R\\\\([1-9][0-9]*\\\\)C\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Coord (int_of_string (Str.matched_group 1 s), int_of_string (Str.matched_group 2 s)))\n else\n None\n\nlet string_to_list s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l)\n in exp (String.length s - 1) []\n\nlet pos_in_alphabet = function\n | 'A' -> 1 | 'B' -> 2 | 'C' -> 3 | 'D' -> 4 | 'E' -> 5\n | 'F' -> 6 | 'G' -> 7 | 'H' -> 8 | 'I' -> 9 | 'J' -> 10\n | 'K' -> 11 | 'L' -> 12 | 'M' -> 13 | 'N' -> 14 | 'O' -> 15\n | 'P' -> 16 | 'Q' -> 17 | 'R' -> 18 | 'S' -> 19 | 'T' -> 20\n | 'U' -> 21 | 'V' -> 22 | 'W' -> 23 | 'X' -> 24 | 'Y' -> 25\n | 'Z' -> 26 | _ -> -1\n\nlet char_at_pos = function\n | 1 -> 'A' | 2 -> 'B' | 3 -> 'C' | 4 -> 'D' | 5 -> 'E'\n | 6 -> 'F' | 7 -> 'G' | 8 -> 'H' | 9 -> 'I' | 10 -> 'J'\n | 11 -> 'K' | 12 -> 'L' | 13 -> 'M' | 14 -> 'N' | 15 -> 'O'\n | 16 -> 'P' | 17 -> 'Q' | 18 -> 'R' | 19 -> 'S' | 20 -> 'T'\n | 21 -> 'U' | 22 -> 'V' | 23 -> 'W' | 24 -> 'X' | 25 -> 'Y'\n | 0 -> 'Z' | x -> ' '\n\nlet string_to_column_number s =\n let rec aux acc cur = function\n | [] -> acc\n | h :: t -> aux ((pos_in_alphabet h)*int_of_float(26. ** (float_of_int cur)) + acc) (cur+1) t\n in aux 0 0 (List.rev (string_to_list s))\n\nlet column_number_to_string col =\n let rec aux acc last_div n =\n if n <= 26\n then (\n if not last_div && ((String.length acc > 0) && ((String.get acc 0) = 'Z')) && (char_at_pos ((n-1) mod 26)) == 'Z'\n then acc\n else if last_div || ((String.length acc > 0) && ((String.get acc 0) = 'Z'))\n then (String.make 1 (char_at_pos ((n-1) mod 26))) ^ acc\n else (String.make 1 (char_at_pos (n mod 26))) ^ acc\n )\n else\n if last_div || ((String.length acc > 0) && ((String.get acc 0) = 'Z'))\n then aux (String.make 1 (char_at_pos ((n-1) mod 26)) ^ acc ) ((n mod 26) = 0) (n / 26)\n else aux (String.make 1 (char_at_pos (n mod 26)) ^ acc ) ((n mod 26) = 0) (n / 26)\n in aux \"\" false col\n\nlet numeration_to_string = function\n | Excel (col, row) -> col ^ (string_of_int row)\n | Coord (row, col) -> \"R\" ^ (string_of_int row) ^ \"C\" ^ (string_of_int col)\n\nlet switch_numeration = function\n | Excel (col, row) -> Coord (row, string_to_column_number(col))\n | Coord (row, col) -> Excel (column_number_to_string(col), row)\n\n(*\nlet spreadsheets l =\n l\n |> List.map string_to_numeration\n |> List.filter (function Some(_) -> true | None -> false)\n |> List.map (function Some(x) -> x | x -> assert false)\n |> List.map switch_numeration\n |> List.map numeration_to_string\n*)\n\nlet spreadsheets l =\n l\n |> List.map (fun x ->\n match string_to_numeration (x) with\n | Some(e) -> numeration_to_string (switch_numeration e)\n | None -> assert false)\n\nlet () =\n let num = read_int () in\n let do_parse cnt =\n let rec loop acc = function\n | c when c < 1 -> acc\n | c ->\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s\\n\" (fun x -> x)\n in loop (s::acc) (c-1)\n in List.rev (loop [] cnt)\n in List.iter (Printf.printf \"%s\\n\") (spreadsheets (do_parse num))\n\n"}, {"source_code": "let ia = int_of_char 'A' in\nlet isrc str = \n if str.[0] <> 'R' then failwith \"Wrong\"\n else let p = String.index_from str 2 'C' in (true, int_of_string (String.sub str (p + 1) (String.length str - p - 1)), int_of_string (String.sub str 1 (p - 1)))\nand isan str =\n let rec strip_al ald pos = \n if str.[pos] < 'A' then (ald, pos) else strip_al (26 * ald + (int_of_char str.[pos] - ia + 1)) (pos + 1) \n in\n let (ra, rp) = strip_al 0 0\n in\n (false, ra, int_of_string (String.sub str rp (String.length str - rp)))\nand oprc y x =\n print_char 'R'; print_int x; print_char 'C'; print_int y\nand opan x y =\n let rec px x = if x > 0 then let _ = px ((x - 1) / 26) in print_char (char_of_int ((x - 1) mod 26 + ia)) else () in\n px x; print_int y\nin\nfor lc = (read_int ()) downto 1 do\n let line = read_line () in\n let (is_rc, x, y) = try isrc line with _ -> isan line in\n (if is_rc then opan else oprc) x y; print_newline ()\ndone\n"}, {"source_code": "let read_line_of_strings () =\n read_line () |> Str.split (Str.regexp \" +\")\n\nlet read_line_of f =\n read_line_of_strings () |> List.map f\n\nlet read_line_of_floats () =\n read_line_of float_of_string\n\nlet coordinates_of_string input =\n let rx1 = Str.regexp \"^R\\\\([0-9]+\\\\)C\\\\([0-9]+\\\\)$\" in\n let rx2 = Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([0-9]+\\\\)$\" in\n if Str.string_match rx1 input 0 then\n let row = Str.matched_group 1 input in\n let col = Str.matched_group 2 input in\n `RC (int_of_string row, int_of_string col)\n else if Str.string_match rx2 input 0 then\n let col = Str.matched_group 1 input in\n let row = Str.matched_group 2 input in\n `A1 (int_of_string row, col)\n else\n raise (Invalid_argument input)\n\nlet name_to_int name =\n let len = String.length name in\n let sum = ref 0 in\n let acc = ref 1 in\n for i = len - 1 downto 0 do\n sum := !sum + (Char.code name.[i] - 64) * !acc;\n acc := !acc * 26;\n done;\n !sum\n\nlet to_char k =\n String.make 1 (Char.chr k)\n\nlet int_to_name n =\n let rec iter dividend name =\n if dividend > 0 then\n let modulo = (dividend - 1) mod 26 in\n let next_char = to_char (65 + modulo) in\n iter ((dividend - modulo) / 26) (next_char ^ name)\n else\n name\n in\n iter n \"\"\n\nlet solve = function\n | `RC (row, col) -> Printf.sprintf \"%s%d\" (int_to_name col) row\n | `A1 (row, col) -> Printf.sprintf \"R%dC%d\" row (name_to_int col)\n\nlet convert input =\n solve (coordinates_of_string input)\n\nlet () =\n let [count] = read_line_of int_of_string in\n for i = 1 to count do\n read_line_of coordinates_of_string\n |> List.iter (fun task -> Printf.printf \"%s\\n\" (solve task))\n done;\n"}], "negative_code": [{"source_code": "let rec base_26 a = \n if a = 0 then []\n else (a mod 26) :: (base_26 (a / 26))\n\nlet inv26 a = \n let n = String.length a in\n let r = ref 0 in\n for i = 0 to (n-1) do \n r := !r * 26 + (Char.code a.[i] - 64)\n done;\n !r\n\nlet rec implode lc = \n match lc with\n |[] -> \"\"\n |c::t -> Printf.sprintf \"%c%s\" c (implode t)\n\nlet convert_nb n = \n let n = int_of_string n in\n let l = if n = 1 then [0] else (base_26 (n - 1)) in\n let l = List.rev ((List.hd l + 1) :: (List.tl l)) in\n implode (List.map (fun n -> Char.chr (n + 64)) l)\n\nlet () = \n let s = read_line () in \n let n = int_of_string s in\n for i = 0 to (n-1) do \n let s = read_line () in \n if Str.string_match (Str.regexp \"R[0-9]+C[0-9]+\") s 0 then begin\n let s = String.sub s 1 (String.length s - 1) in\n let [a;b] = Str.split (Str.regexp \"C\") s in\n Printf.printf \"%s%s\\n\" (convert_nb b) a\n end else begin\n ignore (Str.search_forward (Str.regexp \"[A-Z]+\") s 0);\n let a = Str.matched_string s in\n ignore (Str.search_forward (Str.regexp \"[0-9]+\") s 0);\n let b = Str.matched_string s in\n Printf.printf \"R%sC%i\\n\" b (inv26 a) \n end\n done;\n"}, {"source_code": "let rec base_26 a = \n if a <= 0 then []\n else (a mod 26) :: (base_26 (a / 26 - 1))\n\nlet inv26 a = \n let n = String.length a in\n let r = ref 0 in\n for i = 0 to (n-1) do \n r := !r * 26 + (Char.code a.[i] - 64)\n done;\n !r\n\nlet rec implode lc = \n match lc with\n |[] -> \"\"\n |c::t -> Printf.sprintf \"%c%s\" c (implode t)\n\nlet convert_nb n = \n let n = int_of_string n in\n let l = if n = 1 then [0] else List.rev (base_26 (n - 1)) in\n implode (List.map (fun n -> Char.chr (n + 65)) l)\n\nlet () = \n let s = read_line () in \n let n = int_of_string s in\n for i = 0 to (n-1) do \n let s = read_line () in \n if Str.string_match (Str.regexp \"R[0-9]+C[0-9]+\") s 0 then begin\n let s = String.sub s 1 (String.length s - 1) in\n let [a;b] = Str.split (Str.regexp \"C\") s in\n Printf.printf \"%s%s\\n\" (convert_nb b) a\n end else begin\n ignore (Str.search_forward (Str.regexp \"[A-Z]+\") s 0);\n let a = Str.matched_string s in\n ignore (Str.search_forward (Str.regexp \"[0-9]+\") s 0);\n let b = Str.matched_string s in\n Printf.printf \"R%sC%i\\n\" b (inv26 a) \n end\n done;\n"}, {"source_code": "open Printf\nopen Scanf\n\ntype coord = \n | RC of int * int (* row, column *)\n | Concat of string * int (* column, row *)\n\nlet parse: string -> coord =\n fun s ->\n if (Str.string_match (Str.regexp \"R[0-9]+C[0-9]+\") s 0) then\n let sep = Str.search_forward (Str.regexp \"C[0-9]+\") s 0 in\n let a = int_of_string (Str.string_after (Str.string_before s sep) 1) in\n let b = int_of_string (Str.string_after s (sep + 1)) in\n RC (a, b) \n else\n let sep = Str.search_forward (Str.regexp \"[0-9]+\") s 0 in\n let a = Str.string_before s sep in\n let b = int_of_string (Str.string_after s sep) in\n Concat (a, b)\n\nlet pp: coord -> string =\n fun c ->\n match c with\n | RC(a, b) -> \"R\" ^ (string_of_int a) ^ \"C\" ^ (string_of_int b)\n | Concat(a, b) -> a ^ (string_of_int b)\n\nlet translate: coord -> coord =\n let char_to_num c = (Char.code c) - (Char.code 'A') + 1in\n let num_to_char n = Char.chr ((Char.code 'A') - 1 + n) in\n let num_to_str_system n =\n let rec inner i s =\n let d = i / 26\n and r = i mod 26 in\n if d > 0 then\n if r = 0 then\n inner (d - 1) ((String.make 1 'Z') ^ s)\n else\n inner d ((String.make 1 (num_to_char r)) ^ s)\n else\n (String.make 1 (num_to_char r)) ^ s\n in\n inner n \"\"\n in\n let str_to_num_system s =\n let rec inner s = \n if (String.length s > 1) then\n (char_to_num s.[String.length s - 1]) + 26 * (inner (Str.string_before s (String.length s - 1)))\n else\n (char_to_num s.[String.length s - 1])\n in\n inner s\n in\n fun c ->\n match c with\n | RC(a, b) -> Concat(num_to_str_system b, a)\n | Concat(a, b) -> RC(b, str_to_num_system a)\n\nlet main () =\n let input = input_line stdin in\n let n = sscanf input \"%i\" (fun x -> x) in\n for i = 1 to n do\n let input = input_line stdin in\n let s = sscanf input \"%s\" (fun x -> x) in\n let c = parse s in\n let t = translate c in\n printf \"%s\\n\" (pp t);\n done\n\nlet _ = main ()\n"}, {"source_code": "open Printf\nopen Scanf\n\ntype coord = \n | RC of int * int (* row, column *)\n | Concat of string * int (* column, row *)\n\nlet parse: string -> coord =\n fun s ->\n if (Str.string_match (Str.regexp \"R[0-9]+C[0-9]+\") s 0) then\n let sep = Str.search_forward (Str.regexp \"C[0-9]+\") s 0 in\n let a = int_of_string (Str.string_after (Str.string_before s sep) 1) in\n let b = int_of_string (Str.string_after s (sep + 1)) in\n RC (a, b) \n else\n let sep = Str.search_forward (Str.regexp \"[0-9]+\") s 0 in\n let a = Str.string_before s sep in\n let b = int_of_string (Str.string_after s sep) in\n Concat (a, b)\n\nlet pp: coord -> string =\n fun c ->\n match c with\n | RC(a, b) -> \"R\" ^ (string_of_int a) ^ \"C\" ^ (string_of_int b)\n | Concat(a, b) -> a ^ (string_of_int b)\n\nlet translate: coord -> coord =\n let char_to_num c = (Char.code c) - (Char.code 'A') + 1in\n let num_to_char n = Char.chr ((Char.code 'A') - 1 + n) in\n let num_to_str_system n =\n let rec inner i s =\n let d = i / 26\n and r = i mod 26 in\n if d > 0 then\n inner d ((String.make 1 (num_to_char r)) ^ s)\n else\n (String.make 1 (num_to_char r)) ^ s\n \n in\n inner n \"\"\n in\n let str_to_num_system s =\n let rec inner s = \n if (String.length s > 1) then\n (char_to_num s.[String.length s - 1]) + 26 * (inner (Str.string_before s (String.length s - 1)))\n else\n (char_to_num s.[String.length s - 1])\n in\n inner s\n in\n fun c ->\n match c with\n | RC(a, b) -> Concat(num_to_str_system b, a)\n | Concat(a, b) -> RC(b, str_to_num_system a)\n\nlet main () =\n let input = input_line stdin in\n let n = sscanf input \"%i\" (fun x -> x) in\n for i = 1 to n do\n let input = input_line stdin in\n let s = sscanf input \"%s\" (fun x -> x) in\n let c = parse s in\n let t = translate c in\n printf \"%s\\n\" (pp t);\n done\n\nlet _ = main ()\n"}, {"source_code": "let n = read_int () ;;\nlet r = Str.regexp \"R[0-9]+C[0-9]+\" ;;\nfor i = 1 to n do\n let coord = read_line () in\n let is_first = Str.string_match r coord 0 in\n if is_first then begin\n let coords = Str.split (Str.regexp \"[A-Z]\") coord in\n let col = int_of_string (List.nth coords 0) in\n let row = int_of_string (List.nth coords 1) in\n let buf1 = Buffer.create 1000 in\n let rec rstring num buf = \n let r = num mod 26 in\n if (num/26) = 0 then begin\n let _ = Buffer.add_char buf (Char.chr (r+64)) in\n Buffer.contents buf\n end\n else if r != 0 then begin\n let _ = Buffer.add_char buf (Char.chr (r+64)) in\n rstring (num/26) buf\n end\n else if ((num-1)/26) != 0 then begin\n let _ = Buffer.add_char buf 'Z' in\n rstring ((num-1)/26) buf\n end\n else begin\n let _ = Buffer.add_char buf 'Z' in\n Buffer.contents buf\n end in\n\n let rec rev s =\n let sl = String.length s in\n for j=0 to (sl-1)/2 do\n let c = s.[j] in\n s.[j] <- s.[sl-j-1];\n s.[sl-j-1] <- c;\n done;\n s in\n let row_s = rev (rstring (row) (Buffer.create 2)) in\n let _ = Printf.printf \"%s%d\\n\" row_s col in\n\n\n row\n end\n else begin\n let rec row str j = \n let fchar = Char.code str.[j] in\n let schar = Char.code str.[j+1] in\n if schar >= 65 then\n 26*(fchar-64) + (row str (j+1))\n else\n fchar - 64 in\n let rnum = row coord 0 in\n let cpos = Str.search_forward (Str.regexp \"[0-9]+\") coord 0 in\n (*let cstring = String.sub coord cpos ((String.length coord)-cpos) in\n *)\n let cstring = Str.matched_string coord in\n let cint = int_of_string cstring in\n let _ = Printf.printf \"R%dC%d\\n\" cint rnum in\n 1\n end\ndone;\n"}, {"source_code": "let n = read_int () ;;\nlet r = Str.regexp \"R[0-9]+C[0-9]+\" ;;\nfor i = 1 to n do\n let coord = read_line () in\n let is_first = Str.string_match r coord 0 in\n if is_first then begin\n let coords = Str.split (Str.regexp \"[A-Z]\") coord in\n let row = int_of_string (List.nth coords 0) in\n let col = int_of_string (List.nth coords 1) in\n let buf1 = Buffer.create 1000 in\n let rec rstring num buf = \n let r = num mod 26 in\n if (num/26) = 0 then begin\n let _ = Buffer.add_char buf (Char.chr (r+64)) in\n Buffer.contents buf\n end\n else if r != 0 then begin\n let _ = Buffer.add_char buf (Char.chr (r+64)) in\n rstring (num/26) buf\n end\n else if ((num-1)/26) != 0 then begin\n let _ = Buffer.add_char buf 'Z' in\n rstring ((num-1)/26) buf\n end\n else begin\n let _ = Buffer.add_char buf 'Z' in\n Buffer.contents buf\n end in\n\n let rec rev s =\n let sl = String.length s in\n for j=0 to (sl-1)/2 do\n let c = s.[j] in\n s.[j] <- s.[sl-j-1];\n s.[sl-j-1] <- c;\n done;\n s in\n let row_s = rev (rstring (row) (Buffer.create 2)) in\n let _ = Printf.printf \"%s%d\\n\" row_s col in\n\n\n row\n end\n else begin\n let rec row str j = \n let fchar = Char.code str.[j] in\n let schar = Char.code str.[j+1] in\n if schar >= 65 then\n 26*(fchar-64) + (row str (j+1))\n else\n fchar - 64 in\n let rnum = row coord 0 in\n let cpos = Str.search_forward (Str.regexp \"[0-9]+\") coord 0 in\n (*let cstring = String.sub coord cpos ((String.length coord)-cpos) in\n *)\n let cstring = Str.matched_string coord in\n let cint = int_of_string cstring in\n let _ = Printf.printf \"R%dC%d\\n\" rnum cint in\n 1\n end\ndone;\n"}, {"source_code": "open Scanf;;\nopen Num;;\nopen Printf;;\nopen String;;\n\nexception No_num;;\nexception Digit;; \n\ntype cell = RC | NRC;;\n\nlet print_cell t = match t with\n RC -> print_endline \"RC\"\n |NRC -> print_endline \"NRC\"\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x);;\n\nlet myindex s c = try index s c with Not_found -> -100;;\n\nlet ntostring=[|\"A\";\"B\";\"C\";\"D\";\"E\";\"F\";\"G\";\"H\";\"I\";\"J\";\"K\";\"L\";\"M\";\"N\";\"O\";\"P\";\"Q\";\"R\";\"S\";\"T\";\"U\";\"V\";\"W\";\"X\";\"Y\";\"Z\"|];;\n\nlet is_digit = function\n |'1' | '2' |'3'|'4'|'5'|'6'|'7'|'8'|'9'|'0' -> true\n |_ -> false;;\n\nlet rec process t s = match t with\n RC -> process_RC s\n |NRC -> process_NRC s\nand process_RC x = \n let (rown,coln) = get_num x in\n print_string (convert_to_AB coln); print_int rown; print_endline \"\";\nand get_num x = let m = index x 'C' in\n\t\t(int_of_string (sub x 1 (m-1)),\n\t\t int_of_string (sub x (m+1) ( (length x) - m -1)))\nand convert_to_AB x = \n let y = ref x in\n let ss = ref \"\" in\n let () = \n while !y > 0 do\n let tmp = ((!y-1) mod 26) in\n y := !y / 26;\n ss := ntostring.(tmp) ^ !ss\n done in !ss\nand process_NRC x = \n let (ab,row) = get_content x in\n print_char 'R'; print_int row; print_char 'C'; print_int (convert_to_int ab);\n print_endline \"\";\nand get_content x = let m = digit_index x in\n\t\t (sub x 0 m, int_of_string (sub x m ((length x)-m)))\nand convert_to_int x = \n let k = ref ((length x) - 1) in\n let mul = ref 1 in\n let acc = ref 0 in\n let nA = int_of_char 'A' in\n let () =\n while !k >=0 do\n let f = get x !k in\n let g = (int_of_char f) - nA + 1 in\n acc := !acc + g*(!mul); mul:= !mul*26; k:=!k-1\n done in !acc\n\nand digit_index x =\n let k = ref 0 in\n try\n let () =\n for i = 0 to ((length x) - 1) \n do\n\tlet f = get x i in\n\tif is_digit f then\n\t raise Digit\n\telse k:=!k+1\n done in !k\n with Digit -> !k\n;;\n\n for i=1 to n do\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s \" (fun x -> x) in\n let t = match (myindex s 'R', myindex s 'C') with\n | (-100, _) -> NRC\n | (_,-100) -> NRC\n | (a, b) -> if b - a > 1 then RC else NRC\n in process t s\n done;;\n\n"}, {"source_code": "open Scanf;;\nopen Num;;\nopen Printf;;\nopen String;;\n\nexception No_num;;\nexception Digit;;\n\ntype cell = RC | NRC;;\n\nlet print_cell t = match t with\n RC -> print_endline \"RC\"\n |NRC -> print_endline \"NRC\"\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x);;\n\nlet myindex s c = try index s c with Not_found -> -100;;\n\nlet ntostring=[|\"A\";\"B\";\"C\";\"D\";\"E\";\"F\";\"G\";\"H\";\"I\";\"J\";\"K\";\"L\";\"M\";\"N\";\"O\";\"P\";\"Q\";\"R\";\"S\";\"T\";\"U\";\"V\";\"W\";\"X\";\"Y\";\"Z\"|];;\n\nlet is_digit = function\n |'1' | '2' |'3'|'4'|'5'|'6'|'7'|'8'|'9'|'0' -> true\n |_ -> false;;\n\nlet rec process t s = match t with\n RC -> process_RC s\n |NRC -> process_NRC s\nand process_RC x = \n let (rown,coln) = get_num x in\n print_string (convert_to_AB coln); print_int rown; print_endline \"\";\nand get_num x = let m = index x 'C' in\n\t\t(int_of_string (sub x 1 (m-1)),\n\t\t int_of_string (sub x (m+1) ( (length x) - m -1)))\nand convert_to_AB x = \n let y = ref x in\n let ss = ref \"\" in\n let () = \n while !y > 0 do\n let tmp = ((!y-1) mod 26) in\n y := !y / 26;\n ss := ntostring.(tmp) ^ !ss\n done in !ss\nand process_NRC x = \n let (ab,row) = get_content x in\n print_char 'R'; print_int row; print_char 'C'; print_int (convert_to_int ab);\n print_endline \"\";\nand get_content x = let m = digit_index x in\n\t\t (sub x 0 m, int_of_string (sub x m ((length x)-m)))\nand convert_to_int x = \n let k = ref ((length x) - 1) in\n let mul = ref 1 in\n let acc = ref 0 in\n let nA = int_of_char 'A' in\n let () =\n while !k >=0 do\n let f = get x !k in\n let g = (int_of_char f) - nA + 1 in\n acc := !acc + g*(!mul); mul:= !mul*26; k:=!k-1\n done in !acc\n\nand digit_index x =\n let k = ref 0 in\n try\n let () =\n for i = 0 to ((length x) - 1) \n do\n\tlet f = get x i in\n\tif is_digit f then\n\t raise Digit\n\telse k:=!k+1\n done in !k\n with Digit -> !k\n;;\n\n for i=1 to n do\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s \" (fun x -> x) in\n let t = match (myindex s 'R', myindex s 'C') with\n | (-100, _) -> NRC\n | (_,-100) -> NRC\n | (a, b) -> if b - a > 1 then RC else NRC\n in process t s\n done;;\n\n"}, {"source_code": "open Scanf;;\nopen Num;;\nopen Printf;;\nopen String;;\n\nexception No_num;;\nexception Digit;; \n\ntype cell = RC | NRC;;\n\nlet print_cell t = match t with\n RC -> print_endline \"RC\"\n |NRC -> print_endline \"NRC\"\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x);;\n\nlet myindex s c = try index s c with Not_found -> -100;;\n\nlet ntostring=[|\"A\";\"B\";\"C\";\"D\";\"E\";\"F\";\"G\";\"H\";\"I\";\"J\";\"K\";\"L\";\"M\";\"N\";\"O\";\"P\";\"Q\";\"R\";\"S\";\"T\";\"U\";\"V\";\"W\";\"X\";\"Y\";\"Z\"|];;\n\nlet is_digit = function\n |'1' | '2' |'3'|'4'|'5'|'6'|'7'|'8'|'9'|'0' -> true\n |_ -> false;;\n\nlet rec process t s = match t with\n RC -> process_RC s\n |NRC -> process_NRC s\nand process_RC x = \n let (rown,coln) = get_num x in\n print_string (convert_to_AB coln); print_int rown; print_endline \"\";\nand get_num x = let m = index x 'C' in\n\t\t(int_of_string (sub x 1 (m-1)),\n\t\t int_of_string (sub x (m+1) ( (length x) - m -1)))\nand convert_to_AB x = \n let y = ref x in\n let ss = ref \"\" in\n let () = \n while !y > 0 do\n let tmp = ((!y-1) mod 26) in\n y := (!y - tmp - 1) / 26;\n ss := ntostring.(tmp) ^ !ss\n done in !ss\nand process_NRC x = \n let (ab,row) = get_content x in\n print_char 'R'; print_int row; print_char 'C'; print_int (convert_to_int ab);\n print_endline \"\";\nand get_content x = let m = digit_index x in\n\t\t (sub x 0 m, int_of_string (sub x m ((length x)-m)))\nand convert_to_int x = \n let k = ref ((length x) - 1) in\n let mul = ref 1 in\n let acc = ref 0 in\n let nA = int_of_char 'A' in\n let () =\n while !k >=0 do\n let f = get x !k in\n let g = (int_of_char f) - nA + 1 in\n acc := !acc + g*(!mul); mul:= !mul*26; k:=!k-1\n done in !acc\n\nand digit_index x =\n let k = ref 0 in\n try\n let () =\n for i = 0 to ((length x) - 1) \n do\n\tlet f = get x i in\n\tif is_digit f then\n\t raise Digit\n\telse k:=!k+1\n done in !k\n with Digit -> !k\n;;\n\n for i=1 to n do\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s \" (fun x -> x) in\n let t = match (myindex s 'R', myindex s 'C') with\n | (-100, _) -> NRC\n | (_,-100) -> NRC\n | (a, b) -> if b - a > 1 then RC else NRC\n in print_string s; print_string \" : \"; process t s\n done;;\n\n"}, {"source_code": "let rec split num str =\n match str with\n | \"\" -> []\n | s -> \n let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnIntList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (int_of_string one):: (returnIntList t \"\")\n else returnIntList t (one^h)\n | _ -> (int_of_string one)::[]\n\nlet splitToList line =\n let lineList = split 1 line in\n returnIntList lineList \"\"\n\nlet checkIsRC str =\n match str with\n | \"\" -> false\n | s ->\n if (compare (String.sub str 0 1) \"R\" == 0)\n then true\n else false\n\nlet rec reverseList li o =\n match li with \n | [] -> o\n | h :: t -> reverseList t (h :: o)\n\nlet returnConvertedCol k =\n let rec returnIt s =\n if (s > 0) then\n let n = s / 26 in\n let r = s mod 26 in\n (string_of_int r) :: returnIt n\n else [] in\n reverseList (returnIt (int_of_string k)) []\n\nlet returnConvertedRow n =\n let rec returnIt s =\n let k = s mod 10 in\n if (s > 0) then\n (Char.chr (k+64)) :: (returnIt (s/10))\n else\n [] in\n reverseList (returnIt (int_of_string n)) []\n\nlet rec printList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_string h; printList t\n\nlet rec printCharList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_char h; printCharList t\n\nlet changeRCToAlph line =\n let rec newline l row col=\n if (compare (String.sub l 0 1) \"C\") == 0 then\n (row, String.sub l 1 (String.length l -1))\n else\n let newRow = row ^ (String.sub l 0 1) in\n newline (String.sub l 1 (String.length l -1))\n newRow col in\n let (r,c) = newline line \"\" \"\" in\n let rList = returnConvertedRow r in\n let cList = returnConvertedCol c in\n printCharList rList; printList cList; print_string \"\\n\"\n\nlet changeNumToAscii n =\n let num = int_of_string n in\n let rec returnNum k =\n let s = k/10 in\n let r = k mod 10 in\n if (s > 0) then \n r + 26*(returnNum s)\n else\n r in\n string_of_int (returnNum num)\n\n\nlet changeAlphToRC line =\n let rec newline l row =\n if Char.code(String.get l 0) < 65 then\n (row, l)\n else \n let c = (Char.chr(Char.code(String.get l 0)-16)) in\n newline (String.sub l 1 (String.length l -1)) (row^(Char.escaped c)) in\n let (r,c) = newline line \"\" in\n print_char 'R';print_string r;print_char 'C';\n print_string(changeNumToAscii c)\n\nlet n = read_int()\n\nlet check line =\n if (checkIsRC line) then\n changeRCToAlph(String.sub line 1 (String.length line -1))\n else\n changeAlphToRC line\n\nlet rec strList num =\n if (num > 0) then\n let k = read_line() in\n let _ = check k in\n strList (num-1)\n else\n print_string\"\"\nlet _ = strList n\n"}, {"source_code": "let rec split num str =\n match str with\n | \"\" -> []\n | s -> \n let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnIntList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (int_of_string one):: (returnIntList t \"\")\n else returnIntList t (one^h)\n | _ -> (int_of_string one)::[]\n\nlet splitToList line =\n let lineList = split 1 line in\n returnIntList lineList \"\"\n\nlet rec checkInCHere str =\n match str with\n | \"\" -> false\n | s -> \n if (compare (String.sub str 0 1) \"C\" == 0)\n then true\n else if (int_of_string (String.sub str 0 1)) <= 9 && (int_of_string(String.sub str 0 1)) >= 0 then checkInCHere (String.sub str 1 (String.length str - 1))\n else false\n\nlet checkIsRC str =\n match str with\n | \"\" -> false\n | s ->\n if (compare (String.sub str 0 1) \"R\" == 0)\n then checkInCHere (String.sub str 1 (String.length str - 1))\n else false\n\nlet rec reverseList li o =\n match li with \n | [] -> o\n | h :: t -> reverseList t (h :: o)\n\nlet returnConvertedCol k =\n let rec returnIt s =\n if (s > 0) then\n let n = s / 26 in\n let r = s mod 26 in\n (string_of_int r) :: returnIt n\n else [] in\n reverseList (returnIt (int_of_string k)) []\n\nlet returnConvertedRow n =\n let rec returnIt s =\n let k = s mod 26 in\n if (s > 0) then\n (Char.chr (k+64)) :: (returnIt (s/26))\n else\n [] in\n reverseList (returnIt (int_of_string n)) []\n\nlet rec printList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_string h; printList t\n\nlet rec printCharList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_char h; printCharList t\n\nlet changeRCToAlph line =\n let rec newline l row col=\n if (compare (String.sub l 0 1) \"C\") == 0 then\n (row, String.sub l 1 (String.length l -1))\n else\n let newRow = row ^ (String.sub l 0 1) in\n newline (String.sub l 1 (String.length l -1))\n newRow col in\n let (r,c) = newline line \"\" \"\" in\n let rList = returnConvertedRow c in\n let cList = returnConvertedCol r in\n printCharList rList; printList cList; print_string \"\\n\"\n\nlet changeStringToAscii n =\n let rec returnStringToNum str num =\n match str with\n | \"\" -> num\n | s ->\n returnStringToNum (String.sub s 1 (String.length str - 1))\n ((Char.code(String.get s 0) - 64) + 26*num) in\n string_of_int (returnStringToNum n 0)\n\n\nlet changeAlphToRC line =\n let rec newline l row =\n if Char.code(String.get l 0) < 65 then\n (row, l)\n else \n newline (String.sub l 1 (String.length l -1)) (row^(String.sub l 0 1)) in\n let (r,c) = newline line \"\" in\n print_char 'R';print_string c;print_char 'C';\n print_string(changeStringToAscii r);print_string\"\\n\"\n\nlet n = read_int()\n\nlet check line =\n if (checkIsRC line) then\n changeRCToAlph(String.sub line 1 (String.length line -1))\n else\n changeAlphToRC line\n\nlet rec strList num =\n if (num > 0) then\n let k = read_line() in\n let _ = check k in\n strList (num-1)\n else\n print_string\"\"\nlet _ = strList n\n"}, {"source_code": "let rec split num str =\n match str with\n | \"\" -> []\n | s -> \n let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnIntList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (int_of_string one):: (returnIntList t \"\")\n else returnIntList t (one^h)\n | _ -> (int_of_string one)::[]\n\nlet splitToList line =\n let lineList = split 1 line in\n returnIntList lineList \"\"\n\nlet checkIsRC str =\n match str with\n | \"\" -> false\n | s ->\n if (compare (String.sub str 0 1) \"R\" == 0)\n then true\n else false\n\nlet rec reverseList li o =\n match li with \n | [] -> o\n | h :: t -> reverseList t (h :: o)\n\nlet returnConvertedCol k =\n let rec returnIt s =\n if (s > 0) then\n let n = s / 26 in\n let r = s mod 26 in\n (string_of_int r) :: returnIt n\n else [] in\n reverseList (returnIt (int_of_string k)) []\n\nlet returnConvertedRow n =\n let rec returnIt s =\n let k = s mod 10 in\n if (s > 0) then\n (Char.chr (k+64)) :: (returnIt (s/10))\n else\n Char.chr(s) :: [] in\n reverseList (returnIt (int_of_string n)) []\n\nlet rec printList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_string h; printList t\n\nlet rec printCharList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_char h; printCharList t\n\nlet changeRCToAlph line =\n let rec newline l row col=\n if (compare (String.sub l 0 1) \"C\") == 0 then\n (row, String.sub l 1 (String.length l -1))\n else\n let newRow = row ^ (String.sub l 0 1) in\n newline (String.sub l 1 (String.length l -1))\n newRow col in\n let (r,c) = newline line \"\" \"\" in\n let rList = returnConvertedRow r in\n let cList = returnConvertedCol c in\n printCharList rList; printList cList; print_string \"\\n\"\n\nlet changeNumToAscii n =\n let num = int_of_string n in\n let rec returnNum k =\n let s = k/10 in\n let r = k mod 10 in\n if (s > 0) then \n r + 26*(returnNum s)\n else\n r in\n string_of_int (returnNum num)\n\n\nlet changeAlphToRC line =\n let rec newline l row =\n if Char.code(String.get l 0) < 65 then\n (row, l)\n else \n let c = (Char.chr(Char.code(String.get l 0)-16)) in\n newline (String.sub l 1 (String.length l -1)) (row^(Char.escaped c)) in\n let (r,c) = newline line \"\" in\n print_char 'R';print_string r;print_char 'C';\n print_string(changeNumToAscii c)\n\nlet n = read_int()\n\nlet check line =\n if (checkIsRC line) then\n changeRCToAlph(String.sub line 1 (String.length line -1))\n else\n changeAlphToRC line\n\nlet rec strList num =\n if (num > 0) then\n let k = read_line() in\n let _ = check k in\n strList (num-1)\n else\n print_string\"\"\nlet _ = strList n\n"}, {"source_code": "let rec split num str =\n match str with\n | \"\" -> []\n | s -> \n let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in\n beg :: (split num rest)\n\nlet rec returnIntList strList one =\n match strList with\n | h :: t -> if (compare h \" \" == 0 || compare h \"\\n\" == 0) then\n (int_of_string one):: (returnIntList t \"\")\n else returnIntList t (one^h)\n | _ -> (int_of_string one)::[]\n\nlet splitToList line =\n let lineList = split 1 line in\n returnIntList lineList \"\"\n\nlet rec checkInCHere str =\n match str with\n | \"\" -> false\n | s -> \n if (compare (String.sub str 0 1) \"C\" == 0)\n then true\n else if (int_of_string (String.sub str 0 1)) <= 9 && (int_of_string(String.sub str 0 1)) >= 0 then checkInCHere (String.sub str 1 (String.length str - 1))\n else false\n\nlet checkIsRC str =\n match str with\n | \"\" -> false\n | s ->\n if (compare (String.sub str 0 1) \"R\" == 0)\n then checkInCHere (String.sub str 2 (String.length str - 2))\n else false\n\nlet rec reverseList li o =\n match li with \n | [] -> o\n | h :: t -> reverseList t (h :: o)\n\nlet returnConvertedCol k =\n let rec returnIt s =\n if (s > 0) then\n let n = s / 26 in\n let r = s mod 26 in\n (string_of_int r) :: returnIt n\n else [] in\n reverseList (returnIt (int_of_string k)) []\n\nlet returnConvertedRow n =\n let rec returnIt s =\n let k = s mod 26 in\n if (s > 0) then\n (Char.chr (k+64)) :: (returnIt (s/26))\n else\n [] in\n reverseList (returnIt (int_of_string n)) []\n\nlet rec printList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_string h; printList t\n\nlet rec printCharList li =\n match li with\n | [] -> print_string \"\"\n | h :: t -> print_char h; printCharList t\n\nlet changeRCToAlph line =\n let rec newline l row col=\n if (compare (String.sub l 0 1) \"C\") == 0 then\n (row, String.sub l 1 (String.length l -1))\n else\n let newRow = row ^ (String.sub l 0 1) in\n newline (String.sub l 1 (String.length l -1))\n newRow col in\n let (r,c) = newline line \"\" \"\" in\n let rList = returnConvertedRow c in\n printCharList rList; print_string r; print_string \"\\n\"\n\nlet changeStringToAscii n =\n let rec returnStringToNum str num =\n match str with\n | \"\" -> num\n | s ->\n returnStringToNum (String.sub s 1 (String.length str - 1))\n ((Char.code(String.get s 0) - 64) + 26*num) in\n string_of_int (returnStringToNum n 0)\n\n\nlet changeAlphToRC line =\n let rec newline l row =\n if Char.code(String.get l 0) < 65 then\n (row, l)\n else \n newline (String.sub l 1 (String.length l -1)) (row^(String.sub l 0 1)) in\n let (r,c) = newline line \"\" in\n print_char 'R';print_string c;print_char 'C';\n print_string(changeStringToAscii r);print_string\"\\n\"\n\nlet n = read_int()\n\nlet check line =\n if (checkIsRC line) then\n changeRCToAlph(String.sub line 1 (String.length line -1))\n else\n changeAlphToRC line\n\nlet rec strList num =\n if (num > 0) then\n let k = read_line() in\n let _ = check k in\n strList (num-1)\n else\n print_string\"\"\nlet _ = strList n\n"}, {"source_code": "let get_int c = \nlet n = ref 0 in\ntry\nwhile !c >= '0' && !c <= '9' do\n n := !n * 10 + (int_of_char !c - int_of_char '0');\n c := input_char(stdin)\ndone;\n(n,c);\nwith End_of_file -> (n,c);;\n\nlet n = fst(get_int(ref '0')) in\nwhile !n > 0 do\n\nlet firstchar = input_char(stdin) in\nlet secondchar = input_char(stdin) in \n\nlet int_of_column_header (fc,sc) =\nlet n = ref 0 in\n(n := !n * 26 + (int_of_char !fc - int_of_char 'A' + 1);\ntry\nwhile !sc >= 'A' && !sc <= 'Z' do\n n := !n * 26 + (int_of_char !sc - int_of_char 'A' + 1);\n sc := input_char(stdin)\ndone;\n(n,sc);\nwith End_of_file -> (n,sc)) in\n\nlet column_header_of_int n =\n let s = ref \"\" in\n let nref = ref n in\n while !nref > 0 do\n s := Char.escaped(char_of_int((!nref-1) mod 26 + int_of_char 'A')) ^ !s;\n nref := (!nref-1)/26;\n done;\n !s in\n\nlet row_first c = let row = !(fst(get_int(c))) in let column = !(fst(get_int(ref '0'))) in (row,column) in\n\nlet column_first (fc, sc) = let nc = int_of_column_header(fc,sc) in let column = !(fst(nc)) in let row = !(fst(get_int(snd(nc)))) in (row,column) in\n\nlet rc = if firstchar = 'R' && (secondchar >= '0' && secondchar <= '9') then row_first (ref secondchar) else column_first(ref firstchar, ref secondchar) in\n\nlet alt_format = if firstchar = 'R' && (secondchar >= '0' && secondchar <= '9') then column_header_of_int(snd(rc)) ^ string_of_int(fst(rc))\nelse \"R\" ^ string_of_int(fst(rc)) ^ \"C\" ^ string_of_int(snd(rc)) in\n\nprint_endline(alt_format);\n\nn := !n - 1\n\ndone;;"}, {"source_code": "let get_int c = \nlet n = ref 0 in\ntry\nwhile !c >= '0' && !c <= '9' do\n n := !n * 10 + (int_of_char !c - int_of_char '0');\n c := input_char(stdin)\ndone;\n(n,c);\nwith End_of_file -> (n,c);;\n\nlet n = fst(get_int(ref '0')) in\nwhile !n > 0 do\n\nlet firstchar = input_char(stdin) in\n\nlet int_of_column_header c =\nlet n = ref 0 in\ntry\nwhile !c >= 'A' && !c <= 'Z' do\n n := !n * 26 + (int_of_char !c - int_of_char 'A' + 1);\n c := input_char(stdin)\ndone;\n(n,c);\nwith End_of_file -> (n,c) in\n\nlet column_header_of_int n =\n let s = ref \"\" in\n let nref = ref n in\n while !nref > 0 do\n s := Char.escaped(char_of_int((!nref-1) mod 26 + int_of_char 'A')) ^ !s;\n nref := !nref/26;\n done;\n !s in\n\nlet row_first c = let row = !(fst(get_int(c))) in let column = !(fst(get_int(ref '0'))) in (row,column) in\n\nlet column_first c = let nc = int_of_column_header(c) in let column = !(fst(nc)) in let row = !(fst(get_int(snd(nc)))) in (row,column) in\n\nlet rc = if firstchar = 'R' then let c = input_char(stdin) in row_first (ref c) else column_first(ref firstchar) in\n\nlet alt_format = if firstchar = 'R' then column_header_of_int(snd(rc)) ^ string_of_int(fst(rc))\nelse \"R\" ^ string_of_int(fst(rc)) ^ \"C\" ^ string_of_int(snd(rc)) in\n\nprint_endline(alt_format);\n\nn := !n - 1\n\ndone;;"}, {"source_code": "let rc_format coordinate = \n let pos = try String.index_from coordinate 2 'C' with Not_found -> -1 in\n if coordinate.[0] = 'R' && (coordinate.[1] >= '0' && coordinate.[1] <= '9') && (pos >= 2) then\n\t(true, int_of_string (String.sub coordinate 1 (pos - 1)), int_of_string (String.sub coordinate (pos + 1) (String.length coordinate - pos - 1)))\n else\n\t(false, -1, -1)\n\nlet excel_format coordinate =\n let rec decode_column c pos =\n\tif coordinate.[pos] < 'A' then\n\t (int_of_string (String.sub coordinate pos ((String.length coordinate) - pos)), c)\n\telse\n\t decode_column (c * 26 + (int_of_char coordinate.[pos]) - (int_of_char 'A') + 1) (pos + 1)\n in\n decode_column 0 0\n\nlet to_excel_format r c =\n let rec encode_column c = \n\tif c > 0 then\n\t (encode_column (c / 26)) ^ (String.make 1 (char_of_int ((int_of_char 'A') + ((c - 1) mod 26))))\n\telse\n\t \"\"\n in\n (encode_column c) ^ (string_of_int r)\n\nlet to_rc_format r c =\n \"R\" ^ (string_of_int r) ^ \"C\" ^ (string_of_int c)\n\nlet () =\n for n = read_int () downto 1 do\n\tlet coordinate = read_line () in\n\tlet (is_rc_format, x, y) = rc_format coordinate in\n\tif is_rc_format then\n\t Printf.printf \"%s\" (to_excel_format x y)\n\telse (\n\t (* Printf.printf \"hooray!!!\"; *)\n\t let (x, y) = excel_format coordinate in\n\t Printf.printf \"%s\" (to_rc_format x y)\n\t);\n\tprint_newline()\n done\n"}, {"source_code": "let rc_format coordinate = \n let pos = try String.index_from coordinate 2 'C' with Not_found -> -1 in\n if coordinate.[0] = 'R' && (coordinate.[1] >= '0' && coordinate.[1] <= '9') && (pos >= 2) then\n\t(true, int_of_string (String.sub coordinate 1 (pos - 1)), int_of_string (String.sub coordinate (pos + 1) (String.length coordinate - pos - 1)))\n else\n\t(false, -1, -1)\n\nlet excel_format coordinate =\n let rec decode_column c pos =\n\tif coordinate.[pos] < 'A' then\n\t (int_of_string (String.sub coordinate pos ((String.length coordinate) - pos)), c)\n\telse\n\t decode_column (c * 26 + (int_of_char coordinate.[pos]) - (int_of_char 'A') + 1) (pos + 1)\n in\n decode_column 0 0\n\nlet to_excel_format c r =\n let rec encode_column c = \n\tif c > 0 then\n\t (encode_column (c / 26 - 1)) ^ (String.make 1 (char_of_int ((int_of_char 'A') + (c mod 26))))\n\telse\n\t \"\"\n in\n (encode_column c) ^ (string_of_int r)\n\nlet to_rc_format r c =\n \"R\" ^ (string_of_int r) ^ \"C\" ^ (string_of_int c)\n\nlet () =\n for n = read_int () downto 1 do\n\tlet coordinate = read_line () in\n\tlet (is_rc_format, x, y) = rc_format coordinate in\n\tif is_rc_format then\n\t Printf.printf \"%s\" (to_excel_format (y - 1) x)\n\telse (\n\t (* Printf.printf \"hooray!!!\"; *)\n\t let (x, y) = excel_format coordinate in\n\t Printf.printf \"%s\" (to_rc_format x y)\n\t);\n\tprint_newline()\n done\n"}, {"source_code": "\ntype numeration =\n | Excel of string * int\n | Coord of int * int\n\nlet string_to_numeration s =\n if Str.string_match (Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Excel (Str.matched_group 1 s, int_of_string (Str.matched_group 2 s)))\n else if Str.string_match (Str.regexp \"^R\\\\([1-9][0-9]*\\\\)C\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Coord (int_of_string (Str.matched_group 1 s), int_of_string (Str.matched_group 2 s)))\n else\n None\n\nlet string_to_list s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l)\n in exp (String.length s - 1) []\n\nlet pos_in_alphabet = function\n | 'A' -> 1 | 'B' -> 2 | 'C' -> 3 | 'D' -> 4 | 'E' -> 5\n | 'F' -> 6 | 'G' -> 7 | 'H' -> 8 | 'I' -> 9 | 'J' -> 10\n | 'K' -> 11 | 'L' -> 12 | 'M' -> 13 | 'N' -> 14 | 'O' -> 15\n | 'P' -> 16 | 'Q' -> 17 | 'R' -> 18 | 'S' -> 19 | 'T' -> 20\n | 'U' -> 21 | 'V' -> 22 | 'W' -> 23 | 'X' -> 24 | 'Y' -> 25\n | 'Z' -> 26 | _ -> -1\n\nlet char_at_pos = function\n | 1 -> 'A' | 2 -> 'B' | 3 -> 'C' | 4 -> 'D' | 5 -> 'E'\n | 6 -> 'F' | 7 -> 'G' | 8 -> 'H' | 9 -> 'I' | 10 -> 'J'\n | 11 -> 'K' | 12 -> 'L' | 13 -> 'M' | 14 -> 'N' | 15 -> 'O'\n | 16 -> 'P' | 17 -> 'Q' | 18 -> 'R' | 19 -> 'S' | 20 -> 'T'\n | 21 -> 'U' | 22 -> 'V' | 23 -> 'W' | 24 -> 'X' | 25 -> 'Y'\n | 0 -> 'Z' | x -> ' '\n\nlet string_to_column_number s =\n let rec aux acc cur = function\n | [] -> acc\n | h :: t -> aux ((pos_in_alphabet h)*int_of_float(26. ** (float_of_int cur)) + acc) (cur+1) t\n in aux 0 0 (List.rev (string_to_list s))\n\nlet column_number_to_string col =\n let rec aux acc last_div n =\n if n <= 26\n then (\n if not last_div && ((String.length acc > 0) && ((String.get acc 0) = 'Z'))\n then acc\n else if last_div || ((String.length acc > 0) && ((String.get acc 0) = 'Z'))\n then (String.make 1 (char_at_pos ((n-1) mod 26))) ^ acc\n else (String.make 1 (char_at_pos (n mod 26))) ^ acc\n )\n else\n if last_div || ((String.length acc > 0) && ((String.get acc 0) = 'Z'))\n then aux (String.make 1 (char_at_pos ((n-1) mod 26)) ^ acc ) ((n mod 26) = 0) (n / 26)\n else aux (String.make 1 (char_at_pos (n mod 26)) ^ acc ) ((n mod 26) = 0) (n / 26)\n in aux \"\" false col\n\nlet numeration_to_string = function\n | Excel (col, row) -> col ^ (string_of_int row)\n | Coord (row, col) -> \"R\" ^ (string_of_int row) ^ \"C\" ^ (string_of_int col)\n\nlet switch_numeration = function\n | Excel (col, row) -> Coord (row, string_to_column_number(col))\n | Coord (row, col) -> Excel (column_number_to_string(col), row)\n\n(*\nlet spreadsheets l =\n l\n |> List.map string_to_numeration\n |> List.filter (function Some(_) -> true | None -> false)\n |> List.map (function Some(x) -> x | x -> assert false)\n |> List.map switch_numeration\n |> List.map numeration_to_string\n*)\n\nlet spreadsheets l =\n l\n |> List.map (fun x ->\n match string_to_numeration (x) with\n | Some(e) -> numeration_to_string (switch_numeration e)\n | None -> assert false)\n\nlet () =\n let num = read_int () in\n let do_parse cnt =\n let rec loop acc = function\n | c when c < 1 -> acc\n | c ->\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s\\n\" (fun x -> x)\n in loop (s::acc) (c-1)\n in List.rev (loop [] cnt)\n in List.iter (Printf.printf \"%s\\n\") (spreadsheets (do_parse num))\n\n"}, {"source_code": "\ntype numeration =\n | Excel of string * int\n | Coord of int * int\n\nlet string_to_numeration s =\n if Str.string_match (Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Excel (Str.matched_group 1 s, int_of_string (Str.matched_group 2 s)))\n else if Str.string_match (Str.regexp \"^R\\\\([1-9][0-9]*\\\\)C\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Coord (int_of_string (Str.matched_group 1 s), int_of_string (Str.matched_group 2 s)))\n else\n None\n\nlet string_to_list s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l)\n in exp (String.length s - 1) []\n\nlet pos_in_alphabet = function\n | 'A' -> 1 | 'B' -> 2 | 'C' -> 3 | 'D' -> 4 | 'E' -> 5\n | 'F' -> 6 | 'G' -> 7 | 'H' -> 8 | 'I' -> 9 | 'J' -> 10\n | 'K' -> 11 | 'L' -> 12 | 'M' -> 13 | 'N' -> 14 | 'O' -> 15\n | 'P' -> 16 | 'Q' -> 17 | 'R' -> 18 | 'S' -> 19 | 'T' -> 20\n | 'U' -> 21 | 'V' -> 22 | 'W' -> 23 | 'X' -> 24 | 'Y' -> 25\n | 'Z' -> 26 | _ -> -1\n\nlet char_at_pos = function\n | 1 -> 'A' | 2 -> 'B' | 3 -> 'C' | 4 -> 'D' | 5 -> 'E'\n | 6 -> 'F' | 7 -> 'G' | 8 -> 'H' | 9 -> 'I' | 10 -> 'J'\n | 11 -> 'K' | 12 -> 'L' | 13 -> 'M' | 14 -> 'N' | 15 -> 'O'\n | 16 -> 'P' | 17 -> 'Q' | 18 -> 'R' | 19 -> 'S' | 20 -> 'T'\n | 21 -> 'U' | 22 -> 'V' | 23 -> 'W' | 24 -> 'X' | 25 -> 'Y'\n | 0 -> 'Z' | x -> ' '\n\nlet string_to_column_number s =\n let rec aux acc cur = function\n | [] -> acc\n | h :: t -> aux ((pos_in_alphabet h)*int_of_float(26. ** (float_of_int cur)) + acc) (cur+1) t\n in aux 0 0 (List.rev (string_to_list s))\n\nlet column_number_to_string col =\n let rec aux acc last_div n =\n if n <= 26\n then (\n if last_div || ((String.length acc > 0) && ((String.get acc 0) = 'Z'))\n then (String.make 1 (char_at_pos ((n-1) mod 26))) ^ acc\n else (String.make 1 (char_at_pos (n mod 26))) ^ acc\n )\n else\n if last_div || ((String.length acc > 0) && ((String.get acc 0) = 'Z'))\n then aux (String.make 1 (char_at_pos ((n-1) mod 26)) ^ acc ) ((n mod 26) = 0) (n / 26)\n else aux (String.make 1 (char_at_pos (n mod 26)) ^ acc ) ((n mod 26) = 0) (n / 26)\n in aux \"\" false col\n\nlet numeration_to_string = function\n | Excel (col, row) -> col ^ (string_of_int row)\n | Coord (row, col) -> \"R\" ^ (string_of_int row) ^ \"C\" ^ (string_of_int col)\n\nlet switch_numeration = function\n | Excel (col, row) -> Coord (row, string_to_column_number(col))\n | Coord (row, col) -> Excel (column_number_to_string(col), row)\n\n(*\nlet spreadsheets l =\n l\n |> List.map string_to_numeration\n |> List.filter (function Some(_) -> true | None -> false)\n |> List.map (function Some(x) -> x | x -> assert false)\n |> List.map switch_numeration\n |> List.map numeration_to_string\n*)\n\nlet spreadsheets l =\n l\n |> List.map (fun x ->\n match string_to_numeration (x) with\n | Some(e) -> numeration_to_string (switch_numeration e)\n | None -> assert false)\n\nlet () =\n let num = read_int () in\n let do_parse cnt =\n let rec loop acc = function\n | c when c < 1 -> acc\n | c ->\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s\\n\" (fun x -> x)\n in loop (s::acc) (c-1)\n in List.rev (loop [] cnt)\n in List.iter (Printf.printf \"%s\\n\") (spreadsheets (do_parse num))\n\n"}, {"source_code": "\ntype numeration =\n | Excel of string * int\n | Coord of int * int\n\nlet string_to_numeration s =\n if Str.string_match (Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Excel (Str.matched_group 1 s, int_of_string (Str.matched_group 2 s)))\n else if Str.string_match (Str.regexp \"^R\\\\([1-9][0-9]*\\\\)C\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Coord (int_of_string (Str.matched_group 1 s), int_of_string (Str.matched_group 2 s)))\n else\n None\n\nlet string_to_list s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l)\n in exp (String.length s - 1) []\n\nlet pos_in_alphabet = function\n | 'A' -> 1 | 'B' -> 2 | 'C' -> 3 | 'D' -> 4 | 'E' -> 5\n | 'F' -> 6 | 'G' -> 7 | 'H' -> 8 | 'I' -> 9 | 'J' -> 10\n | 'K' -> 11 | 'L' -> 12 | 'M' -> 13 | 'N' -> 14 | 'O' -> 15\n | 'P' -> 16 | 'Q' -> 17 | 'R' -> 18 | 'S' -> 19 | 'T' -> 20\n | 'U' -> 21 | 'V' -> 22 | 'W' -> 23 | 'X' -> 24 | 'Y' -> 25\n | 'Z' -> 26 | _ -> -1\n\nlet char_at_pos = function\n | 1 -> 'A' | 2 -> 'B' | 3 -> 'C' | 4 -> 'D' | 5 -> 'E'\n | 6 -> 'F' | 7 -> 'G' | 8 -> 'H' | 9 -> 'I' | 10 -> 'J'\n | 11 -> 'K' | 12 -> 'L' | 13 -> 'M' | 14 -> 'N' | 15 -> 'O'\n | 16 -> 'P' | 17 -> 'Q' | 18 -> 'R' | 19 -> 'S' | 20 -> 'T'\n | 21 -> 'U' | 22 -> 'V' | 23 -> 'W' | 24 -> 'X' | 25 -> 'Y'\n | 0 -> 'Z' | x -> ' '\n\nlet string_to_column_number s =\n let rec aux acc cur = function\n | [] -> acc\n | h :: t -> aux ((pos_in_alphabet h)*int_of_float(26. ** (float_of_int cur)) + acc) (cur+1) t\n in aux 0 0 (List.rev (string_to_list s))\n\nlet column_number_to_string col =\n let rec aux acc last_div n =\n if n <= 26\n then (\n if last_div\n then (String.make 1 (char_at_pos ((n-1) mod 26))) ^ acc\n else (String.make 1 (char_at_pos (n mod 26))) ^ acc\n )\n else\n if last_div\n then aux (String.make 1 (char_at_pos ((n-1) mod 26)) ^ acc ) ((n mod 26) = 0) (n / 26)\n else aux (String.make 1 (char_at_pos (n mod 26)) ^ acc ) ((n mod 26) = 0) (n / 26)\n in aux \"\" false col\n\nlet numeration_to_string = function\n | Excel (col, row) -> col ^ (string_of_int row)\n | Coord (row, col) -> \"R\" ^ (string_of_int row) ^ \"C\" ^ (string_of_int col)\n\nlet switch_numeration = function\n | Excel (col, row) -> Coord (row, string_to_column_number(col))\n | Coord (row, col) -> Excel (column_number_to_string(col), row)\n\n(*\nlet spreadsheets l =\n l\n |> List.map string_to_numeration\n |> List.filter (function Some(_) -> true | None -> false)\n |> List.map (function Some(x) -> x | x -> assert false)\n |> List.map switch_numeration\n |> List.map numeration_to_string\n*)\n\nlet spreadsheets l =\n l\n |> List.map (fun x ->\n match string_to_numeration (x) with\n | Some(e) -> numeration_to_string (switch_numeration e)\n | None -> assert false)\n\nlet () =\n let num = read_int () in\n let do_parse cnt =\n let rec loop acc = function\n | c when c < 1 -> acc\n | c ->\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s\\n\" (fun x -> x)\n in loop (s::acc) (c-1)\n in List.rev (loop [] cnt)\n in List.iter (Printf.printf \"%s\\n\") (spreadsheets (do_parse num))\n\n"}, {"source_code": "\ntype numeration =\n | Excel of string * int\n | Coord of int * int\n\nlet string_to_numeration s =\n if Str.string_match (Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Excel (Str.matched_group 1 s, int_of_string (Str.matched_group 2 s)))\n else if Str.string_match (Str.regexp \"^R\\\\([1-9][0-9]*\\\\)C\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Coord (int_of_string (Str.matched_group 1 s), int_of_string (Str.matched_group 2 s)))\n else\n None\n\nlet string_to_list s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l)\n in exp (String.length s - 1) []\n\nlet pos_in_alphabet = function\n | 'A' -> 1 | 'B' -> 2 | 'C' -> 3 | 'D' -> 4 | 'E' -> 5\n | 'F' -> 6 | 'G' -> 7 | 'H' -> 8 | 'I' -> 9 | 'J' -> 10\n | 'K' -> 11 | 'L' -> 12 | 'M' -> 13 | 'N' -> 14 | 'O' -> 15\n | 'P' -> 16 | 'Q' -> 17 | 'R' -> 18 | 'S' -> 19 | 'T' -> 20\n | 'U' -> 21 | 'V' -> 22 | 'W' -> 23 | 'X' -> 24 | 'Y' -> 25\n | 'Z' -> 26 | _ -> 0\n\nlet char_at_pos = function\n | 1 -> 'A' | 2 -> 'B' | 3 -> 'C' | 4 -> 'D' | 5 -> 'E'\n | 6 -> 'F' | 7 -> 'G' | 8 -> 'H' | 9 -> 'I' | 10 -> 'J'\n | 11 -> 'K' | 12 -> 'L' | 13 -> 'M' | 14 -> 'N' | 15 -> 'O'\n | 16 -> 'P' | 17 -> 'Q' | 18 -> 'R' | 19 -> 'S' | 20 -> 'T'\n | 21 -> 'U' | 22 -> 'V' | 23 -> 'W' | 24 -> 'X' | 25 -> 'Y'\n | 26 -> 'Z' | _ -> ' '\n\nlet string_to_column_number s =\n let rec aux acc cur = function\n | [] -> acc\n | h :: t ->\n aux ((pos_in_alphabet h)*int_of_float(26. ** (float_of_int cur)) + acc) (cur+1) t\n in aux 0 0 (List.rev (string_to_list s))\n\nlet colum_number_to_string col =\n let rec aux acc n =\n if n <= 26\n then (Char.escaped (char_at_pos n)) ^ acc\n else aux (Char.escaped (char_at_pos (n mod 26)) ^ acc ) (n / 26)\n in aux \"\" col\n\nlet numeration_to_string = function\n | Excel (col, row) -> col ^ (string_of_int row)\n | Coord (row, col) -> \"R\" ^ (string_of_int row) ^ \"C\" ^ (string_of_int col)\n\nlet switch_numeration = function\n | Excel (col, row) -> Coord (row, string_to_column_number(col))\n | Coord (row, col) -> Excel (colum_number_to_string(col), row)\n\n(*\nlet spreadsheets l =\n l\n |> List.map string_to_numeration\n |> List.filter (function Some(_) -> true | None -> false)\n |> List.map (function Some(x) -> x | x -> assert false)\n |> List.map switch_numeration\n |> List.map numeration_to_string\n*)\n\nlet spreadsheets l =\n l\n |> List.map (fun x ->\n match string_to_numeration (x) with\n | Some(e) -> numeration_to_string (switch_numeration e)\n | None -> assert false)\n\nlet () =\n let num = read_int () in\n let do_parse cnt =\n let rec loop acc = function\n | c when c < 1 -> acc\n | c ->\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s\\n\" (fun x -> x)\n in loop (s::acc) (c-1)\n in\n List.rev (loop [] cnt)\n in\n List.iter (Printf.printf \"%s\\n\") (spreadsheets (do_parse num))\n\n"}, {"source_code": "\ntype numeration =\n | Excel of string * int\n | Coord of int * int\n\nlet string_to_numeration s =\n if Str.string_match (Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Excel (Str.matched_group 1 s, int_of_string (Str.matched_group 2 s)))\n else if Str.string_match (Str.regexp \"^R\\\\([1-9][0-9]*\\\\)C\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Coord (int_of_string (Str.matched_group 1 s), int_of_string (Str.matched_group 2 s)))\n else\n None\n\nlet string_to_list s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l)\n in exp (String.length s - 1) []\n\nlet pos_in_alphabet = function\n | 'A' -> 1 | 'B' -> 2 | 'C' -> 3 | 'D' -> 4 | 'E' -> 5\n | 'F' -> 6 | 'G' -> 7 | 'H' -> 8 | 'I' -> 9 | 'J' -> 10\n | 'K' -> 11 | 'L' -> 12 | 'M' -> 13 | 'N' -> 14 | 'O' -> 15\n | 'P' -> 16 | 'Q' -> 17 | 'R' -> 18 | 'S' -> 19 | 'T' -> 20\n | 'U' -> 21 | 'V' -> 22 | 'W' -> 23 | 'X' -> 24 | 'Y' -> 25\n | 'Z' -> 26 | _ -> -1\n\nlet char_at_pos = function\n | 1 -> 'A' | 2 -> 'B' | 3 -> 'C' | 4 -> 'D' | 5 -> 'E'\n | 6 -> 'F' | 7 -> 'G' | 8 -> 'H' | 9 -> 'I' | 10 -> 'J'\n | 11 -> 'K' | 12 -> 'L' | 13 -> 'M' | 14 -> 'N' | 15 -> 'O'\n | 16 -> 'P' | 17 -> 'Q' | 18 -> 'R' | 19 -> 'S' | 20 -> 'T'\n | 21 -> 'U' | 22 -> 'V' | 23 -> 'W' | 24 -> 'X' | 25 -> 'Y'\n | 0 -> 'Z' | x -> ' '\n\nlet string_to_column_number s =\n let rec aux acc cur = function\n | [] -> acc\n | h :: t -> aux ((pos_in_alphabet h)*int_of_float(26. ** (float_of_int cur)) + acc) (cur+1) t\n in aux 0 0 (List.rev (string_to_list s))\n\nlet column_number_to_string col =\n let rec aux acc n =\n if n <= 26\n then (\n if (String.length acc > 0) && ((String.get acc 0) = 'Z')\n then (String.make 1 (char_at_pos ((n-1) mod 26))) ^ acc\n else (String.make 1 (char_at_pos (n mod 26))) ^ acc\n )\n else\n if (String.length acc > 0) && ((String.get acc 0) = 'Z')\n then aux (String.make 1 (char_at_pos ((n-1) mod 26)) ^ acc ) (n / 26)\n else aux (String.make 1 (char_at_pos (n mod 26)) ^ acc ) (n / 26)\n in aux \"\" col\n\nlet numeration_to_string = function\n | Excel (col, row) -> col ^ (string_of_int row)\n | Coord (row, col) -> \"R\" ^ (string_of_int row) ^ \"C\" ^ (string_of_int col)\n\nlet switch_numeration = function\n | Excel (col, row) -> Coord (row, string_to_column_number(col))\n | Coord (row, col) -> Excel (column_number_to_string(col), row)\n\n(*\nlet spreadsheets l =\n l\n |> List.map string_to_numeration\n |> List.filter (function Some(_) -> true | None -> false)\n |> List.map (function Some(x) -> x | x -> assert false)\n |> List.map switch_numeration\n |> List.map numeration_to_string\n*)\n\nlet spreadsheets l =\n l\n |> List.map (fun x ->\n match string_to_numeration (x) with\n | Some(e) -> numeration_to_string (switch_numeration e)\n | None -> assert false)\n\nlet () =\n let num = read_int () in\n let do_parse cnt =\n let rec loop acc = function\n | c when c < 1 -> acc\n | c ->\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s\\n\" (fun x -> x)\n in loop (s::acc) (c-1)\n in List.rev (loop [] cnt)\n in List.iter (Printf.printf \"%s\\n\") (spreadsheets (do_parse num))\n\n"}, {"source_code": "\ntype numeration =\n | Excel of string * int\n | Coord of int * int\n\nlet string_to_numeration s =\n if Str.string_match (Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Excel (Str.matched_group 1 s, int_of_string (Str.matched_group 2 s)))\n else if Str.string_match (Str.regexp \"^R\\\\([1-9][0-9]*\\\\)C\\\\([1-9][0-9]*\\\\)$\") s 0 then\n Some(Coord (int_of_string (Str.matched_group 1 s), int_of_string (Str.matched_group 2 s)))\n else\n None\n\nlet string_to_list s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l)\n in exp (String.length s - 1) []\n\nlet pos_in_alphabet = function\n | 'A' -> 1 | 'B' -> 2 | 'C' -> 3 | 'D' -> 4 | 'E' -> 5\n | 'F' -> 6 | 'G' -> 7 | 'H' -> 8 | 'I' -> 9 | 'J' -> 10\n | 'K' -> 11 | 'L' -> 12 | 'M' -> 13 | 'N' -> 14 | 'O' -> 15\n | 'P' -> 16 | 'Q' -> 17 | 'R' -> 18 | 'S' -> 19 | 'T' -> 20\n | 'U' -> 21 | 'V' -> 22 | 'W' -> 23 | 'X' -> 24 | 'Y' -> 25\n | 'Z' -> 26 | _ -> -1;;\n\nlet char_at_pos = function\n | 1 -> 'A' | 2 -> 'B' | 3 -> 'C' | 4 -> 'D' | 5 -> 'E'\n | 6 -> 'F' | 7 -> 'G' | 8 -> 'H' | 9 -> 'I' | 10 -> 'J'\n | 11 -> 'K' | 12 -> 'L' | 13 -> 'M' | 14 -> 'N' | 15 -> 'O'\n | 16 -> 'P' | 17 -> 'Q' | 18 -> 'R' | 19 -> 'S' | 20 -> 'T'\n | 21 -> 'U' | 22 -> 'V' | 23 -> 'W' | 24 -> 'X' | 25 -> 'Y'\n | 0 -> 'Z' | x -> ' '\n\nlet string_to_column_number s =\n let rec aux acc cur = function\n | [] -> acc\n | h :: t -> aux ((pos_in_alphabet h)*int_of_float(26. ** (float_of_int cur)) + acc) (cur+1) t\n in aux 0 0 (List.rev (string_to_list s))\n\nlet column_number_to_string col =\n let rec aux acc n =\n if n <= 26\n then (\n if acc = \"Z\"\n then (String.make 1 (char_at_pos ((n-1) mod 26))) ^ acc\n else (String.make 1 (char_at_pos (n mod 26))) ^ acc\n )\n else aux (String.make 1 (char_at_pos (n mod 26)) ^ acc ) (n / 26)\n in aux \"\" col\n\nlet numeration_to_string = function\n | Excel (col, row) -> col ^ (string_of_int row)\n | Coord (row, col) -> \"R\" ^ (string_of_int row) ^ \"C\" ^ (string_of_int col)\n\nlet switch_numeration = function\n | Excel (col, row) -> Coord (row, string_to_column_number(col))\n | Coord (row, col) -> Excel (column_number_to_string(col), row)\n\n(*\nlet spreadsheets l =\n l\n |> List.map string_to_numeration\n |> List.filter (function Some(_) -> true | None -> false)\n |> List.map (function Some(x) -> x | x -> assert false)\n |> List.map switch_numeration\n |> List.map numeration_to_string\n*)\n\nlet spreadsheets l =\n l\n |> List.map (fun x ->\n match string_to_numeration (x) with\n | Some(e) -> numeration_to_string (switch_numeration e)\n | None -> assert false)\n\nlet () =\n let num = read_int () in\n let do_parse cnt =\n let rec loop acc = function\n | c when c < 1 -> acc\n | c ->\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s\\n\" (fun x -> x)\n in loop (s::acc) (c-1)\n in List.rev (loop [] cnt)\n in List.iter (Printf.printf \"%s\\n\") (spreadsheets (do_parse num))\n\n"}, {"source_code": "let ia = int_of_char 'A' in\nlet isrc str = \n if str.[0] <> 'R' then failwith \"Wrong\"\n else let p = String.index_from str 2 'C' in (true, int_of_string (String.sub str (p + 1) (String.length str - p - 1)), int_of_string (String.sub str 1 (p - 1)))\nand isan str =\n let rec strip_al ald pos = \n if str.[pos] < 'A' then (ald, pos) else strip_al (26 * ald + (int_of_char str.[pos] - ia + 1)) (pos + 1) \n in\n let (ra, rp) = strip_al 0 0\n in\n (false, ra, int_of_string (String.sub str rp (String.length str - rp)))\nand oprc y x =\n print_char 'R'; print_int x; print_char 'C'; print_int y\nand opan x y =\n let rec px x = if x > 0 then let _ = px (x / 26) in print_char (char_of_int (x mod 26 - 1 + ia)) else () in\n px x; print_int y\nin\nfor lc = (read_int ()) downto 1 do\n let line = read_line () in\n let (is_rc, x, y) = try isrc line with _ -> isan line in\n (if is_rc then opan else oprc) x y; print_newline ()\ndone\n"}, {"source_code": "\nlet read_line_of_strings () =\n read_line () |> Str.split (Str.regexp \" +\")\n\nlet read_line_of f =\n read_line_of_strings () |> List.map f\n\nlet read_line_of_floats () =\n read_line_of float_of_string\n\nlet coordinates_of_string input =\n let rx1 = Str.regexp \"^R\\\\([0-9]+\\\\)C\\\\([0-9]+\\\\)$\" in\n let rx2 = Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([0-9]+\\\\)$\" in\n if Str.string_match rx1 input 0 then\n let row = Str.matched_group 1 input in\n let col = Str.matched_group 2 input in\n `RC (int_of_string row, int_of_string col)\n else if Str.string_match rx2 input 0 then\n let col = Str.matched_group 1 input in\n let row = Str.matched_group 2 input in\n `A1 (int_of_string row, col)\n else\n raise (Invalid_argument input)\n\nlet col_to_int name =\n let len = String.length name in\n let sum = ref 0 in\n let acc = ref 1 in\n for i = len - 1 downto 0 do\n sum := !sum + (Char.code name.[i] - 65) * !acc;\n acc := !acc * 26;\n done;\n !sum\n\nlet int_to_col n =\n let to_digit k = String.make 1 (Char.chr (k + 65)) in\n let rec iter name n =\n if n > 25 then\n let (d, n) = (n mod 26, n / 26) in\n iter (to_digit d ^ name) n\n else\n to_digit n ^ name\n in\n iter \"\" n\n\nlet solve = function\n | `RC (row, col) -> Printf.sprintf \"%s%d\" (int_to_col col) row\n | `A1 (row, col) -> Printf.sprintf \"R%dC%d\" row (col_to_int col)\n\nlet convert input =\n solve (coordinates_of_string input)\n\nlet () =\n let [count] = read_line_of int_of_string in\n for i = 1 to count do\n read_line_of coordinates_of_string\n |> List.iter (fun task -> Printf.printf \"%s\\n\" (solve task))\n done;\n"}, {"source_code": "let read_line_of_strings () =\n read_line () |> Str.split (Str.regexp \" +\")\n\nlet read_line_of f =\n read_line_of_strings () |> List.map f\n\nlet read_line_of_floats () =\n read_line_of float_of_string\n\nlet coordinates_of_string input =\n let rx1 = Str.regexp \"^R\\\\([0-9]+\\\\)C\\\\([0-9]+\\\\)$\" in\n let rx2 = Str.regexp \"^\\\\([A-Z]+\\\\)\\\\([0-9]+\\\\)$\" in\n if Str.string_match rx1 input 0 then\n let row = Str.matched_group 1 input in\n let col = Str.matched_group 2 input in\n `RC (int_of_string row, int_of_string col)\n else if Str.string_match rx2 input 0 then\n let col = Str.matched_group 1 input in\n let row = Str.matched_group 2 input in\n `A1 (int_of_string row, col)\n else\n raise (Invalid_argument input)\n\nlet col_to_int name =\n let len = String.length name in\n let sum = ref 0 in\n let acc = ref 1 in\n for i = len - 1 downto 0 do\n sum := !sum + (Char.code name.[i] - 64) * !acc;\n acc := !acc * 26;\n done;\n !sum\n\nlet int_to_col n =\n let to_digit k = String.make 1 (Char.chr (k + 64)) in\n let rec iter name n =\n if n > 26 then\n let (d, n) = (n mod 26, n / 26) in\n iter (to_digit d ^ name) n\n else\n to_digit n ^ name\n in\n iter \"\" n\n\nlet solve = function\n | `RC (row, col) -> Printf.sprintf \"%s%d\\n\" (int_to_col col) row\n | `A1 (row, col) -> Printf.sprintf \"R%dC%d\\n\" row (col_to_int col)\n\nlet () =\n let [count] = read_line_of int_of_string in\n for i = 1 to count do\n read_line_of coordinates_of_string\n |> List.iter (fun task -> Printf.printf \"%s\\n\" (solve task))\n done;\n"}], "src_uid": "910c0e650d48af22fa51ab05e8123709"} {"nl": {"description": "Consider the set of all nonnegative integers: $$${0, 1, 2, \\dots}$$$. Given two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^4$$$). We paint all the numbers in increasing number first we paint $$$0$$$, then we paint $$$1$$$, then $$$2$$$ and so on.Each number is painted white or black. We paint a number $$$i$$$ according to the following rules: if $$$i = 0$$$, it is colored white; if $$$i \\ge a$$$ and $$$i - a$$$ is colored white, $$$i$$$ is also colored white; if $$$i \\ge b$$$ and $$$i - b$$$ is colored white, $$$i$$$ is also colored white; if $$$i$$$ is still not colored white, it is colored black. In this way, each nonnegative integer gets one of two colors.For example, if $$$a=3$$$, $$$b=5$$$, then the colors of the numbers (in the order from $$$0$$$) are: white ($$$0$$$), black ($$$1$$$), black ($$$2$$$), white ($$$3$$$), black ($$$4$$$), white ($$$5$$$), white ($$$6$$$), black ($$$7$$$), white ($$$8$$$), white ($$$9$$$), ...Note that: It is possible that there are infinitely many nonnegative integers colored black. For example, if $$$a = 10$$$ and $$$b = 10$$$, then only $$$0, 10, 20, 30$$$ and any other nonnegative integers that end in $$$0$$$ when written in base 10 are white. The other integers are colored black. It is also possible that there are only finitely many nonnegative integers colored black. For example, when $$$a = 1$$$ and $$$b = 10$$$, then there is no nonnegative integer colored black at all. Your task is to determine whether or not the number of nonnegative integers colored black is infinite.If there are infinitely many nonnegative integers colored black, simply print a line containing \"Infinite\" (without the quotes). Otherwise, print \"Finite\" (without the quotes).", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then $$$t$$$ lines follow, each line contains two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^4$$$).", "output_spec": "For each test case, print one line containing either \"Infinite\" or \"Finite\" (without the quotes). Output is case-insensitive (i.e. \"infinite\", \"inFiNite\" or \"finiTE\" are all valid answers).", "sample_inputs": ["4\n10 10\n1 10\n6 9\n7 3"], "sample_outputs": ["Infinite\nFinite\nInfinite\nFinite"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet rec gcd a b =\n\tif b = 0 then a \n\telse gcd b (a mod b)\n\nlet () = \n\tlet n = read_int() in\n\tfor i = 1 to n do\n\t\tlet a = read_int() and b = read_int() in\n\t\tif gcd a b = 1 then printf \"Finite\\n\"\n\t\telse printf \"Infinite\\n\"\n\tdone\n\t\t\n"}, {"source_code": "let rec pgcd a b =\n if b = 0 then a\n else if a > b then\n pgcd b a\n else\n let r = b - a in\n pgcd a r\n\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n let (a,b) =\n match l with\n | [a;b] -> (a,b)\n | _ -> assert false\n in\n if pgcd a b <> 1 then\n Format.printf \"Infinite@.\"\n else\n Format.printf \"Finite@.\"\n done\n"}], "negative_code": [], "src_uid": "388450021f2f33177d905879485bb531"} {"nl": {"description": "It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has gi Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation f of {1,\u20092,\u2009...,\u2009m}, such that f(x)\u2009=\u2009y means that a Pokemon of type x evolves into a Pokemon of type y.The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol.Two evolution plans f1 and f2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an i such that f1(i)\u2009\u2260\u2009f2(i).Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 109\u2009+\u20097.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009m\u2009\u2264\u2009106)\u00a0\u2014 the number of gyms and the number of Pokemon types. The next n lines contain the description of Pokemons in the gyms. The i-th of these lines begins with the integer gi (1\u2009\u2264\u2009gi\u2009\u2264\u2009105)\u00a0\u2014 the number of Pokemon in the i-th gym. After that gi integers follow, denoting types of the Pokemons in the i-th gym. Each of these integers is between 1 and m. The total number of Pokemons (the sum of all gi) does not exceed 5\u00b7105.", "output_spec": "Output the number of valid evolution plans modulo 109\u2009+\u20097.", "sample_inputs": ["2 3\n2 1 2\n2 2 3", "1 3\n3 1 2 3", "2 4\n2 1 2\n3 2 3 4", "2 2\n3 2 2 1\n2 1 2", "3 7\n2 1 2\n2 3 4\n3 5 6 7"], "sample_outputs": ["1", "6", "2", "1", "24"], "notes": "NoteIn the first case, the only possible evolution plan is: In the second case, any permutation of (1,\u2009\u20092,\u2009\u20093) is valid.In the third case, there are two possible plans: In the fourth case, the only possible evolution plan is: "}, "positive_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let n = getnum () in\n let m = getnum () in\n let fact = Array.make (m + 1) 1 in\n let () =\n for i = 2 to m do\n fact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);\n done;\n in\n let s = Array.make (m + 1) [] in\n let sidx = ref 0 in\n for i = 0 to n - 1 do\n let g = getnum () in\n let a = Array.make (g + 1) 0 in\n\tfor j = 0 to g - 1 do\n\t a.(j) <- getnum ();\n\tdone;\n\ta.(g) <- 10000000;\n\tArray.sort compare a;\n\tlet prev = ref a.(0) in\n\tlet cnt = ref 1 in\n\tlet ht = Hashtbl.create 10 in\n\t for j = 1 to g do\n\t if a.(j) = !prev\n\t then incr cnt\n\t else (\n\t (try\n\t\t let xs = Hashtbl.find ht !cnt in\n\t\t Hashtbl.replace ht !cnt (!prev :: xs)\n\t with\n\t\t | Not_found ->\n\t\t Hashtbl.replace ht !cnt [!prev]\n\t );\n\t prev := a.(j);\n\t cnt := 1;\n\t )\n\t done;\n\t Hashtbl.iter\n\t (fun _cnt xs ->\n\t List.iter\n\t\t (fun x ->\n\t\t (*Printf.printf \"qwe %d %d\\n\" _cnt x;*)\n\t\t s.(x) <- !sidx :: s.(x)\n\t\t ) xs;\n\t incr sidx;\n\t ) ht\n done;\n let ht = Hashtbl.create 10 in\n (*for i = 1 to m do\n\tPrintf.printf \"%d\" i;\n\tList.iter (Printf.printf \" %d\") s.(i);\n\tPrintf.printf \"\\n\"\n\tdone;*)\n for i = 1 to m do\n\t(try\n\t let c = Hashtbl.find ht s.(i) in\n\t Hashtbl.replace ht s.(i) (c + 1)\n\t with\n\t | Not_found ->\n\t Hashtbl.replace ht s.(i) 1\n\t);\n done;\n let res = ref 1L in\n\tHashtbl.iter\n\t (fun _ c ->\n\t res := mmod (!res *| Int64.of_int fact.(c))\n\t ) ht;\n\tPrintf.printf \"%Ld\\n\" !res\n"}, {"source_code": "open Printf\nopen Scanf\n\n\nlet p = 1_000_000_007L\n\nlet ( %% ) x n = let y = Int64.rem x n in if y<0L then Int64.add y n else y\nlet ( ** ) a b = (Int64.mul a b) %% p\nlet ( ++ ) a b = (Int64.add a b) %% p\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet prod i j f = fold i j (fun i a -> (f i) ** a) 1L\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in (* gyms *)\n let m = read_int () in (* pokymon types *)\n let dummy = Hashtbl.create 10 in \n let ht = Array.make n dummy in\n\n for i=0 to n-1 do\n let np = read_int () in\n let h = Hashtbl.create 10 in\n ht.(i) <- h;\n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n for j=0 to np-1 do\n let pk = read_int() in\n increment (pk-1);\n done;\n done;\n\n let cl_array = Array.make m 0 in\n\n let classno = ref 1 in (* the next class number to assign *)\n \n for gym = 0 to n-1 do\n (* incorporate the effect of this guy on our class array *)\n let classht = Hashtbl.create 10 in\n Hashtbl.iter (fun pk count ->\n let pair = (cl_array.(pk), count) in\n if not (Hashtbl.mem classht pair) then (\n\tHashtbl.add classht pair !classno;\n\tcl_array.(pk) <- !classno;\n\tclassno := 1 + !classno\n ) else (\n\tcl_array.(pk) <- Hashtbl.find classht pair\n )\n ) ht.(gym);\n done;\n\n let hist = Array.make !classno 0 in\n\n for i=0 to m-1 do\n hist.(cl_array.(i)) <- hist.(cl_array.(i)) + 1\n done;\n\n let fact = Array.make (m+1) 1L in\n\n for i=1 to m do\n fact.(i) <- fact.(i-1) ** (long i)\n done;\n\n let answer = prod 0 (!classno -1) (fun cl -> fact.(hist.(cl))) in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let n = getnum () in\n let m = getnum () in\n let fact = Array.make (m + 1) 1 in\n let () =\n for i = 2 to m do\n fact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);\n done;\n in\n let s = Array.make (m + 1) [] in\n let sidx = ref 0 in\n for i = 0 to n - 1 do\n let g = getnum () in\n let a = Array.make (g + 1) 0 in\n\tfor j = 0 to g - 1 do\n\t a.(j) <- getnum ();\n\tdone;\n\ta.(g) <- 1000000;\n\tArray.sort compare a;\n\tlet prev = ref a.(0) in\n\tlet cnt = ref 1 in\n\tlet ht = Hashtbl.create 10 in\n\t for j = 1 to g do\n\t if a.(j) = !prev\n\t then incr cnt\n\t else (\n\t (try\n\t\t let xs = Hashtbl.find ht !cnt in\n\t\t Hashtbl.replace ht !cnt (!prev :: xs)\n\t with\n\t\t | Not_found ->\n\t\t Hashtbl.replace ht !cnt [!prev]\n\t );\n\t prev := a.(j);\n\t cnt := 1;\n\t )\n\t done;\n\t Hashtbl.iter\n\t (fun _cnt xs ->\n\t List.iter\n\t\t (fun x ->\n\t\t (*Printf.printf \"qwe %d %d\\n\" _cnt x;*)\n\t\t s.(x) <- !sidx :: s.(x)\n\t\t ) xs;\n\t incr sidx;\n\t ) ht\n done;\n let ht = Hashtbl.create 10 in\n (*for i = 1 to m do\n\tPrintf.printf \"%d\" i;\n\tList.iter (Printf.printf \" %d\") s.(i);\n\tPrintf.printf \"\\n\"\n\tdone;*)\n for i = 1 to m do\n\t(try\n\t let c = Hashtbl.find ht s.(i) in\n\t Hashtbl.replace ht s.(i) (c + 1)\n\t with\n\t | Not_found ->\n\t Hashtbl.replace ht s.(i) 1\n\t);\n done;\n let res = ref 1L in\n\tHashtbl.iter\n\t (fun _ c ->\n\t res := mmod (!res *| Int64.of_int fact.(c))\n\t ) ht;\n\tPrintf.printf \"%Ld\\n\" !res\n"}, {"source_code": "let getnum =\n let l = 5120000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let n = getnum () in\n let m = getnum () in\n let fact = Array.make (m + 1) 1 in\n let () =\n for i = 2 to m do\n fact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);\n done;\n in\n let s = Array.make (m + 1) [] in\n let sidx = ref 0 in\n for i = 0 to n - 1 do\n let g = getnum () in\n let a = Array.make (g + 1) 0 in\n\tfor j = 0 to g - 1 do\n\t a.(j) <- getnum ();\n\tdone;\n\ta.(g) <- 1000000;\n\tArray.sort compare a;\n\tlet prev = ref a.(0) in\n\tlet cnt = ref 1 in\n\tlet ht = Hashtbl.create 10 in\n\t for j = 1 to g do\n\t if a.(j) = !prev\n\t then incr cnt\n\t else (\n\t (try\n\t\t let xs = Hashtbl.find ht !cnt in\n\t\t Hashtbl.replace ht !cnt (!prev :: xs)\n\t with\n\t\t | Not_found ->\n\t\t Hashtbl.replace ht !cnt [!prev]\n\t );\n\t prev := a.(j);\n\t cnt := 1;\n\t )\n\t done;\n\t Hashtbl.iter\n\t (fun _cnt xs ->\n\t List.iter\n\t\t (fun x ->\n\t\t (*Printf.printf \"qwe %d %d\\n\" _cnt x;*)\n\t\t s.(x) <- !sidx :: s.(x)\n\t\t ) xs;\n\t incr sidx;\n\t ) ht\n done;\n let ht = Hashtbl.create 10 in\n (*for i = 1 to m do\n\tPrintf.printf \"%d\" i;\n\tList.iter (Printf.printf \" %d\") s.(i);\n\tPrintf.printf \"\\n\"\n\tdone;*)\n for i = 1 to m do\n\t(try\n\t let c = Hashtbl.find ht s.(i) in\n\t Hashtbl.replace ht s.(i) (c + 1)\n\t with\n\t | Not_found ->\n\t Hashtbl.replace ht s.(i) 1\n\t);\n done;\n let res = ref 1L in\n\tHashtbl.iter\n\t (fun _ c ->\n\t res := mmod (!res *| Int64.of_int fact.(c))\n\t ) ht;\n\tPrintf.printf \"%Ld\\n\" !res\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let n = getnum () in\n let m = getnum () in\n let fact = Array.make (m + 1) 1 in\n let () =\n for i = 2 to m do\n fact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);\n done;\n in\n let s = Array.make (m + 1) [] in\n let sidx = ref 0 in\n for i = 0 to n - 1 do\n let g = getnum () in\n let a = Array.make (g + 1) 0 in\n\tfor j = 0 to g - 1 do\n\t a.(j) <- getnum ();\n\tdone;\n\ta.(g) <- 1000000;\n\tArray.sort compare a;\n\tlet prev = ref a.(0) in\n\tlet cnt = ref 1 in\n\tlet ht = Hashtbl.create 10 in\n\t for j = 1 to g do\n\t if a.(j) = !prev\n\t then incr cnt\n\t else (\n\t (try\n\t\t let xs = Hashtbl.find ht !cnt in\n\t\t Hashtbl.replace ht !cnt (!prev :: xs)\n\t with\n\t\t | Not_found ->\n\t\t Hashtbl.replace ht !cnt [!prev]\n\t );\n\t prev := a.(j);\n\t cnt := 1;\n\t )\n\t done;\n\t Hashtbl.iter\n\t (fun _cnt xs ->\n\t List.iter\n\t\t (fun x ->\n\t\t (*Printf.printf \"qwe %d %d\\n\" _cnt x;*)\n\t\t s.(x) <- !sidx :: s.(x)\n\t\t ) xs;\n\t incr sidx;\n\t ) ht\n done;\n let ht = Hashtbl.create 10 in\n (*for i = 1 to m do\n\tPrintf.printf \"%d\" i;\n\tList.iter (Printf.printf \" %d\") s.(i);\n\tPrintf.printf \"\\n\"\n\tdone;*)\n for i = 1 to m do\n\t(try\n\t let c = Hashtbl.find ht s.(i) in\n\t Hashtbl.replace ht s.(i) (c + 1)\n\t with\n\t | Not_found ->\n\t Hashtbl.replace ht s.(i) 1\n\t);\n done;\n let res = ref 1L in\n\tHashtbl.iter\n\t (fun _ c ->\n\t res := !res *| Int64.of_int fact.(c)\n\t ) ht;\n\tPrintf.printf \"%Ld\\n\" !res\n"}], "src_uid": "cff3074a82bffdd49579a47c7491f972"} {"nl": {"description": "This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs n ingredients, and for each ingredient she knows the value ai\u00a0\u2014 how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all n ingredients.Apollinaria has bi gram of the i-th ingredient. Also she has k grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the n ingredients and can be used for baking cookies.Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.", "input_spec": "The first line of the input contains two positive integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u20091000)\u00a0\u2014 the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u20091000), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.", "output_spec": "Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.", "sample_inputs": ["3 1\n2 1 4\n11 3 16", "4 3\n4 3 5 6\n11 12 14 20"], "sample_outputs": ["4", "3"], "notes": "NoteIn the first sample it is profitably for Apollinaria to make the existing 1 gram of her magic powder to ingredient with the index 2, then Apollinaria will be able to bake 4 cookies.In the second sample Apollinaria should turn 1 gram of magic powder to ingredient with the index 1 and 1 gram of magic powder to ingredient with the index 3. Then Apollinaria will be able to bake 3 cookies. The remaining 1 gram of the magic powder can be left, because it can't be used to increase the answer."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n \nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x) \nlet () = \n let n = read_int () in\n let k = read_long () in\n let a = Array.init n (fun _ -> read_long()) in\n let b = Array.init n (fun _ -> read_long()) in\n\n let can_bake m =\n let mp = sum 0 (n-1) (fun i -> max 0L (m ** a.(i) -- b.(i))) 0L in\n mp <= k\n in\n\n let rec bsearch lo hi =\n (* lo can be made, hi cannot *)\n if lo++1L = hi then lo else\n let m = (lo ++ hi) // 2L in\n if can_bake m then bsearch m hi else bsearch lo m\n in\n\n let rec findhi hi = if can_bake hi then findhi (2L ** hi) else hi in\n\n printf \"%Ld\\n\" (bsearch 0L (findhi 1L))\n \n"}], "negative_code": [], "src_uid": "02bb7502135afa0f3bb26527427ba9e3"} {"nl": {"description": "You are given four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$. You should build a sequence $$$a_0, a_1, a_2, \\dots, a_n$$$ where $$$a_0 = 0$$$ and for each $$$i \\ge 1$$$ you can choose: either $$$a_i = a_{i - 1} + x$$$ or $$$a_i = a_{i - 1} - y$$$. Your goal is to build such a sequence $$$a$$$ that $$$a_i \\le B$$$ for all $$$i$$$ and $$$\\sum\\limits_{i=0}^{n}{a_i}$$$ is maximum possible.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Next $$$t$$$ cases follow. The first and only line of each test case contains four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$; $$$1 \\le B, x, y \\le 10^9$$$). It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print one integer\u00a0\u2014 the maximum possible $$$\\sum\\limits_{i=0}^{n}{a_i}$$$.", "sample_inputs": ["3\n5 100 1 30\n7 1000000000 1000000000 1000000000\n4 1 7 3"], "sample_outputs": ["15\n4000000000\n-10"], "notes": "NoteIn the first test case, the optimal sequence $$$a$$$ is $$$[0, 1, 2, 3, 4, 5]$$$.In the second test case, the optimal sequence $$$a$$$ is $$$[0, 10^9, 0, 10^9, 0, 10^9, 0, 10^9]$$$.In the third test case, the optimal sequence $$$a$$$ is $$$[0, -3, -6, 1, -2]$$$."}, "positive_code": [{"source_code": "(* \r\n build sequence a0, a1, ... , an\r\n a0 = 0, \r\n 1)ai = a(i-1)+x or 2)ai = a(i-1)-y\r\n ai <= B \r\n \r\n maximise sum\r\n \r\n want all ai to be as close to B as possible\r\n - do 1) up to B then (2) and (1) alternating\r\n\r\n a0, a1, a2, ... , ak, a(k+1), ... , an\r\n\r\n 0, x, 2*x, ... , k*x where k*x <= B, k*x-y, ... , an\r\n\r\n sum = (x+2*x+...+k*x) + floor((n-k)/2)*(k*x-y+k*x) + (k*x-y if n-k is not even)\r\n\r\n n=5, B=100, x=1, y=30\r\n\r\n 0, 1, 2, 3, 4, 5 = 5/2(5+1) =15\r\n\r\n \r\n n=7, B=1e8, x=1e8, y=1e8\r\n\r\n 0, 1e8, 0, 1e8, 0, 1e8, 0 = 7\r\n\r\n k = 1e8 / 1e8 = 1 < n\r\n s1 = (1e8*1*2/2)=1e8\r\n s2 = 6*(1e8)/2 = 3*1e8\r\n n-k is even so 4*1e8\r\n\r\n n=4, B=1, x=7, y=3\r\n\r\n 0, -3, 4 -> PROBLEM!\r\n\r\n k = 1 / 7 = 0 \r\n s1 = 0\r\n s2 = (4)*(2*0-3)/2=-6 \r\n\r\n add +x until no longer possible\r\n need to -y until we can +x\r\n add +x \r\n need to -y until we can +x\r\n repeat O(n) complexity\r\n\r\n add +x k1 times\r\n subtract y k2 times\r\n add x\r\n subtract y k2 times\r\n O(1) complexity if we calculate k1 and k2\r\n\r\n k1*x-k2*y + x<=B\r\n (k1+1)*x-B<=k2*y\r\n ((k1+1)*x-B)/y <= k2, since k2 isn't necessarily constant we have to do O(n)\r\n\r\n e.g 0, -3, -6, 1, -2, -5, -8, 0 (goes from 2 to 3)\r\n\r\n n=5, B=100, x=1, y=30\r\n\r\n 0 + alternate_sum 100 1 30 1 4\r\n 0 + 1 + alternate_sum ... 2 3\r\n 0 + 1 + 2 + ... 3 2\r\n 0 + 1 + 2 + 3 + ... 4 1\r\n 0 + 1 + 2 + 3 + 4 + ... 5 0\r\n 0 + 1 + 2 + 3 + 4 + 5\r\n\r\n *)\r\n\r\n\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\nlet read_float () = Scanf.scanf \" %f\" (fun x -> x);;\r\n\r\nlet rec alternate_sum _B x y current = function \r\n | 0 -> current\r\n | n -> \r\n if (current +. x<=_B) then current +. alternate_sum _B x y (current +. x) (n-1)\r\n else current +. alternate_sum _B x y (current -. y) (n-1)\r\n;;\r\n\r\nlet run_case = function\r\n | () -> \r\n let n = read_int () in \r\n let _B = read_float () in \r\n let x = read_float () in \r\n let y = read_float () in\r\n alternate_sum _B x y 0.0 n\r\n;;\r\n\r\n\r\nlet print_big_float_as_int = fun x ->\r\n if (x!='.') then print_char (x)\r\n;;\r\n\r\nlet rec iter_cases = function \r\n | 0 -> 0\r\n | n -> \r\n let sum = run_case () in \r\n (*let _ = String.iter print_big_float_as_int (string_of_float sum) in*)\r\n Printf.printf \"%.0f\" sum;\r\n print_newline ();\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t = read_int () in \r\niter_cases t ;;"}, {"source_code": "let n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let n, b, x, y = Scanf.sscanf (input_line stdin) \"%d %d %d %d\" (fun n b x y -> (n,b,x,y)) in\r\n let tot= ref (Int64.zero) in\r\n let curr = ref (Int64.zero) in\r\n for j = 1 to n do\r\n if Int64.add (!tot) (Int64.of_int x) <= Int64.of_int b then \r\n (tot := Int64.add (!tot) (Int64.of_int x) ; curr := Int64.add (!curr) (!tot))\r\n else (tot := Int64.add (!tot) (Int64.of_int (-y)) ; curr := Int64.add (!curr) (!tot)) ; \r\n done;\r\n print_endline (Int64.to_string !curr ) \r\ndone;\r\n;;"}], "negative_code": [{"source_code": "(* \r\n build sequence a0, a1, ... , an\r\n a0 = 0, \r\n 1)ai = a(i-1)+x or 2)ai = a(i-1)-y\r\n ai <= B \r\n \r\n maximise sum\r\n \r\n want all ai to be as close to B as possible\r\n - do 1) up to B then (2) and (1) alternating\r\n \r\n a0, a1, a2, ... , ak, a(k+1), ... , an\r\n \r\n 0, x, 2*x, ... , k*x where k*x <= B, k*x-y, ... , an\r\n \r\n sum = (x+2*x+...+k*x) + floor((n-k)/2)*(k*x-y+k*x) + (k*x-y if n-k is not even)\r\n \r\n n=5, B=100, x=1, y=30\r\n \r\n 0, 1, 2, 3, 4, 5 = 5/2(5+1) =15\r\n \r\n \r\n n=7, B=1e8, x=1e8, y=1e8\r\n \r\n 0, 1e8, 0, 1e8, 0, 1e8, 0 = 7\r\n \r\n k = 1e8 / 1e8 = 1 < n\r\n s1 = (1e8*1*2/2)=1e8\r\n s2 = 6*(1e8)/2 = 3*1e8\r\n n-k is even so 4*1e8\r\n \r\n n=4, B=1, x=7, y=3\r\n \r\n 0, -3, 4 -> PROBLEM!\r\n \r\n k = 1 / 7 = 0 \r\n s1 = 0\r\n s2 = (4)*(2*0-3)/2=-6 \r\n \r\n add +x until no longer possible\r\n need to -y until we can +x\r\n add +x \r\n need to -y until we can +x\r\n repeat O(n) complexity\r\n \r\n add +x k1 times\r\n subtract y k2 times\r\n add x\r\n subtract y k2 times\r\n O(1) complexity if we calculate k1 and k2\r\n \r\n k1*x-k2*y + x<=B\r\n (k1+1)*x-B<=k2*y\r\n ((k1+1)*x-B)/y <= k2, since k2 isn't necessarily constant we have to do O(n)\r\n \r\n e.g 0, -3, -6, 1, -2, -5, -8, 0 (goes from 2 to 3)\r\n \r\n n=5, B=100, x=1, y=30\r\n \r\n 0 + alternate_sum 100 1 30 1 4\r\n 0 + 1 + alternate_sum ... 2 3\r\n 0 + 1 + 2 + ... 3 2\r\n 0 + 1 + 2 + 3 + ... 4 1\r\n 0 + 1 + 2 + 3 + 4 + ... 5 0\r\n 0 + 1 + 2 + 3 + 4 + 5\r\n \r\n *)\r\n \r\n \r\n \r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\nlet read_float () = Scanf.scanf \" %f\" (fun x -> x);;\r\n \r\nlet rec alternate_sum _B x y current = function \r\n | 0 -> current\r\n | n -> \r\n if (current +. x<=_B) then current +. alternate_sum _B x y (current +. x) (n-1)\r\n else current +. alternate_sum _B x y (current -. y) (n-1)\r\n;;\r\n \r\nlet run_case = function\r\n | () -> \r\n let n = read_int () in \r\n let _B = read_float () in \r\n let x = read_float () in \r\n let y = read_float () in\r\n alternate_sum _B x y 0.0 n\r\n;;\r\n \r\n \r\nlet print_big_float_as_int = fun x ->\r\n if (x!='.') then print_char (x)\r\n;;\r\n\r\nlet rec print_big_float_as_int2 = function\r\n| current_float, current_order ->\r\n if (current_float <= float_of_int max_int) then current_float, current_order\r\n else print_big_float_as_int2 ((current_float/.10.0), (current_order+1))\r\n;;\r\nlet rec print_order = function \r\n | 0 -> ()\r\n | n ->\r\n print_int 0;\r\n print_order (n-1)\r\n;;\r\nlet rec iter_cases = function \r\n | 0 -> 0\r\n | n -> \r\n let sum = run_case () in \r\n (* let _ = String.iter print_big_float_as_int (string_of_float sum) in *)\r\n let float_int, order = print_big_float_as_int2 (sum, 0) in \r\n print_int (int_of_float float_int);\r\n print_order order;\r\n print_newline ();\r\n iter_cases (n-1)\r\n;;\r\n \r\nlet t = read_int () in \r\niter_cases t ;;"}, {"source_code": "(* \r\n build sequence a0, a1, ... , an\r\n a0 = 0, \r\n 1)ai = a(i-1)+x or 2)ai = a(i-1)-y\r\n ai <= B \r\n \r\n maximise sum\r\n \r\n want all ai to be as close to B as possible\r\n - do 1) up to B then (2) and (1) alternating\r\n\r\n a0, a1, a2, ... , ak, a(k+1), ... , an\r\n\r\n 0, x, 2*x, ... , k*x where k*x <= B, k*x-y, ... , an\r\n\r\n sum = (x+2*x+...+k*x) + floor((n-k)/2)*(k*x-y+k*x) + (k*x-y if n-k is not even)\r\n\r\n n=5, B=100, x=1, y=30\r\n\r\n 0, 1, 2, 3, 4, 5 = 5/2(5+1) =15\r\n\r\n \r\n n=7, B=1e8, x=1e8, y=1e8\r\n\r\n 0, 1e8, 0, 1e8, 0, 1e8, 0 = 7\r\n\r\n k = 1e8 / 1e8 = 1 < n\r\n s1 = (1e8*1*2/2)=1e8\r\n s2 = 6*(1e8)/2 = 3*1e8\r\n n-k is even so 4*1e8\r\n\r\n n=4, B=1, x=7, y=3\r\n\r\n 0, -3, 4 -> PROBLEM!\r\n\r\n k = 1 / 7 = 0 \r\n s1 = 0\r\n s2 = (4)*(2*0-3)/2=-6 \r\n\r\n add +x until no longer possible\r\n need to -y until we can +x\r\n add +x \r\n need to -y until we can +x\r\n repeat O(n) complexity\r\n\r\n add +x k1 times\r\n subtract y k2 times\r\n add x\r\n subtract y k2 times\r\n O(1) complexity if we calculate k1 and k2\r\n\r\n k1*x-k2*y + x<=B\r\n (k1+1)*x-B<=k2*y\r\n ((k1+1)*x-B)/y <= k2, since k2 isn't necessarily constant we have to do O(n)\r\n\r\n e.g 0, -3, -6, 1, -2, -5, -8, 0 (goes from 2 to 3)\r\n\r\n n=5, B=100, x=1, y=30\r\n\r\n 0 + alternate_sum 100 1 30 1 4\r\n 0 + 1 + alternate_sum ... 2 3\r\n 0 + 1 + 2 + ... 3 2\r\n 0 + 1 + 2 + 3 + ... 4 1\r\n 0 + 1 + 2 + 3 + 4 + ... 5 0\r\n 0 + 1 + 2 + 3 + 4 + 5\r\n\r\n *)\r\n\r\n\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\nlet read_float () = Scanf.scanf \" %f\" (fun x -> x);;\r\n\r\nlet rec alternate_sum _B x y current = function \r\n | 0 -> current\r\n | n -> \r\n if (current +. x<=_B) then current +. alternate_sum _B x y (current +. x) (n-1)\r\n else current +. alternate_sum _B x y (current -. y) (n-1)\r\n;;\r\n\r\nlet run_case = function\r\n | () -> \r\n let n = read_int () in \r\n let _B = read_float () in \r\n let x = read_float () in \r\n let y = read_float () in\r\n alternate_sum _B x y 0.0 n\r\n;;\r\n\r\n\r\nlet print_big_float_as_int = fun x ->\r\n if (x!='.') then print_char (x)\r\n;;\r\n\r\nlet rec iter_cases = function \r\n | 0 -> 0\r\n | n -> \r\n let sum = run_case () in \r\n let _ = String.iter print_big_float_as_int (string_of_float sum) in\r\n print_newline ();\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t = read_int () in \r\niter_cases t ;;\r\n"}, {"source_code": "(* \r\n build sequence a0, a1, ... , an\r\n a0 = 0, \r\n 1)ai = a(i-1)+x or 2)ai = a(i-1)-y\r\n ai <= B \r\n \r\n maximise sum\r\n \r\n want all ai to be as close to B as possible\r\n - do 1) up to B then (2) and (1) alternating\r\n\r\n a0, a1, a2, ... , ak, a(k+1), ... , an\r\n\r\n 0, x, 2*x, ... , k*x where k*x <= B, k*x-y, ... , an\r\n\r\n sum = (x+2*x+...+k*x) + floor((n-k)/2)*(k*x-y+k*x) + (k*x-y if n-k is not even)\r\n\r\n n=5, B=100, x=1, y=30\r\n\r\n 0, 1, 2, 3, 4, 5 = 5/2(5+1) =15\r\n\r\n \r\n n=7, B=1e8, x=1e8, y=1e8\r\n\r\n 0, 1e8, 0, 1e8, 0, 1e8, 0 = 7\r\n\r\n k = 1e8 / 1e8 = 1 < n\r\n s1 = (1e8*1*2/2)=1e8\r\n s2 = 6*(1e8)/2 = 3*1e8\r\n n-k is even so 4*1e8\r\n\r\n n=4, B=1, x=7, y=3\r\n\r\n 0, -3, 4 -> PROBLEM!\r\n\r\n k = 1 / 7 = 0 \r\n s1 = 0\r\n s2 = (4)*(2*0-3)/2=-6 \r\n\r\n add +x until no longer possible\r\n need to -y until we can +x\r\n add +x \r\n need to -y until we can +x\r\n repeat O(n) complexity\r\n\r\n add +x k1 times\r\n subtract y k2 times\r\n add x\r\n subtract y k2 times\r\n O(1) complexity if we calculate k1 and k2\r\n\r\n k1*x-k2*y + x<=B\r\n (k1+1)*x-B<=k2*y\r\n ((k1+1)*x-B)/y <= k2, since k2 isn't necessarily constant we have to do O(n)\r\n\r\n e.g 0, -3, -6, 1, -2, -5, -8, 0 (goes from 2 to 3)\r\n\r\n n=5, B=100, x=1, y=30\r\n\r\n 0 + alternate_sum 100 1 30 1 4\r\n 0 + 1 + alternate_sum ... 2 3\r\n 0 + 1 + 2 + ... 3 2\r\n 0 + 1 + 2 + 3 + ... 4 1\r\n 0 + 1 + 2 + 3 + 4 + ... 5 0\r\n 0 + 1 + 2 + 3 + 4 + 5\r\n\r\n *)\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\nlet read_float () = Scanf.scanf \" %f\" (fun x -> x);;\r\n\r\nlet rec alternate_sum _B x y current = function \r\n | 0 -> current\r\n | n -> \r\n if (current +. x<=_B) then current +. alternate_sum _B x y (current +. x) (n-1)\r\n else current +. alternate_sum _B x y (current -. y) (n-1)\r\n;;\r\n\r\nlet run_case = function\r\n | () -> \r\n let n = read_int () in \r\n let _B = read_float () in \r\n let x = read_float () in \r\n let y = read_float () in\r\n alternate_sum _B x y 0.0 n\r\n;;\r\n\r\nlet rec iter_cases = function \r\n | 0 -> 0\r\n | n -> \r\n print_float (run_case ());\r\n print_newline ();\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t = read_int () in \r\niter_cases t ;;\r\n"}], "src_uid": "2c921093abf2c5963f5f0e96cd430456"} {"nl": {"description": "The BFS algorithm is defined as follows. Consider an undirected graph with vertices numbered from $$$1$$$ to $$$n$$$. Initialize $$$q$$$ as a new queue containing only vertex $$$1$$$, mark the vertex $$$1$$$ as used. Extract a vertex $$$v$$$ from the head of the queue $$$q$$$. Print the index of vertex $$$v$$$. Iterate in arbitrary order through all such vertices $$$u$$$ that $$$u$$$ is a neighbor of $$$v$$$ and is not marked yet as used. Mark the vertex $$$u$$$ as used and insert it into the tail of the queue $$$q$$$. If the queue is not empty, continue from step 2. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex $$$1$$$. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) which denotes the number of nodes in the tree. The following $$$n - 1$$$ lines describe the edges of the tree. Each of them contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\le x, y \\le n$$$)\u00a0\u2014 the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree. The last line contains $$$n$$$ distinct integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the sequence to check.", "output_spec": "Print \"Yes\" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and \"No\" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["4\n1 2\n1 3\n2 4\n1 2 3 4", "4\n1 2\n1 3\n2 4\n1 2 4 3"], "sample_outputs": ["Yes", "No"], "notes": "NoteBoth sample tests have the same tree in them.In this tree, there are two valid BFS orderings: $$$1, 2, 3, 4$$$, $$$1, 3, 2, 4$$$. The ordering $$$1, 2, 4, 3$$$ doesn't correspond to any valid BFS order."}, "positive_code": [{"source_code": "let jajka n k = \n\tlet rzm = min (k + 1) 31 in\n\tlet a = Array.make_matrix (n + 1) rzm 0 in\n\tlet wynik = ref 0 in\n\tfor i = 1 to n do\n\t\tfor j = 1 to rzm - 1 do \n\t\t\ta.(i).(j) <- a.(i - 1).(j - 1) + a.(i - 1).(j) + 1;\n\t\t\tprint_int a.(i).(j);\n\t\t\tprint_string \" \";\n\t\t\tif a.(i).(j) >= n && !wynik = 0 then wynik := i\n\t\tdone;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik;;\n\nlet liczba () =\n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\n\nlet plecak l p =\n\tlet a = Array.make (p + 1) 0 in\n\tlet dodaj (poj, k) =\n\t\tfor i = p downto poj do \n\t\t\ta.(i) <- max a.(i) (a.(i - poj) + k)\n\t\tdone in\n\tList.iter dodaj l;\n\tArray.fold_left max 0 a;;\n\nlet repair_road t x =\n\tlet p = ref 0 in\n\tlet dl = (Array.length t) in\n\tlet wynik = ref 0 in\n\tlet odp = ref 0 in\n\tfor i = 0 to dl - 1 do\n\t\twhile !wynik <= x && !p < dl do \n\t\t\twynik := !wynik + 1 - t.(!p);\n\t\t\tincr p\n\t\tdone;\n\t\tif !wynik > x then begin\n\t\t\tdecr p;\n\t\t\twynik := !wynik - 1 + t.(!p)\n\t\tend;\n\t\todp := max (!odp) (!p - i);\n\t\twynik := !wynik - 1 + t.(i);(* \n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tprint_int !p;\n\t\tprint_endline \"\"; *)\n\tdone;\n\t!odp\n\n\nlet wczytaj () =\n\tlet n = liczba () in\n\tlet s = liczba () in\n\tlet t = Array.make n 0 in\n\tfor i = 0 to n - 1 do \n\t\tlet pole = liczba () in(* \n\t\tprint_int pole;\n\t\tprint_endline \"\"; *)\n\t\tt.(i) <- pole\n\tdone;\n\tprint_int (repair_road t s);\n\tprint_endline \"\";;\n\nlet main () =\n\tlet n = liczba () in\n\tfor i = 1 to n do\n\t\twczytaj ()\n\tdone;;\n\nlet examin x =\n\tlet sito = Array.make (x + 1) 0 in\n\tlet kolejka = Queue.create () in\n\tlet mapa = Hashtbl.create 1000000 in\n\tlet skad = Hashtbl.create 1000000 in\n\tlet prims = ref [] in\n\tfor i = 2 to x do\n\t\tprims := i :: !prims\n\tdone;\n\tlet primes = !prims in\n\tlet dodaj a = \n\t\tif sito.(a) = 0 then\n\t\tlet it = ref (a * a) in\n\t\twhile !it <= x do\n\t\t\tsito.(!it) <- a;\n\t\t\tit := !it + a\n\t\tdone in \n\tlet rec dzielniki a =\n\t\tlet akt_dziel = sito.(a) in\n\t\tif akt_dziel = 0 then [a] else\n\t\tlet aktliczba = ref a in\n\t\twhile !aktliczba mod akt_dziel = 0 do\n\t\t\taktliczba := !aktliczba / akt_dziel\n\t\tdone;\n\t\t(akt_dziel :: dzielniki !aktliczba) in\n\tList.iter dodaj primes;\n\tHashtbl.add mapa x 0;\n\tQueue.add x kolejka;\n\twhile not (Hashtbl.mem mapa 1) do\n\t\tlet gora = Queue.take kolejka in\n\t\tlet przejscia = dzielniki gora in\n\t\tlet dodaj liczba wynik = \n\t\t\tHashtbl.add mapa liczba wynik;\n\t\t\tHashtbl.add skad liczba gora;\n\t\t\tQueue.add liczba kolejka in\n\t\tlet przejdz dzielnik = \n\t\t\tif not (Hashtbl.mem mapa (gora / dzielnik)) then\n\t\t\t\tdodaj (gora / dzielnik) (Hashtbl.find mapa gora + 1) in\n\t\tList.iter przejdz przejscia;\n\t\tif not (Hashtbl.mem mapa (gora - 1)) then\n\t\t\tdodaj (gora - 1) (Hashtbl.find mapa gora + 1)\n\tdone;\n\tlet wynik = ref [] in\n\tlet akt = ref 1 in\n\twhile !akt <> x do\n\t\twynik := (!akt :: !wynik);\n\t\takt := Hashtbl.find skad !akt \n\tdone;\n\twynik := (x :: !wynik);\n\tList.rev !wynik\n\nlet to_array l = \n\tlet n = List.length l in\n\tlet tbl = Array.make n (List.hd l) in\n\tlet lista = ref l in\n\tfor i = 0 to n - 1 do\n\t\ttbl.(i) <- List.hd !lista;\n\t\tlista := List.tl !lista\n\tdone;\n\ttbl\n\nlet dbg t =\n\tArray.iter (fun x -> print_int x) t;\n\tprint_endline \"\"\n\n\nlet palindromy l =\n\tlet n = List.length l in\n\tlet l2 = l @ (List.rev l) in\n\tlet tbl = to_array l2 in\n\tlet knp = Array.make (List.length l2) 0 in \n\tfor j = 0 to 1 do\n\t\tfor i = 1 + n * j to n * (j + 1) - 1 do \n\t\t\tlet odp = ref knp.(i - 1) in\n\t\t\twhile tbl.(!odp) <> tbl.(i) && !odp <> 0 do\n\t\t\t\todp := knp.(!odp - 1)\n\t\t\tdone;\n\t\t\tif tbl.(!odp) = tbl.(i) then\n\t\t\t\tincr odp;\n\t\t\tknp.(i) <- !odp\n\t\tdone;\n\t\tif tbl.(n) = tbl.(0) then \n\t\t\tknp.(n) <- 1\n\tdone;\n\tknp.(2 * n - 1);;\n\nlet main () =\n\tlet n = liczba () in\n\tlet m = liczba () in\n\tlet kraw = Array.make (m + 1) (0, 0, 0) in\n\tfor i = 1 to m do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\tlet w = liczba () in\n\t\tkraw.(i) <- (u, v, w)\n\tdone; \n\tlet fu = Array.make (n + 1) 0 in\n\tlet rozm = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tfu.(i) <- i;\n\t\trozm.(i) <- 1\n\tdone; \n\tlet rec znajdz x =\n\t\tif fu.(x) = x then x else \n\t\t\tlet wynik = znajdz (fu.(x)) in\n\t\t\tfu.(x) <- wynik;\n\t\t\twynik in\n\tlet rec znajdz_rozm x =\n\t\tif fu.(x) = x then rozm.(x) else znajdz_rozm (fu.(x)) in\n\tlet merge (x, y, _) =\n\t\tlet v1 = znajdz x in\n\t\tlet v2 = znajdz y in\n\t\tif znajdz_rozm v1 < znajdz_rozm v2 then begin\n\t\t\tfu.(v1) <- v2;\n\t\t\trozm.(v2) <- rozm.(v2) + rozm.(v1)\n\t\tend else begin\n\t\t\tfu.(v2) <- v1;\n\t\t\trozm.(v1) <- rozm.(v1) + rozm.(v2);\n\t\tend in\n\tlet waga_kraw (_, _, w) = w in\n\tlet pierw_kraw (w, _, _) = w in\n\tlet drug_kraw (_, w, _) = w in\n\tArray.sort (fun (u1, v2, w1) (u2, v2, w2) -> w1 - w2) kraw;\n\tlet poprz_waga = ref 0 in\n\tlet lista = ref [] in\n\tlet wynik = ref (m - n + 1) in\n\tfor i = 1 to m do\n\t\tif waga_kraw kraw.(i) > !poprz_waga then begin\n\t\t\tList.iter (fun x -> merge kraw.(x)) !lista;\n\t\t\tlista := [];\n\t\t\tpoprz_waga := waga_kraw kraw.(i)\n\t\tend;\n\t\tif znajdz (pierw_kraw kraw.(i)) = znajdz (drug_kraw kraw.(i)) then\n\t\t\tdecr wynik\n\t\telse\n\t\t\tlista := (i :: !lista)\n\tdone;\n\tprint_int !wynik;;\n\n\nlet pierw (a, b) = a\nlet drug (a, b) = b\n\nlet daleko tbl =\n\tlet n = Array.length tbl in\n\tif n = 0 then (0, 0) else\n\tlet tbl_pom = Array.make n (0, 0) in\n\tfor i = 0 to n - 1 do\n\t\ttbl_pom.(i) <- (tbl.(i), i)\n\tdone;\n\tArray.sort (fun x y -> (-1) * (compare x y)) tbl_pom;\n\tlet wal = Array.make n 0 in\n\tlet ind = Array.make n 0 in\n\tfor i = 0 to n - 1 do\n\t\twal.(i) <- (pierw (tbl_pom.(i)));\n\t\tind.(i) <- (drug (tbl_pom.(i)))\n\tdone;\n\tlet wynik = ref 0 in\n\tlet lewy = ref 0 in\n\tlet prawy = ref 0 in\n\tlet maks_ind = ref 0 in\n\tlet poprz = ref wal.(0) in\n\tlet akt_maks = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tif wal.(i) <> !poprz then begin\n\t\t\tmaks_ind := !akt_maks;\n\t\t\tpoprz := wal.(i)\n\t\tend;\n\t\tif !wynik < !maks_ind - ind.(i) then begin\n\t\t\tlewy := ind.(i);\n\t\t\tprawy := !maks_ind;\n\t\t\twynik := !maks_ind - ind.(i)\n\t\tend;\n\t\takt_maks := max !akt_maks ind.(i)\n\tdone;\n\t(!lewy, !prawy)\n\nlet kominek k m tbl =\n\tlet plecak = Array.make (k + 1) (-1) in\n\tArray.sort compare tbl;\n\tlet wynik = ref 0 in\n\tplecak.(0) <- 0;\n\tlet d = Array.length tbl in\n\tfor i = 0 to d - 1 do\n\t\tfor j = k downto tbl.(i) do\n\t\t\tif plecak.(j - tbl.(i)) = 0 then begin\n\t\t\t\tplecak.(j) <- 0;\n\t\t\t\twynik := max !wynik (tbl.(i) + min m j)\n\t\t\tend;\n\t\tdone\n\tdone;\n\t!wynik\n\nlet bfs () =\n\t(* let licznik = ref 0 in\n\tlet liczba () =\n\t\tlet tab = [|7;1;2;1;5;2;3;2;4;5;6;6;7;1;2;5;6;3;4;7|] in\n\t\tlet wynik = tab.(!licznik) in\n\t\tincr licznik;\n\t\twynik in *)\n\tlet n = liczba () in\n\tlet mapa = Hashtbl.create 1000000 in\n\n\tlet wez x =\n\t\tif Hashtbl.mem mapa x then\n\t\t\tHashtbl.find mapa x\n\t\telse\n\t\t\t[] in\n\n\tfor i = 0 to n - 2 do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\t(*print_int u;\n\t\tprint_string \" \";\n\t\tprint_int v;\n\t\tprint_endline \"\";*)\n\t\tHashtbl.add mapa u (v :: wez u);\n\t\tHashtbl.add mapa v (u :: wez v)\n\tdone;\n\t(*for i = 0 to n do\n\t print_int i;\n\t print_string \": \";\n\t List.iter (fun x -> print_int x; print_string \" \") (wez i);\n\t print_endline \"\"\n\tdone;*)\n\tlet kolejka = Queue.create () in\n\tQueue.push 1 kolejka;\n\tlet kol = Array.make (n + 1) 0 in\n\tkol.(1) <- 1;\n\tlet ojc = Array.make (n + 1) 0 in\n\twhile not (Queue.is_empty kolejka) do\n\t\tlet w = Queue.take kolejka in\n\t\tList.iter (fun x -> (* print_int x; print_string \" \"; *)if kol.(x) = 0 then begin kol.(x) <- kol.(w) + 1; ojc.(x) <- w; Queue.add x kolejka end) (wez w)\n\tdone;\n\tlet tbl = Array.make (n + 1) 0 in\n\tlet num = Array.make (n + 1) 0 in\n\tfor i = 0 to n - 1 do\n\t\tlet w = liczba () in\n\t\tnum.(w) <- i;\n\t\ttbl.(i) <- w\n\tdone;\n\tlet poprz = ref 0 in\n\tlet poprz_num_ojc = ref 0 in\n\tlet czygut = ref 1 in\n\t(* dbg kol;\n\tdbg ojc; *)\n\tfor i = 0 to n - 1 do\n\t\tlet u = tbl.(i) in\n\t\t(* print_int u;\n\t\tprint_string \" \";\n\t\tprint_int ojc.(u);\n\t\tprint_string \" \";\n\t\tprint_int num.(ojc.(u));\n\t\tprint_string \" \";\n\t\tprint_int !poprz_num_ojc;\n\t\tprint_endline \"\"; *)\n\t\t(* print_int u;\n\t\tprint_endline \"\"; *)\n\t\tif kol.(u) < !poprz || (u <> 1 && num.(ojc.(u)) < !poprz_num_ojc) then czygut := 0;\n\t\tpoprz := kol.(u);\n\t\tpoprz_num_ojc := num.(ojc.(u))\n\tdone;\n\tif !czygut = 1 then print_string \"Yes\" else print_string \"No\";;\n\nbfs ();;\n\nlet segment t =\n\tlet n = Array.length t in\n\tlet p = ref 0 in\n\tlet lista = Array.make n 0 in\n\tlet pocz = ref 0 in\n\tlet kon = ref (-1) in\n\tlet wynik = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tlet mini () =\n\t\t\tif !pocz > !kon then t.(!p) else \n\t\t\tmin t.(lista.(!pocz)) t.(!p) in\n\t\twhile !p < n && mini () >= !p - i + 1 do\n\t\t\twhile pocz <= kon && t.(lista.(!kon)) > t.(i) do\n\t\t\t\tdecr kon\n\t\t\tdone;\n\t\t\tincr kon;\n\t\t\tlista.(!kon) <- !p;\n\t\t\tincr p\n\t\tdone;\n\t\twynik := max !wynik (!p - i);\n\t\tif lista.(!pocz) = i && !pocz <= !kon then\n\t\t\tincr pocz;\n\t\tprint_int !p;\n\t\tif !p = i then\n\t\t\tincr p;\n\t\tprint_int !p;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik\n"}], "negative_code": [{"source_code": "let jajka n k = \n\tlet rzm = min (k + 1) 31 in\n\tlet a = Array.make_matrix (n + 1) rzm 0 in\n\tlet wynik = ref 0 in\n\tfor i = 1 to n do\n\t\tfor j = 1 to rzm - 1 do \n\t\t\ta.(i).(j) <- a.(i - 1).(j - 1) + a.(i - 1).(j) + 1;\n\t\t\tprint_int a.(i).(j);\n\t\t\tprint_string \" \";\n\t\t\tif a.(i).(j) >= n && !wynik = 0 then wynik := i\n\t\tdone;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik;;\n\nlet liczba () =\n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\n\nlet plecak l p =\n\tlet a = Array.make (p + 1) 0 in\n\tlet dodaj (poj, k) =\n\t\tfor i = p downto poj do \n\t\t\ta.(i) <- max a.(i) (a.(i - poj) + k)\n\t\tdone in\n\tList.iter dodaj l;\n\tArray.fold_left max 0 a;;\n\nlet repair_road t x =\n\tlet p = ref 0 in\n\tlet dl = (Array.length t) in\n\tlet wynik = ref 0 in\n\tlet odp = ref 0 in\n\tfor i = 0 to dl - 1 do\n\t\twhile !wynik <= x && !p < dl do \n\t\t\twynik := !wynik + 1 - t.(!p);\n\t\t\tincr p\n\t\tdone;\n\t\tif !wynik > x then begin\n\t\t\tdecr p;\n\t\t\twynik := !wynik - 1 + t.(!p)\n\t\tend;\n\t\todp := max (!odp) (!p - i);\n\t\twynik := !wynik - 1 + t.(i);(* \n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tprint_int !p;\n\t\tprint_endline \"\"; *)\n\tdone;\n\t!odp\n\n\nlet wczytaj () =\n\tlet n = liczba () in\n\tlet s = liczba () in\n\tlet t = Array.make n 0 in\n\tfor i = 0 to n - 1 do \n\t\tlet pole = liczba () in(* \n\t\tprint_int pole;\n\t\tprint_endline \"\"; *)\n\t\tt.(i) <- pole\n\tdone;\n\tprint_int (repair_road t s);\n\tprint_endline \"\";;\n\nlet main () =\n\tlet n = liczba () in\n\tfor i = 1 to n do\n\t\twczytaj ()\n\tdone;;\n\nlet examin x =\n\tlet sito = Array.make (x + 1) 0 in\n\tlet kolejka = Queue.create () in\n\tlet mapa = Hashtbl.create 1000000 in\n\tlet skad = Hashtbl.create 1000000 in\n\tlet prims = ref [] in\n\tfor i = 2 to x do\n\t\tprims := i :: !prims\n\tdone;\n\tlet primes = !prims in\n\tlet dodaj a = \n\t\tif sito.(a) = 0 then\n\t\tlet it = ref (a * a) in\n\t\twhile !it <= x do\n\t\t\tsito.(!it) <- a;\n\t\t\tit := !it + a\n\t\tdone in \n\tlet rec dzielniki a =\n\t\tlet akt_dziel = sito.(a) in\n\t\tif akt_dziel = 0 then [a] else\n\t\tlet aktliczba = ref a in\n\t\twhile !aktliczba mod akt_dziel = 0 do\n\t\t\taktliczba := !aktliczba / akt_dziel\n\t\tdone;\n\t\t(akt_dziel :: dzielniki !aktliczba) in\n\tList.iter dodaj primes;\n\tHashtbl.add mapa x 0;\n\tQueue.add x kolejka;\n\twhile not (Hashtbl.mem mapa 1) do\n\t\tlet gora = Queue.take kolejka in\n\t\tlet przejscia = dzielniki gora in\n\t\tlet dodaj liczba wynik = \n\t\t\tHashtbl.add mapa liczba wynik;\n\t\t\tHashtbl.add skad liczba gora;\n\t\t\tQueue.add liczba kolejka in\n\t\tlet przejdz dzielnik = \n\t\t\tif not (Hashtbl.mem mapa (gora / dzielnik)) then\n\t\t\t\tdodaj (gora / dzielnik) (Hashtbl.find mapa gora + 1) in\n\t\tList.iter przejdz przejscia;\n\t\tif not (Hashtbl.mem mapa (gora - 1)) then\n\t\t\tdodaj (gora - 1) (Hashtbl.find mapa gora + 1)\n\tdone;\n\tlet wynik = ref [] in\n\tlet akt = ref 1 in\n\twhile !akt <> x do\n\t\twynik := (!akt :: !wynik);\n\t\takt := Hashtbl.find skad !akt \n\tdone;\n\twynik := (x :: !wynik);\n\tList.rev !wynik\n\nlet to_array l = \n\tlet n = List.length l in\n\tlet tbl = Array.make n (List.hd l) in\n\tlet lista = ref l in\n\tfor i = 0 to n - 1 do\n\t\ttbl.(i) <- List.hd !lista;\n\t\tlista := List.tl !lista\n\tdone;\n\ttbl\n\nlet dbg t =\n\tArray.iter (fun x -> print_int x) t;\n\tprint_endline \"\"\n\n\nlet palindromy l =\n\tlet n = List.length l in\n\tlet l2 = l @ (List.rev l) in\n\tlet tbl = to_array l2 in\n\tlet knp = Array.make (List.length l2) 0 in \n\tfor j = 0 to 1 do\n\t\tfor i = 1 + n * j to n * (j + 1) - 1 do \n\t\t\tlet odp = ref knp.(i - 1) in\n\t\t\twhile tbl.(!odp) <> tbl.(i) && !odp <> 0 do\n\t\t\t\todp := knp.(!odp - 1)\n\t\t\tdone;\n\t\t\tif tbl.(!odp) = tbl.(i) then\n\t\t\t\tincr odp;\n\t\t\tknp.(i) <- !odp\n\t\tdone;\n\t\tif tbl.(n) = tbl.(0) then \n\t\t\tknp.(n) <- 1\n\tdone;\n\tknp.(2 * n - 1);;\n\nlet main () =\n\tlet n = liczba () in\n\tlet m = liczba () in\n\tlet kraw = Array.make (m + 1) (0, 0, 0) in\n\tfor i = 1 to m do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\tlet w = liczba () in\n\t\tkraw.(i) <- (u, v, w)\n\tdone; \n\tlet fu = Array.make (n + 1) 0 in\n\tlet rozm = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tfu.(i) <- i;\n\t\trozm.(i) <- 1\n\tdone; \n\tlet rec znajdz x =\n\t\tif fu.(x) = x then x else \n\t\t\tlet wynik = znajdz (fu.(x)) in\n\t\t\tfu.(x) <- wynik;\n\t\t\twynik in\n\tlet rec znajdz_rozm x =\n\t\tif fu.(x) = x then rozm.(x) else znajdz_rozm (fu.(x)) in\n\tlet merge (x, y, _) =\n\t\tlet v1 = znajdz x in\n\t\tlet v2 = znajdz y in\n\t\tif znajdz_rozm v1 < znajdz_rozm v2 then begin\n\t\t\tfu.(v1) <- v2;\n\t\t\trozm.(v2) <- rozm.(v2) + rozm.(v1)\n\t\tend else begin\n\t\t\tfu.(v2) <- v1;\n\t\t\trozm.(v1) <- rozm.(v1) + rozm.(v2);\n\t\tend in\n\tlet waga_kraw (_, _, w) = w in\n\tlet pierw_kraw (w, _, _) = w in\n\tlet drug_kraw (_, w, _) = w in\n\tArray.sort (fun (u1, v2, w1) (u2, v2, w2) -> w1 - w2) kraw;\n\tlet poprz_waga = ref 0 in\n\tlet lista = ref [] in\n\tlet wynik = ref (m - n + 1) in\n\tfor i = 1 to m do\n\t\tif waga_kraw kraw.(i) > !poprz_waga then begin\n\t\t\tList.iter (fun x -> merge kraw.(x)) !lista;\n\t\t\tlista := [];\n\t\t\tpoprz_waga := waga_kraw kraw.(i)\n\t\tend;\n\t\tif znajdz (pierw_kraw kraw.(i)) = znajdz (drug_kraw kraw.(i)) then\n\t\t\tdecr wynik\n\t\telse\n\t\t\tlista := (i :: !lista)\n\tdone;\n\tprint_int !wynik;;\n\n\nlet pierw (a, b) = a\nlet drug (a, b) = b\n\nlet daleko tbl =\n\tlet n = Array.length tbl in\n\tif n = 0 then (0, 0) else\n\tlet tbl_pom = Array.make n (0, 0) in\n\tfor i = 0 to n - 1 do\n\t\ttbl_pom.(i) <- (tbl.(i), i)\n\tdone;\n\tArray.sort (fun x y -> (-1) * (compare x y)) tbl_pom;\n\tlet wal = Array.make n 0 in\n\tlet ind = Array.make n 0 in\n\tfor i = 0 to n - 1 do\n\t\twal.(i) <- (pierw (tbl_pom.(i)));\n\t\tind.(i) <- (drug (tbl_pom.(i)))\n\tdone;\n\tlet wynik = ref 0 in\n\tlet lewy = ref 0 in\n\tlet prawy = ref 0 in\n\tlet maks_ind = ref 0 in\n\tlet poprz = ref wal.(0) in\n\tlet akt_maks = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tif wal.(i) <> !poprz then begin\n\t\t\tmaks_ind := !akt_maks;\n\t\t\tpoprz := wal.(i)\n\t\tend;\n\t\tif !wynik < !maks_ind - ind.(i) then begin\n\t\t\tlewy := ind.(i);\n\t\t\tprawy := !maks_ind;\n\t\t\twynik := !maks_ind - ind.(i)\n\t\tend;\n\t\takt_maks := max !akt_maks ind.(i)\n\tdone;\n\t(!lewy, !prawy)\n\nlet kominek k m tbl =\n\tlet plecak = Array.make (k + 1) (-1) in\n\tArray.sort compare tbl;\n\tlet wynik = ref 0 in\n\tplecak.(0) <- 0;\n\tlet d = Array.length tbl in\n\tfor i = 0 to d - 1 do\n\t\tfor j = k downto tbl.(i) do\n\t\t\tif plecak.(j - tbl.(i)) = 0 then begin\n\t\t\t\tplecak.(j) <- 0;\n\t\t\t\twynik := max !wynik (tbl.(i) + min m j)\n\t\t\tend;\n\t\tdone\n\tdone;\n\t!wynik\n\nlet bfs () =\n\t(* let licznik = ref 0 in\n\tlet liczba () =\n\t\tlet tab = [|6;1;2;1;5;2;3;2;4;5;6;1;5;2;3;4;6|] in\n\t\tlet wynik = tab.(!licznik) in\n\t\tincr licznik;\n\t\twynik in *)\n\tlet n = liczba () in\n\tlet mapa = Hashtbl.create 1000000 in\n\n\tlet wez x =\n\t\tif Hashtbl.mem mapa x then\n\t\t\tHashtbl.find mapa x\n\t\telse\n\t\t\t[] in\n\n\tfor i = 0 to n - 2 do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\t(*print_int u;\n\t\tprint_string \" \";\n\t\tprint_int v;\n\t\tprint_endline \"\";*)\n\t\tHashtbl.add mapa u (v :: wez u);\n\t\tHashtbl.add mapa v (u :: wez v)\n\tdone;\n\t(*for i = 0 to n do\n\t print_int i;\n\t print_string \": \";\n\t List.iter (fun x -> print_int x; print_string \" \") (wez i);\n\t print_endline \"\"\n\tdone;*)\n\tlet kolejka = Queue.create () in\n\tQueue.push 1 kolejka;\n\tlet kol = Array.make (n + 1) 0 in\n\tkol.(1) <- 1;\n\tlet ojc = Array.make (n + 1) 0 in\n\twhile not (Queue.is_empty kolejka) do\n\t\tlet w = Queue.take kolejka in\n\t\tList.iter (fun x -> (* print_int x; print_string \" \"; *)if kol.(x) = 0 then begin kol.(x) <- kol.(w) + 1; ojc.(x) <- w; Queue.add x kolejka end) (Hashtbl.find mapa w)\n\tdone;\n\tlet tbl = Array.make (n + 1) 0 in\n\tlet num = Array.make (n + 1) 0 in\n\tfor i = 0 to n - 1 do\n\t\tlet w = liczba () in\n\t\tnum.(w) <- i;\n\t\ttbl.(i) <- w\n\tdone;\n\tlet poprz = ref 0 in\n\tlet poprz_num_ojc = ref 0 in\n\tlet czygut = ref 1 in\n\t(* dbg kol;\n\tdbg ojc; *)\n\tfor i = 0 to n - 1 do\n\t\tlet u = tbl.(i) in\n\t\t(* print_int u;\n\t\tprint_endline \"\"; *)\n\t\tif kol.(u) < !poprz || (u <> 1 && num.(ojc.(u)) < !poprz_num_ojc) then czygut := 0;\n\t\tif (!poprz < kol.(u)) then begin\n\t\t\tpoprz_num_ojc := 0;\n\t\t\tpoprz := kol.(u)\n\t\tend else\n\t\t\tpoprz_num_ojc := num.(ojc.(u));\n\tdone;\n\tif !czygut = 1 then print_string \"Yes\" else print_string \"No\";;\n\nbfs ();;\n\nlet segment t =\n\tlet n = Array.length t in\n\tlet p = ref 0 in\n\tlet lista = Array.make n 0 in\n\tlet pocz = ref 0 in\n\tlet kon = ref (-1) in\n\tlet wynik = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tlet mini () =\n\t\t\tif !pocz > !kon then t.(!p) else \n\t\t\tmin t.(lista.(!pocz)) t.(!p) in\n\t\twhile !p < n && mini () >= !p - i + 1 do\n\t\t\twhile pocz <= kon && t.(lista.(!kon)) > t.(i) do\n\t\t\t\tdecr kon\n\t\t\tdone;\n\t\t\tincr kon;\n\t\t\tlista.(!kon) <- !p;\n\t\t\tincr p\n\t\tdone;\n\t\twynik := max !wynik (!p - i);\n\t\tif lista.(!pocz) = i && !pocz <= !kon then\n\t\t\tincr pocz;\n\t\tprint_int !p;\n\t\tif !p = i then\n\t\t\tincr p;\n\t\tprint_int !p;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik\n"}, {"source_code": "let jajka n k = \n\tlet rzm = min (k + 1) 31 in\n\tlet a = Array.make_matrix (n + 1) rzm 0 in\n\tlet wynik = ref 0 in\n\tfor i = 1 to n do\n\t\tfor j = 1 to rzm - 1 do \n\t\t\ta.(i).(j) <- a.(i - 1).(j - 1) + a.(i - 1).(j) + 1;\n\t\t\tprint_int a.(i).(j);\n\t\t\tprint_string \" \";\n\t\t\tif a.(i).(j) >= n && !wynik = 0 then wynik := i\n\t\tdone;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik;;\n\nlet liczba () =\n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\n\nlet plecak l p =\n\tlet a = Array.make (p + 1) 0 in\n\tlet dodaj (poj, k) =\n\t\tfor i = p downto poj do \n\t\t\ta.(i) <- max a.(i) (a.(i - poj) + k)\n\t\tdone in\n\tList.iter dodaj l;\n\tArray.fold_left max 0 a;;\n\nlet repair_road t x =\n\tlet p = ref 0 in\n\tlet dl = (Array.length t) in\n\tlet wynik = ref 0 in\n\tlet odp = ref 0 in\n\tfor i = 0 to dl - 1 do\n\t\twhile !wynik <= x && !p < dl do \n\t\t\twynik := !wynik + 1 - t.(!p);\n\t\t\tincr p\n\t\tdone;\n\t\tif !wynik > x then begin\n\t\t\tdecr p;\n\t\t\twynik := !wynik - 1 + t.(!p)\n\t\tend;\n\t\todp := max (!odp) (!p - i);\n\t\twynik := !wynik - 1 + t.(i);(* \n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tprint_int !p;\n\t\tprint_endline \"\"; *)\n\tdone;\n\t!odp\n\n\nlet wczytaj () =\n\tlet n = liczba () in\n\tlet s = liczba () in\n\tlet t = Array.make n 0 in\n\tfor i = 0 to n - 1 do \n\t\tlet pole = liczba () in(* \n\t\tprint_int pole;\n\t\tprint_endline \"\"; *)\n\t\tt.(i) <- pole\n\tdone;\n\tprint_int (repair_road t s);\n\tprint_endline \"\";;\n\nlet main () =\n\tlet n = liczba () in\n\tfor i = 1 to n do\n\t\twczytaj ()\n\tdone;;\n\nlet examin x =\n\tlet sito = Array.make (x + 1) 0 in\n\tlet kolejka = Queue.create () in\n\tlet mapa = Hashtbl.create 1000000 in\n\tlet skad = Hashtbl.create 1000000 in\n\tlet prims = ref [] in\n\tfor i = 2 to x do\n\t\tprims := i :: !prims\n\tdone;\n\tlet primes = !prims in\n\tlet dodaj a = \n\t\tif sito.(a) = 0 then\n\t\tlet it = ref (a * a) in\n\t\twhile !it <= x do\n\t\t\tsito.(!it) <- a;\n\t\t\tit := !it + a\n\t\tdone in \n\tlet rec dzielniki a =\n\t\tlet akt_dziel = sito.(a) in\n\t\tif akt_dziel = 0 then [a] else\n\t\tlet aktliczba = ref a in\n\t\twhile !aktliczba mod akt_dziel = 0 do\n\t\t\taktliczba := !aktliczba / akt_dziel\n\t\tdone;\n\t\t(akt_dziel :: dzielniki !aktliczba) in\n\tList.iter dodaj primes;\n\tHashtbl.add mapa x 0;\n\tQueue.add x kolejka;\n\twhile not (Hashtbl.mem mapa 1) do\n\t\tlet gora = Queue.take kolejka in\n\t\tlet przejscia = dzielniki gora in\n\t\tlet dodaj liczba wynik = \n\t\t\tHashtbl.add mapa liczba wynik;\n\t\t\tHashtbl.add skad liczba gora;\n\t\t\tQueue.add liczba kolejka in\n\t\tlet przejdz dzielnik = \n\t\t\tif not (Hashtbl.mem mapa (gora / dzielnik)) then\n\t\t\t\tdodaj (gora / dzielnik) (Hashtbl.find mapa gora + 1) in\n\t\tList.iter przejdz przejscia;\n\t\tif not (Hashtbl.mem mapa (gora - 1)) then\n\t\t\tdodaj (gora - 1) (Hashtbl.find mapa gora + 1)\n\tdone;\n\tlet wynik = ref [] in\n\tlet akt = ref 1 in\n\twhile !akt <> x do\n\t\twynik := (!akt :: !wynik);\n\t\takt := Hashtbl.find skad !akt \n\tdone;\n\twynik := (x :: !wynik);\n\tList.rev !wynik\n\nlet to_array l = \n\tlet n = List.length l in\n\tlet tbl = Array.make n (List.hd l) in\n\tlet lista = ref l in\n\tfor i = 0 to n - 1 do\n\t\ttbl.(i) <- List.hd !lista;\n\t\tlista := List.tl !lista\n\tdone;\n\ttbl\n\nlet dbg t =\n\tArray.iter (fun x -> print_int x) t;\n\tprint_endline \"\"\n\n\nlet palindromy l =\n\tlet n = List.length l in\n\tlet l2 = l @ (List.rev l) in\n\tlet tbl = to_array l2 in\n\tlet knp = Array.make (List.length l2) 0 in \n\tfor j = 0 to 1 do\n\t\tfor i = 1 + n * j to n * (j + 1) - 1 do \n\t\t\tlet odp = ref knp.(i - 1) in\n\t\t\twhile tbl.(!odp) <> tbl.(i) && !odp <> 0 do\n\t\t\t\todp := knp.(!odp - 1)\n\t\t\tdone;\n\t\t\tif tbl.(!odp) = tbl.(i) then\n\t\t\t\tincr odp;\n\t\t\tknp.(i) <- !odp\n\t\tdone;\n\t\tif tbl.(n) = tbl.(0) then \n\t\t\tknp.(n) <- 1\n\tdone;\n\tknp.(2 * n - 1);;\n\nlet main () =\n\tlet n = liczba () in\n\tlet m = liczba () in\n\tlet kraw = Array.make (m + 1) (0, 0, 0) in\n\tfor i = 1 to m do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\tlet w = liczba () in\n\t\tkraw.(i) <- (u, v, w)\n\tdone; \n\tlet fu = Array.make (n + 1) 0 in\n\tlet rozm = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tfu.(i) <- i;\n\t\trozm.(i) <- 1\n\tdone; \n\tlet rec znajdz x =\n\t\tif fu.(x) = x then x else \n\t\t\tlet wynik = znajdz (fu.(x)) in\n\t\t\tfu.(x) <- wynik;\n\t\t\twynik in\n\tlet rec znajdz_rozm x =\n\t\tif fu.(x) = x then rozm.(x) else znajdz_rozm (fu.(x)) in\n\tlet merge (x, y, _) =\n\t\tlet v1 = znajdz x in\n\t\tlet v2 = znajdz y in\n\t\tif znajdz_rozm v1 < znajdz_rozm v2 then begin\n\t\t\tfu.(v1) <- v2;\n\t\t\trozm.(v2) <- rozm.(v2) + rozm.(v1)\n\t\tend else begin\n\t\t\tfu.(v2) <- v1;\n\t\t\trozm.(v1) <- rozm.(v1) + rozm.(v2);\n\t\tend in\n\tlet waga_kraw (_, _, w) = w in\n\tlet pierw_kraw (w, _, _) = w in\n\tlet drug_kraw (_, w, _) = w in\n\tArray.sort (fun (u1, v2, w1) (u2, v2, w2) -> w1 - w2) kraw;\n\tlet poprz_waga = ref 0 in\n\tlet lista = ref [] in\n\tlet wynik = ref (m - n + 1) in\n\tfor i = 1 to m do\n\t\tif waga_kraw kraw.(i) > !poprz_waga then begin\n\t\t\tList.iter (fun x -> merge kraw.(x)) !lista;\n\t\t\tlista := [];\n\t\t\tpoprz_waga := waga_kraw kraw.(i)\n\t\tend;\n\t\tif znajdz (pierw_kraw kraw.(i)) = znajdz (drug_kraw kraw.(i)) then\n\t\t\tdecr wynik\n\t\telse\n\t\t\tlista := (i :: !lista)\n\tdone;\n\tprint_int !wynik;;\n\n\nlet pierw (a, b) = a\nlet drug (a, b) = b\n\nlet daleko tbl =\n\tlet n = Array.length tbl in\n\tif n = 0 then (0, 0) else\n\tlet tbl_pom = Array.make n (0, 0) in\n\tfor i = 0 to n - 1 do\n\t\ttbl_pom.(i) <- (tbl.(i), i)\n\tdone;\n\tArray.sort (fun x y -> (-1) * (compare x y)) tbl_pom;\n\tlet wal = Array.make n 0 in\n\tlet ind = Array.make n 0 in\n\tfor i = 0 to n - 1 do\n\t\twal.(i) <- (pierw (tbl_pom.(i)));\n\t\tind.(i) <- (drug (tbl_pom.(i)))\n\tdone;\n\tlet wynik = ref 0 in\n\tlet lewy = ref 0 in\n\tlet prawy = ref 0 in\n\tlet maks_ind = ref 0 in\n\tlet poprz = ref wal.(0) in\n\tlet akt_maks = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tif wal.(i) <> !poprz then begin\n\t\t\tmaks_ind := !akt_maks;\n\t\t\tpoprz := wal.(i)\n\t\tend;\n\t\tif !wynik < !maks_ind - ind.(i) then begin\n\t\t\tlewy := ind.(i);\n\t\t\tprawy := !maks_ind;\n\t\t\twynik := !maks_ind - ind.(i)\n\t\tend;\n\t\takt_maks := max !akt_maks ind.(i)\n\tdone;\n\t(!lewy, !prawy)\n\nlet kominek k m tbl =\n\tlet plecak = Array.make (k + 1) (-1) in\n\tArray.sort compare tbl;\n\tlet wynik = ref 0 in\n\tplecak.(0) <- 0;\n\tlet d = Array.length tbl in\n\tfor i = 0 to d - 1 do\n\t\tfor j = k downto tbl.(i) do\n\t\t\tif plecak.(j - tbl.(i)) = 0 then begin\n\t\t\t\tplecak.(j) <- 0;\n\t\t\t\twynik := max !wynik (tbl.(i) + min m j)\n\t\t\tend;\n\t\tdone\n\tdone;\n\t!wynik\n\nlet bfs () =\n\tlet n = liczba () in\n\tlet mapa = Hashtbl.create 1000000 in\n\n\tfor i = 0 to n - 2 do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\tHashtbl.add mapa u (v :: Hashtbl.find mapa u);\n\t\tHashtbl.add mapa v (u :: Hashtbl.find mapa v);\n\tdone;\n\n\tlet kolejka = Queue.create () in\n\tQueue.push 1 kolejka;\n\tlet kol = Array.make (n + 1) 0 in\n\tkol.(0) <- 1;\n\twhile not (Queue.is_empty kolejka) do\n\t\tlet w = Queue.take kolejka in\n\t\tList.iter (fun x -> if kol.(x) = 0 then begin kol.(x) <- kol.(w) + 1; Queue.add x kolejka end) (Hashtbl.find mapa w)\n\tdone;\n\tlet poprz = ref 0 in\n\tlet czygut = ref 1 in\n\tfor i = 0 to n - 1 do\n\t\tlet u = liczba () in\n\t\tif u > !poprz then czygut := 0;\n\t\tpoprz := u\n\tdone;\n\tif !czygut = 1 then print_string \"Yes\" else print_string \"No\";;\n\n\n\nlet segment t =\n\tlet n = Array.length t in\n\tlet p = ref 0 in\n\tlet lista = Array.make n 0 in\n\tlet pocz = ref 0 in\n\tlet kon = ref (-1) in\n\tlet wynik = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tlet mini () =\n\t\t\tif !pocz > !kon then t.(!p) else \n\t\t\tmin t.(lista.(!pocz)) t.(!p) in\n\t\twhile !p < n && mini () >= !p - i + 1 do\n\t\t\twhile pocz <= kon && t.(lista.(!kon)) > t.(i) do\n\t\t\t\tdecr kon\n\t\t\tdone;\n\t\t\tincr kon;\n\t\t\tlista.(!kon) <- !p;\n\t\t\tincr p\n\t\tdone;\n\t\twynik := max !wynik (!p - i);\n\t\tif lista.(!pocz) = i && !pocz <= !kon then\n\t\t\tincr pocz;\n\t\tprint_int !p;\n\t\tif !p = i then\n\t\t\tincr p;\n\t\tprint_int !p;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik\n"}, {"source_code": "let jajka n k = \n\tlet rzm = min (k + 1) 31 in\n\tlet a = Array.make_matrix (n + 1) rzm 0 in\n\tlet wynik = ref 0 in\n\tfor i = 1 to n do\n\t\tfor j = 1 to rzm - 1 do \n\t\t\ta.(i).(j) <- a.(i - 1).(j - 1) + a.(i - 1).(j) + 1;\n\t\t\tprint_int a.(i).(j);\n\t\t\tprint_string \" \";\n\t\t\tif a.(i).(j) >= n && !wynik = 0 then wynik := i\n\t\tdone;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik;;\n\nlet liczba () =\n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\n\nlet plecak l p =\n\tlet a = Array.make (p + 1) 0 in\n\tlet dodaj (poj, k) =\n\t\tfor i = p downto poj do \n\t\t\ta.(i) <- max a.(i) (a.(i - poj) + k)\n\t\tdone in\n\tList.iter dodaj l;\n\tArray.fold_left max 0 a;;\n\nlet repair_road t x =\n\tlet p = ref 0 in\n\tlet dl = (Array.length t) in\n\tlet wynik = ref 0 in\n\tlet odp = ref 0 in\n\tfor i = 0 to dl - 1 do\n\t\twhile !wynik <= x && !p < dl do \n\t\t\twynik := !wynik + 1 - t.(!p);\n\t\t\tincr p\n\t\tdone;\n\t\tif !wynik > x then begin\n\t\t\tdecr p;\n\t\t\twynik := !wynik - 1 + t.(!p)\n\t\tend;\n\t\todp := max (!odp) (!p - i);\n\t\twynik := !wynik - 1 + t.(i);(* \n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tprint_int !p;\n\t\tprint_endline \"\"; *)\n\tdone;\n\t!odp\n\n\nlet wczytaj () =\n\tlet n = liczba () in\n\tlet s = liczba () in\n\tlet t = Array.make n 0 in\n\tfor i = 0 to n - 1 do \n\t\tlet pole = liczba () in(* \n\t\tprint_int pole;\n\t\tprint_endline \"\"; *)\n\t\tt.(i) <- pole\n\tdone;\n\tprint_int (repair_road t s);\n\tprint_endline \"\";;\n\nlet main () =\n\tlet n = liczba () in\n\tfor i = 1 to n do\n\t\twczytaj ()\n\tdone;;\n\nlet examin x =\n\tlet sito = Array.make (x + 1) 0 in\n\tlet kolejka = Queue.create () in\n\tlet mapa = Hashtbl.create 1000000 in\n\tlet skad = Hashtbl.create 1000000 in\n\tlet prims = ref [] in\n\tfor i = 2 to x do\n\t\tprims := i :: !prims\n\tdone;\n\tlet primes = !prims in\n\tlet dodaj a = \n\t\tif sito.(a) = 0 then\n\t\tlet it = ref (a * a) in\n\t\twhile !it <= x do\n\t\t\tsito.(!it) <- a;\n\t\t\tit := !it + a\n\t\tdone in \n\tlet rec dzielniki a =\n\t\tlet akt_dziel = sito.(a) in\n\t\tif akt_dziel = 0 then [a] else\n\t\tlet aktliczba = ref a in\n\t\twhile !aktliczba mod akt_dziel = 0 do\n\t\t\taktliczba := !aktliczba / akt_dziel\n\t\tdone;\n\t\t(akt_dziel :: dzielniki !aktliczba) in\n\tList.iter dodaj primes;\n\tHashtbl.add mapa x 0;\n\tQueue.add x kolejka;\n\twhile not (Hashtbl.mem mapa 1) do\n\t\tlet gora = Queue.take kolejka in\n\t\tlet przejscia = dzielniki gora in\n\t\tlet dodaj liczba wynik = \n\t\t\tHashtbl.add mapa liczba wynik;\n\t\t\tHashtbl.add skad liczba gora;\n\t\t\tQueue.add liczba kolejka in\n\t\tlet przejdz dzielnik = \n\t\t\tif not (Hashtbl.mem mapa (gora / dzielnik)) then\n\t\t\t\tdodaj (gora / dzielnik) (Hashtbl.find mapa gora + 1) in\n\t\tList.iter przejdz przejscia;\n\t\tif not (Hashtbl.mem mapa (gora - 1)) then\n\t\t\tdodaj (gora - 1) (Hashtbl.find mapa gora + 1)\n\tdone;\n\tlet wynik = ref [] in\n\tlet akt = ref 1 in\n\twhile !akt <> x do\n\t\twynik := (!akt :: !wynik);\n\t\takt := Hashtbl.find skad !akt \n\tdone;\n\twynik := (x :: !wynik);\n\tList.rev !wynik\n\nlet to_array l = \n\tlet n = List.length l in\n\tlet tbl = Array.make n (List.hd l) in\n\tlet lista = ref l in\n\tfor i = 0 to n - 1 do\n\t\ttbl.(i) <- List.hd !lista;\n\t\tlista := List.tl !lista\n\tdone;\n\ttbl\n\nlet dbg t =\n\tArray.iter (fun x -> print_int x) t;\n\tprint_endline \"\"\n\n\nlet palindromy l =\n\tlet n = List.length l in\n\tlet l2 = l @ (List.rev l) in\n\tlet tbl = to_array l2 in\n\tlet knp = Array.make (List.length l2) 0 in \n\tfor j = 0 to 1 do\n\t\tfor i = 1 + n * j to n * (j + 1) - 1 do \n\t\t\tlet odp = ref knp.(i - 1) in\n\t\t\twhile tbl.(!odp) <> tbl.(i) && !odp <> 0 do\n\t\t\t\todp := knp.(!odp - 1)\n\t\t\tdone;\n\t\t\tif tbl.(!odp) = tbl.(i) then\n\t\t\t\tincr odp;\n\t\t\tknp.(i) <- !odp\n\t\tdone;\n\t\tif tbl.(n) = tbl.(0) then \n\t\t\tknp.(n) <- 1\n\tdone;\n\tknp.(2 * n - 1);;\n\nlet main () =\n\tlet n = liczba () in\n\tlet m = liczba () in\n\tlet kraw = Array.make (m + 1) (0, 0, 0) in\n\tfor i = 1 to m do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\tlet w = liczba () in\n\t\tkraw.(i) <- (u, v, w)\n\tdone; \n\tlet fu = Array.make (n + 1) 0 in\n\tlet rozm = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tfu.(i) <- i;\n\t\trozm.(i) <- 1\n\tdone; \n\tlet rec znajdz x =\n\t\tif fu.(x) = x then x else \n\t\t\tlet wynik = znajdz (fu.(x)) in\n\t\t\tfu.(x) <- wynik;\n\t\t\twynik in\n\tlet rec znajdz_rozm x =\n\t\tif fu.(x) = x then rozm.(x) else znajdz_rozm (fu.(x)) in\n\tlet merge (x, y, _) =\n\t\tlet v1 = znajdz x in\n\t\tlet v2 = znajdz y in\n\t\tif znajdz_rozm v1 < znajdz_rozm v2 then begin\n\t\t\tfu.(v1) <- v2;\n\t\t\trozm.(v2) <- rozm.(v2) + rozm.(v1)\n\t\tend else begin\n\t\t\tfu.(v2) <- v1;\n\t\t\trozm.(v1) <- rozm.(v1) + rozm.(v2);\n\t\tend in\n\tlet waga_kraw (_, _, w) = w in\n\tlet pierw_kraw (w, _, _) = w in\n\tlet drug_kraw (_, w, _) = w in\n\tArray.sort (fun (u1, v2, w1) (u2, v2, w2) -> w1 - w2) kraw;\n\tlet poprz_waga = ref 0 in\n\tlet lista = ref [] in\n\tlet wynik = ref (m - n + 1) in\n\tfor i = 1 to m do\n\t\tif waga_kraw kraw.(i) > !poprz_waga then begin\n\t\t\tList.iter (fun x -> merge kraw.(x)) !lista;\n\t\t\tlista := [];\n\t\t\tpoprz_waga := waga_kraw kraw.(i)\n\t\tend;\n\t\tif znajdz (pierw_kraw kraw.(i)) = znajdz (drug_kraw kraw.(i)) then\n\t\t\tdecr wynik\n\t\telse\n\t\t\tlista := (i :: !lista)\n\tdone;\n\tprint_int !wynik;;\n\n\nlet pierw (a, b) = a\nlet drug (a, b) = b\n\nlet daleko tbl =\n\tlet n = Array.length tbl in\n\tif n = 0 then (0, 0) else\n\tlet tbl_pom = Array.make n (0, 0) in\n\tfor i = 0 to n - 1 do\n\t\ttbl_pom.(i) <- (tbl.(i), i)\n\tdone;\n\tArray.sort (fun x y -> (-1) * (compare x y)) tbl_pom;\n\tlet wal = Array.make n 0 in\n\tlet ind = Array.make n 0 in\n\tfor i = 0 to n - 1 do\n\t\twal.(i) <- (pierw (tbl_pom.(i)));\n\t\tind.(i) <- (drug (tbl_pom.(i)))\n\tdone;\n\tlet wynik = ref 0 in\n\tlet lewy = ref 0 in\n\tlet prawy = ref 0 in\n\tlet maks_ind = ref 0 in\n\tlet poprz = ref wal.(0) in\n\tlet akt_maks = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tif wal.(i) <> !poprz then begin\n\t\t\tmaks_ind := !akt_maks;\n\t\t\tpoprz := wal.(i)\n\t\tend;\n\t\tif !wynik < !maks_ind - ind.(i) then begin\n\t\t\tlewy := ind.(i);\n\t\t\tprawy := !maks_ind;\n\t\t\twynik := !maks_ind - ind.(i)\n\t\tend;\n\t\takt_maks := max !akt_maks ind.(i)\n\tdone;\n\t(!lewy, !prawy)\n\nlet kominek k m tbl =\n\tlet plecak = Array.make (k + 1) (-1) in\n\tArray.sort compare tbl;\n\tlet wynik = ref 0 in\n\tplecak.(0) <- 0;\n\tlet d = Array.length tbl in\n\tfor i = 0 to d - 1 do\n\t\tfor j = k downto tbl.(i) do\n\t\t\tif plecak.(j - tbl.(i)) = 0 then begin\n\t\t\t\tplecak.(j) <- 0;\n\t\t\t\twynik := max !wynik (tbl.(i) + min m j)\n\t\t\tend;\n\t\tdone\n\tdone;\n\t!wynik\n\nlet bfs () =\n\tlet n = liczba () in\n\tlet mapa = Hashtbl.create 1000000 in\n\n\tlet wez x =\n\t\tif Hashtbl.mem mapa x then\n\t\t\tHashtbl.find mapa x\n\t\telse\n\t\t\t[] in\n\n\tfor i = 0 to n - 2 do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\t(*print_int u;\n\t\tprint_string \" \";\n\t\tprint_int v;\n\t\tprint_endline \"\";*)\n\t\tHashtbl.add mapa u (v :: wez u);\n\t\tHashtbl.add mapa v (u :: wez v)\n\tdone;\n\t(*for i = 0 to n do\n\t print_int i;\n\t print_string \": \";\n\t List.iter (fun x -> print_int x; print_string \" \") (wez i);\n\t print_endline \"\"\n\tdone;*)\n\tlet kolejka = Queue.create () in\n\tQueue.push 1 kolejka;\n\tlet kol = Array.make (n + 1) 0 in\n\tkol.(1) <- 1;\n\twhile not (Queue.is_empty kolejka) do\n\t\tlet w = Queue.take kolejka in\n\t\tList.iter (fun x -> (* print_int x; print_string \" \"; *)if kol.(x) = 0 then begin kol.(x) <- kol.(w) + 1; Queue.add x kolejka end) (Hashtbl.find mapa w)\n\tdone;\n\tlet poprz = ref 0 in\n\tlet czygut = ref 1 in\n\tfor i = 0 to n - 1 do\n\t\tlet u = liczba () in\n\t\tif u < !poprz then czygut := 0;\n\t\tpoprz := u\n\tdone;\n\t(* dbg kol; *)\n\tif !czygut = 1 then print_string \"Yes\" else print_string \"No\";;\n\nbfs ();;\n\nlet segment t =\n\tlet n = Array.length t in\n\tlet p = ref 0 in\n\tlet lista = Array.make n 0 in\n\tlet pocz = ref 0 in\n\tlet kon = ref (-1) in\n\tlet wynik = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tlet mini () =\n\t\t\tif !pocz > !kon then t.(!p) else \n\t\t\tmin t.(lista.(!pocz)) t.(!p) in\n\t\twhile !p < n && mini () >= !p - i + 1 do\n\t\t\twhile pocz <= kon && t.(lista.(!kon)) > t.(i) do\n\t\t\t\tdecr kon\n\t\t\tdone;\n\t\t\tincr kon;\n\t\t\tlista.(!kon) <- !p;\n\t\t\tincr p\n\t\tdone;\n\t\twynik := max !wynik (!p - i);\n\t\tif lista.(!pocz) = i && !pocz <= !kon then\n\t\t\tincr pocz;\n\t\tprint_int !p;\n\t\tif !p = i then\n\t\t\tincr p;\n\t\tprint_int !p;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik\n"}, {"source_code": "let jajka n k = \n\tlet rzm = min (k + 1) 31 in\n\tlet a = Array.make_matrix (n + 1) rzm 0 in\n\tlet wynik = ref 0 in\n\tfor i = 1 to n do\n\t\tfor j = 1 to rzm - 1 do \n\t\t\ta.(i).(j) <- a.(i - 1).(j - 1) + a.(i - 1).(j) + 1;\n\t\t\tprint_int a.(i).(j);\n\t\t\tprint_string \" \";\n\t\t\tif a.(i).(j) >= n && !wynik = 0 then wynik := i\n\t\tdone;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik;;\n\nlet liczba () =\n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\n\nlet plecak l p =\n\tlet a = Array.make (p + 1) 0 in\n\tlet dodaj (poj, k) =\n\t\tfor i = p downto poj do \n\t\t\ta.(i) <- max a.(i) (a.(i - poj) + k)\n\t\tdone in\n\tList.iter dodaj l;\n\tArray.fold_left max 0 a;;\n\nlet repair_road t x =\n\tlet p = ref 0 in\n\tlet dl = (Array.length t) in\n\tlet wynik = ref 0 in\n\tlet odp = ref 0 in\n\tfor i = 0 to dl - 1 do\n\t\twhile !wynik <= x && !p < dl do \n\t\t\twynik := !wynik + 1 - t.(!p);\n\t\t\tincr p\n\t\tdone;\n\t\tif !wynik > x then begin\n\t\t\tdecr p;\n\t\t\twynik := !wynik - 1 + t.(!p)\n\t\tend;\n\t\todp := max (!odp) (!p - i);\n\t\twynik := !wynik - 1 + t.(i);(* \n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tprint_int !p;\n\t\tprint_endline \"\"; *)\n\tdone;\n\t!odp\n\n\nlet wczytaj () =\n\tlet n = liczba () in\n\tlet s = liczba () in\n\tlet t = Array.make n 0 in\n\tfor i = 0 to n - 1 do \n\t\tlet pole = liczba () in(* \n\t\tprint_int pole;\n\t\tprint_endline \"\"; *)\n\t\tt.(i) <- pole\n\tdone;\n\tprint_int (repair_road t s);\n\tprint_endline \"\";;\n\nlet main () =\n\tlet n = liczba () in\n\tfor i = 1 to n do\n\t\twczytaj ()\n\tdone;;\n\nlet examin x =\n\tlet sito = Array.make (x + 1) 0 in\n\tlet kolejka = Queue.create () in\n\tlet mapa = Hashtbl.create 1000000 in\n\tlet skad = Hashtbl.create 1000000 in\n\tlet prims = ref [] in\n\tfor i = 2 to x do\n\t\tprims := i :: !prims\n\tdone;\n\tlet primes = !prims in\n\tlet dodaj a = \n\t\tif sito.(a) = 0 then\n\t\tlet it = ref (a * a) in\n\t\twhile !it <= x do\n\t\t\tsito.(!it) <- a;\n\t\t\tit := !it + a\n\t\tdone in \n\tlet rec dzielniki a =\n\t\tlet akt_dziel = sito.(a) in\n\t\tif akt_dziel = 0 then [a] else\n\t\tlet aktliczba = ref a in\n\t\twhile !aktliczba mod akt_dziel = 0 do\n\t\t\taktliczba := !aktliczba / akt_dziel\n\t\tdone;\n\t\t(akt_dziel :: dzielniki !aktliczba) in\n\tList.iter dodaj primes;\n\tHashtbl.add mapa x 0;\n\tQueue.add x kolejka;\n\twhile not (Hashtbl.mem mapa 1) do\n\t\tlet gora = Queue.take kolejka in\n\t\tlet przejscia = dzielniki gora in\n\t\tlet dodaj liczba wynik = \n\t\t\tHashtbl.add mapa liczba wynik;\n\t\t\tHashtbl.add skad liczba gora;\n\t\t\tQueue.add liczba kolejka in\n\t\tlet przejdz dzielnik = \n\t\t\tif not (Hashtbl.mem mapa (gora / dzielnik)) then\n\t\t\t\tdodaj (gora / dzielnik) (Hashtbl.find mapa gora + 1) in\n\t\tList.iter przejdz przejscia;\n\t\tif not (Hashtbl.mem mapa (gora - 1)) then\n\t\t\tdodaj (gora - 1) (Hashtbl.find mapa gora + 1)\n\tdone;\n\tlet wynik = ref [] in\n\tlet akt = ref 1 in\n\twhile !akt <> x do\n\t\twynik := (!akt :: !wynik);\n\t\takt := Hashtbl.find skad !akt \n\tdone;\n\twynik := (x :: !wynik);\n\tList.rev !wynik\n\nlet to_array l = \n\tlet n = List.length l in\n\tlet tbl = Array.make n (List.hd l) in\n\tlet lista = ref l in\n\tfor i = 0 to n - 1 do\n\t\ttbl.(i) <- List.hd !lista;\n\t\tlista := List.tl !lista\n\tdone;\n\ttbl\n\nlet dbg t =\n\tArray.iter (fun x -> print_int x) t;\n\tprint_endline \"\"\n\n\nlet palindromy l =\n\tlet n = List.length l in\n\tlet l2 = l @ (List.rev l) in\n\tlet tbl = to_array l2 in\n\tlet knp = Array.make (List.length l2) 0 in \n\tfor j = 0 to 1 do\n\t\tfor i = 1 + n * j to n * (j + 1) - 1 do \n\t\t\tlet odp = ref knp.(i - 1) in\n\t\t\twhile tbl.(!odp) <> tbl.(i) && !odp <> 0 do\n\t\t\t\todp := knp.(!odp - 1)\n\t\t\tdone;\n\t\t\tif tbl.(!odp) = tbl.(i) then\n\t\t\t\tincr odp;\n\t\t\tknp.(i) <- !odp\n\t\tdone;\n\t\tif tbl.(n) = tbl.(0) then \n\t\t\tknp.(n) <- 1\n\tdone;\n\tknp.(2 * n - 1);;\n\nlet main () =\n\tlet n = liczba () in\n\tlet m = liczba () in\n\tlet kraw = Array.make (m + 1) (0, 0, 0) in\n\tfor i = 1 to m do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\tlet w = liczba () in\n\t\tkraw.(i) <- (u, v, w)\n\tdone; \n\tlet fu = Array.make (n + 1) 0 in\n\tlet rozm = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tfu.(i) <- i;\n\t\trozm.(i) <- 1\n\tdone; \n\tlet rec znajdz x =\n\t\tif fu.(x) = x then x else \n\t\t\tlet wynik = znajdz (fu.(x)) in\n\t\t\tfu.(x) <- wynik;\n\t\t\twynik in\n\tlet rec znajdz_rozm x =\n\t\tif fu.(x) = x then rozm.(x) else znajdz_rozm (fu.(x)) in\n\tlet merge (x, y, _) =\n\t\tlet v1 = znajdz x in\n\t\tlet v2 = znajdz y in\n\t\tif znajdz_rozm v1 < znajdz_rozm v2 then begin\n\t\t\tfu.(v1) <- v2;\n\t\t\trozm.(v2) <- rozm.(v2) + rozm.(v1)\n\t\tend else begin\n\t\t\tfu.(v2) <- v1;\n\t\t\trozm.(v1) <- rozm.(v1) + rozm.(v2);\n\t\tend in\n\tlet waga_kraw (_, _, w) = w in\n\tlet pierw_kraw (w, _, _) = w in\n\tlet drug_kraw (_, w, _) = w in\n\tArray.sort (fun (u1, v2, w1) (u2, v2, w2) -> w1 - w2) kraw;\n\tlet poprz_waga = ref 0 in\n\tlet lista = ref [] in\n\tlet wynik = ref (m - n + 1) in\n\tfor i = 1 to m do\n\t\tif waga_kraw kraw.(i) > !poprz_waga then begin\n\t\t\tList.iter (fun x -> merge kraw.(x)) !lista;\n\t\t\tlista := [];\n\t\t\tpoprz_waga := waga_kraw kraw.(i)\n\t\tend;\n\t\tif znajdz (pierw_kraw kraw.(i)) = znajdz (drug_kraw kraw.(i)) then\n\t\t\tdecr wynik\n\t\telse\n\t\t\tlista := (i :: !lista)\n\tdone;\n\tprint_int !wynik;;\n\n\nlet pierw (a, b) = a\nlet drug (a, b) = b\n\nlet daleko tbl =\n\tlet n = Array.length tbl in\n\tif n = 0 then (0, 0) else\n\tlet tbl_pom = Array.make n (0, 0) in\n\tfor i = 0 to n - 1 do\n\t\ttbl_pom.(i) <- (tbl.(i), i)\n\tdone;\n\tArray.sort (fun x y -> (-1) * (compare x y)) tbl_pom;\n\tlet wal = Array.make n 0 in\n\tlet ind = Array.make n 0 in\n\tfor i = 0 to n - 1 do\n\t\twal.(i) <- (pierw (tbl_pom.(i)));\n\t\tind.(i) <- (drug (tbl_pom.(i)))\n\tdone;\n\tlet wynik = ref 0 in\n\tlet lewy = ref 0 in\n\tlet prawy = ref 0 in\n\tlet maks_ind = ref 0 in\n\tlet poprz = ref wal.(0) in\n\tlet akt_maks = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tif wal.(i) <> !poprz then begin\n\t\t\tmaks_ind := !akt_maks;\n\t\t\tpoprz := wal.(i)\n\t\tend;\n\t\tif !wynik < !maks_ind - ind.(i) then begin\n\t\t\tlewy := ind.(i);\n\t\t\tprawy := !maks_ind;\n\t\t\twynik := !maks_ind - ind.(i)\n\t\tend;\n\t\takt_maks := max !akt_maks ind.(i)\n\tdone;\n\t(!lewy, !prawy)\n\nlet kominek k m tbl =\n\tlet plecak = Array.make (k + 1) (-1) in\n\tArray.sort compare tbl;\n\tlet wynik = ref 0 in\n\tplecak.(0) <- 0;\n\tlet d = Array.length tbl in\n\tfor i = 0 to d - 1 do\n\t\tfor j = k downto tbl.(i) do\n\t\t\tif plecak.(j - tbl.(i)) = 0 then begin\n\t\t\t\tplecak.(j) <- 0;\n\t\t\t\twynik := max !wynik (tbl.(i) + min m j)\n\t\t\tend;\n\t\tdone\n\tdone;\n\t!wynik\n\nlet bfs () =\n\t let licznik = ref 0 in\n\tlet liczba () =\n\t\tlet tab = [|7;1;2;1;5;2;3;2;4;5;6;6;7;1;2;5;6;3;4;7|] in\n\t\tlet wynik = tab.(!licznik) in\n\t\tincr licznik;\n\t\twynik in \n\tlet n = liczba () in\n\tlet mapa = Hashtbl.create 1000000 in\n\n\tlet wez x =\n\t\tif Hashtbl.mem mapa x then\n\t\t\tHashtbl.find mapa x\n\t\telse\n\t\t\t[] in\n\n\tfor i = 0 to n - 2 do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\t(*print_int u;\n\t\tprint_string \" \";\n\t\tprint_int v;\n\t\tprint_endline \"\";*)\n\t\tHashtbl.add mapa u (v :: wez u);\n\t\tHashtbl.add mapa v (u :: wez v)\n\tdone;\n\t(*for i = 0 to n do\n\t print_int i;\n\t print_string \": \";\n\t List.iter (fun x -> print_int x; print_string \" \") (wez i);\n\t print_endline \"\"\n\tdone;*)\n\tlet kolejka = Queue.create () in\n\tQueue.push 1 kolejka;\n\tlet kol = Array.make (n + 1) 0 in\n\tkol.(1) <- 1;\n\tlet ojc = Array.make (n + 1) 0 in\n\twhile not (Queue.is_empty kolejka) do\n\t\tlet w = Queue.take kolejka in\n\t\tList.iter (fun x -> (* print_int x; print_string \" \"; *)if kol.(x) = 0 then begin kol.(x) <- kol.(w) + 1; ojc.(x) <- w; Queue.add x kolejka end) (Hashtbl.find mapa w)\n\tdone;\n\tlet tbl = Array.make (n + 1) 0 in\n\tlet num = Array.make (n + 1) 0 in\n\tfor i = 0 to n - 1 do\n\t\tlet w = liczba () in\n\t\tnum.(w) <- i;\n\t\ttbl.(i) <- w\n\tdone;\n\tlet poprz = ref 0 in\n\tlet poprz_num_ojc = ref 0 in\n\tlet czygut = ref 1 in\n\t(* dbg kol;\n\tdbg ojc; *)\n\tfor i = 0 to n - 1 do\n\t\tlet u = tbl.(i) in\n\t\t(* print_int u;\n\t\tprint_string \" \";\n\t\tprint_int ojc.(u);\n\t\tprint_string \" \";\n\t\tprint_int num.(ojc.(u));\n\t\tprint_string \" \";\n\t\tprint_int !poprz_num_ojc;\n\t\tprint_endline \"\"; *)\n\t\t(* print_int u;\n\t\tprint_endline \"\"; *)\n\t\tif kol.(u) < !poprz || (u <> 1 && num.(ojc.(u)) < !poprz_num_ojc) then czygut := 0;\n\t\tpoprz := kol.(u);\n\t\tpoprz_num_ojc := num.(ojc.(u))\n\tdone;\n\tif !czygut = 1 then print_string \"Yes\" else print_string \"No\";;\n\nbfs ();;\n\nlet segment t =\n\tlet n = Array.length t in\n\tlet p = ref 0 in\n\tlet lista = Array.make n 0 in\n\tlet pocz = ref 0 in\n\tlet kon = ref (-1) in\n\tlet wynik = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tlet mini () =\n\t\t\tif !pocz > !kon then t.(!p) else \n\t\t\tmin t.(lista.(!pocz)) t.(!p) in\n\t\twhile !p < n && mini () >= !p - i + 1 do\n\t\t\twhile pocz <= kon && t.(lista.(!kon)) > t.(i) do\n\t\t\t\tdecr kon\n\t\t\tdone;\n\t\t\tincr kon;\n\t\t\tlista.(!kon) <- !p;\n\t\t\tincr p\n\t\tdone;\n\t\twynik := max !wynik (!p - i);\n\t\tif lista.(!pocz) = i && !pocz <= !kon then\n\t\t\tincr pocz;\n\t\tprint_int !p;\n\t\tif !p = i then\n\t\t\tincr p;\n\t\tprint_int !p;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik\n"}, {"source_code": "let jajka n k = \n\tlet rzm = min (k + 1) 31 in\n\tlet a = Array.make_matrix (n + 1) rzm 0 in\n\tlet wynik = ref 0 in\n\tfor i = 1 to n do\n\t\tfor j = 1 to rzm - 1 do \n\t\t\ta.(i).(j) <- a.(i - 1).(j - 1) + a.(i - 1).(j) + 1;\n\t\t\tprint_int a.(i).(j);\n\t\t\tprint_string \" \";\n\t\t\tif a.(i).(j) >= n && !wynik = 0 then wynik := i\n\t\tdone;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik;;\n\nlet liczba () =\n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\n\nlet plecak l p =\n\tlet a = Array.make (p + 1) 0 in\n\tlet dodaj (poj, k) =\n\t\tfor i = p downto poj do \n\t\t\ta.(i) <- max a.(i) (a.(i - poj) + k)\n\t\tdone in\n\tList.iter dodaj l;\n\tArray.fold_left max 0 a;;\n\nlet repair_road t x =\n\tlet p = ref 0 in\n\tlet dl = (Array.length t) in\n\tlet wynik = ref 0 in\n\tlet odp = ref 0 in\n\tfor i = 0 to dl - 1 do\n\t\twhile !wynik <= x && !p < dl do \n\t\t\twynik := !wynik + 1 - t.(!p);\n\t\t\tincr p\n\t\tdone;\n\t\tif !wynik > x then begin\n\t\t\tdecr p;\n\t\t\twynik := !wynik - 1 + t.(!p)\n\t\tend;\n\t\todp := max (!odp) (!p - i);\n\t\twynik := !wynik - 1 + t.(i);(* \n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tprint_int !p;\n\t\tprint_endline \"\"; *)\n\tdone;\n\t!odp\n\n\nlet wczytaj () =\n\tlet n = liczba () in\n\tlet s = liczba () in\n\tlet t = Array.make n 0 in\n\tfor i = 0 to n - 1 do \n\t\tlet pole = liczba () in(* \n\t\tprint_int pole;\n\t\tprint_endline \"\"; *)\n\t\tt.(i) <- pole\n\tdone;\n\tprint_int (repair_road t s);\n\tprint_endline \"\";;\n\nlet main () =\n\tlet n = liczba () in\n\tfor i = 1 to n do\n\t\twczytaj ()\n\tdone;;\n\nlet examin x =\n\tlet sito = Array.make (x + 1) 0 in\n\tlet kolejka = Queue.create () in\n\tlet mapa = Hashtbl.create 1000000 in\n\tlet skad = Hashtbl.create 1000000 in\n\tlet prims = ref [] in\n\tfor i = 2 to x do\n\t\tprims := i :: !prims\n\tdone;\n\tlet primes = !prims in\n\tlet dodaj a = \n\t\tif sito.(a) = 0 then\n\t\tlet it = ref (a * a) in\n\t\twhile !it <= x do\n\t\t\tsito.(!it) <- a;\n\t\t\tit := !it + a\n\t\tdone in \n\tlet rec dzielniki a =\n\t\tlet akt_dziel = sito.(a) in\n\t\tif akt_dziel = 0 then [a] else\n\t\tlet aktliczba = ref a in\n\t\twhile !aktliczba mod akt_dziel = 0 do\n\t\t\taktliczba := !aktliczba / akt_dziel\n\t\tdone;\n\t\t(akt_dziel :: dzielniki !aktliczba) in\n\tList.iter dodaj primes;\n\tHashtbl.add mapa x 0;\n\tQueue.add x kolejka;\n\twhile not (Hashtbl.mem mapa 1) do\n\t\tlet gora = Queue.take kolejka in\n\t\tlet przejscia = dzielniki gora in\n\t\tlet dodaj liczba wynik = \n\t\t\tHashtbl.add mapa liczba wynik;\n\t\t\tHashtbl.add skad liczba gora;\n\t\t\tQueue.add liczba kolejka in\n\t\tlet przejdz dzielnik = \n\t\t\tif not (Hashtbl.mem mapa (gora / dzielnik)) then\n\t\t\t\tdodaj (gora / dzielnik) (Hashtbl.find mapa gora + 1) in\n\t\tList.iter przejdz przejscia;\n\t\tif not (Hashtbl.mem mapa (gora - 1)) then\n\t\t\tdodaj (gora - 1) (Hashtbl.find mapa gora + 1)\n\tdone;\n\tlet wynik = ref [] in\n\tlet akt = ref 1 in\n\twhile !akt <> x do\n\t\twynik := (!akt :: !wynik);\n\t\takt := Hashtbl.find skad !akt \n\tdone;\n\twynik := (x :: !wynik);\n\tList.rev !wynik\n\nlet to_array l = \n\tlet n = List.length l in\n\tlet tbl = Array.make n (List.hd l) in\n\tlet lista = ref l in\n\tfor i = 0 to n - 1 do\n\t\ttbl.(i) <- List.hd !lista;\n\t\tlista := List.tl !lista\n\tdone;\n\ttbl\n\nlet dbg t =\n\tArray.iter (fun x -> print_int x) t;\n\tprint_endline \"\"\n\n\nlet palindromy l =\n\tlet n = List.length l in\n\tlet l2 = l @ (List.rev l) in\n\tlet tbl = to_array l2 in\n\tlet knp = Array.make (List.length l2) 0 in \n\tfor j = 0 to 1 do\n\t\tfor i = 1 + n * j to n * (j + 1) - 1 do \n\t\t\tlet odp = ref knp.(i - 1) in\n\t\t\twhile tbl.(!odp) <> tbl.(i) && !odp <> 0 do\n\t\t\t\todp := knp.(!odp - 1)\n\t\t\tdone;\n\t\t\tif tbl.(!odp) = tbl.(i) then\n\t\t\t\tincr odp;\n\t\t\tknp.(i) <- !odp\n\t\tdone;\n\t\tif tbl.(n) = tbl.(0) then \n\t\t\tknp.(n) <- 1\n\tdone;\n\tknp.(2 * n - 1);;\n\nlet main () =\n\tlet n = liczba () in\n\tlet m = liczba () in\n\tlet kraw = Array.make (m + 1) (0, 0, 0) in\n\tfor i = 1 to m do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\tlet w = liczba () in\n\t\tkraw.(i) <- (u, v, w)\n\tdone; \n\tlet fu = Array.make (n + 1) 0 in\n\tlet rozm = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tfu.(i) <- i;\n\t\trozm.(i) <- 1\n\tdone; \n\tlet rec znajdz x =\n\t\tif fu.(x) = x then x else \n\t\t\tlet wynik = znajdz (fu.(x)) in\n\t\t\tfu.(x) <- wynik;\n\t\t\twynik in\n\tlet rec znajdz_rozm x =\n\t\tif fu.(x) = x then rozm.(x) else znajdz_rozm (fu.(x)) in\n\tlet merge (x, y, _) =\n\t\tlet v1 = znajdz x in\n\t\tlet v2 = znajdz y in\n\t\tif znajdz_rozm v1 < znajdz_rozm v2 then begin\n\t\t\tfu.(v1) <- v2;\n\t\t\trozm.(v2) <- rozm.(v2) + rozm.(v1)\n\t\tend else begin\n\t\t\tfu.(v2) <- v1;\n\t\t\trozm.(v1) <- rozm.(v1) + rozm.(v2);\n\t\tend in\n\tlet waga_kraw (_, _, w) = w in\n\tlet pierw_kraw (w, _, _) = w in\n\tlet drug_kraw (_, w, _) = w in\n\tArray.sort (fun (u1, v2, w1) (u2, v2, w2) -> w1 - w2) kraw;\n\tlet poprz_waga = ref 0 in\n\tlet lista = ref [] in\n\tlet wynik = ref (m - n + 1) in\n\tfor i = 1 to m do\n\t\tif waga_kraw kraw.(i) > !poprz_waga then begin\n\t\t\tList.iter (fun x -> merge kraw.(x)) !lista;\n\t\t\tlista := [];\n\t\t\tpoprz_waga := waga_kraw kraw.(i)\n\t\tend;\n\t\tif znajdz (pierw_kraw kraw.(i)) = znajdz (drug_kraw kraw.(i)) then\n\t\t\tdecr wynik\n\t\telse\n\t\t\tlista := (i :: !lista)\n\tdone;\n\tprint_int !wynik;;\n\n\nlet pierw (a, b) = a\nlet drug (a, b) = b\n\nlet daleko tbl =\n\tlet n = Array.length tbl in\n\tif n = 0 then (0, 0) else\n\tlet tbl_pom = Array.make n (0, 0) in\n\tfor i = 0 to n - 1 do\n\t\ttbl_pom.(i) <- (tbl.(i), i)\n\tdone;\n\tArray.sort (fun x y -> (-1) * (compare x y)) tbl_pom;\n\tlet wal = Array.make n 0 in\n\tlet ind = Array.make n 0 in\n\tfor i = 0 to n - 1 do\n\t\twal.(i) <- (pierw (tbl_pom.(i)));\n\t\tind.(i) <- (drug (tbl_pom.(i)))\n\tdone;\n\tlet wynik = ref 0 in\n\tlet lewy = ref 0 in\n\tlet prawy = ref 0 in\n\tlet maks_ind = ref 0 in\n\tlet poprz = ref wal.(0) in\n\tlet akt_maks = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tif wal.(i) <> !poprz then begin\n\t\t\tmaks_ind := !akt_maks;\n\t\t\tpoprz := wal.(i)\n\t\tend;\n\t\tif !wynik < !maks_ind - ind.(i) then begin\n\t\t\tlewy := ind.(i);\n\t\t\tprawy := !maks_ind;\n\t\t\twynik := !maks_ind - ind.(i)\n\t\tend;\n\t\takt_maks := max !akt_maks ind.(i)\n\tdone;\n\t(!lewy, !prawy)\n\nlet kominek k m tbl =\n\tlet plecak = Array.make (k + 1) (-1) in\n\tArray.sort compare tbl;\n\tlet wynik = ref 0 in\n\tplecak.(0) <- 0;\n\tlet d = Array.length tbl in\n\tfor i = 0 to d - 1 do\n\t\tfor j = k downto tbl.(i) do\n\t\t\tif plecak.(j - tbl.(i)) = 0 then begin\n\t\t\t\tplecak.(j) <- 0;\n\t\t\t\twynik := max !wynik (tbl.(i) + min m j)\n\t\t\tend;\n\t\tdone\n\tdone;\n\t!wynik\n\nlet bfs () =\n\tlet n = liczba () in\n\tlet mapa = Hashtbl.create 1000000 in\n\n\tlet wez x =\n\t\tif Hashtbl.mem mapa x then\n\t\t\tHashtbl.find mapa x\n\t\telse\n\t\t\t[] in\n\n\tfor i = 0 to n - 2 do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\t(*print_int u;\n\t\tprint_string \" \";\n\t\tprint_int v;\n\t\tprint_endline \"\";*)\n\t\tHashtbl.add mapa u (v :: wez u);\n\t\tHashtbl.add mapa v (u :: wez v)\n\tdone;\n\t(*for i = 0 to n do\n\t print_int i;\n\t print_string \": \";\n\t List.iter (fun x -> print_int x; print_string \" \") (wez i);\n\t print_endline \"\"\n\tdone;*)\n\tlet kolejka = Queue.create () in\n\tQueue.push 1 kolejka;\n\tlet kol = Array.make (n + 1) 0 in\n\tkol.(1) <- 1;\n\twhile not (Queue.is_empty kolejka) do\n\t\tlet w = Queue.take kolejka in\n\t\tList.iter (fun x -> (* print_int x; print_string \" \"; *)if kol.(x) = 0 then begin kol.(x) <- kol.(w) + 1; Queue.add x kolejka end) (Hashtbl.find mapa w)\n\tdone;\n\tlet poprz = ref 0 in\n\tlet czygut = ref 1 in\n\tfor i = 0 to n - 1 do\n\t\tlet u = liczba () in\n\t\tif kol.(u) < !poprz then czygut := 0;\n\t\tpoprz := kol.(u)\n\tdone;\n\t(* dbg kol; *)\n\tif !czygut = 1 then print_string \"Yes\" else print_string \"No\";;\n\nbfs ();;\n\nlet segment t =\n\tlet n = Array.length t in\n\tlet p = ref 0 in\n\tlet lista = Array.make n 0 in\n\tlet pocz = ref 0 in\n\tlet kon = ref (-1) in\n\tlet wynik = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tlet mini () =\n\t\t\tif !pocz > !kon then t.(!p) else \n\t\t\tmin t.(lista.(!pocz)) t.(!p) in\n\t\twhile !p < n && mini () >= !p - i + 1 do\n\t\t\twhile pocz <= kon && t.(lista.(!kon)) > t.(i) do\n\t\t\t\tdecr kon\n\t\t\tdone;\n\t\t\tincr kon;\n\t\t\tlista.(!kon) <- !p;\n\t\t\tincr p\n\t\tdone;\n\t\twynik := max !wynik (!p - i);\n\t\tif lista.(!pocz) = i && !pocz <= !kon then\n\t\t\tincr pocz;\n\t\tprint_int !p;\n\t\tif !p = i then\n\t\t\tincr p;\n\t\tprint_int !p;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik\n"}, {"source_code": "let jajka n k = \n\tlet rzm = min (k + 1) 31 in\n\tlet a = Array.make_matrix (n + 1) rzm 0 in\n\tlet wynik = ref 0 in\n\tfor i = 1 to n do\n\t\tfor j = 1 to rzm - 1 do \n\t\t\ta.(i).(j) <- a.(i - 1).(j - 1) + a.(i - 1).(j) + 1;\n\t\t\tprint_int a.(i).(j);\n\t\t\tprint_string \" \";\n\t\t\tif a.(i).(j) >= n && !wynik = 0 then wynik := i\n\t\tdone;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik;;\n\nlet liczba () =\n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\n\nlet plecak l p =\n\tlet a = Array.make (p + 1) 0 in\n\tlet dodaj (poj, k) =\n\t\tfor i = p downto poj do \n\t\t\ta.(i) <- max a.(i) (a.(i - poj) + k)\n\t\tdone in\n\tList.iter dodaj l;\n\tArray.fold_left max 0 a;;\n\nlet repair_road t x =\n\tlet p = ref 0 in\n\tlet dl = (Array.length t) in\n\tlet wynik = ref 0 in\n\tlet odp = ref 0 in\n\tfor i = 0 to dl - 1 do\n\t\twhile !wynik <= x && !p < dl do \n\t\t\twynik := !wynik + 1 - t.(!p);\n\t\t\tincr p\n\t\tdone;\n\t\tif !wynik > x then begin\n\t\t\tdecr p;\n\t\t\twynik := !wynik - 1 + t.(!p)\n\t\tend;\n\t\todp := max (!odp) (!p - i);\n\t\twynik := !wynik - 1 + t.(i);(* \n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tprint_int !p;\n\t\tprint_endline \"\"; *)\n\tdone;\n\t!odp\n\n\nlet wczytaj () =\n\tlet n = liczba () in\n\tlet s = liczba () in\n\tlet t = Array.make n 0 in\n\tfor i = 0 to n - 1 do \n\t\tlet pole = liczba () in(* \n\t\tprint_int pole;\n\t\tprint_endline \"\"; *)\n\t\tt.(i) <- pole\n\tdone;\n\tprint_int (repair_road t s);\n\tprint_endline \"\";;\n\nlet main () =\n\tlet n = liczba () in\n\tfor i = 1 to n do\n\t\twczytaj ()\n\tdone;;\n\nlet examin x =\n\tlet sito = Array.make (x + 1) 0 in\n\tlet kolejka = Queue.create () in\n\tlet mapa = Hashtbl.create 1000000 in\n\tlet skad = Hashtbl.create 1000000 in\n\tlet prims = ref [] in\n\tfor i = 2 to x do\n\t\tprims := i :: !prims\n\tdone;\n\tlet primes = !prims in\n\tlet dodaj a = \n\t\tif sito.(a) = 0 then\n\t\tlet it = ref (a * a) in\n\t\twhile !it <= x do\n\t\t\tsito.(!it) <- a;\n\t\t\tit := !it + a\n\t\tdone in \n\tlet rec dzielniki a =\n\t\tlet akt_dziel = sito.(a) in\n\t\tif akt_dziel = 0 then [a] else\n\t\tlet aktliczba = ref a in\n\t\twhile !aktliczba mod akt_dziel = 0 do\n\t\t\taktliczba := !aktliczba / akt_dziel\n\t\tdone;\n\t\t(akt_dziel :: dzielniki !aktliczba) in\n\tList.iter dodaj primes;\n\tHashtbl.add mapa x 0;\n\tQueue.add x kolejka;\n\twhile not (Hashtbl.mem mapa 1) do\n\t\tlet gora = Queue.take kolejka in\n\t\tlet przejscia = dzielniki gora in\n\t\tlet dodaj liczba wynik = \n\t\t\tHashtbl.add mapa liczba wynik;\n\t\t\tHashtbl.add skad liczba gora;\n\t\t\tQueue.add liczba kolejka in\n\t\tlet przejdz dzielnik = \n\t\t\tif not (Hashtbl.mem mapa (gora / dzielnik)) then\n\t\t\t\tdodaj (gora / dzielnik) (Hashtbl.find mapa gora + 1) in\n\t\tList.iter przejdz przejscia;\n\t\tif not (Hashtbl.mem mapa (gora - 1)) then\n\t\t\tdodaj (gora - 1) (Hashtbl.find mapa gora + 1)\n\tdone;\n\tlet wynik = ref [] in\n\tlet akt = ref 1 in\n\twhile !akt <> x do\n\t\twynik := (!akt :: !wynik);\n\t\takt := Hashtbl.find skad !akt \n\tdone;\n\twynik := (x :: !wynik);\n\tList.rev !wynik\n\nlet to_array l = \n\tlet n = List.length l in\n\tlet tbl = Array.make n (List.hd l) in\n\tlet lista = ref l in\n\tfor i = 0 to n - 1 do\n\t\ttbl.(i) <- List.hd !lista;\n\t\tlista := List.tl !lista\n\tdone;\n\ttbl\n\nlet dbg t =\n\tArray.iter (fun x -> print_int x) t;\n\tprint_endline \"\"\n\n\nlet palindromy l =\n\tlet n = List.length l in\n\tlet l2 = l @ (List.rev l) in\n\tlet tbl = to_array l2 in\n\tlet knp = Array.make (List.length l2) 0 in \n\tfor j = 0 to 1 do\n\t\tfor i = 1 + n * j to n * (j + 1) - 1 do \n\t\t\tlet odp = ref knp.(i - 1) in\n\t\t\twhile tbl.(!odp) <> tbl.(i) && !odp <> 0 do\n\t\t\t\todp := knp.(!odp - 1)\n\t\t\tdone;\n\t\t\tif tbl.(!odp) = tbl.(i) then\n\t\t\t\tincr odp;\n\t\t\tknp.(i) <- !odp\n\t\tdone;\n\t\tif tbl.(n) = tbl.(0) then \n\t\t\tknp.(n) <- 1\n\tdone;\n\tknp.(2 * n - 1);;\n\nlet main () =\n\tlet n = liczba () in\n\tlet m = liczba () in\n\tlet kraw = Array.make (m + 1) (0, 0, 0) in\n\tfor i = 1 to m do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\tlet w = liczba () in\n\t\tkraw.(i) <- (u, v, w)\n\tdone; \n\tlet fu = Array.make (n + 1) 0 in\n\tlet rozm = Array.make (n + 1) 0 in\n\tfor i = 1 to n do\n\t\tfu.(i) <- i;\n\t\trozm.(i) <- 1\n\tdone; \n\tlet rec znajdz x =\n\t\tif fu.(x) = x then x else \n\t\t\tlet wynik = znajdz (fu.(x)) in\n\t\t\tfu.(x) <- wynik;\n\t\t\twynik in\n\tlet rec znajdz_rozm x =\n\t\tif fu.(x) = x then rozm.(x) else znajdz_rozm (fu.(x)) in\n\tlet merge (x, y, _) =\n\t\tlet v1 = znajdz x in\n\t\tlet v2 = znajdz y in\n\t\tif znajdz_rozm v1 < znajdz_rozm v2 then begin\n\t\t\tfu.(v1) <- v2;\n\t\t\trozm.(v2) <- rozm.(v2) + rozm.(v1)\n\t\tend else begin\n\t\t\tfu.(v2) <- v1;\n\t\t\trozm.(v1) <- rozm.(v1) + rozm.(v2);\n\t\tend in\n\tlet waga_kraw (_, _, w) = w in\n\tlet pierw_kraw (w, _, _) = w in\n\tlet drug_kraw (_, w, _) = w in\n\tArray.sort (fun (u1, v2, w1) (u2, v2, w2) -> w1 - w2) kraw;\n\tlet poprz_waga = ref 0 in\n\tlet lista = ref [] in\n\tlet wynik = ref (m - n + 1) in\n\tfor i = 1 to m do\n\t\tif waga_kraw kraw.(i) > !poprz_waga then begin\n\t\t\tList.iter (fun x -> merge kraw.(x)) !lista;\n\t\t\tlista := [];\n\t\t\tpoprz_waga := waga_kraw kraw.(i)\n\t\tend;\n\t\tif znajdz (pierw_kraw kraw.(i)) = znajdz (drug_kraw kraw.(i)) then\n\t\t\tdecr wynik\n\t\telse\n\t\t\tlista := (i :: !lista)\n\tdone;\n\tprint_int !wynik;;\n\n\nlet pierw (a, b) = a\nlet drug (a, b) = b\n\nlet daleko tbl =\n\tlet n = Array.length tbl in\n\tif n = 0 then (0, 0) else\n\tlet tbl_pom = Array.make n (0, 0) in\n\tfor i = 0 to n - 1 do\n\t\ttbl_pom.(i) <- (tbl.(i), i)\n\tdone;\n\tArray.sort (fun x y -> (-1) * (compare x y)) tbl_pom;\n\tlet wal = Array.make n 0 in\n\tlet ind = Array.make n 0 in\n\tfor i = 0 to n - 1 do\n\t\twal.(i) <- (pierw (tbl_pom.(i)));\n\t\tind.(i) <- (drug (tbl_pom.(i)))\n\tdone;\n\tlet wynik = ref 0 in\n\tlet lewy = ref 0 in\n\tlet prawy = ref 0 in\n\tlet maks_ind = ref 0 in\n\tlet poprz = ref wal.(0) in\n\tlet akt_maks = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tif wal.(i) <> !poprz then begin\n\t\t\tmaks_ind := !akt_maks;\n\t\t\tpoprz := wal.(i)\n\t\tend;\n\t\tif !wynik < !maks_ind - ind.(i) then begin\n\t\t\tlewy := ind.(i);\n\t\t\tprawy := !maks_ind;\n\t\t\twynik := !maks_ind - ind.(i)\n\t\tend;\n\t\takt_maks := max !akt_maks ind.(i)\n\tdone;\n\t(!lewy, !prawy)\n\nlet kominek k m tbl =\n\tlet plecak = Array.make (k + 1) (-1) in\n\tArray.sort compare tbl;\n\tlet wynik = ref 0 in\n\tplecak.(0) <- 0;\n\tlet d = Array.length tbl in\n\tfor i = 0 to d - 1 do\n\t\tfor j = k downto tbl.(i) do\n\t\t\tif plecak.(j - tbl.(i)) = 0 then begin\n\t\t\t\tplecak.(j) <- 0;\n\t\t\t\twynik := max !wynik (tbl.(i) + min m j)\n\t\t\tend;\n\t\tdone\n\tdone;\n\t!wynik\n\nlet bfs () =\n\tlet licznik = ref 0 in\n\tlet liczba () =\n\t\tlet tab = [|6;1;2;1;5;2;3;2;4;5;6;1;5;2;3;4;6|] in\n\t\tlet wynik = tab.(!licznik) in\n\t\tincr licznik;\n\t\twynik in\n\tlet n = liczba () in\n\tlet mapa = Hashtbl.create 1000000 in\n\n\tlet wez x =\n\t\tif Hashtbl.mem mapa x then\n\t\t\tHashtbl.find mapa x\n\t\telse\n\t\t\t[] in\n\n\tfor i = 0 to n - 2 do\n\t\tlet u = liczba () in\n\t\tlet v = liczba () in\n\t\t(*print_int u;\n\t\tprint_string \" \";\n\t\tprint_int v;\n\t\tprint_endline \"\";*)\n\t\tHashtbl.add mapa u (v :: wez u);\n\t\tHashtbl.add mapa v (u :: wez v)\n\tdone;\n\t(*for i = 0 to n do\n\t print_int i;\n\t print_string \": \";\n\t List.iter (fun x -> print_int x; print_string \" \") (wez i);\n\t print_endline \"\"\n\tdone;*)\n\tlet kolejka = Queue.create () in\n\tQueue.push 1 kolejka;\n\tlet kol = Array.make (n + 1) 0 in\n\tkol.(1) <- 1;\n\tlet ojc = Array.make (n + 1) 0 in\n\twhile not (Queue.is_empty kolejka) do\n\t\tlet w = Queue.take kolejka in\n\t\tList.iter (fun x -> (* print_int x; print_string \" \"; *)if kol.(x) = 0 then begin kol.(x) <- kol.(w) + 1; ojc.(x) <- w; Queue.add x kolejka end) (Hashtbl.find mapa w)\n\tdone;\n\tlet tbl = Array.make (n + 1) 0 in\n\tlet num = Array.make (n + 1) 0 in\n\tfor i = 0 to n - 1 do\n\t\tlet w = liczba () in\n\t\tnum.(w) <- i;\n\t\ttbl.(i) <- w\n\tdone;\n\tlet poprz = ref 0 in\n\tlet poprz_num_ojc = ref 0 in\n\tlet czygut = ref 1 in\n\t(* dbg kol;\n\tdbg ojc; *)\n\tfor i = 0 to n - 1 do\n\t\tlet u = tbl.(i) in\n\t\t(* print_int u;\n\t\tprint_endline \"\"; *)\n\t\tif kol.(u) < !poprz || (u <> 1 && num.(ojc.(u)) < !poprz_num_ojc) then czygut := 0;\n\t\tif (!poprz < kol.(u)) then begin\n\t\t\tpoprz_num_ojc := 0;\n\t\t\tpoprz := kol.(u)\n\t\tend else\n\t\t\tpoprz_num_ojc := num.(ojc.(u));\n\tdone;\n\tif !czygut = 1 then print_string \"Yes\" else print_string \"No\";;\n\nbfs ();;\n\nlet segment t =\n\tlet n = Array.length t in\n\tlet p = ref 0 in\n\tlet lista = Array.make n 0 in\n\tlet pocz = ref 0 in\n\tlet kon = ref (-1) in\n\tlet wynik = ref 0 in\n\tfor i = 0 to n - 1 do\n\t\tprint_int i;\n\t\tprint_string \" \";\n\t\tlet mini () =\n\t\t\tif !pocz > !kon then t.(!p) else \n\t\t\tmin t.(lista.(!pocz)) t.(!p) in\n\t\twhile !p < n && mini () >= !p - i + 1 do\n\t\t\twhile pocz <= kon && t.(lista.(!kon)) > t.(i) do\n\t\t\t\tdecr kon\n\t\t\tdone;\n\t\t\tincr kon;\n\t\t\tlista.(!kon) <- !p;\n\t\t\tincr p\n\t\tdone;\n\t\twynik := max !wynik (!p - i);\n\t\tif lista.(!pocz) = i && !pocz <= !kon then\n\t\t\tincr pocz;\n\t\tprint_int !p;\n\t\tif !p = i then\n\t\t\tincr p;\n\t\tprint_int !p;\n\t\tprint_endline \"\"\n\tdone;\n\t!wynik\n"}], "src_uid": "82ff8ae62e39b8e64f9a273b736bf59e"} {"nl": {"description": "Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers li and ri for each of the days\u00a0\u2014 the indices of socks to wear on the day i (obviously, li stands for the left foot and ri for the right). Each sock is painted in one of k colors.When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paint\u00a0\u2014 one for each of k colors.Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.", "input_spec": "The first line of input contains three integers n, m and k (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 0\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of socks, the number of days and the number of available colors respectively. The second line contain n integers c1, c2, ..., cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009k)\u00a0\u2014 current colors of Arseniy's socks. Each of the following m lines contains two integers li and ri (1\u2009\u2264\u2009li,\u2009ri\u2009\u2264\u2009n, li\u2009\u2260\u2009ri)\u00a0\u2014 indices of socks which Arseniy should wear during the i-th day.", "output_spec": "Print one integer\u00a0\u2014 the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.", "sample_inputs": ["3 2 3\n1 2 3\n1 2\n2 3", "3 2 2\n1 1 2\n1 2\n2 1"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first sample, Arseniy can repaint the first and the third socks to the second color.In the second sample, there is no need to change any colors."}, "positive_code": [{"source_code": "let read_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet n = read_int()\nand m = read_int()\nand k = read_int();;\nlet r = Array.make (n + 1) 0\nand c = Array.make (n + 1) 0\nand g = Array.make (n + 1) [];;\n\nlet rec repr u = \n if r.(u) = u then\n u\n else\n begin\n r.(u) <- repr r.(u);\n r.(u)\n end\n;;\n\nfor u = 1 to n do\n c.(u) <- read_int();\n r.(u) <- u\ndone;\n\nfor i = 1 to m do\n let u = read_int()\n and v = read_int() in\n if repr u <> repr v then\n r.(repr u) <- repr v;\ndone;;\n\nfor u = 1 to n do\n g.(repr u) <- u :: g.(repr u)\ndone;;\n\n\nlet rec trier =\n let rec split = function\n | [] -> [], []\n | x :: xs -> let ys, zs = split xs in x :: zs, ys\n in\n let rec merge xs ys = match xs, ys with\n | [], xs -> xs\n | xs, [] -> xs\n | x :: xs, y :: ys when c.(x) < c.(y) -> x :: (merge xs (y :: ys))\n | x :: xs, y :: ys -> y :: (merge (x :: xs) ys)\n in\n function\n | [] -> []\n | [x] -> [x]\n | xs -> let ys, zs = split xs in merge (trier ys) (trier zs)\n;;\n\nlet rec majoritaire = function\n | [] -> 0, 0\n | x :: [] -> 1, 1\n | x :: y :: ys when c.(x) = c.(y) -> let i, j = majoritaire (y :: ys) in i + 1, max (i + 1) j\n | x :: y :: ys -> let _, j = majoritaire (y :: ys) in 1, max 1 j\n;;\n\nlet x = ref 0 in\nfor u = 1 to n do\n let _, l = majoritaire (trier g.(u)) in\n x := !x + List.length g.(u) - l\ndone;\nprint_int !x;;\n"}], "negative_code": [{"source_code": "let read_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet n = read_int()\nand m = read_int()\nand k = read_int();;\nlet r = Array.make (n + 1) 0\nand c = Array.make (n + 1) 0\nand g = Array.make (n + 1) [];;\nfor u = 1 to n do\n c.(u) <- read_int();\n r.(u) <- u\ndone;;\n\n\nlet rec repr u = \n if r.(u) = u then\n u\n else\n begin\n r.(u) <- repr r.(u);\n r.(u)\n end\n;;\n\nfor i = 1 to m do\n let u = read_int()\n and v = read_int() in\n if repr u <> repr v then\n r.(repr u) <- repr v;\ndone;;\n\nfor u = 1 to n do\n g.(repr u) <- u :: g.(repr u)\ndone;;\n\n\nlet rec trier =\n let rec split = function\n | [] -> [], []\n | x :: xs -> let ys, zs = split xs in x :: zs, ys\n in\n let rec merge xs ys = match xs, ys with\n | [], xs -> xs\n | xs, [] -> xs\n | x :: xs, y :: ys when c.(x) < c.(y) -> x :: (merge xs (y :: ys))\n | x :: xs, y :: ys -> y :: (merge (x :: xs) ys)\n in\n function\n | [] -> []\n | [x] -> [x]\n | xs -> let ys, zs = split xs in merge (trier ys) (trier zs)\nin\nlet rec majoritaire = function\n | [] -> 0, 0\n | x :: [] -> 1, 1\n | x :: y :: ys when x = y -> let i, j = majoritaire (y :: ys) in i + 1, max (i + 1) j\n | x :: y :: ys -> let _, j = majoritaire (y :: ys) in 1, max 1 j\nin\n\nlet x = ref 0 in\nfor u = 1 to n do\n let _, l = majoritaire (trier g.(u)) in\n x := !x + List.length g.(u) - l\ndone;\nprint_int !x;;\n"}], "src_uid": "39232c03c033da238c5d1e20e9595d6d"} {"nl": {"description": "Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.Consider that m (m\u2009\u2264\u20094n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.After occupying all the window seats (for m\u2009>\u20092n) the non-window seats are occupied:1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. The seating for n\u2009=\u20099 and m\u2009=\u200936. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.", "input_spec": "The only line contains two integers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009m\u2009\u2264\u20094n) \u2014 the number of pairs of rows and the number of passengers.", "output_spec": "Print m distinct integers from 1 to m \u2014 the order in which the passengers will get off the bus.", "sample_inputs": ["2 7", "9 36"], "sample_outputs": ["5 1 6 2 7 3 4", "19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r = ref [] in\n for i = 0 to n - 1 do\n let row = i in\n let ord =\n\t[ 2 * n + 1 + 2 * row;\n\t 2 * row + 1;\n\t 2 * n + 2 + 2 * row;\n\t 2 * row + 2]\n in\n\tList.iter\n\t (fun x ->\n\t if x <= m\n\t then r := x :: !r) ord\n done;\n List.iter (Printf.printf \"%d \") (List.rev !r);\n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "0a701242ca81029a1791df74dc8ca59b"} {"nl": {"description": "This is an interactive task.Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.There are $$$666$$$ black rooks and $$$1$$$ white king on the chess board of size $$$999 \\times 999$$$. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square $$$(x, y)$$$, it can move to the square $$$(nx, ny)$$$ if and only $$$\\max (|nx - x|, |ny - y|) = 1$$$ , $$$1 \\leq nx, ny \\leq 999$$$. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.Each player makes $$$2000$$$ turns, if the white king wasn't checked by a black rook during those turns, black wins. NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.", "input_spec": "In the beginning your program will receive $$$667$$$ lines from input. Each line contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\leq x, y \\leq 999$$$) \u2014 the piece's coordinates. The first line contains the coordinates of the king and the next $$$666$$$ contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.", "output_spec": "After getting king checked, you program should terminate immediately without printing anything extra.", "sample_inputs": ["999 999\n1 1\n1 2\n2 1\n2 2\n1 3\n2 3\n<...>\n26 13\n26 14\n26 15\n26 16\n\n1 700 800\n\n2 1 2\n\n<...>\n\n-1 -1 -1"], "sample_outputs": ["999 998\n\n999 997\n\n<...>\n\n999 26"], "notes": "NoteThe example is trimmed. The full initial positions of the rooks in the first test are available at https://pastebin.com/qQCTXgKP. It is not guaranteed that they will behave as in the example."}, "positive_code": [{"source_code": "Scanf.(Array.(scanf \" %d %d\" @@ fun x y ->\n let map = make_matrix 1000 1000 false in\n let rooks = make 666 (0,0) in\n init 666 (fun i ->\n scanf \" %d %d\" @@ fun x y ->\n (map.(x).(y) <- true; rooks.(i) <- x,y)\n ) |> ignore;\n let x,y = ref x,ref y in\n let rec move p q =\n if map.(!x+p).(!y+q) then (\n move p 0\n ) else (\n x := !x + p;\n y := !y + q;\n Printf.printf \"%d %d\\n%!\" !x !y;\n let i,u,v = scanf \" %d %d %d\" @@ fun p q r -> p,q,r in\n if i=0 && u=0 && v=0 then exit 0 (* WA *)\n else if i= -1 && u= -1 && v= -1 then exit 0 (* AC *)\n else (\n let pu,pv = rooks.(i-1) in\n map.(pu).(pv) <- false;\n map.( u).( v) <- true;\n rooks.(i-1) <- u,v;\n Printf.eprintf \"%d: %d,%d --> %d %d\\n%!\" i pu pv u v;\n )\n )\n in\n while !x <> 500 || !y <> 500 do\n if !x < 500 then move 1 0\n else if !x > 500 then move (-1) 0\n else if !y < 500 then move 0 1\n else if !y > 500 then move 0 (-1)\n done;\n let tr,tl,bl,br = fold_left (fun (p,q,r,s) (x,y) ->\n match x>500, y>500 with\n (* t/f: right/left, top/bottom *)\n | true, true -> (p+1,q,r,s)\n | false, true -> (p,q+1,r,s)\n | false,false -> (p,q,r+1,s)\n | true,false -> (p,q,r,s+1)\n ) (0,0,0,0) rooks\n in\n Printf.eprintf \"%d; %d; %d; %d\\n%!\" tr tl bl br;\n let mn = fold_left min br [|tr;tl;bl|] in\n ignore @@ init 499 @@ fun _ ->\n if mn=tr then move (-1) (-1)\n else if mn=tl then move 1 (-1)\n else if mn=bl then move 1 1\n else move (-1) 1\n))"}, {"source_code": "open Printf\nopen String\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet nrooks = (* 6 *) 666\nlet (maxx,maxy) = (* (9,9) *) (999,999)\nlet (cx,cy) = ((maxx+1)/2, (maxy+1)/2)\n \nlet split_string s = \n let s = trim s in\n \n let n = String.length s in\n let li = fold 0 (n-1) \n (fun i ac -> if s.[i] = ' ' then i::ac else ac) []\n in\n\n let rec chop prev li ac = \n match li with [] -> List.rev ac\n | i::tail -> \n\tchop i tail ((sub s (prev+1) (i-prev-1))::ac)\n in\n \n chop (-1) (List.rev (n::li)) []\n\nlet read_ints () = \n let c = split_string (read_line()) in\n let c = List.map (fun s -> int_of_string s) c in\n Array.of_list c\n\nlet () =\n let rook = Array.make (nrooks+1) (0,0) in\n\n let line1 = read_ints() in\n let (kx, ky) = (line1.(0), line1.(1)) in\n\n for i=1 to nrooks do\n let linei = read_ints() in\n rook.(i) <- (linei.(0), linei.(1));\n done;\n\n let in_check (kx,ky) =\n (* return true if this king is in check *)\n exists 1 nrooks (fun i ->\n let (x,y) = rook.(i) in\n x = kx || y = ky\n ) \n in\n\n let collide (kx,ky) =\n (* return true if the king is on top of a rook *)\n exists 1 nrooks (fun i -> rook.(i) = (kx,ky))\n in\n\n let dirs = [(-1,-1);(-1,0);(-1,1);(0,-1);(0,1);(1,-1);(1,0);(1,1)] in\n\n let rec move_to_goal (kx,ky) (goalx,goaly) = if kx = goalx && ky = goaly then true else (\n (* assume (kx,ky) has already been checked for being in check, or in a collision *)\n(* printf \"move_to_goal (%d,%d) (%d,%d)\\n\" kx ky goalx goaly; *)\n let check_dirs = List.filter (fun (dx,dy) ->\n let (nx,ny) = (kx+dx, ky+dy) in\n nx >= 1 && ny >= 1 && nx<=maxx && ny <= maxy && in_check (nx,ny) && (not (collide (nx,ny)))\n ) dirs in\n\n let (terminal,kx,ky) = \n if check_dirs <> [] then (\n\tlet (dx,dy) = List.hd check_dirs in\n\tlet (kx,ky) = (kx+dx, ky+dy) in\t\n\tprintf \"%d %d\\n\" kx ky;\n\t(true,kx,ky) (* found a winning move *)\n ) else (\n\tlet dx = Pervasives.compare goalx kx in\n\tlet dy = Pervasives.compare goaly ky in\n\tlet (kx,ky) = (kx+dx, ky+dy) in\n\tprintf \"%d %d\\n\" kx ky;\n\t(in_check (kx,ky), kx, ky)\n )\n in\n\n if terminal then false else (\n (* wait for a move from the other guy *)\n let line = read_ints() in\n let (k,x,y) = (line.(0), line.(1), line.(2)) in\n rook.(k) <- (x,y);\n move_to_goal (kx,ky) (goalx,goaly)\n )\n ) in\n\n if move_to_goal (kx,ky) (cx,cy) then (\n let count = Array.make_matrix 2 2 0 in\n for i=1 to nrooks do\n let wx = if fst rook.(i) < cx then 0 else 1 in\n let wy = if snd rook.(i) < cy then 0 else 1 in\n count.(wx).(wy) <- count.(wx).(wy) + 1\n done;\n let (_, i,j) =\n minf 0 1 (fun i ->\n\tminf 0 1 (fun j ->\n\t (count.(i).(j), i, j)\n\t)\n )\n in\n let goalx = [|0;maxx|].(1-i) in\n let goaly = [|0;maxy|].(1-j) in\n\n if move_to_goal (cx,cy) (goalx, goaly) then failwith \"bad\" else ()\n ) else (\n (* the game is already over *)\n )\n"}], "negative_code": [{"source_code": "Scanf.(Array.(scanf \" %d %d\" @@ fun x y ->\n let map = make_matrix 1000 1000 false in\n let rooks = make 666 (0,0) in\n init 666 (fun i ->\n scanf \" %d %d\" @@\n fun x y -> map.(x).(y) <- true;\n rooks.(i) <- x,y) |> ignore;\n let x,y = ref x,ref y in\n let rec move p q =\n if map.(!x+p).(!y+q) then (\n move p 0\n ) else (\n x := !x + p;\n y := !y + q;\n Printf.printf \"%d %d\\n\" !x !y; flush stdout;\n let i,u,v = scanf \" %d %d %d\" @@ fun p q r -> p,q,r in\n if i=0 && u=0 && v=0 then exit 0 (* WA *)\n else if i= -1 && u= -1 && v= -1 then exit 0 (* AC *)\n else (\n let pu,pv = rooks.(i-1) in\n map.(pu).(pv) <- false;\n map.( u).( v) <- true;\n rooks.(i-1) <- u,v;\n Printf.eprintf \"%d: %d,%d --> %d %d\\n\" i pu pv u v; flush stderr\n )\n )\n in\n while !x <> 499 || !y <> 499 do\n if !x < 499 then move 1 0\n else if !x > 499 then move (-1) 0\n else if !y < 499 then move 0 1\n else if !y > 499 then move 0 (-1)\n done;\n let tr,tl,bl,br = fold_left (fun (p,q,r,s) (x,y) ->\n match x>499, y>499 with\n (* t/f: right/left, top/bottom *)\n | true, true -> (p+1,q,r,s)\n | false, true -> (p,q+1,r,s)\n | false,false -> (p,q,r+1,s)\n | true,false -> (p,q,r,s+1)\n ) (0,0,0,0) rooks\n in\n let mn = fold_left min br [|tr;tl;bl|] in\n ignore @@ init 499 @@ fun _ ->\n if mn=tr then move (-1) (-1)\n else if mn=tl then move 1 (-1)\n else if mn=bl then move 1 1\n else move (-1) 1\n))"}, {"source_code": "(* 11:35 *)\nopen Printf\nopen String\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n \nlet split_string s = \n let s = trim s in\n \n let n = String.length s in\n let li = fold 0 (n-1) \n (fun i ac -> if s.[i] = ' ' then i::ac else ac) []\n in\n\n let rec chop prev li ac = \n match li with [] -> List.rev ac\n | i::tail -> \n\tchop i tail ((sub s (prev+1) (i-prev-1))::ac)\n in\n \n chop (-1) (List.rev (n::li)) []\n\nlet read_ints () = \n let c = split_string (read_line()) in\n let c = List.map (fun s -> int_of_string s) c in\n Array.of_list c\n\nlet () =\n let nrooks = 666 in\n let rook = Array.make (nrooks+1) (0,0) in\n\n let line1 = read_ints() in\n let (kx, ky) = (line1.(0), line1.(1)) in\n\n for i=1 to nrooks do\n let linei = read_ints() in\n rook.(i) <- (linei.(0), linei.(1));\n done;\n\n let in_check (kx,ky) =\n (* return true if this king is in check *)\n exists 1 nrooks (fun i ->\n let (x,y) = rook.(i) in\n x = kx || y = ky\n ) \n in\n\n let collide (kx,ky) =\n (* return true if the king is on top of a rook *)\n exists 1 nrooks (fun i -> rook.(i) = (kx,ky))\n in\n\n let dirs = [(-1,-1);(-1,0);(-1,1);(0,-1);(0,1);(1,-1);(1,0);(1,1)] in\n\n let rec move_to_goal (kx,ky) (goalx,goaly) = if kx = goalx && ky = goaly then true else (\n (* assume (kx,ky) has already been checked for being in check, or in a collision *)\n let check_dirs = List.filter (fun (dx,dy) ->\n let (nx,ny) = (kx+dx, ky+dy) in\n nx >= 1 && ny >= 1 && nx<=999 && ny <= 999 && in_check (nx,ny) && (not (collide (nx,ny)))\n ) dirs in\n\n let terminal = \n if check_dirs <> [] then (\n\tlet (dx,dy) = List.hd check_dirs in\n\tprintf \"%d %d\\n\" (kx+dx) (ky+dy);\n\ttrue (* found a winning move *)\n ) else (\n\tlet dx = Pervasives.compare goalx kx in\n\tlet dy = Pervasives.compare goaly ky in\n\tlet (kx,ky) = (kx+dx, ky+dy) in\n\tprintf \"%d %d\\n\" kx ky;\n\tin_check (kx,ky)\n )\n in\n\n if terminal then false else (\n (* wait for a move from the other guy *)\n let line = read_ints() in\n let (k,x,y) = (line.(0), line.(1), line.(2)) in\n rook.(k) <- (x,y);\n move_to_goal (kx,ky) (goalx,goaly)\n )\n ) in\n\n if move_to_goal (kx,ky) (500,500) then (\n let count = Array.make_matrix 2 2 0 in\n for i=1 to nrooks do\n let wx = if fst rook.(i) < 500 then 0 else 1 in\n let wy = if snd rook.(i) < 500 then 0 else 1 in\n count.(wx).(wy) <- count.(wx).(wy) + 1\n done;\n let (_, i,j) =\n minf 0 1 (fun i ->\n\tminf 0 1 (fun j ->\n\t (count.(i).(j), i, j)\n\t)\n )\n in\n let goalx = [|0;999|].(1-i) in\n let goaly = [|0;999|].(1-j) in\n\n if move_to_goal (500,500) (goalx, goaly) then () else failwith \"bad\"\n ) else (\n (* the game is already over *)\n )\n"}, {"source_code": "(* 11:35 *)\nopen Printf\nopen String\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n \nlet split_string s = \n let s = trim s in\n \n let n = String.length s in\n let li = fold 0 (n-1) \n (fun i ac -> if s.[i] = ' ' then i::ac else ac) []\n in\n\n let rec chop prev li ac = \n match li with [] -> List.rev ac\n | i::tail -> \n\tchop i tail ((sub s (prev+1) (i-prev-1))::ac)\n in\n \n chop (-1) (List.rev (n::li)) []\n\nlet read_ints () = \n let c = split_string (read_line()) in\n let c = List.map (fun s -> int_of_string s) c in\n Array.of_list c\n\nlet () =\n let nrooks = 666 in\n let rook = Array.make (nrooks+1) (0,0) in\n\n let line1 = read_ints() in\n let (kx, ky) = (line1.(0), line1.(1)) in\n\n for i=1 to nrooks do\n let linei = read_ints() in\n rook.(i) <- (linei.(0), linei.(1));\n done;\n\n let in_check (kx,ky) =\n (* return true if this king is in check *)\n exists 1 nrooks (fun i ->\n let (x,y) = rook.(i) in\n x = kx || y = ky\n ) \n in\n\n let collide (kx,ky) =\n (* return true if the king is on top of a rook *)\n exists 1 nrooks (fun i -> rook.(i) = (kx,ky))\n in\n\n let dirs = [(-1,-1);(-1,0);(-1,1);(0,-1);(0,1);(1,-1);(1,0);(1,1)] in\n\n let rec move_to_goal (kx,ky) (goalx,goaly) = if kx = goalx && ky = goaly then true else (\n (* assume (kx,ky) has already been checked for being in check, or in a collision *)\n let check_dirs = List.filter (fun (dx,dy) ->\n let (nx,ny) = (kx+dx, ky+dy) in\n nx >= 0 && ny >= 0 && nx<=999 && ny <= 999 && in_check (nx,ny) && (not (collide (nx,ny)))\n ) dirs in\n\n let terminal = \n if check_dirs <> [] then (\n\tlet (dx,dy) = List.hd check_dirs in\n\tprintf \"%d %d\\n\" (kx+dx) (ky+dy);\n\ttrue (* found a winning move *)\n ) else (\n\tlet dx = Pervasives.compare goalx kx in\n\tlet dy = Pervasives.compare goaly ky in\n\tlet (kx,ky) = (kx+dx, ky+dy) in\n\tprintf \"%d %d\\n\" kx ky;\n\tin_check (kx,ky)\n )\n in\n\n if terminal then false else (\n (* wait for a move from the other guy *)\n let line = read_ints() in\n let (k,x,y) = (line.(0), line.(1), line.(2)) in\n rook.(k) <- (x,y);\n move_to_goal (kx,ky) (goalx,goaly)\n )\n ) in\n\n if move_to_goal (kx,ky) (500,500) then (\n let count = Array.make_matrix 2 2 0 in\n for i=1 to nrooks do\n let wx = if fst rook.(i) < 500 then 0 else 1 in\n let wy = if snd rook.(i) < 500 then 0 else 1 in\n count.(wx).(wy) <- count.(wx).(wy) + 1\n done;\n let (_, i,j) =\n minf 0 1 (fun i ->\n\tminf 0 1 (fun j ->\n\t (count.(i).(j), i, j)\n\t)\n )\n in\n let goalx = [|0;999|].(1-i) in\n let goaly = [|0;999|].(1-j) in\n\n if move_to_goal (500,500) (goalx, goaly) then () else failwith \"bad\"\n ) else (\n (* the game is already over *)\n )\n"}], "src_uid": "3d38584c3bb29e6f84546643b1be8026"} {"nl": {"description": "You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string \"aba,123;1a;0\": \"aba\", \"123\", \"1a\", \"0\". A word can be empty: for example, the string s=\";;\" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings \"101\", \"0\" are INTEGER numbers, but \"01\" and \"1.0\" are not.For example, for the string aba,123;1a;0 the string a would be equal to \"123,0\" and string b would be equal to \"aba,1a\".", "input_spec": "The only line of input contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.", "output_spec": "Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.", "sample_inputs": ["aba,123;1a;0", "1;;01,a0,", "1", "a"], "sample_outputs": ["\"123,0\"\n\"aba,1a\"", "\"1\"\n\",01,a0,\"", "\"1\"\n-", "-\n\"a\""], "notes": "NoteIn the second example the string s contains five words: \"1\", \"\", \"01\", \"a0\", \"\"."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let s1 = ref [] in\n let s2 = ref [] in\n let cs = ref [] in\n let d = ref true in\n let s = s ^ \";\" in\n for i = 0 to String.length s - 1 do\n let c = s.[i] in\n\tmatch c with\n\t | ',' | ';' -> (\n\t let cs' = List.rev !cs in\n\t let dd =\n\t\tif !d then (\n\t\t match cs' with\n\t\t | ['0'] -> true\n\t\t | []\n\t\t | '0' :: _ -> false\n\t\t | _ -> true\n\t\t) else false\n\t in\n\t\td := true;\n\t\tcs := [];\n\t\tif dd\n\t\tthen s1 := cs' :: !s1\n\t\telse s2 := cs' :: !s2\n\t )\n\t | '0'..'9' ->\n\t cs := c :: !cs;\n\t | 'a'..'z' | 'A'..'Z' | '.' ->\n\t d := false;\n\t cs := c :: !cs;\n\t | _ -> assert false\n done;\n let print ss =\n let ss = List.rev ss in\n\tif ss = []\n\tthen Printf.printf \"-\\n\"\n\telse (\n\t let first = ref true in\n\t Printf.printf \"\\\"\";\n\t List.iter\n\t (fun cs ->\n\t\t if not !first\n\t\t then Printf.printf \",\";\n\t\t List.iter (Printf.printf \"%c\") cs;\n\t\t first := false;\n\t ) ss;\n\t Printf.printf \"\\\"\\n\"\n\t)\n in\n print !s1;\n print !s2\n"}], "negative_code": [], "src_uid": "ad02cead427d0765eb642203d13d3b99"} {"nl": {"description": "You are given sequence a1,\u2009a2,\u2009...,\u2009an and m queries lj,\u2009rj (1\u2009\u2264\u2009lj\u2009\u2264\u2009rj\u2009\u2264\u2009n). For each query you need to print the minimum distance between such pair of elements ax and ay (x\u2009\u2260\u2009y), that: both indexes of the elements lie within range [lj,\u2009rj], that is, lj\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009rj; the values of the elements are equal, that is ax\u2009=\u2009ay. The text above understands distance as |x\u2009-\u2009y|.", "input_spec": "The first line of the input contains a pair of integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20095\u00b7105) \u2014 the length of the sequence and the number of queries, correspondingly. The second line contains the sequence of integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109). Next m lines contain the queries, one per line. Each query is given by a pair of numbers lj,\u2009rj (1\u2009\u2264\u2009lj\u2009\u2264\u2009rj\u2009\u2264\u2009n) \u2014 the indexes of the query range limits.", "output_spec": "Print m integers \u2014 the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query.", "sample_inputs": ["5 3\n1 1 2 3 2\n1 5\n2 4\n3 5", "6 5\n1 2 1 3 2 3\n4 6\n1 3\n2 5\n2 4\n1 6"], "sample_outputs": ["1\n-1\n2", "2\n2\n3\n-1\n2"], "notes": null}, "positive_code": [{"source_code": "(*[@@@warning \"-30\"]*)\n\ntype node = {\n l : int;\n r : int;\n x : int;\n left : node;\n right : node\n}\n\nlet rec dummy = { l = 0; r = -1; x = -1; left = dummy; right = dummy }\n\nlet build_min a =\n let next l a a' =\n let rec next i i' =\n if i > l - 1 then i'\n else if i = l - 1 then begin a'.(i') <- a.(i); i' + 1 end\n else begin\n let left = a.(i) and right = a.(i + 1) in\n a'.(i') <- { l = left.l; r = right.r; x = min left.x right.x; left; right };\n next (i + 2) (i' + 1)\n end\n in\n next\n in\n let rec build l a =\n match l with\n | 0 -> dummy\n | 1 -> a.(0)\n | l ->\n let a' = Array.make (l / 2 + 1) dummy in\n let l' = next l a a' 0 0 in\n build l' a'\n in\n let a = Array.mapi (fun i x -> { l = i; r = i; x; left = dummy; right = dummy}) a in\n build (Array.length a) a\n\nlet many = 10000000\n\nlet find_min root l r =\n let rec find root =\n if root.r < l || root.l > r then many\n else if l <= root.l && root.r <= r then root.x\n else\n min (find root.left) (find root.right)\n in\n find root\n\ntype cmp = Lt | Gt | Eq\n\ntype return = Left | Right\n\nlet search compare return arr =\n let rec search l r =\n if r = l + 1 then Some (match return with Left -> l | Right -> r)\n else\n let m = l + (r - l) / 2 in\n match compare arr.(m) with\n | Eq -> Some m\n | Lt -> search m r\n | Gt -> search l m\n in\n let l = 0 and r = Array.length arr - 1 in\n if r < l then None\n else\n let cl = compare arr.(l) and cr = compare arr.(r) in\n if cl = Gt then (if return = Right then Some l else None)\n else if cr = Lt then (if return = Left then Some r else None)\n else if cl = Eq then Some l\n else if cr = Eq then Some r\n else search l r\n\nlet cmp (a : int) b = if a < b then Lt else if a > b then Gt else Eq\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let ns = Array.(init n (fun i -> scanf \"%d \" @@ fun x -> x, i)) in\n Array.sort compare ns;\n let lrs = ref [] in\n Array.iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;\n let lrs = Array.of_list !lrs in\n Array.sort compare lrs;\n let s = Stack.create () in\n Array.iter\n (fun (_, r as lr) ->\n while not (Stack.is_empty s) && snd (Stack.top s) > r do ignore (Stack.pop s) done;\n Stack.push lr s)\n lrs;\n let lrs = Array.init (Stack.length s) (fun _ -> Stack.pop s) in\n (let l = Array.length lrs in\n for i = 0 to l / 2 - 1 do let t = lrs.(l - i - 1) in lrs.(l - i - 1) <- lrs.(i); lrs.(i) <- t done);\n let search_left l' = search (fun (l, _) -> cmp l l') Right lrs in\n let search_right r' = search (fun (_, r) -> cmp r r') Left lrs in\n let root = build_min @@ Array.map (fun (l, r) -> r - l) lrs in\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r ->\n match search_left (l - 1), search_right (r - 1) with\n | Some l, Some r ->\n Printf.printf \"%d\\n\" (let r = find_min root l r in if r = many then -1 else r)\n | _ -> Printf.printf \"-1\\n\"\n done\n"}, {"source_code": "open Stack\nopen Array\n\ntype node = {\n l : int;\n r : int;\n x : int;\n left : node;\n right : node\n}\n\nlet rec dummy = { l = 0; r = -1; x = -1; left = dummy; right = dummy }\n\nlet build_min a =\n let next l a a' =\n let rec next i i' =\n if i > l - 1 then i'\n else if i = l - 1 then (a'.(i') <- a.(i); i' + 1)\n else\n let left = a.(i) and right = a.(i + 1) in\n a'.(i') <- { l = left.l; r = right.r; x = min left.x right.x; left; right };\n next (i + 2) (i' + 1)\n in\n next\n in\n let rec build l a =\n match l with\n | 0 -> dummy\n | 1 -> a.(0)\n | l ->\n let a' = make (l / 2 + 1) dummy in\n let l' = next l a a' 0 0 in\n build l' a'\n in\n let a = mapi (fun i x -> { l = i; r = i; x; left = dummy; right = dummy}) a in\n build (length a) a\n\nlet many = 10000000\n\nlet find_min root l r =\n let rec find root =\n if root.r < l || root.l > r then many\n else if l <= root.l && root.r <= r then root.x\n else min (find root.left) (find root.right)\n in\n find root\n\nlet search compare return arr =\n let rec search l r =\n if r = l + 1 then Some (match return with `Left -> l | `Right -> r)\n else\n let m = l + (r - l) / 2 in\n match compare arr.(m) with\n | `Eq -> Some m\n | `Lt -> search m r\n | `Gt -> search l m\n in\n let l = 0 and r = length arr - 1 in\n if r < l then None\n else\n let cl = compare arr.(l) and cr = compare arr.(r) in\n if cl = `Gt then (if return = `Right then Some l else None)\n else if cr = `Lt then (if return = `Left then Some r else None)\n else if cl = `Eq then Some l\n else if cr = `Eq then Some r\n else search l r\n\nlet cmp (a : int) b = if a < b then `Lt else if a > b then `Gt else `Eq\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let ns = init n (fun i -> scanf \"%d \" @@ fun x -> x, i) in\n sort compare ns;\n let lrs = ref [] in\n iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;\n let lrs = of_list !lrs in\n sort compare lrs;\n let s = Stack.create () in\n iter\n (fun (_, r as lr) ->\n while not (is_empty s) && snd (top s) > r do ignore (pop s) done;\n push lr s)\n lrs;\n let lrs = init (Stack.length s) (fun _ -> pop s) in\n (let l = length lrs in\n for i = 0 to l / 2 - 1 do let t = lrs.(l - i - 1) in lrs.(l - i - 1) <- lrs.(i); lrs.(i) <- t done);\n let search_left l' = search (fun (l, _) -> cmp l l') `Right lrs in\n let search_right r' = search (fun (_, r) -> cmp r r') `Left lrs in\n let root = build_min @@ map (fun (l, r) -> r - l) lrs in\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r ->\n match search_left (l - 1), search_right (r - 1) with\n | Some l, Some r ->\n Printf.printf \"%d\\n\" (let r = find_min root l r in if r = many then -1 else r)\n | _ -> Printf.printf \"-1\\n\"\n done\n"}, {"source_code": "open Stack\nopen Array\n\nlet upd_min a n i (v : int) =\n let rec upd p l r =\n if l <= i && i <= r then begin\n if v < a.(p) then a.(p) <- v;\n if r - l >= 1 then\n let m = l + (r - l) / 2 in\n upd (p lsl 1 + 1) l m;\n upd ((p + 1) lsl 1) (m + 1) r\n end\n in\n upd 0 0 (n - 1)\n\nlet big_n = 10000000\n\nlet find_min a n l r =\n let rec find p l' r' =\n if r' < l || l' > r then big_n\n else if l <= l' && r' <= r then a.(p)\n else if r' - l' >= 1 then\n let m = l' + (r' - l') / 2 in\n min (find (p lsl 1 + 1) l' m) (find ((p + 1) lsl 1) (m + 1) r')\n else big_n\n in\n find 0 0 (n - 1)\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let ns = init n (fun i -> scanf \"%d \" @@ fun x -> x, i) in\n sort compare ns;\n let lrs = ref [] in\n iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;\n let lrs = of_list !lrs in\n sort compare lrs;\n let s = Stack.create () in\n iter\n (fun (_, r as lr) ->\n while not (is_empty s) && snd (top s) > r do ignore (pop s) done;\n push lr s)\n lrs;\n let lrs = init (Stack.length s) (fun _ -> pop s) in\n let len = length lrs in\n for i = 0 to len / 2 - 1 do let t = lrs.(len - i - 1) in lrs.(len - i - 1) <- lrs.(i); lrs.(i) <- t done;\n let ls, rs = make n ~-1, make n ~-1 in\n ignore @@ fold_left (fun (p, i) (l, _) -> for j = p + 1 to l do ls.(j) <- i done; l, i + 1) (~-1, 0) lrs;\n ignore @@ fold_right (fun (_, r) (p, i) -> for j = r to p - 1 do rs.(j) <- i done; r, i - 1) lrs (n, len - 1);\n let a = make (n * 3 + 1) big_n in\n iteri (fun i (l, r) -> upd_min a len i (r - l)) lrs;\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r ->\n let l = ls.(l - 1) and r = rs.(r - 1) in\n if l >= 0 && r >= 0 then Printf.printf \"%d\\n\" (let r = find_min a len l r in if r = big_n then -1 else r)\n else Printf.printf \"-1\\n\"\n done\n"}, {"source_code": "open Stack\nopen Array\n\ntype node = {\n l : int;\n r : int;\n x : int;\n left : node;\n right : node\n}\n\nlet rec dummy = { l = 0; r = -1; x = -1; left = dummy; right = dummy }\n\nlet build_min a =\n let next l a a' =\n let rec next i i' =\n if i > l - 1 then i'\n else if i = l - 1 then (a'.(i') <- a.(i); i' + 1)\n else\n let left = a.(i) and right = a.(i + 1) in\n a'.(i') <- { l = left.l; r = right.r; x = min left.x right.x; left; right };\n next (i + 2) (i' + 1)\n in\n next\n in\n let rec build l a =\n match l with\n | 0 -> dummy\n | 1 -> a.(0)\n | l ->\n let a' = make (l / 2 + 1) dummy in\n let l' = next l a a' 0 0 in\n build l' a'\n in\n let a = mapi (fun i x -> { l = i; r = i; x; left = dummy; right = dummy}) a in\n build (length a) a\n\nlet many = 10000000\n\nlet find_min root l r =\n let rec find root =\n if root.r < l || root.l > r then many\n else if l <= root.l && root.r <= r then root.x\n else min (find root.left) (find root.right)\n in\n find root\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let ns = init n (fun i -> scanf \"%d \" @@ fun x -> x, i) in\n sort compare ns;\n let lrs = ref [] in\n iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;\n let lrs = of_list !lrs in\n sort compare lrs;\n let s = Stack.create () in\n iter\n (fun (_, r as lr) ->\n while not (is_empty s) && snd (top s) > r do ignore (pop s) done;\n push lr s)\n lrs;\n let lrs = init (Stack.length s) (fun _ -> pop s) in\n let l = length lrs in\n for i = 0 to l / 2 - 1 do let t = lrs.(l - i - 1) in lrs.(l - i - 1) <- lrs.(i); lrs.(i) <- t done;\n let ls, rs = make n ~-1, make n ~-1 in\n ignore @@ fold_left (fun (p, i) (l, _) -> for j = p + 1 to l do ls.(j) <- i done; l, i + 1) (~-1, 0) lrs;\n ignore @@ fold_right (fun (_, r) (p, i) -> for j = r to p - 1 do rs.(j) <- i done; r, i - 1) lrs (n, l - 1);\n let root = build_min @@ map (fun (l, r) -> r - l) lrs in\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r ->\n let l = ls.(l - 1) and r = rs.(r - 1) in\n if l >= 0 && r >= 0 then Printf.printf \"%d\\n\" (let r = find_min root l r in if r = many then -1 else r)\n else Printf.printf \"-1\\n\"\n done\n"}], "negative_code": [{"source_code": "\ntype sub = {\n mutable bl : node;\n mutable br : node;\n mutable tr : node\n}\nand node =\n | Empty\n | Node of int ref * sub\n\ntype tree = { mutable root : node; size : int }\n\nlet empty = 0, -1, 0, -1\n\nlet split (lmin, lmax, rmin, rmax) =\n let lmid = lmin + (lmax - lmin) / 2 in\n let rmid = rmin + (rmax - rmin) / 2 in\n if lmin < lmax && rmin < rmax then\n (lmin, lmid, rmin, rmid),\n (lmin, lmid, rmid + 1, rmax),\n (lmid + 1, lmax, rmid + 1, rmax)\n else if lmin < lmax then\n (lmin, lmid, rmin, rmax),\n empty,\n (lmid + 1, lmax, rmin, rmax)\n else if rmin < rmax then\n (lmin, lmax, rmin, rmid),\n (lmin, lmax, rmid + 1, rmax),\n empty\n else\n empty, empty, empty\n\nlet add ({ root; size } as t) l r =\n let dist = r - l in\n let rec add (lmin, lmax, rmin, rmax as rect) t =\n if lmin <= l && l <= lmax && rmin <= r && r <= rmax then\n match t with\n | Empty ->\n let r = { bl = Empty; br = Empty; tr = Empty } in\n add' rect r;\n Node (ref dist, r)\n | Node (min, r) as node ->\n add' rect r;\n if dist < !min then min := dist;\n node\n else t\n and add' rect r =\n let bl, br, tr = split rect in\n r.bl <- add bl r.bl;\n r.br <- add br r.br;\n r.tr <- add tr r.tr\n in\n t.root <- add (0, size - 1, 0, size - 1) root\n\nlet none = max_int\n\nlet min { root; size } l r =\n let rec min (lmin, lmax, rmin, rmax as rect) =\n function\n | Empty -> none\n | _ when lmin > lmax || rmin > rmax -> none\n | Node (m, _)\n when l <= lmin && lmax <= r && l <= rmin && rmax <= r -> !m\n | Node _\n when r < lmin || l > lmax || r < rmin || l > rmax -> none\n | Node (_, rct) ->\n let bl, br, tr = split rect in\n let bl = min bl rct.bl and br = min br rct.br and tr = min tr rct.tr in\n let br = if bl < br then bl else br in\n if br < tr then br else tr\n in\n min (0, size - 1, 0, size - 1) root\n\ntype element = { v : int64; i : int }\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let seq = Array.init n (fun i -> scanf \"%Ld \" @@ fun v -> { v; i }) in\n Array.sort\n (fun e1 e2 ->\n let r = Int64.compare e1.v e2.v in\n if r <> 0 then r else compare e1.i e2.i)\n seq;\n let t = { root = Empty; size = n } in\n Array.iteri (fun i v -> if i < n - 1 && v.v = seq.(i + 1).v then add t v.i seq.(i + 1).i) seq;\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r -> Printf.printf \"%d\\n\" @@ let m = min t (l - 1) (r - 1) in if m = none then -1 else m\n done\n\n"}, {"source_code": "\ntype sub = {\n mutable bl : node;\n mutable br : node;\n mutable tr : node\n}\nand node =\n | Empty\n | Node of int ref * sub\n\ntype tree = { mutable root : node; size : int }\n\nlet empty = 0, -1, 0, -1\n\nlet split (lmin, lmax, rmin, rmax) =\n let lmid = lmin + (lmax - lmin) / 2 in\n let rmid = rmin + (rmax - rmin) / 2 in\n if lmin < lmax && rmin < rmax then\n (lmin, lmid, rmin, rmid),\n (lmin, lmid, rmid + 1, rmax),\n (lmid + 1, lmax, rmid + 1, rmax)\n else if lmin < lmax then\n (lmin, lmid, rmin, rmax),\n (lmid + 1, lmax, rmin, rmax),\n empty\n else if rmin < rmax then\n (lmin, lmax, rmin, rmid),\n (lmin, lmax, rmid + 1, rmax),\n empty\n else\n empty, empty, empty\n\nlet add ({ root; size } as t) l r =\n let dist = r - l in\n let rec add (lmin, lmax, rmin, rmax as rect) t =\n if lmin <= l && l <= lmax && rmin <= r && r <= rmax then\n match t with\n | Empty ->\n let r = { bl = Empty; br = Empty; tr = Empty } in\n add' rect r;\n Node (ref dist, r)\n | Node (min, r) as node ->\n add' rect r;\n if dist < !min then min := dist;\n node\n else t\n and add' rect r =\n let bl, br, tr = split rect in\n r.bl <- add bl r.bl;\n r.br <- add br r.br;\n r.tr <- add tr r.tr\n in\n t.root <- add (0, size - 1, 0, size - 1) root\n\nlet none = max_int\n\nlet min { root; size } l r =\n let rec min (lmin, lmax, rmin, rmax as rect) =\n function\n | Empty -> none\n | Node (m, _)\n when l <= lmin && lmax <= r && l <= rmin && rmax <= r -> !m\n | Node _\n when r < lmin || l > lmax || r < rmin || l > rmax -> none\n | Node (_, rct) ->\n let bl, br, tr = split rect in\n let bl = min bl rct.bl and br = min br rct.br and tr = min tr rct.tr in\n let br = if bl < br then bl else br in\n if br < tr then br else tr\n in\n min (0, size - 1, 0, size - 1) root\n\ntype element = { v : int; i : int }\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let seq = Array.init n (fun i -> scanf \"%d \" @@ fun v -> { v; i }) in\n Array.sort compare seq;\n let t = { root = Empty; size = n } in\n Array.iteri (fun i v -> if i < n - 1 && v.v = seq.(i + 1).v then add t v.i seq.(i + 1).i) seq;\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r -> Printf.printf \"%d\\n\" @@ let m = min t (l - 1) (r - 1) in if m = none then -1 else m\n done\n\n"}, {"source_code": "\ntype sub = {\n mutable bl : node;\n mutable br : node;\n mutable tl : node;\n mutable tr : node\n}\nand node =\n | Empty\n | Node of int * sub\n\ntype tree = { mutable root : node; size : int }\n\nlet split (lmin, lmax, rmin, rmax) =\n let lmid = lmin + (lmax - lmin) / 2 in\n let rmid = rmin + (rmax - rmin) / 2 in\n let empty = 0, -1, 0, -1 in\n if lmin < lmax && rmin < rmax then\n (lmin, lmid, rmin, rmid),\n (lmin, lmid, rmid + 1, rmax),\n (lmid + 1, lmax, rmin, rmid),\n (lmid + 1, lmax, rmid + 1, rmax)\n else if lmin < lmax then\n (lmin, lmid, rmin, rmax),\n empty,\n (lmid + 1, lmax, rmin, rmax),\n empty\n else if rmin < rmax then\n (lmin, lmax, rmin, rmid),\n (lmin, lmax, rmid + 1, rmax),\n empty,\n empty\n else\n empty, empty, empty, empty\n\nlet inside l r (lmin, lmax, rmin, rmax) =\n lmin <= l && l <= lmax && rmin <= r && r <= rmax\n\nlet add ({ root; size } as t) l r =\n let dist = r - l in\n let rec add rect =\n if inside l r rect then\n let add r =\n let bl, br, tl, tr = split rect in\n r.bl <- add bl r.bl;\n r.br <- add br r.br;\n r.tl <- add tl r.tl;\n r.tr <- add tr r.tr\n in\n function\n | Empty ->\n let r = { bl = Empty; br = Empty; tl = Empty; tr = Empty } in\n add r;\n Node (dist, r)\n | Node (min, r) as node ->\n add r;\n if dist < min then Node (dist, r) else node\n else fun x -> x\n in\n t.root <- add (0, size - 1, 0, size - 1) root\n\nlet none = -1\n\nlet min4 x y z k =\n let min x y = if x = none then y else if y = none then x else if x < y then x else y in\n List.fold_left min none [x; y; z; k]\n\nlet min { root; size } l r =\n let rec min (lmin, lmax, rmin, rmax as rect) =\n function\n | Empty -> none\n | Node _\n when not (inside l l rect || inside l r rect || inside r l rect || inside r r rect) -> none\n | Node (m, rct) ->\n if l <= lmin && lmax <= r && l <= rmin && rmax <= r then m\n else\n let bl, br, tl, tr = split rect in\n min4 (min bl rct.bl) (min br rct.br) (min tl rct.tl) (min tr rct.tr)\n in\n min (0, size - 1, 0, size - 1) root\n\ntype element = { v : int; i : int }\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let seq = Array.init n (fun i -> scanf \"%d \" @@ fun v -> { v; i }) in\n Array.sort compare seq;\n let t = { root = Empty; size = n } in\n Array.iteri (fun i v -> if i < n - 1 && v.v = seq.(i + 1).v then add t v.i seq.(i + 1).i) seq;\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r -> Printf.printf \"%d\\n\" @@ min t (l - 1) (r - 1)\n done\n\n"}, {"source_code": "type cmp = Le | Gt\n\nlet cmp a b =\n if a <= b then Le\n else Gt\n\ntype node = {\n l : int;\n r : int;\n mutable ll : quadr;\n mutable lr : quadr;\n mutable rl : quadr;\n mutable rr : quadr;\n}\nand quadr = Some of node | None\n\nlet rec merge a b =\n match a, b with\n | None, None -> None\n | Some _, None -> a\n | None, Some _ -> b\n | Some p, Some c ->\n let lp, rp, lc, rc, p, c, r =\n match cmp (abs (p.r - p.l)) (abs (c.r - c.l)) with\n | Le -> p.l, p.l, c.l, c.l, a, b, p\n | Gt -> c.l, c.r, p.l, p.r, b, a, c\n in\n begin match cmp lp lc, cmp rp rc with\n | Le, Le -> r.ll <- merge r.ll c\n | Le, Gt -> r.lr <- merge r.lr c\n | Gt, Le -> r.rl <- merge r.rl c\n | Gt, Gt -> r.rr <- merge r.rr c\n end;\n p\n\nlet add (l, r) t = merge t (Some { l; r; ll = None; lr = None; rl = None; rr = None })\n\nlet rec find t ((l, r) as e) =\n match t with\n | None -> -1\n | Some { l = l'; r = r'; ll; lr; rl; rr } ->\n let try2 a b =\n let a, b = find a e, find b e in\n match cmp 0 a, cmp 0 b, cmp a b with\n | Le, Le, Le -> a\n | Le, Le, Gt -> b\n | Le, Gt, _ -> a\n | Gt, Le, _ -> b\n | Gt, Gt, _ -> -1\n in\n match cmp l l', cmp r' r, cmp l' r, cmp l r' with\n | Le, Le, _, _ -> abs (r' - l')\n | Le, Gt, Le, _ -> try2 lr rr\n | Le, Gt, Gt, _ -> find rr e\n | Gt, Le, _, Le -> try2 ll lr\n | Gt, Le, _, Gt -> find ll e\n | Gt, Gt, _, _ -> find lr e\n\nlet (@@) a b = a b\n\nexception End of quadr\n\nlet () =\n Scanf.scanf \"%d %d\\n\" @@ fun n m ->\n let a = Array.init n (fun i -> Scanf.scanf \" %d\" @@ fun x -> (x, i)) in\n Array.sort (fun (a, i) (a', i') -> let r = compare a a' in if r <> 0 then r else compare i i') a;\n let t = Array.make (n - 1) ((0, 0), n) in\n Array.iteri\n (fun i (c, ci) ->\n if i > 0 then\n let p, pi = a.(i - 1) in\n if p = c then\n t.(i - 1) <- (pi, ci), Random.int n)\n a;\n Array.sort (fun (_, k) (_, k') -> compare k k') t;\n let t = try Array.fold_left (fun t (e, k)-> if k < n then add e t else raise (End t)) None t with End t -> t in\n for i = 1 to m do\n Scanf.scanf \" %d %d\" @@ fun l r -> Printf.printf \"%d\\n\" @@ find t (l - 1, r - 1)\n done\n"}, {"source_code": "\ntype sub = {\n mutable bl : node;\n mutable br : node;\n mutable tr : node\n}\nand node =\n | Empty\n | Node of int ref * sub\n\ntype tree = { mutable root : node; size : int }\n\nlet empty = 0, -1, 0, -1\n\nlet split (lmin, lmax, rmin, rmax) =\n let lmid = lmin + (lmax - lmin) / 2 in\n let rmid = rmin + (rmax - rmin) / 2 in\n if lmin < lmax && rmin < rmax then\n (lmin, lmid, rmin, rmid),\n (lmin, lmid, rmid + 1, rmax),\n (lmid + 1, lmax, rmid + 1, rmax)\n else if lmin < lmax then\n (lmin, lmid, rmin, rmax),\n empty,\n (lmid + 1, lmax, rmin, rmax)\n else if rmin < rmax then\n (lmin, lmax, rmin, rmid),\n (lmin, lmax, rmid + 1, rmax),\n empty\n else\n empty, empty, empty\n\nlet add ({ root; size } as t) l r =\n let dist = r - l in\n let rec add (lmin, lmax, rmin, rmax as rect) t =\n if lmin <= l && l <= lmax && rmin <= r && r <= rmax then\n match t with\n | Empty ->\n let r = { bl = Empty; br = Empty; tr = Empty } in\n add' rect r;\n Node (ref dist, r)\n | Node (min, r) as node ->\n add' rect r;\n if dist < !min then min := dist;\n node\n else t\n and add' rect r =\n let bl, br, tr = split rect in\n r.bl <- add bl r.bl;\n r.br <- add br r.br;\n r.tr <- add tr r.tr\n in\n t.root <- add (0, size - 1, 0, size - 1) root\n\nlet none = max_int\n\nlet min { root; size } l r =\n let rec min (lmin, lmax, rmin, rmax as rect) =\n function\n | Empty -> none\n | Node (m, _)\n when l <= lmin && lmax <= r && l <= rmin && rmax <= r -> !m\n | Node _\n when r < lmin || l > lmax || r < rmin || l > rmax -> none\n | Node (_, rct) ->\n let bl, br, tr = split rect in\n let bl = min bl rct.bl and br = min br rct.br and tr = min tr rct.tr in\n let br = if bl < br then bl else br in\n if br < tr then br else tr\n in\n min (0, size - 1, 0, size - 1) root\n\ntype element = { v : int64; i : int }\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let seq = Array.init n (fun i -> scanf \"%Ld \" @@ fun v -> { v; i }) in\n Array.sort compare seq;\n let t = { root = Empty; size = n } in\n Array.iteri (fun i v -> if i < n - 1 && v.v = seq.(i + 1).v then add t v.i seq.(i + 1).i) seq;\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r -> Printf.printf \"%d\\n\" @@ let m = min t (l - 1) (r - 1) in if m = none then -1 else m\n done\n\n"}, {"source_code": "(*[@@@warning \"-30\"]*)\n\ntype node = {\n left : node option;\n mutable right : node option;\n mutable parent : node option;\n l : int;\n r : int;\n olca : olca\n}\nand olca = {\n uf : uf;\n mutable ancestor : node option;\n mutable colored : bool\n}\nand uf = {\n mutable parent : node option;\n mutable rank : int\n}\n\nmodule H = Hashtbl.Make(struct type t = node let equal = (==) let hash n = n.l end)\n\nlet olca () = { uf = { parent = None; rank = 0 }; ancestor = None; colored = false }\n\nlet rec add curr l r =\n match curr with\n | Some curr when curr.r - curr.l < r - l ->\n let olca = olca () in\n begin match curr.right with\n | Some right as left ->\n let node = Some { left; right = None; parent = Some curr; l; r; olca } in\n right.parent <- node;\n curr.right <- node;\n node\n | None ->\n let node = Some { left = None; right = None; parent = Some curr; l; r; olca } in\n curr.right <- node;\n node\n end\n | Some curr ->\n begin match curr.parent with\n | Some _ as p -> add p l r\n | None ->\n let node = Some { left = Some curr; right = None; parent = None; l; r; olca = olca () } in\n curr.parent <- node;\n node\n end\n | None -> Some { left = None; right = None; parent = None; l; r; olca = olca () }\n\nexception Empty_tree\n\nlet of_some = function Some x -> x | None -> raise Empty_tree\n\nlet tarjan_olca queries =\n let init n =\n n.olca.uf.parent <- Some n;\n n.olca.uf.rank <- 0\n in\n let rec find n =\n match n.olca.uf.parent with\n | Some n' when n' == n -> n\n | Some n' ->\n let p = find n' in\n n.olca.uf.parent <- Some p;\n p\n | None -> assert false\n in\n let union u v =\n let u, v = find u, find v in\n if u.olca.uf.rank > v.olca.uf.rank then\n v.olca.uf.parent <- Some u\n else if u.olca.uf.rank < v.olca.uf.rank then\n u.olca.uf.parent <- Some v\n else if u != v then begin\n v.olca.uf.parent <- Some u;\n u.olca.uf.rank <- u.olca.uf.rank + 1\n end\n in\n let rec tarjan u =\n init u;\n u.olca.ancestor <- Some u;\n let recur v =\n tarjan v;\n union u v;\n (find u).olca.ancestor <- Some u\n in\n let handle =\n match u.parent with\n | None -> (function Some v -> recur v | None -> ())\n | Some v' -> function Some v -> if v != v' then recur v | None -> ()\n in\n handle u.left;\n handle u.right;\n u.olca.colored <- true;\n try\n H.iter\n (fun v a ->\n if v.olca.colored then\n let r = of_some (find v).olca.ancestor in\n a := r;\n H.find (H.find queries v) u := r)\n (H.find queries u)\n with\n | Not_found -> ()\n in\n tarjan\n\ntype cmp = Lt | Gt | Eq\n\nlet search compare return arr =\n let rec search l r =\n if r = l + 1 then Some (return (arr.(l), arr.(r)))\n else\n let m = l + (r - l) / 2 in\n match compare arr.(m) with\n | Eq -> Some arr.(m)\n | Lt -> search m r\n | Gt -> search l m\n in\n let l = 0 and r = Array.length arr - 1 in\n if compare arr.(l) = Gt || compare arr.(r) = Lt then None\n else if compare arr.(l) = Eq then Some arr.(l)\n else if compare arr.(r) = Eq then Some arr.(r)\n else search l r\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let ns = Array.init n (fun i -> scanf \"%d \" @@ fun x -> x, i) in\n Array.sort compare ns;\n let lrs = ref [] in\n Array.iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;\n let lrs = Array.of_list !lrs in\n Array.sort compare lrs;\n let lrs' = ref [] in\n try\n let root =\n let r =\n of_some @@ Array.fold_left (fun root (l, r) -> let r = add root l r in lrs' := of_some r :: !lrs'; r) None lrs\n in\n let rec root r = match r.parent with None -> r | Some p -> root p in\n root r\n in\n let lrs' = Array.of_list @@ List.rev !lrs' in\n let queries, queries_list = H.create 32, ref [] in\n let add_query u v =\n H.replace\n (try H.find queries u with Not_found -> let h = H.create 16 in H.replace queries u h; h)\n v\n (ref root)\n in\n let add_query l r u v = add_query u v; add_query v u; queries_list := Some (l, r, u, v) :: !queries_list in\n let cmp a b = if a < b then Lt else if b < a then Gt else Eq in\n let search_left l' = search (fun { l; _ } -> cmp l l') snd lrs' in\n let search_right r' = search (fun { r; _ } -> cmp r r') fst lrs' in\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r ->\n match search_left (l - 1), search_right (r - 1) with\n | Some u, Some v -> add_query (l - 1) (r - 1) u v\n | _ -> queries_list := None :: !queries_list\n done;\n tarjan_olca queries root;\n List.iter Printf.(\n function\n | None -> printf \"-1\\n\"\n | Some (l', r', u, v) ->\n let { l; r; _ } = !H.(find (find queries u) v) in\n if l' <= l && r <= r' then printf \"%d\\n\" (r - l)\n else printf \"-1\\n\")\n (List.rev !queries_list)\n with\n | Empty_tree -> for _ = 1 to m do Printf.printf \"-1\\n\" done\n"}, {"source_code": "(*[@@@warning \"-30\"]*)\n\ntype node = {\n l : int;\n r : int;\n x : int;\n left : node option;\n right : node option\n}\n\nlet build f l =\n let rec next acc =\n function\n | [] -> List.rev acc\n | [x] -> List.rev (x :: acc)\n | x :: y :: xs ->\n next ({ l = x.l; r = y.r; x = f x.x y.x; left = Some x; right = Some y } :: acc) xs\n in\n let next = next [] in\n let rec build =\n function\n | [] -> { l = 0; r = -1; x = -1; left = None; right = None }\n | [root] -> root\n | layer -> build (next layer)\n in\n build @@ List.mapi (fun i x -> { l = i; r = i; x; left = None; right = None}) l\n\nlet find f root l r =\n let rec find root =\n if l <= root.l && root.r <= r then [root.x]\n else if root.r < l || root.l > r then []\n else\n let map = function None -> [] | Some t -> find t in\n let l = map root.left @ map root.right in\n match l with\n | [] -> []\n | _ :: _ -> List.[fold_left f (hd l) (tl l)]\n in\n find root\n\nlet build_min = build min and find_min = find min\n\ntype cmp = Lt | Gt | Eq\n\nlet search compare return arr =\n let rec search l r =\n if r = l + 1 then Some (return (l, r))\n else\n let m = l + (r - l) / 2 in\n match compare arr.(m) with\n | Eq -> Some m\n | Lt -> search m r\n | Gt -> search l m\n in\n let l = 0 and r = Array.length arr - 1 in\n if r < l || compare arr.(l) = Gt || compare arr.(r) = Lt then None\n else if compare arr.(l) = Eq then Some l\n else if compare arr.(r) = Eq then Some r\n else search l r\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let ns = Array.(init n (fun i -> scanf \"%d \" @@ fun x -> x, i)) in\n Array.sort compare ns;\n let lrs = ref [] in\n Array.iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;\n let lrs = Array.of_list !lrs in\n Array.sort compare lrs;\n let s = Stack.create () in\n Array.iter\n (fun (_, r as lr) ->\n while not (Stack.is_empty s) && snd (Stack.top s) > r do ignore (Stack.pop s) done;\n Stack.push lr s)\n lrs;\n let lrs =\n Array.(init (Stack.length s) (fun _ -> Stack.pop s) |>\n to_list |>\n List.rev |>\n of_list)\n in\n let cmp a b = if a < b then Lt else if a > b then Gt else Eq in\n let search_left l' = search (fun (l, _) -> cmp l l') snd lrs in\n let search_right r' = search (fun (_, r) -> cmp r r') fst lrs in\n let root = build_min Array.(to_list @@ map (fun (l, r) -> r - l) lrs) in\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun l r ->\n match search_left (l - 1), search_right (r - 1) with\n | Some l, Some r ->\n Printf.printf \"%d\\n\" @@\n begin match find_min root l r with\n | [] -> -1\n | [x] -> x\n | l -> List.(fold_left min (hd l) (tl l))\n end\n | _ -> Printf.printf \"-1\\n\"\n done\n"}], "src_uid": "358da9c353708ba834d0348ba88c2d0c"} {"nl": {"description": "You are given a binary matrix $$$A$$$ of size $$$n \\times n$$$. Rows are numbered from top to bottom from $$$1$$$ to $$$n$$$, columns are numbered from left to right from $$$1$$$ to $$$n$$$. The element located at the intersection of row $$$i$$$ and column $$$j$$$ is called $$$A_{ij}$$$. Consider a set of $$$4$$$ operations: Cyclically shift all rows up. The row with index $$$i$$$ will be written in place of the row $$$i-1$$$ ($$$2 \\le i \\le n$$$), the row with index $$$1$$$ will be written in place of the row $$$n$$$. Cyclically shift all rows down. The row with index $$$i$$$ will be written in place of the row $$$i+1$$$ ($$$1 \\le i \\le n - 1$$$), the row with index $$$n$$$ will be written in place of the row $$$1$$$. Cyclically shift all columns to the left. The column with index $$$j$$$ will be written in place of the column $$$j-1$$$ ($$$2 \\le j \\le n$$$), the column with index $$$1$$$ will be written in place of the column $$$n$$$. Cyclically shift all columns to the right. The column with index $$$j$$$ will be written in place of the column $$$j+1$$$ ($$$1 \\le j \\le n - 1$$$), the column with index $$$n$$$ will be written in place of the column $$$1$$$. The $$$3 \\times 3$$$ matrix is shown on the left before the $$$3$$$-rd operation is applied to it, on the right\u00a0\u2014 after. You can perform an arbitrary (possibly zero) number of operations on the matrix; the operations can be performed in any order.After that, you can perform an arbitrary (possibly zero) number of new xor-operations: Select any element $$$A_{ij}$$$ and assign it with new value $$$A_{ij} \\oplus 1$$$. In other words, the value of $$$(A_{ij} + 1) \\bmod 2$$$ will have to be written into element $$$A_{ij}$$$. Each application of this xor-operation costs one burl. Note that the $$$4$$$ shift operations\u00a0\u2014 are free. These $$$4$$$ operations can only be performed before xor-operations are performed.Output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. A unitary matrix is a matrix with ones on the main diagonal and the rest of its elements are zeros (that is, $$$A_{ij} = 1$$$ if $$$i = j$$$ and $$$A_{ij} = 0$$$ otherwise).", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014the number of test cases in the test. The descriptions of the test cases follow. Before each test case, an empty line is written in the input. The first line of each test case contains a single number $$$n$$$ ($$$1 \\le n \\le 2000$$$) This is followed by $$$n$$$ lines, each containing exactly $$$n$$$ characters and consisting only of zeros and ones. These lines describe the values in the elements of the matrix. It is guaranteed that the sum of $$$n^2$$$ values over all test cases does not exceed $$$4 \\cdot 10^6$$$.", "output_spec": "For each test case, output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. In other words, print the minimum number of xor-operations it will take after applying cyclic shifts to the matrix for the $$$A$$$ matrix to become unitary.", "sample_inputs": ["4\n\n\n\n\n3\n\n010\n\n011\n\n100\n\n\n\n\n5\n\n00010\n\n00001\n\n10000\n\n01000\n\n00100\n\n\n\n\n2\n\n10\n\n10\n\n\n\n\n4\n\n1111\n\n1011\n\n1111\n\n1111"], "sample_outputs": ["1\n0\n2\n11"], "notes": "NoteIn the first test case, you can do the following: first, shift all the rows down cyclically, then the main diagonal of the matrix will contain only \"1\". Then it will be necessary to apply xor-operation to the only \"1\" that is not on the main diagonal.In the second test case, you can make a unitary matrix by applying the operation $$$2$$$\u00a0\u2014 cyclic shift of rows upward twice to the matrix."}, "positive_code": [{"source_code": "open Printf\nopen Char\nopen Scanf\nmodule LL = Int64\nlet ( !! ) x = LL.to_int x\nlet ( ++ ) x y = LL.add x y\nlet ( -- ) x y = LL.sub x y\nlet ( ** ) x y = LL.mul x y\nlet ( // ) x y = LL.div x y\nlet ( %% ) x y = LL.rem x y\nlet ( >> ) x y = (LL.compare x y) > 0\nlet ( << ) x y = (LL.compare x y) < 0\nlet ( == ) x y = (LL.compare x y) = 0\nlet rd_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet rd_ll _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x)\nlet rd_arr n = Array.init n rd_ll\nlet rd_str _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet rd_mat n m = Array.init n rd_str\n\nlet diag i j n = (i - j + n) mod n\nlet c2i ch = int_of_char ch - int_of_char '0'\nlet solve n mat = \n let s = ref 0 in\n let cnt = Array.init n (fun _ -> 0) in\n for i=0 to n-1 do\n for j=0 to n-1 do\n let d = diag i j n in \n let c = cnt.(d) in \n let x = c2i mat.(i).[j] in\n cnt.(d) <- (c + x);\n s := !s + x;\n done;\n done;\n let best = (Array.fold_right max cnt 0) in\n let offD = !s - best in\n n - best + offD\n\nlet () =\n let t = rd_int () in\n for i=1 to t do\n let n = rd_int () in\n let mat = rd_mat n n in\n printf \"%d\\n\" (solve n mat)\n done;"}, {"source_code": "open Printf\r\nopen Char\r\nopen Scanf\r\nmodule LL = Int64\r\nlet ( !! ) x = LL.to_int x\r\nlet ( ++ ) x y = LL.add x y\r\nlet ( -- ) x y = LL.sub x y\r\nlet ( ** ) x y = LL.mul x y\r\nlet ( // ) x y = LL.div x y\r\nlet ( %% ) x y = LL.rem x y\r\nlet ( >> ) x y = (LL.compare x y) > 0\r\nlet ( << ) x y = (LL.compare x y) < 0\r\nlet ( == ) x y = (LL.compare x y) = 0\r\nlet rd_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet rd_ll _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x)\r\nlet rd_arr n = Array.init n rd_ll\r\nlet rd_str _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\r\nlet rd_mat n m = Array.init n rd_str\r\n\r\nlet diag i j n = (i - j + n) mod n\r\nlet c2i ch = int_of_char ch - int_of_char '0'\r\nlet solve n mat = \r\n let cnt = Array.init n (fun _ -> 0) in\r\n let rec loop ij sum =\r\n match ij with\r\n | (-1, _) -> sum\r\n | (i, j) -> \r\n let d = diag i j n in\r\n let c = cnt.(d) in\r\n let x = c2i mat.(i).[j] in\r\n let di = if j-1 < 0 then 1 else 0 in\r\n cnt.(d) <- (c + x);\r\n loop (i-di, (j-1+n) mod n) (sum + x)\r\n in\r\n let s = loop (n-1, n-1) 0 in\r\n let onD = (Array.fold_right max cnt 0) in\r\n let offD = s - onD in\r\n n - onD + offD\r\n\r\nlet () =\r\n let t = rd_int () in\r\n for i=1 to t do\r\n let n = rd_int () in\r\n let mat = rd_mat n n in\r\n printf \"%d\\n\" (solve n mat)\r\n done;"}], "negative_code": [], "src_uid": "d174982b64cc9e8d8a0f4b8646f1157c"} {"nl": {"description": "You are given two integers $$$l$$$ and $$$r$$$, $$$l\\le r$$$. Find the largest possible value of $$$a \\bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\\ge a \\ge b \\ge l$$$.As a reminder, $$$a \\bmod b$$$ is a remainder we get when dividing $$$a$$$ by $$$b$$$. For example, $$$26 \\bmod 8 = 2$$$.", "input_spec": "Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ $$$(1\\le t\\le 10^4)$$$, denoting the number of test cases. Description of the test cases follows. The only line of each test case contains two integers $$$l$$$, $$$r$$$ ($$$1\\le l \\le r \\le 10^9$$$).", "output_spec": "For every test case, output the largest possible value of $$$a \\bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\\ge a \\ge b \\ge l$$$.", "sample_inputs": ["4\n1 1\n999999999 1000000000\n8 26\n1 999999999"], "sample_outputs": ["0\n1\n12\n499999999"], "notes": "NoteIn the first test case, the only allowed pair is $$$(a, b) = (1, 1)$$$, for which $$$a \\bmod b = 1 \\bmod 1 = 0$$$.In the second test case, the optimal choice is pair $$$(a, b) = (1000000000, 999999999)$$$, for which $$$a \\bmod b = 1$$$."}, "positive_code": [{"source_code": "(* OCaml template *)\nopen Printf\nopen Scanf\n\n(* Redefine operators for Int32 *)\n(*\nlet ( + ) = Int32.add;;\nlet ( - ) = Int32.sub;;\nlet ( * ) = Int32.mul;;\nlet ( / ) = Int32.div;;\nlet ( % ) = Int32.rem;;\n*)\n\n(* Redefine operators for Int64 *)\nlet ( + ) = Int64.add;;\nlet ( - ) = Int64.sub;;\nlet ( * ) = Int64.mul;;\nlet ( / ) = Int64.div;;\nlet ( % ) = Int64.rem;;\n\n(* Input *)\nlet read_int32 _ = bscanf Scanning.stdin \"%ld \" @@ fun x -> x;;\nlet read_int64 _ = bscanf Scanning.stdin \"%Ld \" @@ fun x -> x;;\n\n(* Output *)\nlet print_int32 n = printf \"%ld \" n;;\nlet print_int32_endl n = printf \"%ld\\n\" n;;\nlet print_int64 n = printf \"%Ld \" n;;\nlet print_int64_endl n = printf \"%Ld\\n\" n;;\n\n(* Utility functions *)\nlet comp f g x = f @@ g x;;\nlet rec fac n = if n = 0L then 1L else n * fac (n - 1L);;\nlet rec fib n = if n < 2L then n else fib (n - 2L) + fib (n - 1L);;\nlet sum = List.fold_left (+) 0L;;\n\n(* Solve test case *)\nlet solve l r = \n\tif r < 2L * l then\n\t\tr - l\n\telse \n\t\t(r - 1L) / 2L;;\n\n(* Main *)\nlet t = read_int ();;\n\nfor t' = 1 to t do\n\tlet l = read_int64 () in\n\t\tlet r = read_int64 () in\n\t\t\tprint_int64_endl @@ solve l r\ndone\n"}, {"source_code": "open Printf\r\nopen Scanf\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\r\n \r\nlet () = \r\n let cases = read_int () in\r\n for case = 1 to cases do\r\n let (a, b) = read_pair () in\r\n let c = b/2+1 in\r\n let result = \r\n if c >= a then b mod c\r\n else b mod a\r\n in\r\n printf \"%d\\n\" result\r\n done"}], "negative_code": [], "src_uid": "c34db7897f051b0de2f49f2696c6ee2f"} {"nl": {"description": "You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.", "input_spec": "The first line of input contains one integer number N (1\u2009\u2264\u2009N\u2009\u2264\u2009100\u2009000) \u2014 the number of points. Each of the following N lines contain two integer numbers X and Y (\u2009-\u200910\u2009000\u2009\u2264\u2009X,\u2009Y\u2009\u2264\u200910\u2009000) \u2014 the coordinates of points. Two or more points may coincide.", "output_spec": "The only line of output should contain the required sum of squares of distances between all pairs of points.", "sample_inputs": ["4\n1 1\n-1 -1\n1 -1\n-1 1"], "sample_outputs": ["32"], "notes": null}, "positive_code": [{"source_code": "let (+) = Int64.add\nlet ( * ) = Int64.mul\nlet ( - ) = Int64.sub\nlet two = Int64.one + Int64.one\nlet one = Int64.one\nlet zero = Int64.zero\n\nlet solve =\n let n = Scanf.scanf \"%Ld\\n\" (fun n -> n) in\n let readPoints() = Scanf.scanf \"%Ld %Ld\\n\" (fun x y -> (x,y)) in\n let rec readInput i (accX,accY) =\n match i with\n | i when i = n -> (List.rev accX,List.rev accY)\n | i -> let (x,y) = readPoints() in\n readInput (i+one) ((x::accX),(y::accY))\n in\n let rec sumpoints lst sum sqsum i acc =\n match lst with \n | [] -> acc\n | x::xs -> let newval = ((i-one)*(x*x)-two*x*sum+sqsum) in\n sumpoints xs (sum+x) (sqsum+(x*x)) (i+one) (acc+newval)\n in\n let xs,ys = readInput zero ([],[]) in\n Printf.printf \"%Ld\\n\" ((sumpoints xs zero zero one zero)+(sumpoints ys zero zero one zero))\n;;"}, {"source_code": "let (+) = Int64.add\nlet ( * ) = Int64.mul\nlet ( - ) = Int64.sub\nlet two = Int64.one + Int64.one\nlet one = Int64.one\nlet zero = Int64.zero\n\nlet solve =\n let n = Scanf.scanf \"%Ld\\n\" (fun n -> n) in\n let readPoints() = Scanf.scanf \"%Ld %Ld\\n\" (fun x y -> (x,y)) in\n let rec readInput i (accX,accY) =\n match i with\n | i when i = n -> (List.rev accX,List.rev accY)\n | i -> let (x,y) = readPoints() in\n readInput (i+one) ((x::accX),(y::accY))\n in\n let rec sumpoints lst sum sqsum i acc =\n match lst with \n | [] -> acc\n | x::xs -> let newval = ((i-one)*(x*x)-(two*x*sum)+sqsum) in\n sumpoints xs (sum+x) (sqsum+(x*x)) (i+one) (acc+newval)\n in\n let xs,ys = readInput zero ([],[]) in\n Printf.printf \"%Ld\\n\" ((sumpoints xs zero zero one zero)+(sumpoints ys zero zero one zero))\n;;\n \n"}], "negative_code": [{"source_code": "let solve =\n let n = Scanf.scanf \"%d\\n\" (fun n -> n) in\n let readPoints() = Scanf.scanf \"%d %d\\n\" (fun x y -> (x,y)) in\n let rec readInput i (accX,accY) =\n match i with\n | i when i = n -> (List.rev accX,List.rev accY)\n | i -> let (x,y) = readPoints() in\n readInput (i+1) ((x::accX),(y::accY))\n in\n let rec sumpoints lst sum sqsum i acc =\n match lst with \n | [] -> acc\n | x::xs -> let newval = ((i-1)*(x*x)-2*x*sum+sqsum) in\n sumpoints xs (sum+x) (sqsum+(x*x)) (i+1) (acc+newval)\n in\n let xs,ys = readInput 0 ([],[]) in\n Printf.printf \"%d\\n\" ((sumpoints xs 0 0 1 0)+(sumpoints ys 0 0 1 0))\n;;"}, {"source_code": "let solve =\n let n = Scanf.scanf \"%d\\n\" (fun n -> n) in\n let readPoints() = Scanf.scanf \"%d %d\\n\" (fun x y -> (x,y)) in\n let rec readInput i (accX,accY) =\n match i with\n | i when i = n -> (List.rev accX,List.rev accY)\n | i -> let (x,y) = readPoints() in\n readInput (i+1) ((x::accX),(y::accY))\n in\n let rec sumpoints lst sum sqsum i acc =\n match lst with \n | [] -> acc\n | x::xs -> let newval = ((i-1)*(x*x)-2*x*sum+sqsum) in\n sumpoints xs (sum+x) (sqsum+(x*x)) (i+1) (acc+newval)\n in\n let xs,ys = readInput 0 ([],[]) in\n let result = (sumpoints xs 0 0 1 0)+(sumpoints ys 0 0 1 0) in\n Printf.printf \"%d\\n\" result\n;;\n"}], "src_uid": "9bd6fea892857d7c94ebce4d4cd46d30"} {"nl": {"description": "You have a string $$$s_1 s_2 \\ldots s_n$$$ and you stand on the left of the string looking right. You want to choose an index $$$k$$$ ($$$1 \\le k \\le n$$$) and place a mirror after the $$$k$$$-th letter, so that what you see is $$$s_1 s_2 \\ldots s_k s_k s_{k - 1} \\ldots s_1$$$. What is the lexicographically smallest string you can see?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \\ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. ", "input_spec": "The first line of input contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10\\,000$$$): the number of test cases. The next $$$t$$$ lines contain the description of the test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$): the length of the string. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase English characters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print the lexicographically smallest string you can see.", "sample_inputs": ["4\n10\ncodeforces\n9\ncbacbacba\n3\naaa\n4\nbbaa"], "sample_outputs": ["cc\ncbaabc\naa\nbb"], "notes": "NoteIn the first test case choose $$$k = 1$$$ to obtain \"cc\".In the second test case choose $$$k = 3$$$ to obtain \"cbaabc\".In the third test case choose $$$k = 1$$$ to obtain \"aa\".In the fourth test case choose $$$k = 1$$$ to obtain \"bb\"."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\n \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let a = read_string () in\n\n let rec findk k = if k = n-1 then n-1 else (\n if (a.[k] > a.[k+1]) || (k > 0 && (a.[k] >= a.[k+1])) then findk (k+1) else k\n ) in\n let k = findk 0 in\n for i=0 to k do printf \"%c\" a.[i] done;\n for i=k downto 0 do printf \"%c\" a.[i] done;\n print_newline()\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\n \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let a = read_string () in\n\n let rec findk k = if k = n-1 then n-1 else (\n if a.[k] > a.[k+1] then findk (k+1) else k\n ) in\n let k = findk 0 in\n for i=0 to k do printf \"%c\" a.[i] done;\n for i=k downto 0 do printf \"%c\" a.[i] done;\n print_newline()\n done\n"}], "src_uid": "dd7faacff9f57635f8e00c2f8f5a4650"} {"nl": {"description": "The secondary diagonal of a square matrix is a diagonal going from the top right to the bottom left corner. Let's define an n-degree staircase as a square matrix n\u2009\u00d7\u2009n containing no squares above the secondary diagonal (the picture below shows a 5-degree staircase). The squares of the n-degree staircase contain m sportsmen. A sportsman needs one second to move to a side-neighboring square of the staircase. Before the beginning of the competition each sportsman must choose one of the shortest ways to the secondary diagonal. After the starting whistle the competition begins and all sportsmen start moving along the chosen paths. When a sportsman reaches a cell of the secondary diagonal, he stops and moves no more. The competition ends when all sportsmen reach the secondary diagonal. The competition is considered successful if during it no two sportsmen were present in the same square simultaneously. Any square belonging to the secondary diagonal also cannot contain more than one sportsman. If a sportsman at the given moment of time leaves a square and another sportsman comes to it, then they are not considered to occupy the same square simultaneously. Note that other extreme cases (for example, two sportsmen moving towards each other) are impossible as the chosen ways are the shortest ones.You are given positions of m sportsmen on the staircase. Your task is to choose among them the maximum number of sportsmen for who the competition can be successful, that is, so that there existed such choice of shortest ways for the sportsmen at which no two sportsmen find themselves in the same square simultaneously. All other sportsmen that are not chosen will be removed from the staircase before the competition starts. ", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). Then m lines contain coordinates of sportsmen on the staircase as pairs of integers ri,\u2009ci (1\u2009\u2264\u2009ri,\u2009ci\u2009\u2264\u2009n, n\u2009-\u2009ci\u2009<\u2009ri), where ri is the number of the staircase row, ci is the number of the staircase column (to understand the principle of numbering rows and columns see the explanatory pictures). No two sportsmen stand on the same square of the staircase.", "output_spec": "In the first line print the number of the chosen sportsmen. In the second line print the numbers of chosen sportsmen in any order, separating the numbers with spaces. If there are several answers, you are permitted to print any of them. The sportsmen are numbered starting from one in the order in which they are given in the input data.", "sample_inputs": ["3 3\n2 3\n3 2\n3 3"], "sample_outputs": ["3\n1 2 3"], "notes": "NoteA note to the first sample. The picture shows a three-degree staircase. The arrows show the shortest paths that the sportsmen choose."}, "positive_code": [{"source_code": "(* codeforces 103. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\n(* 1:34 --- 2:42 *)\n\nmodule Sset = Set.Make (struct type t = int*int*int let compare = compare end)\n\nlet n = read_int ()\nlet m = read_int ()\n\nlet row = Array.make n []\n;;\n\nfor i=0 to m-1 do\n let r = n-(read_int()) in\n let c = read_int() -1 in\n row.(r) <- (c, r, i)::row.(r)\ndone\n\nlet alive = Array.make m false\nlet count = ref 0\n\nlet rec proc r s = if r=n then () else\n (* merge the current row r into the set *)\n (* process them in left to right order marking dead the ones in column < r *)\n (* when we come to one with a column >= r, that's the one that goes into the place *)\n let s = List.fold_left (fun ac e -> Sset.add e ac ) s row.(r) in\n let rec scan s = if Sset.is_empty s then s else \n let (cc, rr, ii) = Sset.min_elt s in\n let s = Sset.remove (cc,rr,ii) s in\n if cc>=r then (\n\talive.(ii) <- true;\n\tcount := !count +1;\n\ts;\n ) else scan s\n in\n proc (r+1) (scan s)\n\n;;\n\nproc 0 Sset.empty;\nPrintf.printf \"%d\\n\" !count;\nfor i=0 to m-1 do\n if alive.(i) then Printf.printf \"%d \" (i+1)\ndone;\nPrintf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "52bbca93357cfeb61057bc4d71342249"} {"nl": {"description": "You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \\le k \\le n$$$ that $$$k \\bmod x = y$$$, where $$$\\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 5 \\cdot 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \\le x \\le 10^9;~ 0 \\le y < x;~ y \\le n \\le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints.", "output_spec": "For each test case, print the answer \u2014 maximum non-negative integer $$$k$$$ such that $$$0 \\le k \\le n$$$ and $$$k \\bmod x = y$$$. It is guaranteed that the answer always exists.", "sample_inputs": ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"], "sample_outputs": ["12339\n0\n15\n54306\n999999995\n185\n999999998"], "notes": "NoteIn the first test case of the example, the answer is $$$12339 = 7 \\cdot 1762 + 5$$$ (thus, $$$12339 \\bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$."}, "positive_code": [{"source_code": "open Printf\nopen Str\n\nlet read_ints() =\n Array.map (int_of_string) (Array.of_list (Str.split (Str.regexp \" +\") (read_line())))\n\nlet main =\n let t = read_int() in\n for i = 1 to t do\n let tc = read_ints() in\n let x = tc.(0) in\n let y = tc.(1) in\n let n = tc.(2) in \n let r = n mod x in\n let m = n / x * x in\n printf \"%d\\n\" (if y <= r then m + y else m - x + y)\n done"}], "negative_code": [], "src_uid": "2589e832f22089fac9ccd3456c0abcec"} {"nl": {"description": " You have one chip and one chance to play roulette. Are you feeling lucky?", "input_spec": null, "output_spec": "Print your bet. Your chip must be placed entirely within some square (not on an edge or a corner shared by adjacent squares).", "sample_inputs": [], "sample_outputs": [], "notes": null}, "positive_code": [{"source_code": "let _ =\n let x = read_int () in\n if x mod 2 = 0 then\n Format.printf \"even@.\"\n else\n Format.printf \"odd@.\"\n\n \t \t\t \t\t \t\n \t \t\t \t\t\t\n\t \t \t\t\t \t\n \t\t\t \t\t\t"}], "negative_code": [{"source_code": "let _ =\n Format.printf \"%s@.\" (read_line ())\n\n \t \t \t \t\t\t\n\t\t\t\t\t \t\t \n \t\t \t \t\n \t\t \t \t"}, {"source_code": "let _ =\n let x = read_int () in\n if x mod 2 = 0 then\n Format.printf \"even@.\"\n else\n Format.printf \"odd@.\"\n\n\t\t\t\t\t\t \t\n\t\t \t \t \n \t \t\t \t\n \t \t \t "}, {"source_code": "let _ =\n Format.printf \"even@.\"\n\n\t\t \t\t\t \t\t\n \t \t\t \t\t \n \t\t\t \t \t \t\n \t\t \t \t "}, {"source_code": "let _ =\n Format.printf \"even@.\"\n\n\t \t\t\t\t\n\t\t\t \t\t \t \n\t \t\t \t \t \n\t \t\t \t"}, {"source_code": "let _ =\n Format.printf \"%s@.\" (read_line ());\n Format.printf \"even@.\"\n\n\t\t \t \n \t\t\t\t \t\t\n\t \t \t\t\t\n\t \t\t"}, {"source_code": "let _ =\n let x = read_int () in\n if x mod 2 = 0 then\n Format.printf \"even@.\"\n else\n Format.printf \"odd@.\"\n\n \t \t \t\n \t\t \t\t\t\t \n \t \n \t\t\t \t \t"}], "src_uid": "f2a71cb9706b76317f2f442a9129055f"} {"nl": {"description": "Little X has a tree consisting of n nodes (they are numbered from 1 to n). Each edge of the tree has a positive length. Let's define the distance between two nodes v and u (we'll denote it d(v,\u2009u)) as the sum of the lengths of edges in the shortest path between v and u. A permutation p is a sequence of n distinct integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n). Little X wants to find a permutation p such that sum is maximal possible. If there are multiple optimal permutations, he wants to find the lexicographically smallest one. Help him with the task!", "input_spec": "The first line contains an integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009105). Each of the next n\u2009-\u20091 lines contains three space separated integers ui,\u2009\u2009vi,\u2009wi\u00a0(1\u2009\u2264\u2009\u2009ui,\u2009\u2009vi\u2009\u2264\u2009\u2009n;\u00a01\u2009\u2264\u2009\u2009wi\u2009\u2264\u2009\u2009105), denoting an edge between nodes ui and vi with length equal to wi. It is guaranteed that these edges form a tree.", "output_spec": "In the first line print the maximum possible value of the described sum. In the second line print n integers, representing the lexicographically smallest permutation.", "sample_inputs": ["2\n1 2 3", "5\n1 2 2\n1 3 3\n2 4 4\n2 5 5"], "sample_outputs": ["6\n2 1", "32\n2 1 4 5 3"], "notes": null}, "positive_code": [{"source_code": "(* define the queue data structure *)\n(* which is a set of sorted lists, ordered by the first element of the list. *)\nlet complist a b = match (a,b) with (a::_,b::_) -> compare a b | _-> failwith \"bogus list\"\nmodule Lset = Set.Make (struct type t = int list let compare = complist end)\n\n(* define the tightness data structure *)\n(* a set of pairs (O(i) + I(i), i), where i is a component number\n and O(i) is the remaining outdegree of the component and I(i) is\n the remaining indegree of the component. A component i is going\n to be tight if the value of \"total\" = O(i) + I(i) *)\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let tree = Array.make n [] in\n\n for i=0 to n-2 do\n let u = read_int()-1 in\n let v = read_int()-1 in\n let w = long (read_int()) in\n\n tree.(u) <- (v,w)::tree.(u);\n tree.(v) <- (u,w)::tree.(v)\n done;\n\n(* The center of a tree is a node, which if deleted, divides the tree\n into connected components none of which is larger than n/2. We need\n to find the center. *)\n\n(*---------------------------- find the center ----------------------------*)\n let size = Array.make n 0 in\n let rec size_dfs p u =\n size.(u) <- List.fold_left (fun ac (v,_) -> if v=p then ac else ac + size_dfs u v) 1 tree.(u);\n size.(u)\n in\n ignore (size_dfs (-1) 0);\n\n let rec find_center p u =\n let i = List.fold_left (\n fun i (v,_) -> if v = p then i else if i<0 || size.(v) > size.(i) then v else i\n ) (-1) tree.(u) in\n \n if i<0 then failwith \"failed to find center\";\n if size.(i) > n/2 then find_center u i else u\n in\n\n let center = if n=1 then 0 else find_center (-1) 0 in\n\n(*---------------------------- label all nodes with their appropriate component ----------------------------*)\n\n let comp = Array.make n 0 in (* comp.(v) is the component number of vertex v *)\n let rec comp_dfs p u lab =\n comp.(u) <- lab;\n List.iter (fun (v,_) -> if v<>p then comp_dfs u v lab) tree.(u);\n in\n\n let ncomp = List.fold_left (fun ac (v,_) -> comp_dfs center v ac; ac+1) 1 tree.(center) in\n (* component 0 is just vertex center *)\n let center_component = 0 in\n\n(*---------------------------- compute the total cost of the solution ----------------------------*)\n ignore (size_dfs (-1) center); (* recompute sizes with center (instead of 0) being the root *)\n\n let rec cost_dfs p u =\n List.fold_left (fun ac (v,w) -> if v=p then ac else ac ++ (cost_dfs u v) ++ 2L**w**(long size.(v))) 0L tree.(u)\n in\n\n let solution_cost = cost_dfs (-1) center in\n\n(* ---------------------------- *)\n\n(* build the initial queue data structure *)\n let nodes = Array.make ncomp [] in\n for i=0 to n-1 do\n nodes.(comp.(i)) <- i::nodes.(comp.(i))\n done;\n\n for i=0 to ncomp-1 do\n nodes.(i) <- List.sort compare nodes.(i)\n done;\n\n let initial_queue = fold 0 (ncomp-1) (fun i ac -> (Lset.add nodes.(i)) ac) Lset.empty in\n\n(* define primitives for working with our special priority queue, which is a set\n of sorted lists, ordered by the first element of the list. *)\n\n let getmin ls = (* return the minimum element of ls. non-destructive *)\n List.hd (Lset.min_elt ls)\n in\n \n let deletemin ls = \n let l1 = Lset.min_elt ls in\n let ls = Lset.remove l1 ls in\n let tail = List.tl l1 in\n let x = List.hd l1 in\n nodes.(comp.(x)) <- tail;\n if tail = [] then ls else Lset.add tail ls\n in\n\n let deletemin_exclude ls c = \n (* delete the minimum not in the specified component *)\n (* return the pair (x,queue) *)\n if nodes.(c) = [] then (getmin ls, deletemin ls) else\n let ls_withoutc = Lset.remove nodes.(c) ls in\n let x = getmin ls_withoutc in\n let ls1 = deletemin ls_withoutc in\n let ls2 = Lset.add nodes.(c) ls1 in\n (x,ls2)\n in\n\n let deletemin_from_comp ls c = \n (* delete the minimum in the specified component *)\n (* return the pair (x,queue) *)\n let ls_withoutc = Lset.remove nodes.(c) ls in\n let x = List.hd nodes.(c) in\n nodes.(c) <- List.tl nodes.(c);\n let ls1 = if nodes.(c) = [] then ls_withoutc else Lset.add nodes.(c) ls_withoutc in\n (x,ls1)\n in\n\n(* functions for dealing with the tightness data structure *)\n\n let lhs = Array.init ncomp (fun c -> 2 * (List.length nodes.(c))) in\n lhs.(center_component) <- 1;\n\n let initial_tight = fold 0 (ncomp-1) (fun i ac -> Pset.add (lhs.(i),i) ac) Pset.empty in\n\n let findtight tight total =\n (* assumes there are at least two things in tight *)\n (* returns a list consisting of either 0, 1, or 2 tight components. *)\n let (lhs1, c1) = Pset.max_elt tight in\n if lhs1 < total then [] else\n let (lhs2,c2) = Pset.max_elt (Pset.remove (lhs1,c1) tight) in\n if lhs2 < total then [c1] else [c1;c2]\n in\n\n let makemove tight i j =\n (* we're making a move to add an edge from O(i) to I(j) *)\n (* this updates the tightness data structure to reflect this change *)\n if i=j && i<>center_component then failwith \"i=j\";\n lhs.(i) <- lhs.(i) - 1;\n let tight = Pset.add (lhs.(i), i) (Pset.remove (lhs.(i)+1,i) tight) in\n if j=center_component then tight else (\n lhs.(j) <- lhs.(j) - 1;\n Pset.add (lhs.(j), j) (Pset.remove (lhs.(j)+1,j) tight)\n )\n in \n\n(*---------------------------- compute the permutation ----------------------------*)\n \n let perm = Array.make n 0 in\n\n let rec scan i queue tight = \n if i=n-1 then (\n perm.(i) <- getmin queue;\n ) else (\n let total = n-i in (* number of links left to be added *)\n let (x, queue) = if i <> center then\n\t match findtight tight total with \n\t | [] -> deletemin_exclude queue comp.(i)\n\t | [t1] when t1 = comp.(i) -> deletemin_exclude queue comp.(i)\n\t | [t1] -> deletemin_from_comp queue t1\n\t | [t1;t2] -> let othercomp = if t1=comp.(i) then t2 else t1 in\n\t\t\t\t deletemin_from_comp queue othercomp\n\t | _ -> failwith \"impossible\"\n\telse \n\t match findtight tight total with \n\t | [] -> (getmin queue, deletemin queue)\n\t | [t1] when t1 = comp.(i) -> (getmin queue, deletemin queue) (* probably impossible *)\n\t | [t1] -> deletemin_from_comp queue t1\n\t | [t1;t2] -> let othercomp = if t1=comp.(i) then t2 else t1 in\n\t\t\t\t deletemin_from_comp queue othercomp (* probably impossible *)\n\t | _ -> failwith \"impossible\"\n in\n perm.(i) <- x;\n let tight = makemove tight comp.(i) comp.(x) in\n scan (i+1) queue tight\n ) in\n \n ignore (scan 0 initial_queue initial_tight);\n\n printf \"%Ld\\n\" solution_cost;\n for i=0 to n-1 do\n printf \"%d%s\" (perm.(i)+1) (if i=n-1 then \"\\n\" else \" \")\n done;\n"}], "negative_code": [{"source_code": "(* define the queue data structure *)\n(* which is a set of sorted lists, ordered by the first element of the list. *)\nlet complist a b = match (a,b) with (a::_,b::_) -> compare a b | _-> failwith \"bogus list\"\nmodule Lset = Set.Make (struct type t = int list let compare = complist end)\n\n(* define the tightness data structure *)\n(* a set of pairs (O(i) + I(i), i), where i is a component number\n and O(i) is the remaining outdegree of the component and I(i) is\n the remaining indegree of the component. A component i is going\n to be tight if the value of \"total\" = O(i) + I(i) *)\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let tree = Array.make n [] in\n\n for i=0 to n-2 do\n let u = read_int()-1 in\n let v = read_int()-1 in\n let w = read_int() in\n\n tree.(u) <- (v,w)::tree.(u);\n tree.(v) <- (u,w)::tree.(v)\n done;\n\n(* The center of a tree is a node, which if deleted, divides the tree\n into connected components none of which is larger than n/2. We need\n to find the center. *)\n\n(*---------------------------- find the center ----------------------------*)\n let size = Array.make n 0 in\n let rec size_dfs p u =\n size.(u) <- List.fold_left (fun ac (v,_) -> if v=p then ac else ac + size_dfs u v) 1 tree.(u);\n size.(u)\n in\n ignore (size_dfs (-1) 0);\n\n let rec find_center p u =\n let i = List.fold_left (\n fun i (v,_) -> if v = p then i else if i<0 || size.(v) > size.(i) then v else i\n ) (-1) tree.(u) in\n \n if i<0 then failwith \"failed to find center\";\n if size.(i) > n/2 then find_center u i else u\n in\n\n let center = if n=1 then 0 else find_center (-1) 0 in\n\n(*---------------------------- label all nodes with their appropriate component ----------------------------*)\n\n let comp = Array.make n 0 in (* comp.(v) is the component number of vertex v *)\n let rec comp_dfs p u lab =\n comp.(u) <- lab;\n List.iter (fun (v,_) -> if v<>p then comp_dfs u v lab) tree.(u);\n in\n\n let ncomp = List.fold_left (fun ac (v,_) -> comp_dfs center v ac; ac+1) 1 tree.(center) in\n (* component 0 is just vertex center *)\n let center_component = 0 in\n\n(*---------------------------- compute the total cost of the solution ----------------------------*)\n ignore (size_dfs (-1) center); (* recompute sizes with center (instead of 0) being the root *)\n\n let rec cost_dfs p u =\n List.fold_left (fun ac (v,w) -> if v=p then ac else ac + (cost_dfs u v) + 2*w*size.(v)) 0 tree.(u)\n in\n\n let solution_cost = cost_dfs (-1) center in\n\n(* ---------------------------- *)\n\n(* build the initial queue data structure *)\n let nodes = Array.make ncomp [] in\n for i=0 to n-1 do\n nodes.(comp.(i)) <- i::nodes.(comp.(i))\n done;\n\n for i=0 to ncomp-1 do\n nodes.(i) <- List.sort compare nodes.(i)\n done;\n\n let initial_queue = fold 0 (ncomp-1) (fun i ac -> (Lset.add nodes.(i)) ac) Lset.empty in\n\n(* define primitives for working with our special priority queue, which is a set\n of sorted lists, ordered by the first element of the list. *)\n\n let getmin ls = (* return the minimum element of ls. non-destructive *)\n List.hd (Lset.min_elt ls)\n in\n \n let deletemin ls = \n let l1 = Lset.min_elt ls in\n let ls = Lset.remove l1 ls in\n let tail = List.tl l1 in\n let x = List.hd l1 in\n nodes.(comp.(x)) <- tail;\n if tail = [] then ls else Lset.add tail ls\n in\n\n let deletemin_exclude ls c = \n (* delete the minimum not in the specified component *)\n (* return the pair (x,queue) *)\n if nodes.(c) = [] then (getmin ls, deletemin ls) else\n let ls_withoutc = Lset.remove nodes.(c) ls in\n let x = getmin ls_withoutc in\n let ls1 = deletemin ls_withoutc in\n let ls2 = Lset.add nodes.(c) ls1 in\n (x,ls2)\n in\n\n let deletemin_from_comp ls c = \n (* delete the minimum in the specified component *)\n (* return the pair (x,queue) *)\n let ls_withoutc = Lset.remove nodes.(c) ls in\n let x = List.hd nodes.(c) in\n nodes.(c) <- List.tl nodes.(c);\n let ls1 = if nodes.(c) = [] then ls_withoutc else Lset.add nodes.(c) ls_withoutc in\n (x,ls1)\n in\n\n(* functions for dealing with the tightness data structure *)\n\n let lhs = Array.init ncomp (fun c -> 2 * (List.length nodes.(c))) in\n lhs.(center_component) <- 1;\n\n let initial_tight = fold 0 (ncomp-1) (fun i ac -> Pset.add (lhs.(i),i) ac) Pset.empty in\n\n let findtight tight total =\n (* assumes there are at least two things in tight *)\n (* returns a list consisting of either 0, 1, or 2 tight components. *)\n let (lhs1, c1) = Pset.max_elt tight in\n if lhs1 < total then [] else\n let (lhs2,c2) = Pset.max_elt (Pset.remove (lhs1,c1) tight) in\n if lhs2 < total then [c1] else [c1;c2]\n in\n\n let makemove tight i j =\n (* we're making a move to add an edge from O(i) to I(j) *)\n (* this updates the tightness data structure to reflect this change *)\n if i=j && i<>center_component then failwith \"i=j\";\n lhs.(i) <- lhs.(i) - 1;\n let tight = Pset.add (lhs.(i), i) (Pset.remove (lhs.(i)+1,i) tight) in\n if j=center_component then tight else (\n lhs.(j) <- lhs.(j) - 1;\n Pset.add (lhs.(j), j) (Pset.remove (lhs.(j)+1,j) tight)\n )\n in \n\n(*---------------------------- compute the permutation ----------------------------*)\n \n let perm = Array.make n 0 in\n\n let rec scan i queue tight = \n if i=n-1 then (\n perm.(i) <- getmin queue;\n ) else (\n let total = n-i in (* number of links left to be added *)\n let (x, queue) = if i <> center then\n\t match findtight tight total with \n\t | [] -> deletemin_exclude queue comp.(i)\n\t | [t1] when t1 = comp.(i) -> deletemin_exclude queue comp.(i)\n\t | [t1] -> deletemin_from_comp queue t1\n\t | [t1;t2] -> let othercomp = if t1=comp.(i) then t2 else t1 in\n\t\t\t\t deletemin_from_comp queue othercomp\n\t | _ -> failwith \"impossible\"\n\telse \n\t match findtight tight total with \n\t | [] -> (getmin queue, deletemin queue)\n\t | [t1] when t1 = comp.(i) -> (getmin queue, deletemin queue) (* probably impossible *)\n\t | [t1] -> deletemin_from_comp queue t1\n\t | [t1;t2] -> let othercomp = if t1=comp.(i) then t2 else t1 in\n\t\t\t\t deletemin_from_comp queue othercomp (* probably impossible *)\n\t | _ -> failwith \"impossible\"\n in\n perm.(i) <- x;\n let tight = makemove tight comp.(i) comp.(x) in\n scan (i+1) queue tight\n ) in\n \n ignore (scan 0 initial_queue initial_tight);\n\n printf \"%d\\n\" solution_cost;\n for i=0 to n-1 do\n printf \"%d%s\" (perm.(i)+1) (if i=n-1 then \"\\n\" else \" \")\n done;\n"}], "src_uid": "3488701f4f765efd9aef596113e3208a"} {"nl": {"description": "Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.In total, Nastya dropped $$$n$$$ grains. Nastya read that each grain weighs some integer number of grams from $$$a - b$$$ to $$$a + b$$$, inclusive (numbers $$$a$$$ and $$$b$$$ are known), and the whole package of $$$n$$$ grains weighs from $$$c - d$$$ to $$$c + d$$$ grams, inclusive (numbers $$$c$$$ and $$$d$$$ are known). The weight of the package is the sum of the weights of all $$$n$$$ grains in it.Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the $$$i$$$-th grain weighs some integer number $$$x_i$$$ $$$(a - b \\leq x_i \\leq a + b)$$$, and in total they weigh from $$$c - d$$$ to $$$c + d$$$, inclusive ($$$c - d \\leq \\sum\\limits_{i=1}^{n}{x_i} \\leq c + d$$$).", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 1000)$$$ \u00a0\u2014 the number of test cases. The next $$$t$$$ lines contain descriptions of the test cases, each line contains $$$5$$$ integers: $$$n$$$ $$$(1 \\leq n \\leq 1000)$$$ \u00a0\u2014 the number of grains that Nastya counted and $$$a, b, c, d$$$ $$$(0 \\leq b < a \\leq 1000, 0 \\leq d < c \\leq 1000)$$$ \u00a0\u2014 numbers that determine the possible weight of one grain of rice (from $$$a - b$$$ to $$$a + b$$$) and the possible total weight of the package (from $$$c - d$$$ to $$$c + d$$$).", "output_spec": "For each test case given in the input print \"Yes\", if the information about the weights is not inconsistent, and print \"No\" if $$$n$$$ grains with masses from $$$a - b$$$ to $$$a + b$$$ cannot make a package with a total mass from $$$c - d$$$ to $$$c + d$$$.", "sample_inputs": ["5\n7 20 3 101 18\n11 11 10 234 2\n8 9 7 250 122\n19 41 21 321 10\n3 10 8 6 1"], "sample_outputs": ["Yes\nNo\nYes\nNo\nYes"], "notes": "NoteIn the first test case of the example, we can assume that each grain weighs $$$17$$$ grams, and a pack $$$119$$$ grams, then really Nastya could collect the whole pack.In the third test case of the example, we can assume that each grain weighs $$$16$$$ grams, and a pack $$$128$$$ grams, then really Nastya could collect the whole pack.In the fifth test case of the example, we can be assumed that $$$3$$$ grains of rice weigh $$$2$$$, $$$2$$$, and $$$3$$$ grams, and a pack is $$$7$$$ grams, then really Nastya could collect the whole pack.In the second and fourth test cases of the example, we can prove that it is impossible to determine the correct weight of all grains of rice and the weight of the pack so that the weight of the pack is equal to the total weight of all collected grains."}, "positive_code": [{"source_code": "(* Codeforces 1341 A Nastya and Rice train *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\nlet list_to_s li = (String.concat \" \" (List.map string_of_int li));;\n\nlet intersect al ar bl br = \n\tif al < bl then ar >= bl\n\telse if al <= br then true\n\telse false;;\n\nlet rec consistent n a b c d = \n\tlet min = n * (a-b) in\n\tlet max = n * (a+b) in\n\tlet cons = intersect min max (c-d) (c+d) in\n\t(* let _ = Printf.printf \"min max cons = %d %d %b\\n\" min max cons in *)\n\tcons;;\n\nlet do_one () = \n let n = gr () in\n let a = gr () in\n let b = gr () in\n let c = gr () in\n let d = gr () in\n\tlet co = consistent n a b c d in\n\tlet ans = if co then \"Yes\" else \"No\" in\n\tbegin\n print_string ans;\n print_string \"\\n\"\n\tend;;\t\t\n\nlet rec do_all t = match t with\n\t| 0 -> ()\n\t| _ -> \n\t\tbegin\n\t\t\tdo_one ();\n\t\t\tdo_all (t-1)\n\t\tend;; \n\nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n\nmain();;"}], "negative_code": [], "src_uid": "30cfce44a7a0922929fbe54446986748"} {"nl": {"description": "To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the selling are made only once. To carry out his plan, Qwerty is going to take a bank loan that covers all expenses and to return the loaned money at the end of the operation (the money is returned without the interest). At the same time, Querty wants to get as much profit as possible.The system has n planets in total. On each of them Qwerty can buy or sell items of m types (such as food, medicine, weapons, alcohol, and so on). For each planet i and each type of items j Qwerty knows the following: aij \u2014 the cost of buying an item; bij \u2014 the cost of selling an item; cij \u2014 the number of remaining items.It is not allowed to buy more than cij items of type j on planet i, but it is allowed to sell any number of items of any kind.Knowing that the hold of Qwerty's ship has room for no more than k items, determine the maximum profit which Qwerty can get.", "input_spec": "The first line contains three space-separated integers n, m and k (2\u2009\u2264\u2009n\u2009\u2264\u200910, 1\u2009\u2264\u2009m,\u2009k\u2009\u2264\u2009100) \u2014 the number of planets, the number of question types and the capacity of Qwerty's ship hold, correspondingly. Then follow n blocks describing each planet. The first line of the i-th block has the planet's name as a string with length from 1 to 10 Latin letters. The first letter of the name is uppercase, the rest are lowercase. Then in the i-th block follow m lines, the j-th of them contains three integers aij, bij and cij (1\u2009\u2264\u2009bij\u2009<\u2009aij\u2009\u2264\u20091000, 0\u2009\u2264\u2009cij\u2009\u2264\u2009100) \u2014 the numbers that describe money operations with the j-th item on the i-th planet. The numbers in the lines are separated by spaces. It is guaranteed that the names of all planets are different.", "output_spec": "Print a single number \u2014 the maximum profit Qwerty can get.", "sample_inputs": ["3 3 10\nVenus\n6 5 3\n7 6 5\n8 6 10\nEarth\n10 9 0\n8 6 4\n10 9 3\nMars\n4 3 0\n8 4 12\n7 2 5"], "sample_outputs": ["16"], "notes": "NoteIn the first test case you should fly to planet Venus, take a loan on 74 units of money and buy three items of the first type and 7 items of the third type (3\u00b76\u2009+\u20097\u00b78\u2009=\u200974). Then the ranger should fly to planet Earth and sell there all the items he has bought. He gets 3\u00b79\u2009+\u20097\u00b79\u2009=\u200990 units of money for the items, he should give 74 of them for the loan. The resulting profit equals 16 units of money. We cannot get more profit in this case."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m 0 in\n let b = Array.make_matrix n m 0 in\n let c = Array.make_matrix n m 0 in\n let () =\n for i = 0 to n - 1 do\n let _name = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tfor j = 0 to m - 1 do\n\t a.(i).(j) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n\t b.(i).(j) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n\t c.(i).(j) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n\tdone\n done;\n in\n let res = ref 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif i <> j then (\n\t let d = Array.make m (0, 0) in\n\t for l = 0 to m - 1 do\n\t d.(l) <- (b.(j).(l) - a.(i).(l), c.(i).(l))\n\t done;\n\t Array.sort compare d;\n\t let k = ref k in\n\t let p = ref (m - 1) in\n\t let r = ref 0 in\n\t while !k > 0 && !p >= 0 do\n\t\tlet (pr, c) = d.(!p) in\n\t\t if pr > 0 then (\n\t\t let c = min c !k in\n\t\t k := !k - c;\n\t\t r := !r + pr * c;\n\t\t );\n\t\t decr p;\n\t done;\n\t res := max !res !r\n\t)\n done\n done;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [], "src_uid": "7419c4268a9815282fadca6581f28ec1"} {"nl": {"description": "An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons \u2014 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: \"0124:5678:90ab:cdef:0124:5678:90ab:cdef\". We'll call such format of recording an IPv6-address full.Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: \"a56f:00d3:0000:0124:0001:f19a:1000:0000\" \u2009\u2192\u2009 \"a56f:d3:0:0124:01:f19a:1000:00\". There are more ways to shorten zeroes in this IPv6 address.Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to \"::\". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: \"a56f:00d3:0000:0124:0001:0000:0000:0000\" \u2009\u2192\u2009 \"a56f:00d3:0000:0124:0001::\"; \"a56f:0000:0000:0124:0001:0000:1234:0ff0\" \u2009\u2192\u2009 \"a56f::0124:0001:0000:1234:0ff0\"; \"a56f:0000:0000:0000:0001:0000:1234:0ff0\" \u2009\u2192\u2009 \"a56f:0000::0000:0001:0000:1234:0ff0\"; \"a56f:00d3:0000:0124:0001:0000:0000:0000\" \u2009\u2192\u2009 \"a56f:00d3:0000:0124:0001::0000\"; \"0000:0000:0000:0000:0000:0000:0000:0000\" \u2009\u2192\u2009 \"::\". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters \"::\" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.You've got several short records of IPv6 addresses. Restore their full record.", "input_spec": "The first line contains a single integer n \u2014 the number of records to restore (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Each of the following n lines contains a string \u2014 the short IPv6 addresses. Each string only consists of string characters \"0123456789abcdef:\". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.", "output_spec": "For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.", "sample_inputs": ["6\na56f:d3:0:0124:01:f19a:1000:00\na56f:00d3:0000:0124:0001::\na56f::0124:0001:0000:1234:0ff0\na56f:0000::0000:0001:0000:1234:0ff0\n::\n0ea::4d:f4:6:0"], "sample_outputs": ["a56f:00d3:0000:0124:0001:f19a:1000:0000\na56f:00d3:0000:0124:0001:0000:0000:0000\na56f:0000:0000:0124:0001:0000:1234:0ff0\na56f:0000:0000:0000:0001:0000:1234:0ff0\n0000:0000:0000:0000:0000:0000:0000:0000\n00ea:0000:0000:0000:004d:00f4:0006:0000"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 250B *)\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet rdln() = input_line stdin;;\nlet spli s = Str.split (Str.regexp \" \") s;;\n\nlet rec fill0 s =\n\tif String.length s >= 4 then s\n\telse fill0 (\"0\" ^ s);;\n\nlet rec repeat0 n = match n with\n\t| 0 -> \"0000\"\n\t| _ -> \"0000:\" ^ repeat0 (n -1);;\n\nlet doTerm s ndiff = match s with\n\t| \"Z\" -> repeat0 ndiff\n\t| _ -> fill0 s;;\n\nlet rec priList ls sep = match ls with\n\t| [] -> \"!!!ERROR!!!\"\n\t| h :: [] -> h\n\t| h :: t -> h ^ sep ^ priList t sep;;\n\nlet main () =\n\tlet sn = rdln() in\n\tlet n = int_of_string sn in\n\tbegin\n\t\tfor i = 0 to (n-1) do\n\t\t\tlet s = rdln() in\n\t\t\tlet sz = Str.global_replace (Str.regexp \"::\") \":Z:\" s in\n\t\t\tlet ss = Str.split (Str.regexp \":\") sz in\n\t\t\tlet diff = 8 - List.length ss in\n\t\t\tlet ssm = List.map (fun x -> doTerm x diff) ss in\n\t\t\tlet prs = priList ssm \":\" in\n\t\t\tprint_string (prs ^ \"\\n\")\n\t\tdone\n\tend;;\n\nmain();;\n"}], "negative_code": [], "src_uid": "20f69ee5f04c8cbb769be3ab646031ab"} {"nl": {"description": "Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told \"no genome, no degree\". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.", "input_spec": "The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.", "output_spec": "Print \"YES\", if the dwarves belong to the same race. Otherwise, print \"NO\".", "sample_inputs": ["ab\nba", "aa\nab"], "sample_outputs": ["YES", "NO"], "notes": "Note First example: you can simply swap two letters in string \"ab\". So we get \"ba\". Second example: we can't change string \"aa\" into string \"ab\", because \"aa\" does not contain letter \"b\". "}, "positive_code": [{"source_code": "let a = read_line () in\nlet b = read_line () in\nlet x, y = ref [], ref [] in\nlet na = String.length a in\nlet nb = String.length b in\nfor i = 0 to min na nb - 1 do\n if a.[i] <> b.[i] then begin\n x := a.[i] :: !x;\n y := b.[i] :: !y\n end\ndone;\nlet m = List.length !x in\nlet sort = List.sort (fun a b -> Char.code a - Char.code b) in\nprint_endline (if na = nb && m = 2 && sort !x = sort !y\n then \"YES\" else \"NO\")\n"}, {"source_code": "open String;;\nlet diff s a b =\n let l = ref [] in\n for i = 0 to length a - 1 do\n if a.[i] <> b.[i] then\n l := (i) :: (!l)\n done; \n !l;;\n \nlet swap a h k =\n let n = a.[h] in\n a.[h] <- a.[k];\n a.[k] <- n;;\n \nlet ch l a b= match l with\n [] -> false\n |h:: t -> match t with\n [] -> false\n |k :: [] -> swap a h k;a = b\n |t :: k -> false\n;;\nlet main _ =\n let a = Scanf.scanf \"%s\\n\" (fun a -> a) in\n let b = Scanf.scanf \"%s\\n\" (fun a -> a) in\n if length a <> length b\n then print_endline \"NO\"\n else \n let l = diff [] a b in\n if (ch l a b)\n then print_endline \"YES\"\n else print_endline \"NO\"\n;;\nmain ();;"}, {"source_code": "let solve a b =\n let rec loop lst1 lst2 cnt =\n match lst1 with\n | [] -> if cnt <= 2 then true else false\n | h :: t ->\n\tif h = List.hd lst2 then loop t (List.tl lst2) cnt\n\telse loop t (List.tl lst2) (cnt+1)\n in\n if List.sort compare a = List.sort compare b && loop a b 0 then \"YES\"\n else \"NO\"\n\nlet _ =\n let a = (Scanf.scanf \" %s\" (Str.split (Str.regexp \"\"))) in\n let b = (Scanf.scanf \" %s\" (Str.split (Str.regexp \"\"))) in\n Printf.printf \"%s\\n\" (solve a b)\n"}], "negative_code": [{"source_code": "let solve a b =\n let sorted_a = List.sort compare a in\n let sorted_b = List.sort compare b in\n if sorted_a = sorted_b then \"YES\" else \"NO\"\n\nlet _ =\n let a = (Scanf.scanf \" %s\" (Str.split (Str.regexp \"\"))) in\n let b = (Scanf.scanf \" %s\" (Str.split (Str.regexp \"\"))) in\n Printf.printf \"%s\\n\" (solve a b)\n \n\n \n\n\n"}], "src_uid": "c659bdeda1c1da08cfc7f71367222332"} {"nl": {"description": "This is yet another problem dealing with regular bracket sequences.We should remind you that a bracket sequence is called regular, if by inserting \u00ab+\u00bb and \u00ab1\u00bb into it we can get a correct mathematical expression. For example, sequences \u00ab(())()\u00bb, \u00ab()\u00bb and \u00ab(()(()))\u00bb are regular, while \u00ab)(\u00bb, \u00ab(()\u00bb and \u00ab(()))(\u00bb are not. You are given a string of \u00ab(\u00bb and \u00ab)\u00bb characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.", "input_spec": "The first line of the input file contains a non-empty string, consisting of \u00ab(\u00bb and \u00ab)\u00bb characters. Its length does not exceed 106.", "output_spec": "Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing \"0 1\".", "sample_inputs": [")((())))(()())", "))("], "sample_outputs": ["6 2", "0 1"], "notes": null}, "positive_code": [{"source_code": "\n(* Utils \n --------------------------------------------------------------------------- *)\n\nlet read_string () =\n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n\n\n(* Solution \n --------------------------------------------------------------------------- *)\n\nlet rec rev acc = function\n | '(' :: xs -> rev (')' :: acc) xs\n | ')' :: xs -> rev ('(' :: acc) xs\n | x :: xs -> rev (x :: acc) xs\n | [] -> acc\n\nlet merge (l1, t1) (l2, t2) = \n match (compare l1 l2) with\n | 1 -> (l1, t1)\n | 0 when l1 = 0 -> (0, 1)\n | 0 -> (l1, t1 + t2)\n | _ -> (l2, t2)\n\nlet rec count b ct res = function\n | [] -> if b = 0 then merge res (ct, 1) else res\n | '(' :: xs ->\n count (b + 1) (ct + 1) res xs\n | _ :: xs ->\n if b > 0 then\n count (b - 1) (ct + 1) res xs\n else\n count 0 0 (merge res (ct, 1)) xs\n\nlet solve s =\n let s1 = ')' :: explode s in\n let s2 = rev [] s1 in\n merge (count 0 0 (0, 1) s1) (count 0 0 (0, 1) s2)\n\nlet _ =\n let (len, count) = solve (read_string ()) in\n Printf.printf \"%d %d\" len count\n"}, {"source_code": "\n(* Utils \n --------------------------------------------------------------------------- *)\n\nlet read_string () =\n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\n\n(* Solution \n --------------------------------------------------------------------------- *)\n\nlet solve s =\n let stk = Stack.create () in\n\n let b = ref (-1) in\n let max = ref 0 in\n let max_ct = ref 1 in\n\n for i = 0 to String.length s - 1 do\n try\n match s.[i] with\n | '(' -> Stack.push i stk\n | ')' ->\n let top = Stack.pop stk in\n let len = i - (if Stack.is_empty stk then !b else Stack.top stk) in\n match compare !max len with\n | 1 -> ()\n | 0 -> incr max_ct\n | _ -> max := len; max_ct := 1\n\n with Stack.Empty -> b := i\n done;\n\n (!max, !max_ct)\n\n\nlet _ =\n let (len, count) = solve (read_string ()) in\n Printf.printf \"%d %d\" len count\n"}, {"source_code": "let foldli f acc s =\n let n = String.length s in\n let rec go i acc =\n if i >= n then\n acc\n else\n go (i+1) (f i acc s.[i])\n in go 0 acc\n\nlet () =\n let a = read_line () in\n let opt,cnt,_,_ = foldli (fun i (opt,cnt,b,s) c ->\n if c = '(' then\n (opt,cnt,b,i::s)\n else if s = [] then\n (opt,cnt,i,[])\n else\n let s' = List.tl s in\n let opt' = i - (if s' = [] then b else List.hd s') in\n if opt' > opt then\n (opt',1,b,s')\n else if opt' = opt then\n (opt,cnt+1,b,s')\n else\n (opt,cnt,b,s')\n ) (0,1,-1,[]) a in\n Printf.printf \"%d %d\\n\" opt cnt\n"}], "negative_code": [{"source_code": "\n(* Utils \n --------------------------------------------------------------------------- *)\n\nlet read_string () =\n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n\n\n(* Solution \n --------------------------------------------------------------------------- *)\n\nlet rec rev acc = function\n | '(' :: xs -> rev (')' :: acc) xs\n | ')' :: xs -> rev ('(' :: acc) xs\n | x :: xs -> rev (x :: acc) xs\n | [] -> acc\n\nlet merge (l1, t1) (l2, t2) = \n match (compare l1 l2) with\n | 1 -> (l1, t1)\n | 0 when l1 = 0 -> (0, 1)\n | 0 -> (l1, t1 + t2)\n | _ -> (l2, t2)\n\nlet rec count b ct = function\n | [] -> if b = 0 then (ct, 1) else (0, 1)\n | '(' :: xs -> count (b + 1) (ct + 1) xs\n | _ :: xs ->\n if b > 0 then\n count (b - 1) (ct + 1) xs\n else\n merge (count 0 0 xs) (ct, 1)\n\nlet solve s =\n let s1 = ')' :: explode s in\n let s2 = rev [] s1 in\n merge (count 0 0 s1) (count 0 0 s2)\n\nlet _ =\n let (len, count) = solve (read_string ()) in\n Printf.printf \"%d %d\" len count\n"}, {"source_code": "\n(* Utils \n --------------------------------------------------------------------------- *)\n\nlet read_string () =\n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\n\n(* Solution \n --------------------------------------------------------------------------- *)\n\nlet srev s1 =\n let s2 = String.copy s1 in\n let len = String.length s1 - 1 in\n for i = 0 to len do\n s2.[i] <- match s1.[len - i] with\n | '(' -> ')'\n | ')' -> '('\n done;\n s2\n\nlet merge (l1, t1) (l2, t2) = \n match (compare l1 l2) with\n | 1 -> (l1, t1)\n | 0 when l1 = 0 -> (0, 1)\n | 0 -> (l1, t1 + t2)\n | -1 -> (l2, t2)\n\nlet count s =\n let rec iter b ct i =\n try\n match s.[i] with\n | '(' -> iter (b + 1) (ct + 1) (i + 1)\n | ')' ->\n if b > 0 then\n iter (b - 1) (ct + 1) (i + 1)\n else\n merge (iter 0 0 (i + 1)) (ct, 1)\n\n with Invalid_argument _ ->\n if b = 0 then (ct, 1) else (0, 1)\n \n in iter 0 0 0\n\nlet solve s =\n let s1 = \")\" ^ s in\n let s2 = srev s1 in\n merge (count s1) (count s2)\n\nlet _ =\n let (len, count) = solve (read_string ()) in\n Printf.printf \"%d %d\" len count\n"}, {"source_code": "\n(* Utils \n --------------------------------------------------------------------------- *)\n\nlet read_string () =\n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\n\n(* Solution \n --------------------------------------------------------------------------- *)\n\nlet solve s =\n let stk = Stack.create () in\n\n let b = ref 0 in\n let max = ref 0 in\n let max_ct = ref 1 in\n\n for i = 0 to String.length s - 1 do\n try\n match s.[i] with\n | '(' -> Stack.push i stk\n | ')' ->\n let top = Stack.pop stk in\n let len = if Stack.is_empty stk then i - !b else i - top in\n match compare !max len with\n | 1 -> ()\n | 0 -> incr max_ct\n | _ -> max := len; max_ct := 1\n\n with Stack.Empty -> b := i\n done;\n\n (!max, !max_ct)\n\n\nlet _ =\n let (len, count) = solve (read_string ()) in\n Printf.printf \"%d %d\" (len+1) count\n"}, {"source_code": "\n(* Utils \n --------------------------------------------------------------------------- *)\n\nlet read_string () =\n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n\n\n(* Solution \n --------------------------------------------------------------------------- *)\n\nlet rec rev acc = function\n | '(' :: xs -> rev (')' :: acc) xs\n | ')' :: xs -> rev ('(' :: acc) xs\n | [] -> acc\n\nlet merge (l1, t1) (l2, t2) = \n match (compare l1 l2) with\n | 1 -> (l1, t1)\n | 0 when l1 = 0 -> (0, 1)\n | 0 -> (l1, t1 + t2)\n | -1 -> (l2, t2)\n\nlet rec count b ct = function\n | [] -> if b = 0 then (ct, 1) else (0, 1)\n | '(' :: xs -> count (b + 1) (ct + 1) xs\n | ')' :: xs ->\n if b > 0 then\n count (b - 1) (ct + 1) xs\n else\n merge (count 0 0 xs) (ct, 1)\n\nlet solve s =\n let s1 = ')' :: explode s in\n let s2 = rev [] s1 in\n merge (count 0 0 s1) (count 0 0 s2)\n\nlet _ =\n let (len, count) = solve (read_string ()) in\n Printf.printf \"%d %d\" len count\n"}, {"source_code": "\n(* Utils \n --------------------------------------------------------------------------- *)\n\nlet read_string () =\n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n\n\n(* Solution \n --------------------------------------------------------------------------- *)\n\nlet rec rev acc = function\n | '(' :: xs -> rev (')' :: acc) xs\n | ')' :: xs -> rev ('(' :: acc) xs\n | [] -> acc\n\nlet merge (l1, t1) (l2, t2) = \n match (compare l1 l2) with\n | 1 -> (l1, t1)\n | 0 when l1 = 0 -> (0, 1)\n | 0 -> (l1, t1 + t2)\n | -1 -> (l2, t2)\n\nlet rec count b ct = function\n | [] -> if b = 0 then (ct, 1) else (0, 1)\n | '(' :: xs -> count (b + 1) (ct + 1) xs\n | ')' :: xs ->\n if b > 0 then\n count (b - 1) (ct + 1) xs\n else\n merge (count 0 0 xs) (ct, 1)\n\nlet solve s =\n let s1 = explode s in\n let s2 = rev [] s1 in\n merge (count 0 0 s1) (count 0 0 s2)\n\nlet _ =\n let (len, count) = solve (read_string ()) in\n Printf.printf \"%d %d\" len count\n"}, {"source_code": "\n(* Utils \n --------------------------------------------------------------------------- *)\n\nlet read_string () =\n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\n\n(* Solution \n --------------------------------------------------------------------------- *)\n\nlet solve s =\n let stk = Stack.create () in\n\n let max = ref 0 in\n let max_ct = ref 1 in\n\n for i = 0 to String.length s - 1 do\n try\n match s.[i] with\n | '(' -> Stack.push i stk\n | ')' ->\n let len = i - Stack.pop stk + 1 in\n match compare !max len with\n | 1 -> ()\n | 0 -> incr max_ct\n | _ -> max := len; max_ct := 1\n\n with Stack.Empty -> ()\n done;\n\n (!max, !max_ct)\n\n\nlet _ =\n let (len, count) = solve (read_string ()) in\n Printf.printf \"%d %d\" len count\n"}], "src_uid": "91c3af92731cd7d406674598c0dcbbbc"} {"nl": {"description": "N ladies attend the ball in the King's palace. Every lady can be described with three values: beauty, intellect and richness. King's Master of Ceremonies knows that ladies are very special creatures. If some lady understands that there is other lady at the ball which is more beautiful, smarter and more rich, she can jump out of the window. He knows values of all ladies and wants to find out how many probable self-murderers will be on the ball. Lets denote beauty of the i-th lady by Bi, her intellect by Ii and her richness by Ri. Then i-th lady is a probable self-murderer if there is some j-th lady that Bi\u2009<\u2009Bj,\u2009Ii\u2009<\u2009Ij,\u2009Ri\u2009<\u2009Rj. Find the number of probable self-murderers.", "input_spec": "The first line contains one integer N (1\u2009\u2264\u2009N\u2009\u2264\u2009500000). The second line contains N integer numbers Bi, separated by single spaces. The third and the fourth lines contain sequences Ii and Ri in the same format. It is guaranteed that 0\u2009\u2264\u2009Bi,\u2009Ii,\u2009Ri\u2009\u2264\u2009109.", "output_spec": "Output the answer to the problem.", "sample_inputs": ["3\n1 4 2\n4 3 2\n2 5 3"], "sample_outputs": ["1"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet (@@@) x y = if x <> 0 then x else y\n\nlet getx (v,_,_) = v\nlet gety (_,v,_) = v\nlet getz (_,_,v) = v\n\nlet lbound a n x =\n let rec go l h =\n if l >= h then\n l\n else\n let m = (l+h) lsr 1 in\n if a.(m) < x then\n go (m+1) h\n else\n go l m\n in go 0 n\n\nlet () =\n let n = read_int 0 in\n let a = Array.make n (0,0,0) in\n for i = 0 to n-1 do let (_,y,z) = a.(i) in let x = read_int 0 in a.(i) <- (x,y,z) done;\n for i = 0 to n-1 do let (x,_,z) = a.(i) in let y = read_int 0 in a.(i) <- (x,y,z) done;\n for i = 0 to n-1 do let (x,y,_) = a.(i) in let z = read_int 0 in a.(i) <- (x,y,z) done;\n Array.sort (fun (x,y,z) (xx,yy,zz) -> compare xx x @@@ compare y yy @@@ compare z zz) a;\n\n let ys = Array.make n 0 in\n for i = 0 to n-1 do\n ys.(i) <- gety a.(i)\n done;\n Array.sort compare ys;\n\n let fenwick = Array.make n (-1) in\n let ans = ref 0 in\n for i = 0 to n-1 do\n let yi = gety a.(i) |> lbound ys n in\n let z = getz a.(i) in\n let rec getmax i ma =\n if i = 0 then\n ma\n else\n let ii = i land (i-1) in\n getmax ii (max ma fenwick.(i-1))\n in\n let rec add i =\n if i < n then (\n let ii = i lor (i+1) in\n fenwick.(i) <- max fenwick.(i) z;\n add ii\n )\n in\n let ma = getmax (n-1-yi) (-1) in\n if ma > z then\n incr ans\n else\n add (n-1-yi)\n done;\n Printf.printf \"%d\\n\" !ans\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet (@@@) x y = if x <> 0 then x else y\n\nlet gety (_,v,_) = v\nlet getz (_,_,v) = v\n\nlet lbound a n x =\n let rec go l h =\n if l >= h then\n l\n else\n let m = (l+h) lsr 1 in\n if a.(m) < x then\n go (m+1) h\n else\n go l m\n in go 0 n\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n (fun _ ->\n let x = read_int 0 in\n let y = read_int 0 in\n let z = read_int 0 in\n x,y,z) in\n Array.sort (fun (x,y,z) (xx,yy,zz) -> compare xx x @@@ compare y yy @@@ compare z zz) a;\n\n let ys = Array.make n 0 in\n for i = 0 to n-1 do\n ys.(i) <- gety a.(i)\n done;\n Array.sort compare ys;\n\n let fenwick = Array.make n (-1) in\n let ans = ref 0 in\n for i = 0 to n-1 do\n let yi = gety a.(i) |> lbound ys n in\n let z = getz a.(i) in\n let rec getmax i ma =\n if i = 0 then\n ma\n else\n let ii = i land (i-1) in\n getmax ii (max ma fenwick.(i-1))\n in\n let rec add i =\n if i < n then (\n let ii = i lor (i+1) in\n fenwick.(i) <- max fenwick.(i) z;\n add ii\n )\n in\n let ma = getmax (n-1-yi) (-1) in\n if ma > z then\n incr ans\n else\n add (n-1-yi)\n done;\n Printf.printf \"%d\\n\" !ans\n"}], "src_uid": "316187d15c7604025fb6fe4a17a19647"} {"nl": {"description": "Emuskald is an avid horticulturist and owns the world's longest greenhouse \u2014 it is effectively infinite in length.Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line.Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m\u2009-\u20091 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left.Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.", "input_spec": "The first line of input contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20095000, n\u2009\u2265\u2009m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1\u2009\u2264\u2009si\u2009\u2264\u2009m), and one real number xi (0\u2009\u2264\u2009xi\u2009\u2264\u2009109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order \"from left to the right\", that is in the ascending order of their xi coordinates (xi\u2009<\u2009xi\u2009+\u20091,\u20091\u2009\u2264\u2009i\u2009<\u2009n).", "output_spec": "Output a single integer \u2014 the minimum number of plants to be replanted.", "sample_inputs": ["3 2\n2 1\n1 2.0\n1 3.100", "3 3\n1 5.0\n2 5.5\n3 6.0", "6 3\n1 14.284235\n2 17.921382\n1 20.328172\n3 20.842331\n1 25.790145\n1 27.204125"], "sample_outputs": ["1", "0", "2"], "notes": "NoteIn the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1.In the second test case, the species are already in the correct order, so no replanting is needed."}, "positive_code": [{"source_code": "open Scanf\nopen Num\nopen Printf\nopen String\n\ntype plant = P of int * float;;\n\nlet (n,m) = Scanf.scanf \"%d %d \" (fun x y -> (x,y));;\nlet read_P () = Scanf.scanf \"%d %f \" (fun x y -> P (x, y) );;\nlet read_P2 () = Scanf.scanf \"%d %f \" (fun x y -> x );;\n\nlet plants = Array.init n (fun i -> read_P2 () );;\n\n(* DEBUG\nlet printx = function\n | P(x,y) -> printf \"%d %f\\n\" x y\nin Array.iter (fun x -> print_int x; print_endline \"\") plants;;\n*)\n(* longest increasing subsequence*)\nlet d = Array.make n 1;;\n\nlet max_length = ref 1;;\nfor i = 1 to n -1 do\n for j = i - 1 downto 0 do\n if ( (plants.(i) >= plants.(j) ) && (d.(j)+1 > d.(i)) ) then (d.(i) <- d.(j) + 1)\n done;\n if(d.(i) > !max_length) then max_length := d.(i)\n\ndone\n\nlet () = print_int (n - !max_length); print_endline \"\";;\n"}], "negative_code": [{"source_code": "open Scanf\nopen Num\nopen Printf\nopen String\n\nlet s = Scanf.bscanf Scanf.Scanning.stdin \"%s \" ( fun x -> x) |> String.lowercase\n\nlet explode s =\n let r = ref [] in\n for i = 0 to (length s - 1) do\n let c = String.get s i in\n r := !r@[c]\n done; !r\n;;\n\nlet is_vowel = function\n | 'a' -> true\n | 'o' -> true\n | 'y' -> true\n | 'e' -> true\n | 'u' -> true\n | 'i' -> true\n | _ -> false\n\nlet l = ( explode s \n |> List.filter (fun x -> (not (is_vowel x)) )\n );;\n\nList.iter (fun x -> print_string (\".\"^(String.make 1 x)) ) l; print_endline \"\";;\n"}, {"source_code": "open Scanf\nopen Num\nopen Printf\nopen String\n\ntype plant = P of int * float;;\n\nlet (n,m) = Scanf.scanf \"%d %d \" (fun x y -> (x,y));;\nlet read_P () = Scanf.scanf \"%d %f \" (fun x y -> P (x, y) );;\nlet read_P2 () = Scanf.scanf \"%d %f \" (fun x y -> x );;\n\nlet plants = Array.init n (fun i -> read_P2 () );;\n\n(* DEBUG\nlet printx = function\n | P(x,y) -> printf \"%d %f\\n\" x y\nin Array.iter (fun x -> printx x) plants;;\n*)\n\n(* longest increasing subsequence*)\nlet d = Array.create n 1;;\n\nfor i = 1 to n -1 do\n for j = i - 1 downto 0 do\n if ( (plants.(i) >= plants.(j) ) && (d.(j)+1 > d.(i)) ) then (d.(i) <- d.(j) + 1)\n done\ndone\n\nlet () = print_int (n-d.(n-1)); print_endline \"\";;\n"}], "src_uid": "32f245fa1a2d99bfabd30b558687ca5f"} {"nl": {"description": "Boboniu gives you $$$r$$$ red balls, $$$g$$$ green balls, $$$b$$$ blue balls, $$$w$$$ white balls. He allows you to do the following operation as many times as you want: Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations. ", "input_spec": "The first line contains one integer $$$T$$$ ($$$1\\le T\\le 100$$$) denoting the number of test cases. For each of the next $$$T$$$ cases, the first line contains four integers $$$r$$$, $$$g$$$, $$$b$$$ and $$$w$$$ ($$$0\\le r,g,b,w\\le 10^9$$$).", "output_spec": "For each test case, print \"Yes\" if it's possible to arrange all the balls into a palindrome after doing several (possibly zero) number of described operations. Otherwise, print \"No\".", "sample_inputs": ["4\n0 1 1 1\n8 1 9 3\n0 0 0 0\n1000000000 1000000000 1000000000 1000000000"], "sample_outputs": ["No\nYes\nYes\nYes"], "notes": "NoteIn the first test case, you're not able to do any operation and you can never arrange three balls of distinct colors into a palindrome.In the second test case, after doing one operation, changing $$$(8,1,9,3)$$$ to $$$(7,0,8,6)$$$, one of those possible palindromes may be \"rrrwwwbbbbrbbbbwwwrrr\".A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. For example, \"rggbwbggr\", \"b\", \"gg\" are palindromes while \"rgbb\", \"gbbgr\" are not. Notice that an empty word, phrase, or sequence is palindrome."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_4 _ = bscanf Scanning.stdin \" %d %d %d %d \" (fun a b c d -> (a,b,c,d)) \n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let (r,g,b,w) = read_4() in\n let c = (r mod 2) + (g mod 2) + (b mod 2) + (w mod 2) in\n let can_toggle = r>0 && g>0 && b>0 in\n let answer =\n if can_toggle then c <> 2\n else c=0 || c=1\n in\n\n if answer then printf \"Yes\\n\" else printf \"No\\n\"\n done\n"}], "negative_code": [], "src_uid": "749a106d462555543c91753f00a5a479"} {"nl": {"description": "A permutation p of size n is the sequence p1,\u2009p2,\u2009...,\u2009pn, consisting of n distinct integers, each of them is from 1 to n (1\u2009\u2264\u2009pi\u2009\u2264\u2009n).A lucky permutation is such permutation p, that any integer i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) meets this condition ppi\u2009=\u2009n\u2009-\u2009i\u2009+\u20091.You have integer n. Find some lucky permutation p of size n.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the required permutation size.", "output_spec": "Print \"-1\" (without the quotes) if the lucky permutation p of size n doesn't exist. Otherwise, print n distinct integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) after a space \u2014 the required permutation. If there are multiple answers, you can print any of them.", "sample_inputs": ["1", "2", "4", "5"], "sample_outputs": ["1", "-1", "2 4 1 3", "2 5 3 1 4"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 287C - HappyPermutations *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet n = gr();; (* size of permutation *)\n\nlet p = Array.make n 1;;\n\nlet pp i n =\n\tlet n2 = n /2 in\n\tif (i == n2 +1) && (n mod 4 == 1) then i\n\telse if i <= n2\tthen\n\t\t(if (i mod 2) == 1\n\t\t\tthen i + 1\n\t\t\telse n - i + 2)\n\telse\n\t\t(if ((n-i) mod 2) == 1\n\t\t\tthen n - i\n\t\t\telse i - 1);;\n\nlet countp n =\n\tfor i = 1 to n do\n\t\tp.(i -1) <- pp i n\n\tdone;;\n\nlet main() =\n\tif ((n mod 4) == 2) or ((n mod 4) == 3)\n\tthen print_string \"-1\"\n\telse\n\t\tbegin\n\t\t\tcountp n;\n\t\t\tprintarri p\n\t\tend;;\n\nmain();;\n"}], "negative_code": [], "src_uid": "dfca19b36c1d682ee83224a317e495e9"} {"nl": {"description": "Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.", "input_spec": "The first line of the input contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input.", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible total length of words in Andrew's article.", "sample_inputs": ["4\nabb\ncacc\naaa\nbbb", "5\na\na\nbcbcb\ncdecdecdecdecdecde\naaaa"], "sample_outputs": ["9", "6"], "notes": "NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}."}, "positive_code": [{"source_code": "open Char;;\nlet n = read_int () and kol = ref 0 and answer = ref 0;;\nlet a = Array.create n \"\";;\nlet check c x = \nbegin\n\tkol := 0;\n\tfor i = 0 to (String.length x) - 1 do\n\t\tif String.get x i = c then kol := !kol + 1\t\n\tdone; \n\t!kol;\nend;;\nfor i = 0 to n - 1 do let ss = read_line() in Array.set a i ss done;;\nfor i = 1 to 26 do\n\tfor j = 1 to 26 do\n\t\tif i <> j then\n\t\tbegin\n\t\t\tlet ans = ref 0 in\n\t\t\tbegin\n\t\t\t\tfor k = 0 to n - 1 do\n\t\t\t\t\tif (check (chr (i + 96)) a.(k)) + (check (chr (j + 96)) a.(k)) = String.length a.(k) then ans := !ans + String.length a.(k);\n\t\t\t\tdone;\n\t\t\t\tanswer := max !answer !ans;\n\t\t\tend\n\t\tend\n\tdone\ndone;;\nprint_int !answer;;\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet n2l n = char_of_int ((int_of_char 'a') + n)\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n \nlet () = \n let n = read_int () in\n let word = Array.init n (fun _ -> read_string()) in\n\n let word_contains_only w c d =\n let n = String.length w in\n forall 0 (n-1) (fun i -> w.[i] = c || w.[i] = d)\n in\n\n \n let answer = maxf 0 25 (fun i ->\n maxf 0 25 (fun j ->\n let c = n2l i in\n let d = n2l j in\n sum 0 (n-1) (fun k ->\n\tif word_contains_only word.(k) c d then String.length word.(k) else 0\n ) 0\n )\n ) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "d8a93129cb5e7f05a5d6bbeedbd9ef1a"} {"nl": {"description": "The board has got a painted tree graph, consisting of n nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles.Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge contains its value written on it as a non-negative integer.A bad boy Vasya came up to the board and wrote number sv near each node v \u2014 the sum of values of all edges that are incident to this node. Then Vasya removed the edges and their values from the board.Your task is to restore the original tree by the node colors and numbers sv.", "input_spec": "The first line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of nodes in the tree. Next n lines contain pairs of space-separated integers ci, si (0\u2009\u2264\u2009ci\u2009\u2264\u20091, 0\u2009\u2264\u2009si\u2009\u2264\u2009109), where ci stands for the color of the i-th vertex (0 is for white, 1 is for black), and si represents the sum of values of the edges that are incident to the i-th vertex of the tree that is painted on the board.", "output_spec": "Print the description of n\u2009-\u20091 edges of the tree graph. Each description is a group of three integers vi, ui, wi (1\u2009\u2264\u2009vi,\u2009ui\u2009\u2264\u2009n, vi\u2009\u2260\u2009ui, 0\u2009\u2264\u2009wi\u2009\u2264\u2009109), where vi and ui \u2014 are the numbers of the nodes that are connected by the i-th edge, and wi is its value. Note that the following condition must fulfill cvi\u2009\u2260\u2009cui. It is guaranteed that for any input data there exists at least one graph that meets these data. If there are multiple solutions, print any of them. You are allowed to print the edges in any order. As you print the numbers, separate them with spaces.", "sample_inputs": ["3\n1 3\n1 2\n0 5", "6\n1 0\n0 3\n1 8\n0 2\n0 3\n0 0"], "sample_outputs": ["3 1 3\n3 2 2", "2 3 3\n5 3 3\n4 3 2\n1 6 0\n2 1 0"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 260D BlackWhiteTree ??? *)\n\nopen String;;\nopen Array;;\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec readprs idx n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> let c = gr() in\n\t\t\tlet v = gr() in\n\t\t\treadprs (idx +1) (n -1) ((c, v, idx) :: acc);;\n\nlet rec split1 li la lb = match li with\n\t| [] -> (la, lb)\n\t| h :: t ->\n\t\t\tlet (c, _, _) = h in\n\t\t\tmatch c with\n\t\t\t| 0 -> split1 t (h :: la) lb\n\t\t\t| 1 -> split1 t la (h :: lb);;\n\nlet sortfun a b =\n\tlet (ca, va, ia) = a in\n\tlet (cb, vb, ib) = b in\n\t(va - vb);;\n\nlet rec combine_witha lasta lb acc = match lb with\n| [] -> acc\n| hb :: tb ->\n\t\t\t\t\tlet (_, va, ia) = lasta in\n\t\t\t\t\tlet (_, vb, ib) = hb in\n\t\t\t\t\tcombine_witha lasta tb ((ia, ib, vb) :: acc);;\n\nlet rec combine_withb la lastb acc = match la with\n| [] -> acc\n| ha :: ta ->\n\t\t\t\t\tlet (_, va, ia) = ha in\n\t\t\t\t\tlet (_, vb, ib) = lastb in\n\t\t\t\t\tcombine_withb ta lastb ((ia, ib, va) :: acc);;\n\n\nlet rec combine la lb acc = match la with\n\t| [] -> acc\n\t| ha :: [] -> combine_witha ha lb acc\n\t| ha :: ta -> match lb with\n\t\t\t| [] -> acc\n\t\t\t| hb :: [] -> combine_withb la hb acc\n\t\t\t| hb :: tb ->\n\t\t\t\t\tlet (_, va, ia) = ha in\n\t\t\t\t\tlet (_, vb, ib) = hb in\n\t\t\t\t\tif va <= vb then\n\t\t\t\t\t\tcombine ta ((1, (vb - va), ib) :: tb) ((ia, ib, va) :: acc)\n\t\t\t\t\telse\n\t\t\t\t\t\tcombine ((0, (va - vb), ia) :: ta) tb ((ia, ib, vb) :: acc);;\n\nlet rec pricomb co =\n\tlet (ia, ib, w) = co in\n\tbegin\n\t\tprint_int ia; print_string \" \";\n\t\tprint_int ib; print_string \" \";\n\t\tprint_int w;\n\t\tprint_newline()\n\tend;;\n\nlet n = gr();;\n\nlet main () =\n\tlet prs = readprs 1 n [] in\n\tlet (ula, ulb) = split1 prs [] [] in\n\tlet la = List.sort sortfun ula in\n\tlet lb = List.sort sortfun ulb in\n\tlet comb = combine la lb [] in\n\tList.iter pricomb comb;;\n\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) ;;\n\nlet n = read_int () ;;\n\nlet nodes =\n let rec loop i f =\n if i > n then f []\n else let ci = read_int () and si = read_int ()\n in loop (i + 1) (fun l -> f ((i, ci, si) :: l))\n in loop 1 (fun x -> x) ;;\n\nlet white = List.filter (fun (i, c, s) -> c = 0) nodes ;;\nlet black = List.filter (fun (i, c, s) -> c = 1) nodes ;;\n\nlet tree = \n let rec build_tree u cu su w b tree =\n if w = [] && b = [] then tree\n else let (node, color, sum, white, black, edge) = \n let (v, cv, sv), nw, nb, opposite_nodes = \n if cu = 0 then let t = List.tl b in (List.hd b), w, t, t \n else let t = List.tl w in (List.hd w), t, b, t\n in if su > sv || su = sv && opposite_nodes <> [] \n then (u, cu, su - sv, nw, nb, (u, v, sv))\n else (v, cv, sv - su, nw, nb, (u, v, su))\n in build_tree node color sum white black (edge :: tree)\n in let (u, c, s) = List.hd white\n in build_tree u c s (List.tl white) black [] ;;\n \nlet rec print_tree = function\n | [] -> ()\n | (u, v, w) :: t -> Printf.printf \"%d %d %d\\n\" u v w ; print_tree t\nin print_tree tree ;;\n "}, {"source_code": "module Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet () = \n let n = read_int() in\n\n let color = [|ref Pset.empty; ref Pset.empty|] in\n\n let () = for i=1 to n do\n let c = read_int() in\n let s = read_int() in\n color.(c) := Pset.add (s,i) (!(color.(c)));\n done in\n\n let step (set0, size0, set1, size1) = \n let i = if size0 = 1 then 0 else if size1 = 1 then 1 else\n ( let (m0,_) = Pset.min_elt set0 in\n\tlet (m1,_) = Pset.min_elt set1 in\n\t if m0 > m1 then 0 else 1\n )\n in\n (* i is the one which stays, 1-i is removed *)\n let (set0, size0, set1, size1) = if i=0 then (set0, size0, set1, size1) else (set1, size1, set0, size0) in\n let (s0,i0) = Pset.min_elt set0 in\n let set0 = Pset.remove (s0,i0) set0 in\n let (s1,i1) = Pset.min_elt set1 in\n let set1 = Pset.remove (s1,i1) set1 in\n \n Printf.printf \"%d %d %d\\n\" i0 i1 s1;\n \n let set0 = Pset.add (s0-s1, i0) set0 in\n\t(set0, size0, set1, size1-1)\n in\n\n let rec loop sets i = if i=n-1 then () else loop (step sets) (i+1) in\n\n loop (!(color.(0)), Pset.cardinal !(color.(0)), !(color.(1)), Pset.cardinal !(color.(1))) 0\n"}], "negative_code": [{"source_code": "(* Codeforces 260D BlackWhiteTree works *)\n\nopen String;;\nopen Array;;\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec readprs idx n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> let c = gr() in\n\t\t\tlet v = gr() in\n\t\t\treadprs (idx +1) (n -1) ((c, v, idx) :: acc);;\n\nlet rec split1 li la lb = match li with\n\t| [] -> (la, lb)\n\t| h :: t ->\n\t\t\tlet (c, _, _) = h in\n\t\t\tmatch c with\n\t\t\t| 0 -> split1 t (h :: la) lb\n\t\t\t| 1 -> split1 t la (h :: lb);;\n\nlet sortfun a b =\n\tlet (ca, va, ia) = a in\n\tlet (cb, vb, ib) = b in\n\t(va - vb);;\n\nlet rec combine la lb acc = match la with\n\t| [] -> acc\n\t| ha :: ta -> match lb with\n\t\t\t| [] -> acc\n\t\t\t| hb :: tb ->\n\t\t\t\t\tlet (_, va, ia) = ha in\n\t\t\t\t\tlet (_, vb, ib) = hb in\n\t\t\t\t\tif va <= vb then\n\t\t\t\t\t\tcombine ta ((1, (vb - va), ib) :: tb) ((ia, ib, va) :: acc)\n\t\t\t\t\telse\n\t\t\t\t\t\tcombine ((0, (va - vb), ia) :: ta) tb ((ia, ib, vb) :: acc);;\n\nlet rec pricomb co =\n\tlet (ia, ib, w) = co in\n\tbegin\n\t\tprint_int ia; print_string \" \";\n\t\tprint_int ib; print_string \" \";\n\t\tprint_int w;\n\t\tprint_newline()\n\tend;;\n\nlet n = gr();;\n\nlet main () =\n\tlet prs = readprs 1 n [] in\n\tlet (ula, ulb) = split1 prs [] [] in\n\tlet la = List.sort sortfun ula in\n\tlet lb = List.sort sortfun ulb in\n\tlet comb = combine la lb [] in\n\tList.iter pricomb comb;;\n\nmain();;\n"}], "src_uid": "b1ece35f190b13a3dfd64ab30c905765"} {"nl": {"description": "Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi,\u2009j items in the basket. Vasya knows that: the cashier needs 5 seconds to scan one item; after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of cashes in the shop. The second line contains n space-separated integers: k1,\u2009k2,\u2009...,\u2009kn (1\u2009\u2264\u2009ki\u2009\u2264\u2009100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi,\u20091,\u2009mi,\u20092,\u2009...,\u2009mi,\u2009ki (1\u2009\u2264\u2009mi,\u2009j\u2009\u2264\u2009100)\u00a0\u2014 the number of products the j-th person in the queue for the i-th cash has.", "output_spec": "Print a single integer \u2014 the minimum number of seconds Vasya needs to get to the cashier.", "sample_inputs": ["1\n1\n1", "4\n1 4 3 2\n100\n1 2 2 3\n1 9 1\n7 8"], "sample_outputs": ["20", "100"], "notes": "NoteIn the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100\u00b75\u2009+\u200915\u2009=\u2009515 seconds. But if he chooses the second queue, he will need 1\u00b75\u2009+\u20092\u00b75\u2009+\u20092\u00b75\u2009+\u20093\u00b75\u2009+\u20094\u00b715\u2009=\u2009100 seconds. He will need 1\u00b75\u2009+\u20099\u00b75\u2009+\u20091\u00b75\u2009+\u20093\u00b715\u2009=\u2009100 seconds for the third one and 7\u00b75\u2009+\u20098\u00b75\u2009+\u20092\u00b715\u2009=\u2009105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue."}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int();;\nlet tab=Array.make (n+1) 0;;\nlet nb=Array.make (n+1) 0;;\n\nfor i=1 to n do\n let k=read_int() in\n nb.(i)<-k;\n tab.(i)<-15*k;\ndone;;\n\nfor i=1 to n do\n for j=1 to nb.(i) do\n tab.(i)<-tab.(i)+5*read_int()\n done\ndone;;\n\nlet m=ref tab.(1);;\nfor i=1 to n do\n if tab.(i)< !m then m:= tab.(i)\ndone;;\n\nprint_int !m;;"}], "negative_code": [], "src_uid": "0ea79b2a7ddf3d4da9c7a348e61933a7"} {"nl": {"description": "Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings \"aba\" and \"abc\" are perfectly balanced but \"abb\" is not because for the triplet (\"bb\",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1\\leq t\\leq 2\\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\\leq |s|\\leq 2\\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case, print \"YES\" if $$$s$$$ is a perfectly balanced string, and \"NO\" otherwise. You may print each letter in any case (for example, \"YES\", \"Yes\", \"yes\", \"yEs\" will all be recognized as positive answer).", "sample_inputs": ["5\naba\nabb\nabc\naaaaa\nabcba"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO"], "notes": "NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\\in\\{a,b,c\\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced."}, "positive_code": [{"source_code": "module CharOrd = struct\r\n type t = char\r\n\r\n let compare x y = if x < y then -1 else if x > y then 1 else 0\r\nend\r\n\r\nmodule CharSet = Set.Make (CharOrd)\r\n\r\nlet solve () =\r\n let str = read_line () in\r\n let n = String.length str in\r\n let c = ref CharSet.empty in\r\n let rec find_k i =\r\n if i >= n then n\r\n else if CharSet.exists (fun x -> x == String.get str i) !c then i\r\n else (\r\n c := CharSet.add (String.get str i) !c;\r\n find_k (i + 1))\r\n in\r\n let k = find_k 0 in\r\n let rec is_ok i =\r\n if i >= n then true\r\n else if String.get str i = String.get str (i - k) then is_ok (i + 1)\r\n else false\r\n in\r\n if is_ok k then \"YES\" else \"NO\"\r\n\r\nlet () =\r\n let t = read_int () in\r\n for i = 0 to t - 1 do\r\n print_endline (solve ())\r\n done\r\n"}, {"source_code": "let n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let a = input_line stdin in \r\n let tab = Array.make 26 (-1) in\r\n let rep = ref true in\r\n for i = 0 to String.length a - 1 do\r\n let lett = a.[i] in\r\n let num = Char.code lett - 97 in\r\n if tab.(num) = -2 then begin rep := false end ;\r\n if !rep && (tab.(num) <> -1) then begin\r\n let last = tab.(num) in\r\n for j = 0 to 25 do\r\n if tab.(j) <> -1 && tab.(j) <> -2 && num<>j && tab.(j) < last then rep := false ;\r\n if tab.(j) = -1 then tab.(j) <- (-2)\r\n done;\r\n end ; tab.(num) <- i ;\r\n \r\n done;\r\n if !rep then print_endline \"YES\" else print_endline \"NO\"\r\ndone;;\r\n "}], "negative_code": [{"source_code": "module CharOrd = struct\r\n type t = char\r\n\r\n let compare x y = if x < y then -1 else if x > y then 1 else 0\r\nend\r\n\r\nmodule CharSet = Set.Make (CharOrd)\r\n\r\nlet solve () =\r\n let str = read_line () in\r\n let n = String.length str in\r\n let c = ref CharSet.empty in\r\n let rec find_k i =\r\n if i >= n then n - 1\r\n else if CharSet.exists (fun x -> x == String.get str i) !c then i\r\n else (\r\n c := CharSet.add (String.get str i) !c;\r\n find_k (i + 1))\r\n in\r\n let k = find_k 0 in\r\n let rec is_ok i =\r\n if i >= n then true\r\n else if String.get str i = String.get str (i - k) then is_ok (i + 1)\r\n else false\r\n in\r\n if is_ok k then \"YES\" else \"NO\"\r\n\r\nlet () =\r\n let t = read_int () in\r\n for i = 0 to t - 1 do\r\n print_endline (solve ())\r\n done\r\n"}, {"source_code": "let n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let a = input_line stdin in \r\nlet tab = Array.make 26 (-1) in\r\n let rep = ref true in\r\n for i = 0 to String.length a - 1 do\r\n let lett = a.[i] in\r\n let num = Char.code lett - 97 in\r\n if !rep && (tab.(num) <> -1) then begin\r\n let last = tab.(num) in\r\n for j = 0 to 25 do\r\n if tab.(j) <> -1 && tab.(j) < last then rep := false\r\n done;\r\n \r\n end ; tab.(num) <- i ;\r\n \r\n done;\r\n if !rep then print_endline \"YES\" else print_endline \"NO\"\r\ndone;;\r\n "}], "src_uid": "dd098a17343a02fa5dc0d2d6cea853c7"} {"nl": {"description": "There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x,\u2009y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0,\u2009y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0,\u2009y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. ", "input_spec": "The first line contains three integers n, x0 \u0438 y0 (1\u2009\u2264\u2009n\u2009\u2264\u20091000, \u2009-\u2009104\u2009\u2264\u2009x0,\u2009y0\u2009\u2264\u2009104) \u2014 the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi (\u2009-\u2009104\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009104) \u2014 the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.", "output_spec": "Print a single integer \u2014 the minimum number of shots Han Solo needs to destroy all the stormtroopers. ", "sample_inputs": ["4 0 0\n1 1\n2 2\n2 0\n-1 -1", "2 1 2\n1 1\n1 0"], "sample_outputs": ["2", "1"], "notes": "NoteExplanation to the first and second samples from the statement, respectively: "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a\n\nlet ( -- ) (a,b) (c,d) = (a-c,b-d)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let gun = read_pair () in\n let point = Array.init n (fun _ -> (read_pair()) -- gun) in\n\n let h = Hashtbl.create 10 in\n\n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n for i=0 to n-1 do\n let (x,y) = point.(i) in\n let g = gcd (abs x) (abs y) in\n let (x,y) = (x/g, y/g) in\n let (x,y) = min (x,y) (-x,-y) in\n increment (x,y);\n done;\n\n printf \"%d\\n\" (Hashtbl.length h)\n"}, {"source_code": "(* test if points a, b, c are colinear *)\nlet colinear (ax, ay) (bx, by) (cx, cy) =\n (ax - cx) * (by - cy) = (ay - cy) * (bx - cx)\n\nlet () = Scanf.scanf \"%d %d %d\\n\" (fun n x0 y0 ->\n let colinear = colinear (x0, y0) in\n let points = Array.init n (fun _ ->\n Scanf.scanf \"%d %d\\n\" (fun x y -> (x, y)))\n in\n let rays = ref [points.(0)] in\n Array.iter (fun p ->\n (* check each ray to see if it hits this point *)\n let rec aux = function\n | [] -> false\n | q :: ps -> if colinear p q then true else aux ps\n in\n if not (aux !rays) then\n rays := p :: !rays\n ) points;\n Printf.printf \"%d\\n\" (List.length !rays)\n)\n"}], "negative_code": [], "src_uid": "8d2845c33645ac45d4d37f9493b0c380"} {"nl": {"description": "You are given a sequence of integers of length $$$n$$$ and integer number $$$k$$$. You should print any integer number $$$x$$$ in the range of $$$[1; 10^9]$$$ (i.e. $$$1 \\le x \\le 10^9$$$) such that exactly $$$k$$$ elements of given sequence are less than or equal to $$$x$$$.Note that the sequence can contain equal elements.If there is no such $$$x$$$, print \"-1\" (without quotes).", "input_spec": "The first line of the input contains integer numbers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le k \\le n$$$). The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the sequence itself.", "output_spec": "Print any integer number $$$x$$$ from range $$$[1; 10^9]$$$ such that exactly $$$k$$$ elements of given sequence is less or equal to $$$x$$$. If there is no such $$$x$$$, print \"-1\" (without quotes).", "sample_inputs": ["7 4\n3 7 5 1 10 3 20", "7 2\n3 7 5 1 10 3 20"], "sample_outputs": ["6", "-1"], "notes": "NoteIn the first example $$$5$$$ is also a valid answer because the elements with indices $$$[1, 3, 4, 6]$$$ is less than or equal to $$$5$$$ and obviously less than or equal to $$$6$$$.In the second example you cannot choose any number that only $$$2$$$ elements of the given sequence will be less than or equal to this number because $$$3$$$ elements of the given sequence will be also less than or equal to this number."}, "positive_code": [{"source_code": "let split_string ?(pattern=\" \") = Str.split @@ Str.regexp pattern\nlet (n, k) = Scanf.sscanf (read_line ()) \"%d %d\" @@ fun n k -> (n, k)\nlet a = read_line () |> split_string |> List.map int_of_string |> List.sort compare |> Array.of_list\n\nlet () = \n if k = 0 then Printf.printf \"%d\\n\" (if a.(0) > 1 then a.(0) - 1 else -1) \n else if n = k then Printf.printf \"%d\\n\" a.(k - 1)\n else if a.(k - 1) <> a.(k) then Printf.printf \"%d\\n\" a.(k - 1)\n else print_endline \"-1\""}], "negative_code": [], "src_uid": "55297e2a65144323af4d6abd6a6ef050"} {"nl": {"description": "Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string si\u00a0\u2014 the name of the i-th polyhedron in Anton's collection. The string can look like this: \"Tetrahedron\" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. \"Cube\" (without quotes), if the i-th polyhedron in Anton's collection is a cube. \"Octahedron\" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. \"Dodecahedron\" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. \"Icosahedron\" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron. ", "output_spec": "Output one number\u00a0\u2014 the total number of faces in all the polyhedrons in Anton's collection.", "sample_inputs": ["4\nIcosahedron\nCube\nTetrahedron\nDodecahedron", "3\nDodecahedron\nOctahedron\nOctahedron"], "sample_outputs": ["42", "28"], "notes": "NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20\u2009+\u20096\u2009+\u20094\u2009+\u200912\u2009=\u200942 faces."}, "positive_code": [{"source_code": "let make_list () = \n let n = Pervasives.read_int () in\n let rec loop i list =\n if i < n\n then\n let shape = Pervasives.read_line () in\n loop (i + 1) (shape :: list)\n else\n list\n in loop 0 []\n\nlet counter count shape =\n match shape with\n | \"Tetrahedron\" -> count + 4\n | \"Cube\" -> count + 6\n | \"Octahedron\" -> count + 8\n | \"Dodecahedron\" -> count + 12\n | \"Icosahedron\" -> count + 20\n\nlet () = \n let shapes = make_list () in\n let count = List.fold_left counter 0 shapes in\n Pervasives.print_int count"}, {"source_code": "let counter shape count =\n match shape with\n | \"Tetrahedron\" -> count + 4\n | \"Cube\" -> count + 6\n | \"Octahedron\" -> count + 8\n | \"Dodecahedron\" -> count + 12\n | \"Icosahedron\" -> count + 20\n\nlet () = \n let n = Pervasives.read_int () in\n let rec loop i count =\n if i < n\n then\n let shape = Pervasives.read_line () in\n loop (i + 1) (counter shape count)\n else\n Pervasives.print_int count\n in loop 0 0"}, {"source_code": "let main () =\n let gr () = Scanf.scanf \"%d\" (fun i -> i) in \n let gs () = Scanf.scanf \"\\n%s\" (fun i -> i) in \n let n = gr () in\n let rec solve cnt ans = \n match cnt with \n | 0 -> ans\n | cnt -> \n let line = gs() in \n let sides = match line with \n | \"Tetrahedron\" -> 4\n | \"Cube\" -> 6\n | \"Octahedron\" -> 8\n | \"Dodecahedron\" -> 12\n | \"Icosahedron\" -> 20\n | somestr -> Printf.printf \"!!!%s\\n\" (somestr); 0\n in \n solve (cnt - 1) (ans + sides)\n in \n Printf.printf \"%d\\n\" (solve n 0);;\nlet _ = main();;\n"}, {"source_code": "let n = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet rec names n = \n if n == 0 \n then [] \n else Scanf.scanf \" %s\" (fun x -> x::(names (n - 1))) \nin\n\nlet sides names =\n let rec helper names acc =\n match names with\n | [] -> acc\n | hd::tl ->\n match hd with\n | \"Tetrahedron\" -> helper tl (acc + 4)\n | \"Cube\" -> helper tl (acc + 6)\n | \"Octahedron\" -> helper tl (acc + 8)\n | \"Dodecahedron\" -> helper tl (acc + 12)\n | \"Icosahedron\" -> helper tl (acc + 20)\n | _ -> 0\n in helper names 0\nin\n\nPrintf.printf \"%d\\n\" (sides (names n))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n\n let answer = sum 0 (n-1) (fun _ ->\n match read_string() with\n | \"Tetrahedron\" -> 4\n | \"Cube\" -> 6\n | \"Octahedron\" -> 8\n | \"Dodecahedron\" -> 12\n | \"Icosahedron\" -> 20\n | _ -> failwith \"bad input\"\n ) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "e6689123fefea251555e0e096f58f6d1"} {"nl": {"description": "Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1,\u2009x2,\u2009...,\u2009xk (k\u2009>\u20091) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1,\u2009x2,\u2009...,\u2009xk (k\u2009>\u20091) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1,\u2009s2,\u2009...,\u2009sn (n\u2009>\u20091). Let's denote sequence sl,\u2009sl\u2009+\u20091,\u2009...,\u2009sr as s[l..r] (1\u2009\u2264\u2009l\u2009<\u2009r\u2009\u2264\u2009n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence.", "input_spec": "The first line contains integer n (1\u2009<\u2009n\u2009\u2264\u2009105). The second line contains n distinct integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009si\u2009\u2264\u2009109).", "output_spec": "Print a single integer \u2014 the maximum lucky number among all lucky numbers of sequences s[l..r].", "sample_inputs": ["5\n5 2 1 4 3", "5\n9 8 3 5 7"], "sample_outputs": ["7", "15"], "notes": "NoteFor the first sample you can choose s[4..5]\u2009=\u2009{4,\u20093} and its lucky number is (4\u00a0xor\u00a03)\u2009=\u20097. You can also choose s[1..2].For the second sample you must choose s[2..5]\u2009=\u2009{8,\u20093,\u20095,\u20097}."}, "positive_code": [{"source_code": "let read_int() = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nmodule Imap = Map.Make (struct type t = int let compare = compare end)\n\nlet () = \n let n = read_int() in\n let s = Array.init n (fun i-> (read_int(), i)) in\n \n let () = Array.sort compare s in\n \n let bestxor = ref 0 in\n\n let trypair x y = bestxor := max !bestxor (x lxor y) in\n\n let rec loop i m = if i<0 then () else \n let (s,j) = s.(i) in\n let (l,_,r) = Imap.split j m in\n if not (Imap.is_empty l) then (\n\tlet (_, h) = Imap.max_binding l in\n\t trypair h s\n );\n if not (Imap.is_empty r) then (\n\tlet (_, h) = Imap.min_binding r in\n\t trypair h s\n );\n loop (i-1) (Imap.add j s m)\n in\n\n loop (n-1) Imap.empty;\n Printf.printf \"%d\\n\" !bestxor\n"}], "negative_code": [], "src_uid": "c9b9c56d50eaf605e7bc088385a42a1d"} {"nl": {"description": "Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.", "input_spec": "First line contains four integers n,\u2009m,\u2009k,\u2009s (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105,\u20091\u2009\u2264\u2009s\u2009\u2264\u2009109) \u2014 number of days, total number and required number of gadgets, number of burles Nura has. Second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the cost of one dollar in burles on i-th day. Third line contains n integers bi (1\u2009\u2264\u2009bi\u2009\u2264\u2009106) \u2014 the cost of one pound in burles on i-th day. Each of the next m lines contains two integers ti,\u2009ci (1\u2009\u2264\u2009ti\u2009\u2264\u20092,\u20091\u2009\u2264\u2009ci\u2009\u2264\u2009106) \u2014 type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.", "output_spec": "If Nura can't buy k gadgets print the only line with the number -1. Otherwise the first line should contain integer d \u2014 the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi,\u2009di \u2014 the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n. In case there are multiple possible solutions, print any of them.", "sample_inputs": ["5 4 2 2\n1 2 3 2 1\n3 2 1 2 3\n1 1\n2 1\n1 2\n2 2", "4 3 2 200\n69 70 71 72\n104 105 106 107\n1 1\n2 2\n1 2", "4 3 1 1000000000\n900000 910000 940000 990000\n990000 999000 999900 999990\n1 87654\n2 76543\n1 65432"], "sample_outputs": ["3\n1 1\n2 3", "-1", "-1"], "notes": null}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let a0 = Array.make n 0 in\n let a1 = Array.make n 0 in\n let am0 = Array.make n 0 in\n let am1 = Array.make n 0 in\n let c0 = Array.make m (0, 0) in\n let c1 = Array.make m (0, 0) in\n let cnt0 = ref 0 in\n let cnt1 = ref 0 in\n let t0 = ref 0L in\n let t1 = ref 0L in\n for i = 0 to n - 1 do\n a0.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am0.(i) <-\n\tif i = 0\n\tthen a0.(i)\n\telse min am0.(i - 1) a0.(i);\n done;\n for i = 0 to n - 1 do\n a1.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am1.(i) <-\n\tif i = 0\n\tthen a1.(i)\n\telse min am1.(i - 1) a1.(i);\n done;\n for i = 0 to m - 1 do\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tif t = 1 then (\n\t c0.(!cnt0) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t incr cnt0;\n\t) else (\n\t c1.(!cnt1) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t incr cnt1;\n\t)\n done;\n let cnt0 = !cnt0 in\n let cnt1 = !cnt1 in\n let c0 = Array.sub c0 0 cnt0 in\n let c1 = Array.sub c1 0 cnt1 in\n let res = ref (n + 1) in\n let best0 = ref 0 in\n Array.sort compare c0;\n Array.sort compare c1;\n for i = 0 to min k cnt1 - 1 do\n\tt1 := !t1 +| Int64.of_int (fst c1.(i));\n done;\n for i = 0 to cnt0 do\n\tif k - i <= cnt1 then (\n(*Printf.printf \"asd %d %Ld %Ld\\n\" i !t0 !t1;*)\n\t let l = ref (-1)\n\t and r = ref n in\n\t while !l < !r - 1 do\n\t let m = (!l + !r) / 2 in\n\t let t =\n\t\tInt64.of_int am0.(m) *| !t0 +|\n\t\t Int64.of_int am1.(m) *| !t1\n\t in\n\t\tif t <= s\n\t\tthen r := m\n\t\telse l := m\n\t done;\n(*if n = 34 then Printf.printf \"asd %d %Ld %Ld %d\\n\" i !t0 !t1 (!r + 1);*)\n\t if !res > !r + 1 then (\n\t res := !r + 1;\n\t best0 := i;\n\t )\n\t);\n\tif i < cnt0 then (\n\t t0 := !t0 +| Int64.of_int (fst c0.(i));\n\t);\n\tif k - 1 - i < cnt1 && k - 1 - i >= 0 then (\n\t t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));\n\t);\n done;\n if !res > n\n then Printf.printf \"%d\\n\" (-1)\n else (\n\tPrintf.printf \"%d\\n\" !res;\n\tlet d0 = ref 0 in\n\tlet d1 = ref 0 in\n\tlet s' = ref 0L in\n\t for i = 0 to !res - 1 do\n\t if a0.(i) < a0.(!d0)\n\t then d0 := i;\n\t if a1.(i) < a1.(!d1)\n\t then d1 := i;\n\t done;\n\t incr d0;\n\t incr d1;\n\t for i = 0 to !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c0.(i) + 1) !d0;\n\t s' := !s' +| Int64.of_int (fst c0.(i)) *| Int64.of_int a0.(!d0 - 1);\n\t done;\n\t for i = 0 to k - !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c1.(i) + 1) !d1;\n\t s' := !s' +| Int64.of_int (fst c1.(i)) *| Int64.of_int a1.(!d1 - 1);\n\t done;\n\t (*Printf.printf \"qwe %Ld\\n\" !s';*)\n\t assert (!s' <= s);\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet ( ++ ) a b = Int64.add a b\nlet ( ** ) a b = Int64.mul a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n let k = read_int() in\n let s = long (read_int()) in \n\n let dcost = Array.init n (fun _ -> long (read_int())) in\n let pcost = Array.init n (fun _ -> long (read_int())) in \n\n let rec read_loop i plist dlist = if i=m then (plist,dlist) else\n let t = read_int () in\n let cost = long (read_int ()) in\n if t = 1\n then read_loop (i+1) plist ((cost,i)::dlist)\n else read_loop (i+1) ((cost,i)::plist) dlist\n in\n\n let (plist,dlist) = read_loop 0 [] [] in\n let parray = Array.of_list (List.sort compare plist) in\n let darray = Array.of_list (List.sort compare dlist) in\n\n (*\n let rec firstk i li ac = if i = k then List.rev ac else\n match li with\n\t| [] -> List.rev ac\t \n\t| h::t -> firstk (i+1) t (h::ac)\n in\n \n let plist = firstk 0 plist [] in\n let dlist = firstk 0 dlist [] in \n let dlist = List.rev dlist in\n *)\n \n let nd = min k (Array.length darray) in\n let np = Array.length parray in\n let p_start = k - nd in\n let dsum = sum 0 (nd-1) (fun i -> fst darray.(i)) 0L in\n let psum = sum 0 (p_start-1) (fun i -> fst parray.(i)) 0L in\n \n let is_possible d =\n (* return true if it's possible to get k gadgets in the first d days *)\n (* days are numbered 0, 1, 2, ... n-1. so we're looking at days 0,1,..d-1 *)\n let (best_dollar, dday) = minf 0 (d-1) (fun j -> (dcost.(j), j)) in\n let (best_pound, pday) = minf 0 (d-1) (fun j -> (pcost.(j), j)) in\n\n let rec scan i dsum psum = \n if best_dollar ** dsum ++ best_pound ** psum <= s then i\n else if i >= nd || i + p_start >= np then -1 else\n\tscan (i+1) (dsum -- (fst darray.(nd-1-i))) (psum ++ (fst parray.(p_start+i)))\n in\n\n let goodi = scan 0 dsum psum in\n (goodi >= 0, (dday, pday, goodi))\n in\n\n let rec bsearch lo hi =\n (* lo is impossible, hi is possible *)\n if lo = hi-1 then hi else\n let m = (lo+hi)/2 in\n if fst (is_possible m) then bsearch lo m else bsearch m hi\n in\n\n if not (fst (is_possible n)) then printf \"-1\\n\" else (\n let answer = bsearch 0 n in\n printf \"%d\\n\" answer;\n\n let (_, (dday, pday, goodi)) = is_possible answer in\n\n for j=0 to nd-goodi-1 do\n printf \"%d %d\\n\" (1+ snd darray.(j)) (1+dday)\n done;\n\n for j=0 to p_start+goodi-1 do\n printf \"%d %d\\n\" (1+ snd parray.(j)) (1+pday)\n done\n \n )\n"}], "negative_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let a0 = Array.make n 0 in\n let a1 = Array.make n 0 in\n let am0 = Array.make n 0 in\n let am1 = Array.make n 0 in\n let c0 = Array.make m (0, 0) in\n let c1 = Array.make m (0, 0) in\n let cnt0 = ref 0 in\n let cnt1 = ref 0 in\n let t0 = ref 0L in\n let t1 = ref 0L in\n for i = 0 to n - 1 do\n a0.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am0.(i) <-\n\tif i = 0\n\tthen a0.(i)\n\telse min am0.(i - 1) a0.(i);\n done;\n for i = 0 to n - 1 do\n a1.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am1.(i) <-\n\tif i = 0\n\tthen a1.(i)\n\telse min am1.(i - 1) a1.(i);\n done;\n for i = 0 to m - 1 do\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tif t = 1 then (\n\t c0.(!cnt0) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t incr cnt0;\n\t) else (\n\t c1.(!cnt1) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t t1 := !t1 +| Int64.of_int (fst c1.(!cnt1));\n\t incr cnt1;\n\t)\n done;\n let cnt0 = !cnt0 in\n let cnt1 = !cnt1 in\n let c0 = Array.sub c0 0 cnt0 in\n let c1 = Array.sub c1 0 cnt1 in\n let res = ref (n + 1) in\n let best0 = ref 0 in\n Array.sort compare c0;\n Array.sort compare c1;\n for i = 0 to cnt0 do\n\tif k - i <= cnt1 then (\n(*Printf.printf \"asd %d %Ld %Ld\\n\" i !t0 !t1;*)\n\t let l = ref (-1)\n\t and r = ref n in\n\t while !l < !r - 1 do\n\t let m = (!l + !r) / 2 in\n\t let t =\n\t\tInt64.of_int am0.(m) *| !t0 +|\n\t\t Int64.of_int am1.(m) *| !t1\n\t in\n\t\tif t <= s\n\t\tthen r := m\n\t\telse l := m\n\t done;\nif n = 34 then Printf.printf \"asd %d %Ld %Ld %d\\n\" i !t0 !t1 (!r + 1);\n\t if !res > !r + 1 then (\n\t res := !r + 1;\n\t best0 := i;\n\t )\n\t);\n\tif i < cnt0 then (\n\t t0 := !t0 +| Int64.of_int (fst c0.(i));\n\t);\n\tif k - 1 - i < cnt1 && k - 1 - i >= 0 then (\n\t t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));\n\t);\n done;\n if !res > n\n then Printf.printf \"%d\\n\" (-1)\n else (\n\tPrintf.printf \"%d\\n\" !res;\n\tlet d0 = ref 0 in\n\tlet d1 = ref 0 in\n\tlet s' = ref 0L in\n\t for i = 0 to !res - 1 do\n\t if a0.(i) < a0.(!d0)\n\t then d0 := i;\n\t if a1.(i) < a1.(!d1)\n\t then d1 := i;\n\t done;\n\t incr d0;\n\t incr d1;\n\t for i = 0 to !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c0.(i) + 1) !d0;\n\t s' := !s' +| Int64.of_int (fst c0.(i)) *| Int64.of_int a0.(!d0 - 1);\n\t done;\n\t for i = 0 to k - !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c1.(i) + 1) !d1;\n\t s' := !s' +| Int64.of_int (fst c1.(i)) *| Int64.of_int a1.(!d1 - 1);\n\t done;\n\t (*Printf.printf \"qwe %Ld\\n\" !s';*)\n\t assert (!s' <= s);\n )\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a0 = Array.make n 0 in\n let a1 = Array.make n 0 in\n let am0 = Array.make n 0 in\n let am1 = Array.make n 0 in\n let c0 = Array.make m (0, 0) in\n let c1 = Array.make m (0, 0) in\n let cnt0 = ref 0 in\n let cnt1 = ref 0 in\n let t0 = ref 0L in\n let t1 = ref 0L in\n for i = 0 to n - 1 do\n a0.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am0.(i) <-\n\tif i = 0\n\tthen a0.(i)\n\telse min am0.(i - 1) a0.(i);\n done;\n for i = 0 to n - 1 do\n a1.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am1.(i) <-\n\tif i = 0\n\tthen a1.(i)\n\telse min am1.(i - 1) a1.(i);\n done;\n for i = 0 to m - 1 do\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tif t = 1 then (\n\t c0.(!cnt0) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t incr cnt0;\n\t) else (\n\t c1.(!cnt1) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t t1 := !t1 +| Int64.of_int (fst c1.(!cnt1));\n\t incr cnt1;\n\t)\n done;\n let cnt0 = !cnt0 in\n let cnt1 = !cnt1 in\n let c0 = Array.sub c0 0 cnt0 in\n let c1 = Array.sub c1 0 cnt1 in\n let res = ref (n + 1) in\n let best0 = ref 0 in\n Array.sort compare c0;\n Array.sort compare c1;\n for i = 0 to cnt0 do\n\tif k - i <= cnt1 then (\n(*Printf.printf \"asd %d %Ld %Ld\\n\" i !t0 !t1;*)\n\t let l = ref (-1)\n\t and r = ref n in\n\t while !l < !r - 1 do\n\t let m = (!l + !r) / 2 in\n\t let t =\n\t\tInt64.of_int am0.(m) *| !t0 +|\n\t\t Int64.of_int am1.(m) *| !t1\n\t in\n\t\tif t <= Int64.of_int s\n\t\tthen r := m\n\t\telse l := m\n\t done;\n\t if !res > !r + 1 then (\n\t res := !r + 1;\n\t best0 := i;\n\t )\n\t);\n\tif i < cnt0 then (\n\t t0 := !t0 +| Int64.of_int (fst c0.(i));\n\t);\n\tif k - 1 - i < cnt1 && k - 1 - i >= 0 then (\n\t t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));\n\t);\n done;\n if !res > n\n then Printf.printf \"%d\\n\" (-1)\n else (\n\tPrintf.printf \"%d\\n\" !res;\n\tlet d0 = ref 0 in\n\tlet d1 = ref 0 in\n\tlet s' = ref 0L in\n\t for i = 0 to !res - 1 do\n\t if a0.(i) < a0.(!d0)\n\t then d0 := i;\n\t if a1.(i) < a1.(!d1)\n\t then d1 := i;\n\t done;\n\t incr d0;\n\t incr d1;\n\t for i = 0 to !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c0.(i) + 1) !d0;\n\t s' := !s' +| Int64.of_int (fst c0.(i)) *| Int64.of_int a0.(!d0 - 1);\n\t done;\n\t for i = 0 to k - !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c1.(i) + 1) !d1;\n\t s' := !s' +| Int64.of_int (fst c1.(i)) *| Int64.of_int a1.(!d1 - 1);\n\t done;\n\t assert (!s' <= Int64.of_int s);\n )\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let a0 = Array.make n 0 in\n let a1 = Array.make n 0 in\n let am0 = Array.make n 0 in\n let am1 = Array.make n 0 in\n let c0 = Array.make m (0, 0) in\n let c1 = Array.make m (0, 0) in\n let cnt0 = ref 0 in\n let cnt1 = ref 0 in\n let t0 = ref 0L in\n let t1 = ref 0L in\n for i = 0 to n - 1 do\n a0.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am0.(i) <-\n\tif i = 0\n\tthen a0.(i)\n\telse min am0.(i - 1) a0.(i);\n done;\n for i = 0 to n - 1 do\n a1.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am1.(i) <-\n\tif i = 0\n\tthen a1.(i)\n\telse min am1.(i - 1) a1.(i);\n done;\n for i = 0 to m - 1 do\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tif t = 1 then (\n\t c0.(!cnt0) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t incr cnt0;\n\t) else (\n\t c1.(!cnt1) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t if !cnt1 < k\n\t then t1 := !t1 +| Int64.of_int (fst c1.(!cnt1));\n\t incr cnt1;\n\t)\n done;\n let cnt0 = !cnt0 in\n let cnt1 = !cnt1 in\n let c0 = Array.sub c0 0 cnt0 in\n let c1 = Array.sub c1 0 cnt1 in\n let res = ref (n + 1) in\n let best0 = ref 0 in\n Array.sort compare c0;\n Array.sort compare c1;\n for i = 0 to cnt0 do\n\tif k - i <= cnt1 then (\n(*Printf.printf \"asd %d %Ld %Ld\\n\" i !t0 !t1;*)\n\t let l = ref (-1)\n\t and r = ref n in\n\t while !l < !r - 1 do\n\t let m = (!l + !r) / 2 in\n\t let t =\n\t\tInt64.of_int am0.(m) *| !t0 +|\n\t\t Int64.of_int am1.(m) *| !t1\n\t in\n\t\tif t <= s\n\t\tthen r := m\n\t\telse l := m\n\t done;\n(*if n = 34 then Printf.printf \"asd %d %Ld %Ld %d\\n\" i !t0 !t1 (!r + 1);*)\n\t if !res > !r + 1 then (\n\t res := !r + 1;\n\t best0 := i;\n\t )\n\t);\n\tif i < cnt0 then (\n\t t0 := !t0 +| Int64.of_int (fst c0.(i));\n\t);\n\tif k - 1 - i < cnt1 && k - 1 - i >= 0 then (\n\t t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));\n\t);\n done;\n if !res > n\n then Printf.printf \"%d\\n\" (-1)\n else (\n\tPrintf.printf \"%d\\n\" !res;\n\tlet d0 = ref 0 in\n\tlet d1 = ref 0 in\n\tlet s' = ref 0L in\n\t for i = 0 to !res - 1 do\n\t if a0.(i) < a0.(!d0)\n\t then d0 := i;\n\t if a1.(i) < a1.(!d1)\n\t then d1 := i;\n\t done;\n\t incr d0;\n\t incr d1;\n\t for i = 0 to !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c0.(i) + 1) !d0;\n\t s' := !s' +| Int64.of_int (fst c0.(i)) *| Int64.of_int a0.(!d0 - 1);\n\t done;\n\t for i = 0 to k - !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c1.(i) + 1) !d1;\n\t s' := !s' +| Int64.of_int (fst c1.(i)) *| Int64.of_int a1.(!d1 - 1);\n\t done;\n\t (*Printf.printf \"qwe %Ld\\n\" !s';*)\n\t assert (!s' <= s);\n )\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a0 = Array.make n 0 in\n let a1 = Array.make n 0 in\n let am0 = Array.make n 0 in\n let am1 = Array.make n 0 in\n let c0 = Array.make m (0, 0) in\n let c1 = Array.make m (0, 0) in\n let cnt0 = ref 0 in\n let cnt1 = ref 0 in\n let t0 = ref 0L in\n let t1 = ref 0L in\n for i = 0 to n - 1 do\n a0.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am0.(i) <-\n\tif i = 0\n\tthen a0.(i)\n\telse min am0.(i - 1) a0.(i);\n done;\n for i = 0 to n - 1 do\n a1.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n am1.(i) <-\n\tif i = 0\n\tthen a1.(i)\n\telse min am1.(i - 1) a1.(i);\n done;\n for i = 0 to m - 1 do\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tif t = 1 then (\n\t c0.(!cnt0) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t incr cnt0;\n\t) else (\n\t c1.(!cnt1) <- (Scanf.bscanf sb \"%d \" (fun s -> s), i);\n\t t1 := !t1 +| Int64.of_int (fst c1.(!cnt1));\n\t incr cnt1;\n\t)\n done;\n let cnt0 = !cnt0 in\n let cnt1 = !cnt1 in\n let c0 = Array.sub c0 0 cnt0 in\n let c1 = Array.sub c1 0 cnt1 in\n let res = ref (n + 1) in\n let best0 = ref 0 in\n Array.sort compare c0;\n Array.sort compare c1;\n for i = 0 to cnt0 do\n\tif k - i <= cnt1 then (\n\t let l = ref (-1)\n\t and r = ref n in\n\t while !l < !r - 1 do\n\t let m = (!l + !r) / 2 in\n\t let t =\n\t\tInt64.of_int am0.(m) *| !t0 +|\n\t\t Int64.of_int am1.(m) *| !t1\n\t in\n\t\tif t <= Int64.of_int s\n\t\tthen r := m\n\t\telse l := m\n\t done;\n\t if !res > !r + 1 then (\n\t res := !r + 1;\n\t best0 := i;\n\t )\n\t);\n\tif i < cnt0 then (\n\t t0 := !t0 +| Int64.of_int (fst c0.(i));\n\t);\n\tif k - 1 - i < cnt1 && k - 1 - i >= 0 then (\n\t t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));\n\t);\n done;\n if !res > n\n then Printf.printf \"%d\\n\" (-1)\n else (\n\tPrintf.printf \"%d\\n\" !res;\n\tlet d0 = ref 0 in\n\tlet d1 = ref 0 in\n\t for i = 0 to !res - 1 do\n\t if a0.(i) < a0.(!d0)\n\t then d0 := i;\n\t if a1.(i) < a1.(!d0)\n\t then d1 := i;\n\t done;\n\t incr d0;\n\t incr d1;\n\t for i = 0 to !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c0.(i) + 1) !d0;\n\t done;\n\t for i = 0 to k - !best0 - 1 do\n\t Printf.printf \"%d %d\\n\" (snd c1.(i) + 1) !d1;\n\t done;\n )\n"}], "src_uid": "045c8f116415f277fb7cf1109488b589"} {"nl": {"description": "Codeforces user' handle color depends on his rating\u00a0\u2014 it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of participants Anton has outscored in this contest . The next n lines describe participants results: the i-th of them consists of a participant handle namei and two integers beforei and afteri (\u2009-\u20094000\u2009\u2264\u2009beforei,\u2009afteri\u2009\u2264\u20094000)\u00a0\u2014 participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters \u00ab_\u00bb and \u00ab-\u00bb characters. It is guaranteed that all handles are distinct.", "output_spec": "Print \u00abYES\u00bb (quotes for clarity), if Anton has performed good in the contest and \u00abNO\u00bb (quotes for clarity) otherwise.", "sample_inputs": ["3\nBurunduk1 2526 2537\nBudAlNik 2084 2214\nsubscriber 2833 2749", "3\nApplejack 2400 2400\nFluttershy 2390 2431\nPinkie_Pie -2500 -2450"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest.In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let res = ref false in\n for i = 1 to n do\n let _s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tif b >= 2400 && a > b\n\tthen res := true\n done;\n if !res\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}], "negative_code": [], "src_uid": "3bff9b69423cf6c8425e347a4beef96b"} {"nl": {"description": "Bob came to a cash & carry store, put n items into his trolley, and went to the checkout counter to pay. Each item is described by its price ci and time ti in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. To steal one item Bob needs exactly 1 second. What is the minimum amount of money that Bob will have to pay to the checkout assistant? Remember, please, that it is Bob, who determines the order of items for the checkout assistant.", "input_spec": "The first input line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u20092000). In each of the following n lines each item is described by a pair of numbers ti, ci (0\u2009\u2264\u2009ti\u2009\u2264\u20092000,\u20091\u2009\u2264\u2009ci\u2009\u2264\u2009109). If ti is 0, Bob won't be able to steal anything, while the checkout assistant is occupied with item i.", "output_spec": "Output one number \u2014 answer to the problem: what is the minimum amount of money that Bob will have to pay.", "sample_inputs": ["4\n2 10\n0 20\n1 5\n1 3", "3\n0 1\n0 10\n0 100"], "sample_outputs": ["8", "111"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\n\nopen Int64\n\nlet () =\n let n = read_int 0 in\n let s = Array.make (n+1) (shift_right max_int 1) in\n s.(0) <- 0L;\n for i = 1 to n do\n let t = read_int 0 in\n let c = read_int64 0 in\n for j = n-1 downto 0 do\n let x = min (j+t+1) n in\n s.(x) <- min s.(x) (add s.(j) c)\n done\n done;\n Printf.printf \"%Ld\\n\" s.(n)\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let s = Array.make (n+1) (max_int/2) in\n s.(0) <- 0;\n for i = 1 to n do\n let t = read_int 0 in\n let c = read_int 0 in\n for j = n-1 downto 0 do\n let x = min (j+t+1) n in\n s.(x) <- min s.(x) (s.(j)+c)\n done\n done;\n Printf.printf \"%d\\n\" s.(n)\n"}], "src_uid": "97bbbf864fafcf95794db671deb6924b"} {"nl": {"description": "Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.There are $$$n$$$ flights from A to B, they depart at time moments $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ and arrive at B $$$t_a$$$ moments later.There are $$$m$$$ flights from B to C, they depart at time moments $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ and arrive at C $$$t_b$$$ moments later.The connection time is negligible, so one can use the $$$i$$$-th flight from A to B and the $$$j$$$-th flight from B to C if and only if $$$b_j \\ge a_i + t_a$$$.You can cancel at most $$$k$$$ flights. If you cancel a flight, Arkady can not use it.Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel $$$k$$$ flights. If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$.", "input_spec": "The first line contains five integers $$$n$$$, $$$m$$$, $$$t_a$$$, $$$t_b$$$ and $$$k$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$, $$$1 \\le k \\le n + m$$$, $$$1 \\le t_a, t_b \\le 10^9$$$)\u00a0\u2014 the number of flights from A to B, the number of flights from B to C, the flight time from A to B, the flight time from B to C and the number of flights you can cancel, respectively. The second line contains $$$n$$$ distinct integers in increasing order $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ ($$$1 \\le a_1 < a_2 < \\ldots < a_n \\le 10^9$$$)\u00a0\u2014 the times the flights from A to B depart. The third line contains $$$m$$$ distinct integers in increasing order $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ ($$$1 \\le b_1 < b_2 < \\ldots < b_m \\le 10^9$$$)\u00a0\u2014 the times the flights from B to C depart.", "output_spec": "If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$. Otherwise print the earliest time Arkady can arrive at C if you cancel $$$k$$$ flights in such a way that maximizes this time.", "sample_inputs": ["4 5 1 1 2\n1 3 5 7\n1 2 3 9 10", "2 2 4 4 2\n1 10\n10 20", "4 3 2 3 1\n1 999999998 999999999 1000000000\n3 4 1000000000"], "sample_outputs": ["11", "-1", "1000000003"], "notes": "NoteConsider the first example. The flights from A to B depart at time moments $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ and arrive at B at time moments $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, respectively. The flights from B to C depart at time moments $$$1$$$, $$$2$$$, $$$3$$$, $$$9$$$, and $$$10$$$ and arrive at C at time moments $$$2$$$, $$$3$$$, $$$4$$$, $$$10$$$, $$$11$$$, respectively. You can cancel at most two flights. The optimal solution is to cancel the first flight from A to B and the fourth flight from B to C. This way Arkady has to take the second flight from A to B, arrive at B at time moment $$$4$$$, and take the last flight from B to C arriving at C at time moment $$$11$$$.In the second example you can simply cancel all flights from A to B and you're done.In the third example you can cancel only one flight, and the optimal solution is to cancel the first flight from A to B. Note that there is still just enough time to catch the last flight from B to C."}, "positive_code": [{"source_code": "let (++) = Int64.add\nlet (--) = Int64.sub\nlet (/) = Int64.div\nlet ( * ) = Int64.mul\n\nlet () =\n let n, m, ta, tb, k = Scanf.scanf \"%d %d %Ld %Ld %d\\n\" (fun x y z q e -> x, y, z, q, e) in\n let a =\n Array.init n\n (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x))\n |> Array.map ((++) ta)\n in\n let b =\n Array.init m\n (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x))\n in\n let ia = ref 0 in\n let prev = ref 0 in\n let toto =\n Array.mapi\n (fun ib b ->\n while ((!ia < n) && a.(!ia) <= b) do incr ia done;\n let x = min (!prev+1) (!ia) in\n prev := x;\n x\n ) b\n in\n if toto.(m-1) <= k then Printf.printf \"-1\"\n else begin\n let idx = ref 0 in\n while toto.(!idx) <= k do incr idx done;\n Printf.printf \"%Ld\" (b.(!idx) ++ tb)\n end\n;;\n"}], "negative_code": [], "src_uid": "bf60899aa2bd7350c805437d0fee1583"} {"nl": {"description": "Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.For each edge (u,\u2009v) find the minimal possible weight of the spanning tree that contains the edge (u,\u2009v).The weight of the spanning tree is the sum of weights of all edges included in spanning tree.", "input_spec": "First line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105,\u2009n\u2009-\u20091\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the number of vertices and edges in graph. Each of the next m lines contains three integers ui,\u2009vi,\u2009wi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n,\u2009ui\u2009\u2260\u2009vi,\u20091\u2009\u2264\u2009wi\u2009\u2264\u2009109) \u2014 the endpoints of the i-th edge and its weight.", "output_spec": "Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge. The edges are numbered from 1 to m in order of their appearing in input.", "sample_inputs": ["5 7\n1 2 3\n1 3 1\n1 4 5\n2 3 2\n2 5 3\n3 4 2\n4 5 4"], "sample_outputs": ["9\n8\n11\n8\n8\n8\n9"], "notes": null}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\ntype element = {mutable p : int;\n\t\tmutable rank : int;\n\t\tmutable w : int64}\n\ntype t = element array\n\nlet makeset set x =\n set.(x) <- {p = x; rank = 0; w = 0L}\n\n(*\nlet rec find set x =\n if x <> set.(x).p then set.(x).p <- find set set.(x).p;\n set.(x).p\n*)\nlet rec find set x =\n if x <> set.(x).p\n then find set set.(x).p\n else x\n\nlet link set x y w =\n if set.(x).rank > set.(y).rank then (\n set.(y).p <- x;\n set.(y).w <- w;\n x\n ) else (\n if set.(x).rank = set.(y).rank then set.(y).rank <- set.(y).rank + 1;\n set.(x).p <- y;\n set.(x).w <- w;\n y\n )\n\nlet newsets size =\n let set = Array.make size {p = -1; rank = 0; w = 0L} in\n for i = 0 to size-1 do\n makeset set i\n done;\n set\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make m (0L, 0, 0) in\n for i = 0 to m - 1 do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let w = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n\tes.(i) <- (w, u - 1, v - 1)\n done;\n let es' = Array.copy es in\n let () = Array.sort compare es in\n let ds = newsets n in\n let c = Array.make n (-1) in\n let t = ref 0L in\n for i = 0 to m - 1 do\n\tlet (w, u, v) = es.(i) in\n\tlet ru = find ds u in\n\tlet rv = find ds v in\n\t if ru <> rv then (\n\t ignore (link ds ru rv w);\n\t t := !t +| w\n\t )\n done;\n for i = 0 to m - 1 do\n\tlet lca =\n\t let (_w, u, v) = es'.(i) in\n\t let u = ref u in\n\t let v = ref v in\n\t while ds.(!u).p <> !u do\n\t c.(!u) <- i;\n\t u := ds.(!u).p\n\t done;\n\t c.(!u) <- i;\n\t while c.(!v) <> i do\n\t v := ds.(!v).p\n\t done;\n\t !v\n\tin\n\tlet (w, u, v) = es'.(i) in\n\tlet ww = ref 0L in\n\tlet u = ref u in\n\tlet v = ref v in\n\t while !u <> lca do\n\t ww := max !ww ds.(!u).w;\n\t u := ds.(!u).p\n\t done;\n\t while !v <> lca do\n\t ww := max !ww ds.(!v).w;\n\t v := ds.(!v).p\n\t done;\n\t let t = !t -| !ww +| w in\n\t Printf.printf \"%Ld\\n\" t\n done;\n"}, {"source_code": "(* started 1:10 *)\n\nopen Printf\nopen Scanf\n\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n\n let n = read_int() in\n let m = read_int() in\n\n let edges_unsorted = fold 1 m (fun i ac ->\n let u = read_int() -1 in\n let v = read_int() -1 in\n let w = long (read_int()) in\n (w,u,v)::ac) []\n in\n\n let edges_unsorted = List.rev edges_unsorted in\n \n let edges = List.sort compare edges_unsorted in\n\n let uf = Array.make n (-1) in\n let weight = Array.make n 0L in\n\n let rec find i = if uf.(i) < 0 then i else find uf.(i) in\n\n let union i j w =\n (* assume i and j are both canonical elements *)\n let (wi,wj) = (-uf.(i), -uf.(j)) in\n if wi < wj then (\n uf.(j) <- uf.(i) + uf.(j); \n uf.(i) <- j;\n weight.(i) <- w;\n ) else (\n uf.(i) <- uf.(i) + uf.(j); \n uf.(j) <- i;\n weight.(j) <- w; \n )\n in\n\n List.iter (fun (w,u,v) ->\n let (i,j) = (find u, find v) in\n if i <> j then union i j w\n ) edges;\n\n let path = Array.make n (-1) in\n\n let total_cost = sum 0 (n-1) (fun v -> weight.(v)) 0L in\n\n let lca u v i =\n let rec mark u = if u >= 0 then (path.(u) <- i; mark uf.(u)) in\n mark u;\n let rec fmark v = if path.(v) = i then v else fmark uf.(v) in\n fmark v\n in\n\n let rec max_cost_to v l ac = if v = l then ac else\n max_cost_to uf.(v) l (max ac weight.(v))\n in\n \n List.iteri (fun i (w,u,v) ->\n let l = lca u v i in\n let wt = max (max_cost_to u l 0L) (max_cost_to v l 0L) in\n printf \"%Ld\\n\" (total_cost ++ w -- wt)\n ) edges_unsorted;\n"}], "negative_code": [], "src_uid": "bab40fe0052e2322116c084008c43366"} {"nl": {"description": "You are given $$$n$$$ pairs of integers $$$(a_1, b_1), (a_2, b_2), \\ldots, (a_n, b_n)$$$. All of the integers in the pairs are distinct and are in the range from $$$1$$$ to $$$2 \\cdot n$$$ inclusive.Let's call a sequence of integers $$$x_1, x_2, \\ldots, x_{2k}$$$ good if either $$$x_1 < x_2 > x_3 < \\ldots < x_{2k-2} > x_{2k-1} < x_{2k}$$$, or $$$x_1 > x_2 < x_3 > \\ldots > x_{2k-2} < x_{2k-1} > x_{2k}$$$. You need to choose a subset of distinct indices $$$i_1, i_2, \\ldots, i_t$$$ and their order in a way that if you write down all numbers from the pairs in a single sequence (the sequence would be $$$a_{i_1}, b_{i_1}, a_{i_2}, b_{i_2}, \\ldots, a_{i_t}, b_{i_t}$$$), this sequence is good.What is the largest subset of indices you can choose? You also need to construct the corresponding index sequence $$$i_1, i_2, \\ldots, i_t$$$.", "input_spec": "The first line contains single integer $$$n$$$ ($$$2 \\leq n \\leq 3 \\cdot 10^5$$$)\u00a0\u2014 the number of pairs. Each of the next $$$n$$$ lines contain two numbers\u00a0\u2014 $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le 2 \\cdot n$$$)\u00a0\u2014 the elements of the pairs. It is guaranteed that all integers in the pairs are distinct, that is, every integer from $$$1$$$ to $$$2 \\cdot n$$$ is mentioned exactly once.", "output_spec": "In the first line print a single integer $$$t$$$\u00a0\u2014 the number of pairs in the answer. Then print $$$t$$$ distinct integers $$$i_1, i_2, \\ldots, i_t$$$\u00a0\u2014 the indexes of pairs in the corresponding order.", "sample_inputs": ["5\n1 7\n6 4\n2 10\n9 8\n3 5", "3\n5 4\n3 2\n6 1"], "sample_outputs": ["3\n1 5 3", "3\n3 2 1"], "notes": "NoteThe final sequence in the first example is $$$1 < 7 > 3 < 5 > 2 < 10$$$.The final sequence in the second example is $$$6 > 1 < 3 > 2 < 5 > 4$$$."}, "positive_code": [{"source_code": "\nlet () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let l =\n (* List.init n (fun i -> i+1) *)\n let l = ref [] in\n for i = 1 to n do\n l := i :: !l\n done;\n List.rev !l\n in\n let lu, ld =\n List.fold_left\n (fun (lu, ld) idx ->\n let a, b = Scanf.scanf \"%d %d\\n\" (fun x y -> x, y) in\n if a < b then (a, b, idx) :: lu, ld else lu, (a, b, idx)::ld\n ) ([], []) l\n in\n if List.length lu < List.length ld\n then (* ld*)\n begin\n Printf.printf \"%d\\n\" (List.length ld);\n List.sort (fun (a1, b1, _) (a2, b2, _) -> compare a1 a2) ld\n |> List.iter (fun (_, _, idx) -> Printf.printf \"%d \" idx)\n end\n else begin\n Printf.printf \"%d\\n\" (List.length lu);\n List.sort (fun (a1, b1, _) (a2, b2, _) -> compare a2 a1) lu\n |> List.iter (fun (_, _, idx) -> Printf.printf \"%d \" idx)\n end\n;;\n"}], "negative_code": [], "src_uid": "6b720be3d26719ce649158e8903527e3"} {"nl": {"description": "The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n\u2009\u00d7\u2009m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.", "input_spec": "The first line contains three space-separated integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000, 1\u2009\u2264\u2009k\u2009\u2264\u2009500000) \u2014 the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each \u2014 the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0\u2009\u2264\u2009p\u2009\u2264\u2009106. Next k lines contain queries in the format \"si xi yi\", where si is one of the characters \"\u0441\", \"r\" or \"g\", and xi, yi are two integers. If si = \"c\", then the current query is the query to swap columns with indexes xi and yi (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009m,\u2009x\u2009\u2260\u2009y); If si = \"r\", then the current query is the query to swap rows with indexes xi and yi (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n,\u2009x\u2009\u2260\u2009y); If si = \"g\", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1\u2009\u2264\u2009x\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009y\u2009\u2264\u2009m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns \u2014 from left to right from 1 to m.", "output_spec": "For each query to obtain a number (si = \"g\") print the required number. Print the answers to the queries in the order of the queries in the input.", "sample_inputs": ["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"], "sample_outputs": ["8\n9\n6", "5"], "notes": "NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5."}, "positive_code": [{"source_code": "open Scanf\nopen Str\n\nlet (|>) x f = f x \nlet identity x = x\nlet regexp_spc = regexp \" \"\n\nlet swap ar x y =\n let tmp = ar.(x) in\n ar.(x) <- ar.(y);\n ar.(y) <- tmp\n\nlet _ =\n let n :: m :: k :: _ = () |> read_line |> (split regexp_spc) |> List.map int_of_string in\n let mp = Array.make n (Array.make 0 0) in\n for i = 0 to n-1 do\n mp.(i) <-\n () |> read_line |> (split regexp_spc) |> List.map int_of_string |> Array.of_list\n done;\n\n let rs = Array.init n identity in\n let cs = Array.init m identity in\n for i = 1 to k do\n let op = read_line () in\n let m, x, y = sscanf op \"%c %d %d\" (fun m x y -> m, x-1, y-1) in\n match m with\n | 'c' -> swap cs x y\n | 'r' -> swap rs x y\n | 'g' -> mp.(rs.(x)).(cs.(y)) |> string_of_int |> print_endline\n done\n\n\n"}], "negative_code": [], "src_uid": "290d9779a6be44ce6a2e62989aee0dbd"} {"nl": {"description": "Little penguin Polo has an n\u2009\u00d7\u2009m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.", "input_spec": "The first line contains three integers n, m and d (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009d\u2009\u2264\u2009104) \u2014 the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009104).", "output_spec": "In a single line print a single integer \u2014 the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print \"-1\" (without the quotes).", "sample_inputs": ["2 2 2\n2 4\n6 8", "1 2 7\n6 7"], "sample_outputs": ["4", "-1"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet n = read_int ();;\nlet m = read_int ();;\nlet d = read_int ();;\n\nlet data = Array.init (n*m) (fun i -> read_int ());;\n\nArray.sort compare data;;\n\nlet isok = ref true;;\n\nlet solve a b = if (b-a) mod d = 0 then true else false in \n for i = 1 to (n*m-1) do\n isok := !isok && (solve data.(i) data.(i-1))\n done;;\n\n\nlet work ii data = let cnt = ref 0 in \n for i = 0 to (ii-1) do cnt := !cnt + (data.(ii) - data.(i))/d done;\n for i = (ii+1) to (n*m-1) do cnt := !cnt + (data.(i) - data.(ii))/d done;\n !cnt;;\n\nif n*m = 1 then Printf.printf \"0\\n\"\nelse if !isok = false then Printf.printf \"-1\\n\"\nelse\n if (n*m) mod 2 = 0 then \n let a = work ((n*m)/2-1) data in let b = work ((n*m)/2) data in Printf.printf \"%d\\n\" (min a b)\n else \n let a = work ((n*m+1)/2-1) data in Printf.printf \"%d\\n\" a;;\n \n"}], "negative_code": [], "src_uid": "3488bb49de69c0c17ea0439e71b1e6ae"} {"nl": {"description": "Bizon the Champion isn't just attentive, he also is very hardworking.Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 the number of fence planks. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print a single integer \u2014 the minimum number of strokes needed to paint the whole fence.", "sample_inputs": ["5\n2 2 1 2 1", "2\n2 2", "1\n5"], "sample_outputs": ["3", "2", "1"], "notes": "NoteIn the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.In the third sample there is only one plank that can be painted using a single vertical stroke."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\nlet n = scan_int ();;\nlet a = Array.init n (fun i -> scan_int());;\n\nlet rec licz l r = \n (*dbg l; dbg r; pnl();*)\n let minek = ref max_int in\n for i = l to r do\n minek := min !minek a.(i);\n done;\n\n let pocz = ref (-1) and wyn = ref !minek in\n for i = l to r do\n if a.(i) - !minek <> 0 then begin\n a.(i) <- a.(i) - !minek;\n if !pocz = -1 then pocz := i;\n if i = r || a.(i + 1) - !minek = 0 then begin\n wyn := !wyn + (licz !pocz i);\n pocz := -1;\n end;\n end;\n done;\n min (r - l + 1) !wyn;;\n\nprint_int (licz 0 (n - 1));;"}], "negative_code": [], "src_uid": "ddab0e510f9aceb2fbf75e26d27df166"} {"nl": {"description": "Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x\u2009+\u2009y\u2009=\u2009n). The sizes of teams differ in no more than one (|x\u2009-\u2009y|\u2009\u2264\u20091). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.", "input_spec": "The first line contains the only integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009104), the i-th number represents the i-th boy's playing skills. ", "output_spec": "On the first line print an integer x \u2014 the number of boys playing for the first team. On the second line print x integers \u2014 the individual numbers of boys playing for the first team. On the third line print an integer y \u2014 the number of boys playing for the second team, on the fourth line print y integers \u2014 the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x\u2009+\u2009y\u2009=\u2009n, |x\u2009-\u2009y|\u2009\u2264\u20091, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.", "sample_inputs": ["3\n1 2 1", "5\n2 3 3 1 1"], "sample_outputs": ["2\n1 2 \n1\n3", "3\n4 1 3 \n2\n5 2"], "notes": "NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2\u2009-\u20091|\u2009=\u20091\u2009\u2264\u20091) is fulfilled, the third limitation on the difference in skills ((2\u2009+\u20091)\u2009-\u2009(1)\u2009=\u20092\u2009\u2264\u20092) is fulfilled."}, "positive_code": [{"source_code": "(* codeforces 106. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\nlet () =\n let n = read_int() in\n\n let a = Array.make n (0,0) in\n for i = 0 to n-1 do \n a.(i) <- (read_int(), i+1)\n done;\n Array.sort compare a;\n\n let n1 = (n+1)/2 in\n let n2 = n-n1 in\n\n Printf.printf \"%d\\n\" n1;\n for i=0 to n1-1 do\n\tPrintf.printf \"%d \" (snd a.(2*i))\n done;\n print_newline();\n\t\n Printf.printf \"%d\\n\" n2;\n for i=0 to n2-1 do\n\tPrintf.printf \"%d \" (snd a.(2*i+1))\n done;\n print_newline();\n"}], "negative_code": [], "src_uid": "0937a7e2f912fc094cc4275fd47cd457"} {"nl": {"description": "Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0\u2009<\u2009a1\u2009<\u2009a2\u2009<\u2009...\u2009<\u2009an) teeth, and the j-th star on the rear wheel axle has bj (0\u2009<\u2009b1\u2009<\u2009b2\u2009<\u2009...\u2009<\u2009bm) teeth. Any pair (i,\u2009j) (1\u2009\u2264\u2009i\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009j\u2009\u2264\u2009m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i,\u2009j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i,\u2009j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all \"integer\" gears (i,\u2009j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction denotes division in real numbers, that is, no rounding is performed.", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of stars on the bicycle's pedal axle. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009104) in the order of strict increasing. The third input line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u200950) \u2014 the number of stars on the rear wheel axle. The fourth line contains m integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i,\u2009j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.", "output_spec": "Print the number of \"integer\" gears with the maximum ratio among all \"integer\" gears.", "sample_inputs": ["2\n4 5\n3\n12 13 15", "4\n1 2 3 4\n5\n10 11 12 13 14"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample the maximum \"integer\" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1\u2009=\u20094,\u2009b1\u2009=\u200912, and for the other a2\u2009=\u20095,\u2009b3\u2009=\u200915."}, "positive_code": [{"source_code": "open Scanf;;\nopen Printf;;\nopen Str;;\n\nlet split_by_space = split (regexp \" +\")\n\nlet rec head n ls =\n if n < 0 then invalid_arg \"head : passed negative integer\"\n else \n match (n, ls) with\n (0, _) -> []\n | (n, []) -> failwith \"head : list is too short\"\n | (n, x::xs) -> x :: (head (n - 1) xs)\n\nlet rec tail n ls =\n if n < 0 then invalid_arg \"tail : passed negative integer\"\n else\n match (n, ls) with\n (0, ls) -> ls\n | (n, []) -> failwith \"tail : list is too short\"\n | (n, x::xs) -> tail (n - 1) xs\n\nmodule UF = struct\n type t = int array\n\n let make n = Array.make n (-1)\n\n let rec root x uf =\n if uf.(x) < 0 then x \n else (uf.(x) <- root uf.(x) uf; uf.(x))\n\n let union_set x y uf =\n let x = root x uf and\n y = root y uf in\n begin\n if x != y then \n let x, y = if uf.(y) < uf.(x) then y, x else x, y in\n begin\n uf.(x) <- uf.(x) + uf.(y);\n uf.(y) <- x\n end\n end;\n x != y\n\n let find_set x y uf = root x uf = root y uf\n\n let size x uf = - uf.(x)\nend\n\nlet input () = \n let f () = \n let n = scanf \"%d \" (fun x -> x) in\n let a_arr = Array.make n 0 in\n for i = 0 to (n - 1) do\n a_arr.(i) <- scanf \"%d \" (fun x -> x)\n done;\n (n, a_arr) in\n let (n, a_arr) = f () and\n (m, b_arr) = f () in\n (n, a_arr, m, b_arr)\n\nlet get_fst_count lst = \n let rec match_count tar = function\n [] -> 0\n | x :: xs when x = tar -> 1 + match_count tar xs\n | _ -> 0 in\n match lst with\n x :: xs -> 1 + match_count x xs\n | [] -> invalid_arg \"\"\n\nlet solve (n, a_arr, m, b_arr) =\n let rat_lst = \n ArrayLabels.fold_left ~init:[] ~f:(fun acc x ->\n ArrayLabels.fold_left ~init:acc ~f:(fun acc y ->\n if y mod x = 0 then (y / x) :: acc else acc) b_arr) a_arr in\n let sorted_rat_lst = List.sort (fun x y -> y - x) rat_lst in\n get_fst_count sorted_rat_lst\n\nlet () = \n let inp = input () in\n printf \"%d\\n\" (solve inp)\n"}], "negative_code": [], "src_uid": "102667eaa3aee012fef70f4192464674"} {"nl": {"description": "DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s\u2009=\u2009s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get? ", "input_spec": "The first line contains a single string s\u00a0(1\u2009\u2264\u2009|s|\u2009\u2264\u2009103). The second line contains a single integer k\u00a0(0\u2009\u2264\u2009k\u2009\u2264\u2009103). The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.", "output_spec": "Print a single integer \u2014 the largest possible value of the resulting string DZY could get.", "sample_inputs": ["abc\n3\n1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"], "sample_outputs": ["41"], "notes": "NoteIn the test sample DZY can obtain \"abcbbc\", value\u2009=\u20091\u00b71\u2009+\u20092\u00b72\u2009+\u20093\u00b72\u2009+\u20094\u00b72\u2009+\u20095\u00b72\u2009+\u20096\u00b72\u2009=\u200941."}, "positive_code": [{"source_code": "module H = Hashtbl ;;\n\nlet ctbl = H.create 10 ;;\n\nlet (@@) f x = f x ;;\n\nlet solve str n m =\n let sum = ref 0L in\n let (+/) = Int64.add in\n let ( */ ) = Int64.mul in\n for i = 0 to String.length str - 1 do\n sum := !sum +/ (Int64.of_int i +/ 1L) */ H.find ctbl str.[i]\n done;\n Printf.eprintf \"%Ld\\n\" !sum;\n for i = String.length str + 1 to String.length str + n do\n sum := !sum +/ Int64.of_int i */ m\n done;\n Printf.printf \"%Ld\\n\" !sum\n;;\n\nlet () =\n Scanf.scanf \"%s \" (fun str ->\n Scanf.scanf \"%d \" (fun n ->\n let m = ref (-1L) in\n for i = 0 to 25 do\n Scanf.scanf \"%d \" (fun n ->\n H.add ctbl (Char.chr (Char.code 'a' + i)) (Int64.of_int n);\n m := max !m @@ Int64.of_int n;)\n done;\n Printf.eprintf \"%Ld\\n\" !m;\n solve str n !m));\n;;\n"}], "negative_code": [{"source_code": "module H = Hashtbl ;;\n\nlet ctbl = H.create 10 ;;\n\nlet (@@) f x = f x ;;\n\nlet solve str n m =\n let sum = ref 0 in\n for i = 0 to String.length str - 1 do\n sum := !sum + (i + 1) * H.find ctbl str.[i]\n done;\n Printf.eprintf \"%d\\n\" !sum;\n for i = String.length str to String.length str + n - 1 do\n sum := !sum + (i + 1) * m\n done;\n Printf.printf \"%d\\n\" !sum\n;;\n\nlet () =\n Scanf.scanf \"%s \" (fun str ->\n Scanf.scanf \"%d \" (fun n ->\n let m = ref (-1) in\n for i = 0 to 25 do\n Scanf.scanf \"%d \" (fun n ->\n H.add ctbl (Char.chr (Char.code 'a' + i)) n;\n m := max !m n;)\n done;\n Printf.eprintf \"%d\\n\" !m;\n solve str n !m));\n;;\n"}], "src_uid": "85f90533a9840e944deef9f3b4229cb8"} {"nl": {"description": "You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: \"You have to write names in this notebook during $$$n$$$ consecutive days. During the $$$i$$$-th day you have to write exactly $$$a_i$$$ names.\". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $$$m$$$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $$$1$$$ to $$$n$$$.", "input_spec": "The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le m \\le 10^9$$$) \u2014 the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ means the number of names you will write in the notebook during the $$$i$$$-th day.", "output_spec": "Print exactly $$$n$$$ integers $$$t_1, t_2, \\dots, t_n$$$, where $$$t_i$$$ is the number of times you will turn the page during the $$$i$$$-th day.", "sample_inputs": ["3 5\n3 7 9", "4 20\n10 9 19 2", "1 100\n99"], "sample_outputs": ["0 2 1", "0 0 1 1", "0"], "notes": "NoteIn the first example pages of the Death Note will look like this $$$[1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]$$$. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * )\n\tlet (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v\n\tlet labs p = if p < 0L then -1L*p else p\n\tlet (~|) p = Int64.to_int p\n\tlet (~~|) p = Int64.of_int p\n\n\tlet input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n = n |> Int64.to_string |> print_endline\n\t\n\tlet (mod) m n = m - (m/n) * n let (%) = (mod)\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = (m*n) / gcd m n\n\tlet rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ok -> i := !i +$ 1; | `Ng -> f := false done\n\tlet repi64 from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ok -> i := !i +$ 1; | `Ng -> f := false done\nend\n\n\n\nopen MyInt64\nlet () =\n\tlet n,m = get_2_i64 ()\n\tin let a = input_i64_array n\n\tin\n\tArray.fold_left (fun (res,sum,cur) v -> \n\t\tlet w = cur + v\n\t\tin if w >= m then (\n\t\t\tlet q = w / m in let r = w - q * m\n\t\t\tin\n\t\t\t(q::res,sum+q,r)\n\t\t\t(* if sum+q >= n then (\n\t\t\t\tlet q' = n - sum in\n\t\t\t\t(q'::res,n,r)\n\t\t\t) else (\n\t\t\t\t(q::res,sum+q,r)\n\t\t\t) *)\n\t\t) else (0L::res,sum,w)\n\t) ([],0L,0L) a\n\t|> (fun (r,_,_) -> r)\n\t|> List.rev\n\t|> List.iter (printf \"%Ld \")"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let c = ref 0L in\n for i = 1 to n do\n let k = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n\tc := !c +| k;\n\tPrintf.printf \"%Ld \" (!c /| m);\n\tc := Int64.rem !c m;\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * )\n\tlet (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v\n\tlet labs p = if p < 0L then -1L*p else p\n\tlet (~|) p = Int64.to_int p\n\tlet (~~|) p = Int64.of_int p\n\n\tlet input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n = n |> Int64.to_string |> print_endline\n\t\n\tlet (mod) m n = m - (m/n) * n let (%) = (mod)\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = (m*n) / gcd m n\n\tlet rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ok -> i := !i +$ 1; | `Ng -> f := false done\n\tlet repi64 from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ok -> i := !i +$ 1; | `Ng -> f := false done\nend\n\n\n\nopen MyInt64\nlet () =\n\tlet n,m = get_2_i64 ()\n\tin let a = input_i64_array n\n\tin\n\tArray.fold_left (fun (res,sum,cur) v -> \n\t\tif sum = n then (res,sum,cur)\n\t\telse if sum > n then failwith \"\"\n\t\telse \n\t\tlet w = cur + v\n\t\tin if w >= m then (\n\t\t\tlet q = w / m in let r = w - q * m\n\t\t\tin\n\t\t\tif sum+q >= n then (\n\t\t\t\tlet q' = n - sum in\n\t\t\t\t(q'::res,n,r)\n\t\t\t) else (\n\t\t\t\t(q::res,sum+q,r)\n\t\t\t)\n\t\t) else (0L::res,sum,w)\n\t) ([],0L,0L) a\n\t|> (fun (r,_,_) -> r)\n\t|> List.rev\n\t|> List.iter (printf \"%Ld \")"}], "src_uid": "a2085c2d21b2dbe4cc27a15fa4a1ec4f"} {"nl": {"description": "You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.", "input_spec": "The first line contains two integers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u20093000, 1\u2009\u2264\u2009m\u2009\u2264\u20093000) \u2014 the number of words in the professor's lecture and the number of words in each of these languages. The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once. The next line contains n space-separated strings c1,\u2009c2,\u2009...,\u2009cn \u2014 the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1,\u2009a2,\u2009... am}. All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.", "output_spec": "Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.", "sample_inputs": ["4 3\ncodeforces codesecrof\ncontest round\nletter message\ncodeforces contest letter contest", "5 3\njoll wuqrd\neuzf un\nhbnyiyc rsoqqveh\nhbnyiyc joll joll euzf joll"], "sample_outputs": ["codeforces round letter round", "hbnyiyc joll joll un joll"], "notes": null}, "positive_code": [{"source_code": "module StringMap = Map.Make(String)\n\nlet read_int () = Scanf.scanf \"%d %d \" (fun n m -> (n, m))\nlet read_str () = Scanf.scanf \"%s \" (fun s -> s)\n\nlet get_short str1 str2 = \n if String.length str1 <= String.length str2\n then\n str1\n else\n str2\n\nlet fill_map m =\n let map = StringMap.empty in \n let rec loop i map =\n if i < m\n then\n let key = read_str () in\n let temp = read_str () in\n let value = get_short key temp in\n let map = StringMap.add key value map in\n loop (i + 1) map\n else\n map\n in loop 0 map\n\nlet fill_list n = \n let rec loop i list =\n if i < n\n then\n let temp = read_str () in\n loop (i + 1) (temp :: list)\n else\n List.rev list\n in loop 0 []\n\nlet input () =\n let (n, m) = read_int () in\n let words = fill_map m in\n let text = fill_list n in\n (words, text)\n\nlet solve (words, text) =\n let rec loop list acc =\n match list with\n | (head :: tail) -> \n let short = StringMap.find head words in\n loop tail (short :: acc)\n | [] -> List.rev acc\n in loop text []\n\nlet print result = \n (List.iter (Printf.printf \"%s \") result;\n Printf.printf \"\\n\")\n\nlet () = print (solve (input ()))"}, {"source_code": "let () = Scanf.scanf \"%d %d\\n\" (fun n m ->\n let h = Hashtbl.create n in\n for i = 1 to m do\n Scanf.scanf \"%[^ ] %s\\n\" (Hashtbl.add h)\n done;\n let w = Array.init n (fun _ ->\n Scanf.scanf \"%[^ \\n]%_c\" (fun s ->\n let t = Hashtbl.find h s in\n if String.length t < String.length s\n then t else s\n )) in\n print_endline (String.concat \" \" (Array.to_list w))\n)\n"}, {"source_code": "module A = Array;;\nmodule C = Char;;\nmodule L = List;;\nmodule S = String;;\n\nlet pf = Printf.printf;;\nlet sf = Scanf.scanf;;\nlet ssf = Scanf.sscanf;;\n\nlet (@@) f x = f x;;\nlet (|>) x f = f x;;\n\nexception Error of string\n\nlet inf = 1000000000;;\nlet eps = 1e-11;;\n\ntype ('a, 'b) avl_data =\n | Empty\n | Node of int * ('a * 'b) * ('a, 'b) avl_data * ('a, 'b) avl_data\n;;\n\ntype 'a option = Nothing | Just of 'a;;\n\ntype ('a, 'b) avl_tree =\n { set : ('a * 'b) -> unit; value : 'a -> 'b option }\n;;\n\nlet new_avl_tree cmp =\n let tree = ref Empty in\n let err() = raise @@ Error \"AVL-Tree Internal Error.\" in\n let height = function Empty -> 0 | Node (h, _, _, _) -> h in\n let make_node a l r = Node (max (height l) (height r) + 1, a, l, r) in\n let rotate = function\n Empty -> Empty\n | Node (_, a, l, r) ->\n if height l > height r + 1\n then (match l with\n Empty -> err()\n | Node (_, b, ll, lr) ->\n if height ll >= height lr\n then make_node b ll (make_node a lr r)\n else (match lr with\n Empty -> err()\n | Node (_, c, lrl, lrr) ->\n make_node c (make_node b ll lrl) (make_node a lrr r)))\n else if height l + 1 < height r\n then (match r with\n Empty -> err()\n | Node (_, b, rl, rr) ->\n if height rl <= height rr\n then make_node b (make_node a l rl) rr\n else (match rl with\n Empty -> err()\n | Node (_, c, rll, rlr) ->\n make_node c (make_node a l rll) (make_node b rlr rr)))\n else make_node a l r in\n let rec insert (x, y) = function\n Empty -> Node (1, (x, y), Empty, Empty)\n | Node (h, (k, v), l, r) ->\n let t = if cmp x k = 0\n then Node (h, (x, y), l, r)\n else if cmp x k < 0\n then Node (h, (k, v), insert (x, y) l, r)\n else Node (h, (k, v), l, insert (x, y) r) in\n rotate t in\n let rec find x = function\n Empty -> Nothing\n | Node (_, (k, v), l, r) ->\n if cmp x k = 0\n then Just v\n else if cmp x k < 0\n then find x l\n else find x r in\n let this() =\n { set = (fun x -> tree := insert x !tree);\n value = (fun x -> find x !tree) } in\n this();\n;;\n\nlet _ =\n let str = read_line() in\n let (n, m) = ssf str \"%d %d\" (fun x y -> x, y) in\n let avl = new_avl_tree compare in\n for i = 1 to m do\n let s = read_line() in\n let (a, b) = ssf s \"%s %s\" (fun x y -> x, y) in\n let res = if String.length a <= String.length b then a else b in\n avl.set (a, res); avl.set (b, res);\n done;\n let str = read_line() in\n let slist = Str.split (Str.regexp \" \") str in\n let reveal = function Nothing -> \" \" | Just a -> a in\n List.map (fun s -> print_string @@ reveal (avl.value s) ^ \" \") slist\n;;\n"}], "negative_code": [], "src_uid": "edd556d60de89587f1b8daa893538530"} {"nl": {"description": "You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle \u03b1. Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.", "input_spec": "The first line contains three integers w,\u2009h,\u2009\u03b1 (1\u2009\u2264\u2009w,\u2009h\u2009\u2264\u2009106;\u00a00\u2009\u2264\u2009\u03b1\u2009\u2264\u2009180). Angle \u03b1 is given in degrees.", "output_spec": "In a single line print a real number \u2014 the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["1 1 45", "6 4 30"], "sample_outputs": ["0.828427125", "19.668384925"], "notes": "NoteThe second sample has been drawn on the picture above."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet pi = 4.0 *. atan2 1.0 1.0\n\nlet line_intersection (a1, b1, c1) (a2, b2, c2) =\n (* non-parallel lines defined by ax+by=c. Intersect them *)\n let (a1,b1,c1,a2,b2,c2) = if a2=0.0 then (a2,b2,c2,a1,b1,c1) else (a1,b1,c1,a2,b2,c2) in\n if a1=0.0 then (\n let y = c1 /. b1 in\n let x = (c2 -. b2 *. y) /. a2 in\n (x,y)\n ) else (\n let (b1,c1) = (b1/.a1, c1/.a1) in\n let (b2,c2) = (b2/.a2, c2/.a2) in\n let y = (c1 -. c2) /. (b1 -. b2) in\n let x = c1 -. b1*.y in\n (x,y)\n )\n\nlet triangle_area p q r = \n let sq x = x *. x in\n let dist (x1,y1) (x2,y2) = sqrt ((sq (x1-.x2)) +. (sq (y1-.y2))) in\n let a = dist p q in\n let b = dist q r in\n let c = dist r p in\n let s = (a +. b +. c) /. 2.0 in\n sqrt ((s -. a) *. (s -. b) *. (s -. c) *. s)\n\nlet () = \n let w = float (read_int()) in\n let h = float (read_int()) in\n let (w,h) = (max w h, min w h) in\n let alpha = read_int() in\n let alpha = min alpha (180-alpha) in\n let alpha = ((float alpha) /. 180.0) *. pi in\n\n let alpha0 = 2.0 *. (atan (h /. w)) in\n\n let area = \n if alpha = 0.0 then w *. h \n else if alpha >= alpha0 then\n let base = h /. (sin alpha) in\n\tbase *. h\n else\n let l1 = (0.0, 1.0, -.(h/.2.0)) in\n let l2 = (1.0, 0.0, (w/.2.0)) in\n let l3 = (0.0, 1.0, (h/.2.0)) in\n let l4 = (sin alpha, -.(cos alpha), h /. 2.0) in\n let l5 = (cos alpha, sin alpha, w /. 2.0) in\n let p1 = line_intersection l1 l4 in\n let p2 = line_intersection l4 l2 in\n let p3 = line_intersection l2 l5 in\n let p4 = line_intersection l5 l3 in\n let p0 = (0.0, -. (h/.2.0)) in\n let p5 = (0.0, (h/.2.0)) in\n let area = triangle_area p0 p1 p2 in\n let area = area +. (triangle_area p0 p2 p3) in\n let area = area +. (triangle_area p0 p3 p4) in\n let area = area +. (triangle_area p0 p4 p5) in\n\t2.0 *. area\n in\n Printf.printf \"%.7f\\n\" area\n"}], "negative_code": [], "src_uid": "21432a74b063b008cf9f04d2804c1c3f"} {"nl": {"description": "The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y\u2009=\u2009ki\u00b7x\u2009+\u2009bi. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between x1\u2009<\u2009x2. In other words, is it true that there are 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n and x',\u2009y', such that: y'\u2009=\u2009ki\u2009*\u2009x'\u2009+\u2009bi, that is, point (x',\u2009y') belongs to the line number i; y'\u2009=\u2009kj\u2009*\u2009x'\u2009+\u2009bj, that is, point (x',\u2009y') belongs to the line number j; x1\u2009<\u2009x'\u2009<\u2009x2, that is, point (x',\u2009y') lies inside the strip bounded by x1\u2009<\u2009x2. You can't leave Anton in trouble, can you? Write a program that solves the given task.", "input_spec": "The first line of the input contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of lines in the task given to Anton. The second line contains integers x1 and x2 (\u2009-\u20091\u2009000\u2009000\u2009\u2264\u2009x1\u2009<\u2009x2\u2009\u2264\u20091\u2009000\u2009000) defining the strip inside which you need to find a point of intersection of at least two lines. The following n lines contain integers ki, bi (\u2009-\u20091\u2009000\u2009000\u2009\u2264\u2009ki,\u2009bi\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two i\u2009\u2260\u2009j it is true that either ki\u2009\u2260\u2009kj, or bi\u2009\u2260\u2009bj.", "output_spec": "Print \"Yes\" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print \"No\" (without quotes).", "sample_inputs": ["4\n1 2\n1 2\n1 0\n0 1\n0 2", "2\n1 3\n1 0\n-1 3", "2\n1 3\n1 0\n0 2", "2\n1 3\n1 0\n0 3"], "sample_outputs": ["NO", "YES", "YES", "NO"], "notes": "NoteIn the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it. "}, "positive_code": [{"source_code": "open List open Str open Int64;;\nlet cmp x y =\n if(nth x 0) < (nth y 0) || (((nth x 0) = (nth y 0)) && ((nth x 1) < (nth y 1)))\n then -1 else 1;;\nlet n = read_int ();;\nlet par = Array.create n [0L;0L] and x_1 :: x_2 :: [] =\n map (of_string) (split (regexp \" \") (read_line ()));;\nfor i = 1 to n do\n let k :: b :: [] = \n map (of_string) (split (regexp \" \") (read_line ())) in\n Array.set par (i - 1) [(add (mul k x_1) b); (add (mul k x_2) b)];\ndone;;\nArray.sort cmp par;;\nfor i = 0 to (Array.length par) - 2 do\n if (nth par.(i + 1) 1) < (nth par.(i) 1) then begin\n print_endline \"YES\";\n exit 0;\nend done;;\nprint_endline \"NO\";;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x) \n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n \nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n \nlet () = \n let n = read_int () in\n let x1 = read_long () in\n let x2 = read_long () in \n\n let k = Array.make n 0L in\n let b = Array.make n 0L in\n\n for i=0 to n-1 do\n k.(i) <- read_long();\n b.(i) <- read_long()\n done;\n\n let y1 = Array.init n (fun i -> (k.(i) ** x1 ++ b.(i), i)) in\n let y2 = Array.init n (fun i -> (k.(i) ** x2 ++ b.(i), i)) in\n\n let y1_init = Array.copy y1 in\n let y2_init = Array.copy y2 in \n \n Array.sort compare y1;\n Array.sort compare y2;\n\n Array.sort (fun (v1,i1) (v2,i2) ->\n if v1 <> v2 then compare v1 v2\n else compare y2_init.(i1) y2_init.(i2)\n ) y1;\n\n Array.sort (fun (v1,i1) (v2,i2) ->\n if v1 <> v2 then compare v1 v2\n else compare y1_init.(i1) y1_init.(i2)\n ) y2;\n\n let answer = forall 0 (n-1) (\n fun i ->\n let (_,i1) = y1.(i) in\n let (_,i2) = y2.(i) in \n i1 = i2\n ) in\n\n if answer then printf \"NO\\n\" else printf \"YES\\n\"\n"}], "negative_code": [{"source_code": "open Array;;\nopen String;;\nopen Str;;\n\n"}, {"source_code": "let cmp x y = if x.(0) < y.(0) then -1 else 1;;\nlet n = read_int ();;\nlet ls = ref (Array.create n [|0;0|]);;\nlet x_1 = ref 0 and x_2 = ref 0;;\nlet ins = List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\nbegin\n\tx_1 := List.nth ins 0; \n\tx_2 := List.nth ins 1;\nend;;\nfor i = 1 to n do\n\tlet ins = List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\n\tlet k = List.nth ins 0 and b = List.nth ins 1 in\n\tbegin\n\t\tls := Array.append !ls [|[|(!x_1 * k + b);(!x_2 * k + b)|]|];\n\tend;\ndone;\nArray.stable_sort cmp !ls;;\nlet fl = ref 0;;\nfor i = 0 to Array.length !ls - 2 do\n\tif (!ls.(i).(1) > !ls.(i + 1).(1)) then fl := 1;\ndone;;\nif !fl = 0 then print_endline \"NO\" else print_endline \"YES\";;\n\n(*\nfor i = 0 to Array.length !ls - 1 do\n\tprint_int !ls.(i).(0);\n\tprint_string \" \";\n\tprint_int !ls.(i).(1);\n\tprint_endline \"\";\ndone;;*)\n"}, {"source_code": "let cmp x y = if x.(0) < y.(0) then -1 else 1;;\nlet n = read_int ();;\nlet ls = ref (Array.create n [|0;0|]);;\nlet x_1 = ref 0 and x_2 = ref 0;;\nlet ins = List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\nbegin\n\tx_1 := List.nth ins 0; \n\tx_2 := List.nth ins 1;\nend;;\nfor i = 1 to n do\n\tlet ins = List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\n\tlet k = List.nth ins 0 and b = List.nth ins 1 in\n\tbegin\n Array.set (!ls) (i - 1) [|!x_1 * k + b; !x_2 * k + b|];\n\tend;\ndone;\nArray.stable_sort cmp !ls;;\nlet fl = ref 0;;\nfor i = 0 to Array.length !ls - 2 do\n\tif ((!ls.(i).(1) > !ls.(i + 1).(1))) && (!ls.(i).(0) != !ls.(i + 1).(0)) then fl := 1;\ndone;;\nif !fl = 0 then print_endline \"NO\" else print_endline \"YES\";;\n(*\nfor i = 0 to Array.length !ls - 1 do\n\tprint_int !ls.(i).(0);\n\tprint_string \" \";\n\tprint_int !ls.(i).(1);\n\tprint_endline \"\";\ndone;;*)\n"}, {"source_code": "let cmp x y = if x.(0) < y.(0) then -1 else 1;;\nlet n = read_int ();;\nlet ls = ref (Array.create n [|0;0|]);;\nlet x_1 = ref 0 and x_2 = ref 0;;\nlet ins = List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\nbegin\n\tx_1 := List.nth ins 0; \n\tx_2 := List.nth ins 1;\nend;;\nfor i = 1 to n do\n\tlet ins = List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\n\tlet k = List.nth ins 0 and b = List.nth ins 1 in\n\tbegin\n Array.set (!ls) (i - 1) [|!x_1 * k + b; !x_2 * k + b|];\n\tend;\ndone;\nArray.stable_sort cmp !ls;;\nlet fl = ref 0;;\nfor i = 0 to Array.length !ls - 2 do\n\tif (!ls.(i).(1) > !ls.(i + 1).(1)) then fl := 1;\ndone;;\nif !fl = 0 then print_endline \"NO\" else print_endline \"YES\";;\n(*\nfor i = 0 to Array.length !ls - 1 do\n\tprint_int !ls.(i).(0);\n\tprint_string \" \";\n\tprint_int !ls.(i).(1);\n\tprint_endline \"\";\ndone;;*)\n"}], "src_uid": "8b61213e2ce76b938aa68ffd1e4c1429"} {"nl": {"description": "Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to insidious taxi drivers.The mayor of the city decided to change the direction of certain roads so that the taxi drivers wouldn't be able to increase the cost of the trip endlessly. More formally, if the taxi driver is on a certain crossroads, they wouldn't be able to reach it again if he performs a nonzero trip. Traffic controllers are needed in order to change the direction the road goes. For every road it is known how many traffic controllers are needed to change the direction of the road to the opposite one. It is allowed to change the directions of roads one by one, meaning that each traffic controller can participate in reversing two or more roads.You need to calculate the minimum number of traffic controllers that you need to hire to perform the task and the list of the roads that need to be reversed.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \\leq n \\leq 100\\,000$$$, $$$1 \\leq m \\leq 100\\,000$$$)\u00a0\u2014 the number of crossroads and the number of roads in the city, respectively. Each of the following $$$m$$$ lines contain three integers $$$u_{i}$$$, $$$v_{i}$$$ and $$$c_{i}$$$ ($$$1 \\leq u_{i}, v_{i} \\leq n$$$, $$$1 \\leq c_{i} \\leq 10^9$$$, $$$u_{i} \\ne v_{i}$$$)\u00a0\u2014 the crossroads the road starts at, the crossroads the road ends at and the number of traffic controllers required to reverse this road.", "output_spec": "In the first line output two integers the minimal amount of traffic controllers required to complete the task and amount of roads $$$k$$$ which should be reversed. $$$k$$$ should not be minimized. In the next line output $$$k$$$ integers separated by spaces \u2014 numbers of roads, the directions of which should be reversed. The roads are numerated from $$$1$$$ in the order they are written in the input. If there are many solutions, print any of them.", "sample_inputs": ["5 6\n2 1 1\n5 2 6\n2 3 2\n3 4 3\n4 5 5\n1 5 4", "5 7\n2 1 5\n3 2 3\n1 3 3\n2 4 1\n4 3 5\n5 4 1\n1 5 3"], "sample_outputs": ["2 2\n1 3", "3 3\n3 4 7"], "notes": "NoteThere are two simple cycles in the first example: $$$1 \\rightarrow 5 \\rightarrow 2 \\rightarrow 1$$$ and $$$2 \\rightarrow 3 \\rightarrow 4 \\rightarrow 5 \\rightarrow 2$$$. One traffic controller can only reverse the road $$$2 \\rightarrow 1$$$ and he can't destroy the second cycle by himself. Two traffic controllers can reverse roads $$$2 \\rightarrow 1$$$ and $$$2 \\rightarrow 3$$$ which would satisfy the condition.In the second example one traffic controller can't destroy the cycle $$$ 1 \\rightarrow 3 \\rightarrow 2 \\rightarrow 1 $$$. With the help of three controllers we can, for example, reverse roads $$$1 \\rightarrow 3$$$ ,$$$ 2 \\rightarrow 4$$$, $$$1 \\rightarrow 5$$$."}, "positive_code": [{"source_code": "let binary_search ng ok f = let d = if ng < ok then 1 else -1 in\n let rec f0 ng ok =\n if abs (ok - ng) <= 1 then ok\n else let mid = ng + (ok - ng) / 2 in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-d) (ok+d)\n;;\nScanf.(Array.(scanf \" %d %d\" @@ fun n m ->\n let edges = make n [] in\n let edges0 =\n init m (fun i -> scanf \" %d %d %d\" @@ fun u v c ->\n let u,v = u-1,v-1 in\n edges.(u) <- (v,c,i) :: edges.(u); u,v)\n in\n let solve w =\n let state = Array.make n `Todo in\n let res = ref [] in\n let rec visit i =\n if state.(i) = `Done then true\n else if state.(i) = `Temp then false\n else (\n state.(i) <- `Temp;\n let f =\n List.fold_left (fun u (j,cost,_) ->\n if cost <= w || not u then u\n else u && visit j\n ) true edges.(i)\n in\n state.(i) <- `Done; res := i :: !res;\n f\n )\n in\n if\n fold_left (fun u i ->\n if state.(i) = `Todo then\n u && visit i\n else u\n ) true @@ init n (fun i -> i)\n then Some !res else None\n in\n let c = binary_search 0 (1000000050) (fun w ->\n match solve w with Some _ -> true | None -> false\n ) in\n let res = match solve c with Some r -> r | None -> failwith \"\" in\n let edges2 = init n (fun i -> edges.(i)) in\n iteri (fun i -> List.iter (fun (j,cost,idx) ->\n edges2.(j) <- (i,cost,idx) :: edges2.(j)\n )) edges;\n let used = make n false in\n let res2 = ref [] in\n List.iter (fun i ->\n List.iter (fun (j,cost,idx) ->\n if cost <= c && not used.(j)\n && (i,j) <> edges0.(idx)\n then res2 := idx :: !res2\n ) edges2.(i);\n used.(i) <- true;\n ) res;\n Printf.(\n printf \"%d %d\\n\" c @@ List.length !res2;\n List.iter (printf \"%d \") @@ List.map ((+) 1) !res2);\n))\n"}], "negative_code": [{"source_code": "let binary_search ng ok f = let d = if ng < ok then 1 else -1 in\n let rec f0 ng ok =\n if abs (ok - ng) <= 1 then ok\n else let mid = ng + (ok - ng) / 2 in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-d) (ok+d)\n;;\nScanf.(Array.(scanf \" %d %d\" @@ fun n m ->\n let edges = make n [] in\n init m (fun i -> scanf \" %d %d %d\" @@ fun u v c ->\n edges.(u-1) <- (v-1,c,i) :: edges.(u-1);\n ) |> ignore;\n let solve w =\n let state = Array.make n `Todo in\n let res = ref [] in\n let rec visit i =\n if state.(i) = `Done then true\n else if state.(i) = `Temp then false\n else (\n state.(i) <- `Temp;\n let f =\n List.fold_left (fun u (j,cost,_) ->\n if cost <= w || not u then u\n else u && visit j\n ) true edges.(i)\n in\n state.(i) <- `Done;\n res := i :: !res; f\n )\n in\n if\n fold_left (fun u i ->\n if state.(i) = `Todo then\n u && visit i\n else u\n ) true @@ init n (fun i -> i)\n then Some !res else None\n in\n let c = binary_search 0 (1000000050) (fun w ->\n match solve w with Some _ -> true | None -> false\n ) in\n let res = match solve c with Some r -> r | None -> failwith \"\" in\n let edges2 = init n (fun i -> edges.(i)) in\n iteri (fun i -> List.iter (fun (j,cost,idx) ->\n edges2.(j) <- (i,cost,idx) :: edges2.(j)\n )) edges;\n let used = make n false in\n let res2 = ref [] in\n List.iter (fun i ->\n List.iter (fun (j,cost,idx) ->\n if cost <= c && not used.(j) then (\n res2 := idx :: !res2\n )\n ) edges2.(i);\n used.(i) <- true;\n ) res;\n Printf.(\n printf \"%d %d\\n\" c @@ List.length !res2;\n List.iter (printf \"%d \") @@ List.map ((+) 1) !res2)\n))"}], "src_uid": "f1121338e84c757d1165d1d645bb26ed"} {"nl": {"description": "You are given a string $$$s$$$ consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings \"abacaba\", \"aa\" and \"z\" are palindromes and strings \"bba\", \"xd\" are not.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 number of queries. Each of the next $$$t$$$ lines contains one string. The $$$i$$$-th line contains a string $$$s_i$$$ consisting only of lowercase Latin letter. It is guaranteed that the length of $$$s_i$$$ is from $$$1$$$ to $$$1000$$$ (inclusive).", "output_spec": "Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: -1 if it is impossible to obtain a good string by rearranging the letters of $$$s_i$$$ and any good string which can be obtained from the given one (by rearranging the letters) otherwise.", "sample_inputs": ["3\naa\nabacaba\nxdd"], "sample_outputs": ["-1\nabaacba\nxdd"], "notes": "NoteIn the first query we cannot rearrange letters to obtain a good string.Other examples (not all) of correct answers to the second query: \"ababaca\", \"abcabaa\", \"baacaba\".In the third query we can do nothing to obtain a good string."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make(struct type t=char let compare=compare end)\nlet () =\n let t = gi 0 in\n let _ = init (i32 t) (fun _ ->\n let s = scanf \" %s\" @@ id in\n let a = init (String.length s) (fun i -> s.[i]) in\n (* let same,_,(p,q) = fold_left (fun (f,u,((p,q) as w)) v -> if f=false then false,v,w else if u<>v then false,v,(u,v) else true,v,w) (true,s.[0],(s.[0],s.[0])) a in\n if same then printf \"-1\\n\" else printf \"%c%c\\n\" p q *)\n let mp = ref IMap.empty in\n iter (fun c ->\n mp := IMap.add c (1L+try IMap.find c !mp with _ -> 0L) !mp\n ) a;\n let mp = !mp in\n if IMap.cardinal mp = 1 then printf \"-1\"\n else (\n IMap.iter (fun c n ->\n rep 1L n (fun _ -> printf \"%c\" c)\n ) mp;\n );\n print_newline ()\n ) in ()\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let t = gi 0 in\n let _ = init (i32 t) (fun _ ->\n let s = scanf \" %s\" @@ id in\n let a = init (String.length s) (fun i -> s.[i]) in\n let same,_,(p,q) = fold_left (fun (f,u,((p,q) as w)) v -> if f=false then false,v,w else if u<>v then false,v,(u,v) else true,v,w) (true,s.[0],(s.[0],s.[0])) a in\n if same then printf \"-1\\n\" else printf \"%c%c\\n\" p q\n ) in ()\n\n\n\n\n\n\n\n"}], "src_uid": "b9f0c38c6066bdafa2e4c6daf7f46816"} {"nl": {"description": "A flowerbed has many flowers and two fountains.You can adjust the water pressure and set any values r1(r1\u2009\u2265\u20090) and r2(r2\u2009\u2265\u20090), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains.You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12\u2009+\u2009r22 is minimum possible. Find this minimum value.", "input_spec": "The first line of the input contains integers n, x1, y1, x2, y2 (1\u2009\u2264\u2009n\u2009\u2264\u20092000, \u2009-\u2009107\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2\u2009\u2264\u2009107)\u00a0\u2014 the number of flowers, the coordinates of the first and the second fountain. Next follow n lines. The i-th of these lines contains integers xi and yi (\u2009-\u2009107\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009107)\u00a0\u2014 the coordinates of the i-th flower. It is guaranteed that all n\u2009+\u20092 points in the input are distinct.", "output_spec": "Print the minimum possible value r12\u2009+\u2009r22. Note, that in this problem optimal answer is always integer.", "sample_inputs": ["2 -1 0 5 3\n0 2\n5 2", "4 0 0 5 0\n9 4\n8 3\n-1 0\n1 4"], "sample_outputs": ["6", "33"], "notes": "NoteThe first sample is (r12\u2009=\u20095, r22\u2009=\u20091): The second sample is (r12\u2009=\u20091, r22\u2009=\u200932): "}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read5 () = Scanf.scanf \"%d %d %d %d %d\\n\" ( fun x y z a b-> x, y, z,a,b);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet (n,x1,y1,x2,y2) = read5 ();;\n\nlet coord = Array.init n ( fun _ -> read2 () );;\n\nlet square a = a *| a;;\n\nlet dis (a,b) (c,d) =\n square ( Int64.of_int(a-c) ) +| ( square ( Int64.of_int(b-d) ) );;\n\nlet licz () =\n Array.sort ( fun a b -> compare ( dis a (x1,y1) ) (dis b (x1,y1) ) ) coord;\n let wynik = ref Int64.max_int in\n for i=0 to n do\n let r1 = if i=0 then Int64.zero else dis coord.(i-1) (x1,y1) in\n let r2 = ref Int64.zero in\n for j=i to (n-1) do\n r2 := max !r2 ( dis coord.(j) (x2,y2) )\n done;\n wynik := min !wynik ( r1 +| !r2 )\n done;\n !wynik;;\n\nlet _ = \n Printf.printf \"%Ld\\n\" ( licz () ) ;;\n\n\n"}, {"source_code": "let bs = Scanf.Scanning.stdin\nlet xint() = Scanf.bscanf bs \" %d\" (fun x -> x)\nlet xint32() = Scanf.bscanf bs \" %ld\" (fun x -> x)\nlet xint64() = Scanf.bscanf bs \" %Ld\" (fun x -> x)\nlet xstr() = Scanf.bscanf bs \" %s\" (fun x -> x)\nlet xreal() = Scanf.bscanf bs \" %f\" (fun x -> x)\nlet printf = Printf.printf\n\nlet ( +| ) = Int64.add\nlet ( -| ) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\nlet ( %| ) = Int64.rem\n\nlet () = \n let n = xint() in\n let x1 = xint64() and y1 = xint64() in\n let x2 = xint64() and y2 = xint64() in\n let x = Array.make n 0L and y = Array.make n 0L in\n for i = 0 to n - 1 do\n x.(i) <- xint64();\n y.(i) <- xint64();\n done;\n \n let sqr x = x *| x in\n let max x y =\n if Int64.compare x y > 0 then x\n else y\n in\n let min x y =\n if Int64.compare x y < 0 then x\n else y\n in\n\n let ret = ref 9223372036854775807L in\n for i = -1 to n - 1 do\n let r1 = (if i = -1 then 0L else ((sqr (x.(i) -| x1)) +| (sqr (y.(i) -| y1)))) in\n let r2 = ref 0L in\n for j = 0 to n - 1 do\n let a = (sqr (x.(j) -| x1)) +| (sqr (y.(j) -| y1)) in\n let b = (sqr (x.(j) -| x2)) +| (sqr (y.(j) -| y2)) in\n if Int64.compare a r1 > 0 then (\n r2 := max !r2 b;\n );\n done;\n ret := min !ret (r1 +| !r2);\n done;\n printf \"%Ld\\n\" !ret;"}, {"source_code": "let bs = Scanf.Scanning.stdin\nlet xint() = Scanf.bscanf bs \" %d\" (fun x -> x)\nlet xint32() = Scanf.bscanf bs \" %ld\" (fun x -> x)\nlet xint64() = Scanf.bscanf bs \" %Ld\" (fun x -> x)\nlet xstr() = Scanf.bscanf bs \" %s\" (fun x -> x)\nlet xreal() = Scanf.bscanf bs \" %f\" (fun x -> x)\nlet printf = Printf.printf\n\nlet ( +| ) = Int64.add\nlet ( -| ) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\nlet ( %| ) = Int64.rem\n\nlet () = \n let n = xint() in\n let x1 = xint64() and y1 = xint64() in\n let x2 = xint64() and y2 = xint64() in\n let x = Array.make n 0L and y = Array.make n 0L in\n for i = 0 to n - 1 do\n x.(i) <- xint64();\n y.(i) <- xint64();\n done;\n \n let sqr x = x *| x in\n let max x y =\n if Int64.compare x y > 0 then x\n else y\n in\n let min x y =\n if Int64.compare x y < 0 then x\n else y\n in\n\n let ret = ref 9223372036854775807L in\n for i = -1 to n - 1 do\n let r1 = (if i = -1 then 0L else ((sqr (x.(i) -| x1)) +| (sqr (y.(i) -| y1)))) in\n let r2 = ref 0L in\n for j = 0 to n - 1 do\n let a = (sqr (x.(j) -| x1)) +| (sqr (y.(j) -| y1)) in\n let b = (sqr (x.(j) -| x2)) +| (sqr (y.(j) -| y2)) in\n if Int64.compare a r1 > 0 then (\n r2 := max !r2 b;\n );\n done;\n ret := min !ret (r1 +| !r2);\n done;\n printf \"%Ld\\n\" !ret;\n"}], "negative_code": [{"source_code": "let bs = Scanf.Scanning.stdin\nlet xint() = Scanf.bscanf bs \" %d\" (fun x -> x)\nlet xint32() = Scanf.bscanf bs \" %ld\" (fun x -> x)\nlet xint64() = Scanf.bscanf bs \" %Ld\" (fun x -> x)\nlet xstr() = Scanf.bscanf bs \" %s\" (fun x -> x)\nlet xreal() = Scanf.bscanf bs \" %f\" (fun x -> x)\nlet printf = Printf.printf\n\nlet ( +| ) = Int64.add\nlet ( -| ) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\nlet ( %| ) = Int64.rem\n\nlet () = \n let n = xint() in\n let x1 = xint64() and y1 = xint64() in\n let x2 = xint64() and y2 = xint64() in\n let x = Array.make n 0L and y = Array.make n 0L in\n for i = 0 to n - 1 do\n x.(i) <- xint64();\n y.(i) <- xint64();\n done;\n \n let sqr x = x *| x in\n let max x y =\n if Int64.compare x y > 0 then x\n else y\n in\n let min x y =\n if Int64.compare x y < 0 then x\n else y\n in\n\n let ret = ref 9223372036854775807L in\n for i = 0 to n - 1 do\n let r1 = (sqr (x.(i) -| x1)) +| (sqr (y.(i) -| y1)) in\n let r2 = ref 0L in\n for j = 0 to n - 1 do\n let a = (sqr (x.(j) -| x1)) +| (sqr (y.(j) -| y1)) in\n let b = (sqr (x.(j) -| x2)) +| (sqr (y.(j) -| y2)) in\n if Int64.compare a r1 > 0 then (\n r2 := max !r2 b;\n );\n done;\n ret := min !ret (r1 +| !r2);\n done;\n printf \"%Ld\\n\" !ret;"}], "src_uid": "5db9c5673a04256c52f180dbfca2a52f"} {"nl": {"description": "There are $$$n$$$ athletes in front of you. Athletes are numbered from $$$1$$$ to $$$n$$$ from left to right. You know the strength of each athlete\u00a0\u2014 the athlete number $$$i$$$ has the strength $$$s_i$$$.You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $$$A$$$ and $$$B$$$ so that the value $$$|\\max(A) - \\min(B)|$$$ is as small as possible, where $$$\\max(A)$$$ is the maximum strength of an athlete from team $$$A$$$, and $$$\\min(B)$$$ is the minimum strength of an athlete from team $$$B$$$.For example, if $$$n=5$$$ and the strength of the athletes is $$$s=[3, 1, 2, 6, 4]$$$, then one of the possible split into teams is: first team: $$$A = [1, 2, 4]$$$, second team: $$$B = [3, 6]$$$. In this case, the value $$$|\\max(A) - \\min(B)|$$$ will be equal to $$$|4-3|=1$$$. This example illustrates one of the ways of optimal split into two teams.Print the minimum value $$$|\\max(A) - \\min(B)|$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains positive integer $$$n$$$ ($$$2 \\le n \\le 50$$$)\u00a0\u2014 number of athletes. The second line contains $$$n$$$ positive integers $$$s_1, s_2, \\ldots, s_n$$$ ($$$1 \\le s_i \\le 1000$$$), where $$$s_i$$$\u00a0\u2014 is the strength of the $$$i$$$-th athlete. Please note that $$$s$$$ values may not be distinct.", "output_spec": "For each test case print one integer\u00a0\u2014 the minimum value of $$$|\\max(A) - \\min(B)|$$$ with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.", "sample_inputs": ["5\n5\n3 1 2 6 4\n6\n2 1 3 2 4 3\n4\n7 9 3 1\n2\n1 1000\n3\n100 150 200"], "sample_outputs": ["1\n0\n2\n999\n50"], "notes": "NoteThe first test case was explained in the statement. In the second test case, one of the optimal splits is $$$A=[2, 1]$$$, $$$B=[3, 2, 4, 3]$$$, so the answer is $$$|2-2|=0$$$."}, "positive_code": [{"source_code": "let split_string ?(pattern=\"\") = Str.split @@ Str.regexp pattern\nlet t = Scanf.sscanf (read_line ()) \"%d\" @@ fun t -> t\n\nlet () =\n for i = 0 to t - 1 do\n let n = Scanf.sscanf (read_line ()) \"%d\" @@ fun n -> n in\n let s = read_line () |> split_string ~pattern:\" \" |> List.map int_of_string |> List.sort compare |> Array.of_list in\n let ans = ref max_int in\n for i = 1 to n - 1 do\n ans := min !ans (s.(i) - s.(i - 1))\n done;\n Printf.printf \"%d\\n\" !ans\n done"}], "negative_code": [], "src_uid": "d2669f85bdb59715352c6bc3d7ba9652"} {"nl": {"description": "You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of digits on the display. The second line contains n digits\u00a0\u2014 the initial state of the display.", "output_spec": "Print a single line containing n digits\u00a0\u2014 the desired state of the display containing the smallest possible number.", "sample_inputs": ["3\n579", "4\n2014"], "sample_outputs": ["024", "0142"], "notes": null}, "positive_code": [{"source_code": "let s = read_line ();;\nlet sx = List.map int_of_string (Str.split (Str.regexp \" +\") s);;\nlet n = List.hd sx;;\n\n\nlet s = read_line ();;\nlet x = List.map int_of_string (Str.split (Str.regexp \"\") s);;\n\n\nlet shift = function\n| [] -> []\n| x::xs -> xs @ [x]\n\n\nlet rec add = function\n| [] -> []\n| 9::xs -> 0 :: (add xs)\n| x::xs -> (x+1) :: (add xs);;\n\nlet smaller xx yy = let rec aux = function\n | (x::xs, y::ys) when x < y -> xx\n | (x::xs, y::ys) when x = y -> aux (xs, ys)\n | (_, _) -> yy in\n aux (xx, yy);;\n\nlet rec find_min min x = function\n| i when i = 10 -> min\n| i ->\n let rec aux min x = function\n | j when j = n -> find_min min (add x) (i+1)\n | j -> aux (smaller x min) (shift x) (j+1) in\n aux min x 0;;\n\nprint_newline(List.iter print_int (find_min x x 0));;\n"}], "negative_code": [], "src_uid": "6ee356f2b3a4bb88087ed76b251afec2"} {"nl": {"description": "Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.", "input_spec": "The first line contains three integers L, b \u0438 f (10\u2009\u2264\u2009L\u2009\u2264\u2009100000,\u20091\u2009\u2264\u2009b,\u2009f\u2009\u2264\u2009100). The second line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.", "output_spec": "For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.", "sample_inputs": ["30 1 2\n6\n1 5\n1 4\n1 5\n2 2\n1 5\n1 4", "30 1 1\n6\n1 5\n1 4\n1 5\n2 2\n1 5\n1 4", "10 1 1\n1\n1 12"], "sample_outputs": ["0\n6\n11\n17\n23", "0\n6\n11\n17\n6", "-1"], "notes": null}, "positive_code": [{"source_code": "let split_by_whitespace s =\n let rec split_loop s idx res =\n let rec length_of_char s idx len =\n if idx >= (String.length s)\n then len\n else\n begin\n if (s.[idx] == ' ' || s.[idx] == '\\t' || s.[idx] == '\\n')\n then len\n else length_of_char s (idx+1) (len+1)\n end\n in\n\n if idx >= (String.length s)\n then res\n else\n begin\n if (s.[idx] != ' ' && s.[idx] != '\\t' && s.[idx] != '\\n')\n then\n begin\n let len = length_of_char s idx 0 in\n split_loop s (idx+len) ((idx, len)::res)\n end\n else split_loop s (idx+1) res\n end\n in\n\n let whitespaces = split_loop s 0 [] in\n List.fold_left (fun res (idx, len) ->\n (String.sub s idx len)::res\n ) [] whitespaces\n\nlet parking_lot l f b cars =\n let check_behind position car_size behind_position = position + car_size + b <= behind_position in\n\n let park_car req_no car_size parking_lot parking_history =\n if (List.length parking_lot) = 0\n then (\n if check_behind 0 car_size (l+b)\n then ((req_no, 0, car_size)::parking_lot), (0::parking_history)\n else parking_lot, (-1::parking_history)\n )\n else (\n let position, parking_lot =\n List.fold_left (fun (position, parking_lot) (behind_req_no, behind_position, behind_car_size) ->\n let front_req_no, front_position, front_car_size = List.hd parking_lot in\n if front_req_no = behind_req_no\n then position, parking_lot\n else if position != -1\n then position, ((behind_req_no, behind_position, behind_car_size)::parking_lot)\n else (\n let candidate_position = front_position + front_car_size + f in\n if check_behind candidate_position car_size behind_position\n then candidate_position, ((req_no, candidate_position, car_size)::(behind_req_no, behind_position, behind_car_size)::parking_lot)\n else position, ((behind_req_no, behind_position, behind_car_size)::parking_lot)\n )\n ) (-1, [(0, 0, -1 * f)]) (parking_lot @ [(0, l + b, 0)])\n in\n let parking_lot =\n List.sort (fun (_,a,_) (_,b,_) -> compare a b)\n (List.filter (fun (x,_,_) -> x != 0) parking_lot)\n in\n parking_lot, (position::parking_history)\n )\n in\n\n let leave_car leaving_req_no parking_lot =\n let parking_lot =\n List.fold_left (fun parking_lot (req_no, position, car_size) ->\n if req_no = leaving_req_no\n then parking_lot\n else (req_no, position, car_size)::parking_lot\n ) [] parking_lot\n in\n List.rev parking_lot\n in\n\n let rec find_lot req_no parking_lot parking_history cars =\n match cars with\n | [] -> List.rev parking_history\n | (req_type,data)::t -> (\n if req_type = 1\n then (\n let parking_lot, parking_history = park_car req_no data parking_lot parking_history in\n find_lot (req_no + 1) parking_lot parking_history t\n )\n else find_lot (req_no + 1) (leave_car data parking_lot) parking_history t\n )\n in\n find_lot 1 [] [] cars\n\nlet main =\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let l, f, b = (List.nth data 0), (List.nth data 1), (List.nth data 2) in\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let req_size = List.nth data 0 in\n let rec parse_req idx reqs =\n if idx == req_size\n then reqs\n else (\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n parse_req (idx + 1) (((List.nth data 0), (List.nth data 1))::reqs)\n )\n in\n let reqs = parse_req 0 [] in\n let reqs = List.rev reqs in\n\n let result = parking_lot l f b reqs in\n List.iter (fun x -> print_endline(string_of_int(x))) result\n\nlet _ =\n main\n"}], "negative_code": [{"source_code": "let split_by_whitespace s =\n let rec split_loop s idx res =\n let rec length_of_char s idx len =\n if idx >= (String.length s)\n then len\n else\n begin\n if (s.[idx] == ' ' || s.[idx] == '\\t' || s.[idx] == '\\n')\n then len\n else length_of_char s (idx+1) (len+1)\n end\n in\n\n if idx >= (String.length s)\n then res\n else\n begin\n if (s.[idx] != ' ' && s.[idx] != '\\t' && s.[idx] != '\\n')\n then\n begin\n let len = length_of_char s idx 0 in\n split_loop s (idx+len) ((idx, len)::res)\n end\n else split_loop s (idx+1) res\n end\n in\n\n let whitespaces = split_loop s 0 [] in\n List.fold_left (fun res (idx, len) ->\n (String.sub s idx len)::res\n ) [] whitespaces\n\nlet parking_lot l f b cars =\n let check_behind position car_size behind_position = position + car_size + b <= behind_position in\n\n let park_car req_no car_size parking_lot parking_history =\n if (List.length parking_lot) = 0\n then (\n if check_behind 0 car_size (l+b)\n then ((req_no, 0, car_size)::parking_lot), (0::parking_history)\n else parking_lot, (-1::parking_history)\n )\n else (\n let position, parking_lot =\n List.fold_left (fun (position, parking_lot) (behind_req_no, behind_position, behind_car_size) ->\n let front_req_no, front_position, front_car_size = List.hd parking_lot in\n if front_req_no = behind_req_no\n then position, parking_lot\n else if position != -1\n then position, parking_lot\n else (\n let candidate_position = front_position + front_car_size + f in\n if check_behind candidate_position car_size behind_position\n then candidate_position, ((req_no, candidate_position, car_size)::(behind_req_no, behind_position, behind_car_size)::parking_lot)\n else position, ((behind_req_no, behind_position, behind_car_size)::parking_lot)\n )\n ) (-1, [(0, 0, -1 * f)]) (parking_lot @ [(0, l + b, 0)])\n in\n let parking_lot =\n List.sort (fun (_,a,_) (_,b,_) -> compare a b)\n (List.filter (fun (x,_,_) -> x != 0) parking_lot)\n in\n parking_lot, (position::parking_history)\n )\n in\n\n let leave_car leaving_req_no parking_lot =\n let parking_lot =\n List.fold_left (fun parking_lot (req_no, position, car_size) ->\n if req_no = leaving_req_no\n then parking_lot\n else (req_no, position, car_size)::parking_lot\n ) [] parking_lot\n in\n List.rev parking_lot\n in\n\n let rec find_lot req_no parking_lot parking_history cars =\n match cars with\n | [] -> List.rev parking_history\n | (req_type,data)::t -> (\n if req_type = 1\n then (\n let parking_lot, parking_history = park_car req_no data parking_lot parking_history in\n find_lot (req_no + 1) parking_lot parking_history t\n )\n else find_lot (req_no + 1) (leave_car data parking_lot) parking_history t\n )\n in\n find_lot 1 [] [] cars\n\nlet main =\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let l, f, b = (List.nth data 0), (List.nth data 1), (List.nth data 2) in\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let req_size = List.nth data 0 in\n let rec parse_req idx reqs =\n if idx == req_size\n then reqs\n else (\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n parse_req (idx + 1) (((List.nth data 0), (List.nth data 1))::reqs)\n )\n in\n let reqs = parse_req 0 [] in\n let reqs = List.rev reqs in\n\n let result = parking_lot l f b reqs in\n List.iter (fun x -> print_endline(string_of_int(x))) result\n\nlet _ =\n main\n"}, {"source_code": "let split_by_whitespace s =\n let rec split_loop s idx res =\n let rec length_of_char s idx len =\n if idx >= (String.length s)\n then len\n else\n begin\n if (s.[idx] == ' ' || s.[idx] == '\\t' || s.[idx] == '\\n')\n then len\n else length_of_char s (idx+1) (len+1)\n end\n in\n\n if idx >= (String.length s)\n then res\n else\n begin\n if (s.[idx] != ' ' && s.[idx] != '\\t' && s.[idx] != '\\n')\n then\n begin\n let len = length_of_char s idx 0 in\n split_loop s (idx+len) ((idx, len)::res)\n end\n else split_loop s (idx+1) res\n end\n in\n\n let whitespaces = split_loop s 0 [] in\n List.fold_left (fun res (idx, len) ->\n (String.sub s idx len)::res\n ) [] whitespaces\n\nlet parking_lot l f b cars =\n let check_behind position car_size behind_position = position + car_size + b <= behind_position in\n\n let park_car req_no car_size parking_lot parking_history =\n if (List.length parking_lot) = 0\n then (\n if check_behind 0 car_size (l+b)\n then [(req_no, 0, car_size)], (0::parking_history)\n else [], (-1::parking_history)\n )\n else (\n let position, parking_lot =\n List.fold_left (fun (position, parking_lot) (behind_req_no, behind_position, behind_car_size) ->\n let front_req_no, front_position, front_car_size = List.hd parking_lot in\n if front_req_no = behind_req_no\n then position, parking_lot\n else if position != -1\n then position, parking_lot\n else (\n let candidate_position = front_position + front_car_size + f in\n if check_behind candidate_position car_size behind_position\n then (\n if behind_req_no = 0\n then candidate_position, ((req_no, candidate_position, car_size)::parking_lot)\n else candidate_position, ((req_no, candidate_position, car_size)::(behind_req_no, behind_position, behind_car_size)::parking_lot)\n )\n else (\n if behind_req_no = 0\n then position, parking_lot\n else position, ((behind_req_no, behind_position, behind_car_size)::parking_lot)\n )\n )\n ) (-1, [List.hd parking_lot]) (parking_lot @ [(0, l + b, 0)])\n in\n (List.rev parking_lot), (position::parking_history)\n )\n in\n\n let leave_car leaving_req_no parking_lot =\n let parking_lot =\n List.fold_left (fun parking_lot (req_no, position, car_size) ->\n if req_no = leaving_req_no\n then parking_lot\n else (req_no, position, car_size)::parking_lot\n ) [] parking_lot\n in\n List.rev parking_lot\n in\n\n let rec find_lot req_no parking_lot parking_history cars =\n match cars with\n | [] -> List.rev parking_history\n | (req_type,data)::t -> (\n if req_type = 1\n then (\n let parking_lot, parking_history = park_car req_no data parking_lot parking_history in\n find_lot (req_no + 1) parking_lot parking_history t\n )\n else find_lot (req_no + 1) (leave_car data parking_lot) parking_history t\n )\n in\n find_lot 1 [] [] cars\n\nlet main =\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let l, f, b = (List.nth data 0), (List.nth data 1), (List.nth data 2) in\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let req_size = List.nth data 0 in\n let rec parse_req idx reqs =\n if idx == req_size\n then reqs\n else (\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n parse_req (idx + 1) (((List.nth data 0), (List.nth data 1))::reqs)\n )\n in\n let reqs = parse_req 0 [] in\n let reqs = List.rev reqs in\n\n let result = parking_lot l f b reqs in\n List.iter (fun x -> print_endline(string_of_int(x))) result\n\nlet _ =\n main\n"}, {"source_code": "\"12\""}, {"source_code": "let split_by_whitespace s =\n let rec split_loop s idx res =\n let rec length_of_char s idx len =\n if idx >= (String.length s)\n then len\n else\n begin\n if (s.[idx] == ' ' || s.[idx] == '\\t' || s.[idx] == '\\n')\n then len\n else length_of_char s (idx+1) (len+1)\n end\n in\n\n if idx >= (String.length s)\n then res\n else\n begin\n if (s.[idx] != ' ' && s.[idx] != '\\t' && s.[idx] != '\\n')\n then\n begin\n let len = length_of_char s idx 0 in\n split_loop s (idx+len) ((idx, len)::res)\n end\n else split_loop s (idx+1) res\n end\n in\n\n let whitespaces = split_loop s 0 [] in\n List.fold_left (fun res (idx, len) ->\n (String.sub s idx len)::res\n ) [] whitespaces\n\nlet parking_lot l f b cars =\n let check_behind position car_size behind_position = position + car_size + b <= behind_position in\n\n let park_car req_no car_size parking_lot parking_history =\n if (List.length parking_lot) = 0\n then (\n if check_behind 0 car_size (l+b)\n then [(req_no, 0, car_size)], [0]\n else [], [-1]\n )\n else (\n let position, parking_lot =\n List.fold_left (fun (position, parking_lot) (behind_req_no, behind_position, behind_car_size) ->\n let front_req_no, front_position, front_car_size = List.hd parking_lot in\n if front_req_no = behind_req_no\n then position, parking_lot\n else if position != -1\n then position, parking_lot\n else (\n let candidate_position = front_position + front_car_size + f in\n if check_behind candidate_position car_size behind_position\n then (\n if behind_req_no = 0\n then candidate_position, ((req_no, candidate_position, car_size)::parking_lot)\n else candidate_position, ((req_no, candidate_position, car_size)::(behind_req_no, behind_position, behind_car_size)::parking_lot)\n )\n else (\n if behind_req_no = 0\n then position, parking_lot\n else position, ((behind_req_no, behind_position, behind_car_size)::parking_lot)\n )\n )\n ) (-1, [List.hd parking_lot]) (parking_lot @ [(0, l + b, 0)])\n in\n (List.rev parking_lot), (position::parking_history)\n )\n in\n\n let leave_car leaving_req_no parking_lot =\n let parking_lot =\n List.fold_left (fun parking_lot (req_no, position, car_size) ->\n if req_no = leaving_req_no\n then parking_lot\n else (req_no, position, car_size)::parking_lot\n ) [] parking_lot\n in\n List.rev parking_lot\n in\n\n let rec find_lot req_no parking_lot parking_history cars =\n match cars with\n | [] -> List.rev parking_history\n | (req_type,data)::t -> (\n if req_type = 1\n then (\n let parking_lot, parking_history = park_car req_no data parking_lot parking_history in\n find_lot (req_no + 1) parking_lot parking_history t\n )\n else find_lot (req_no + 1) (leave_car data parking_lot) parking_history t\n )\n in\n find_lot 1 [] [] cars\n\nlet main =\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let l, f, b = (List.nth data 0), (List.nth data 1), (List.nth data 2) in\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let req_size = List.nth data 0 in\n let rec parse_req idx reqs =\n if idx == req_size\n then reqs\n else (\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n parse_req (idx + 1) (((List.nth data 0), (List.nth data 1))::reqs)\n )\n in\n let reqs = parse_req 0 [] in\n let reqs = List.rev reqs in\n\n let result = parking_lot l f b reqs in\n List.iter (fun x -> print_endline(string_of_int(x))) result\n\nlet _ =\n main\n"}, {"source_code": "let split_by_whitespace s =\n let rec split_loop s idx res =\n let rec length_of_char s idx len =\n if idx >= (String.length s)\n then len\n else\n begin\n if (s.[idx] == ' ' || s.[idx] == '\\t' || s.[idx] == '\\n')\n then len\n else length_of_char s (idx+1) (len+1)\n end\n in\n\n if idx >= (String.length s)\n then res\n else\n begin\n if (s.[idx] != ' ' && s.[idx] != '\\t' && s.[idx] != '\\n')\n then\n begin\n let len = length_of_char s idx 0 in\n split_loop s (idx+len) ((idx, len)::res)\n end\n else split_loop s (idx+1) res\n end\n in\n\n let whitespaces = split_loop s 0 [] in\n List.fold_left (fun res (idx, len) ->\n (String.sub s idx len)::res\n ) [] whitespaces\n\nlet parking_lot l f b cars =\n let check_behind position car_size behind_position = position + car_size + b <= behind_position in\n\n let park_car req_no car_size parking_lot parking_history =\n if (List.length parking_lot) = 0\n then (\n if check_behind 0 car_size (l+b)\n then [(req_no, 0, car_size)], [0]\n else [], [-1]\n )\n else (\n let position, parking_lot =\n List.fold_left (fun (position, parking_lot) (behind_req_no, behind_position, behind_car_size) ->\n let front_req_no, front_position, front_car_size = List.hd parking_lot in\n if front_req_no = behind_req_no\n then position, parking_lot\n else if position != -1\n then position, parking_lot\n else (\n let candidate_position = front_position + front_car_size + f in\n if check_behind candidate_position car_size behind_position\n then (\n if behind_req_no = 0\n then candidate_position, ((req_no, candidate_position, car_size)::parking_lot)\n else candidate_position, ((req_no, candidate_position, car_size)::(behind_req_no, behind_position, behind_car_size)::parking_lot)\n )\n else (\n if behind_req_no = 0\n then position, parking_lot\n else position, ((behind_req_no, behind_position, behind_car_size)::parking_lot)\n )\n )\n ) (-1, [List.hd parking_lot]) (parking_lot @ [(0, l + b, 0)])\n in\n (List.rev parking_lot), (position::parking_history)\n )\n in\n\n let leave_car leaving_req_no parking_lot =\n let parking_lot =\n List.fold_left (fun parking_lot (req_no, position, car_size) ->\n if req_no = leaving_req_no\n then parking_lot\n else (req_no, position, car_size)::parking_lot\n ) [] parking_lot\n in\n List.rev parking_lot\n in\n\n let rec find_lot req_no parking_lot parking_history cars =\n match cars with\n | [] -> List.rev parking_history\n | (req_type,data)::t -> (\n if req_type = 1\n then (\n let parking_lot, parking_history = park_car req_no data parking_lot parking_history in\n find_lot (req_no + 1) parking_lot parking_history t\n )\n else find_lot (req_no + 1) (leave_car data parking_lot) parking_history t\n )\n in\n find_lot 1 [] [] cars\n\nlet main =\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let l, f, b = (List.nth data 0), (List.nth data 1), (List.nth data 2) in\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n let req_size = List.nth data 0 in\n let rec parse_req idx reqs =\n if idx == req_size\n then reqs\n else (\n let data = List.map int_of_string (split_by_whitespace (read_line())) in\n parse_req (idx + 1) (((List.nth data 0), (List.nth data 1))::reqs)\n )\n in\n let reqs = parse_req 0 [] in\n let reqs = List.rev reqs in\n\n let result = parking_lot l f b reqs in\n List.map string_of_int result\n\nlet _ =\n main\n"}], "src_uid": "900ab562f1e71721bfefd4ebd9159965"} {"nl": {"description": "After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $$$n$$$. Let's call them $$$a$$$ and $$$b$$$.Note that a permutation of $$$n$$$ elements is a sequence of numbers $$$a_1, a_2, \\ldots, a_n$$$, in which every number from $$$1$$$ to $$$n$$$ appears exactly once. The message can be decoded by an arrangement of sequence $$$a$$$ and $$$b$$$, such that the number of matching pairs of elements between them is maximum. A pair of elements $$$a_i$$$ and $$$b_j$$$ is said to match if: $$$i = j$$$, that is, they are at the same index. $$$a_i = b_j$$$ His two disciples are allowed to perform the following operation any number of times: choose a number $$$k$$$ and cyclically shift one of the permutations to the left or right $$$k$$$ times. A single cyclic shift to the left on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_2, c_2:=c_3, \\ldots, c_n:=c_1$$$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_n, c_2:=c_1, \\ldots, c_n:=c_{n-1}$$$ simultaneously.Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.", "input_spec": "The first line of the input contains a single integer $$$n$$$ $$$(1 \\le n \\le 2 \\cdot 10^5)$$$\u00a0\u2014 the size of the arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \\le a_i \\le n)$$$ \u2014 the elements of the first permutation. The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \\le b_i \\le n)$$$ \u2014 the elements of the second permutation.", "output_spec": "Print the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.", "sample_inputs": ["5\n1 2 3 4 5\n2 3 4 5 1", "5\n5 4 3 2 1\n1 2 3 4 5", "4\n1 3 2 4\n4 2 3 1"], "sample_outputs": ["5", "1", "2"], "notes": "NoteFor the first case: $$$b$$$ can be shifted to the right by $$$k = 1$$$. The resulting permutations will be $$$\\{1, 2, 3, 4, 5\\}$$$ and $$$\\{1, 2, 3, 4, 5\\}$$$.For the second case: The operation is not required. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$1$$$.For the third case: $$$b$$$ can be shifted to the left by $$$k = 1$$$. The resulting permutations will be $$$\\{1, 3, 2, 4\\}$$$ and $$$\\{2, 3, 1, 4\\}$$$. Positions $$$2$$$ and $$$4$$$ have matching pairs of elements. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$2$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n\n let a = Array.init n (fun _ -> -1 + read_int()) in\n let b = Array.init n (fun _ -> -1 + read_int()) in\n\n let ainv = Array.make n 0 in\n for i=0 to n-1 do\n ainv.(a.(i)) <- i;\n done;\n \n (* let b' = Array.init n (fun i -> b.(ainv.(i))) in *)\n let b' = Array.init n (fun i -> ainv.(b.(i))) in\n let bb = Array.init n (fun i -> (b'.(i) - i + n) mod n) in\n\n let hist = Array.make n 0 in\n\n for i=0 to n-1 do\n hist.(bb.(i)) <- 1 + hist.(bb.(i))\n done;\n\n let answer = maxf 0 (n-1) (fun i -> hist.(i)) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n\n let a = Array.init n (fun _ -> -1 + read_int()) in\n let b = Array.init n (fun _ -> -1 + read_int()) in\n\n let ainv = Array.make n 0 in\n for i=0 to n-1 do\n ainv.(a.(i)) <- i;\n done;\n \n let b' = Array.init n (fun i -> b.(ainv.(i))) in\n let bb = Array.init n (fun i -> (b'.(i) - i + n) mod n) in\n\n let hist = Array.make n 0 in\n\n for i=0 to n-1 do\n hist.(bb.(i)) <- 1 + hist.(bb.(i))\n done;\n\n let answer = maxf 0 (n-1) (fun i -> hist.(i)) in\n\n printf \"%d\\n\" answer\n"}], "src_uid": "eb1bb862dc2b0094383192f6998891c5"} {"nl": {"description": "The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.", "input_spec": "The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.", "output_spec": "In the single line print the number that is written without leading zeroes in the binary notation \u2014 the answer to the problem.", "sample_inputs": ["101", "110010"], "sample_outputs": ["11", "11010"], "notes": "NoteIn the first sample the best strategy is to delete the second digit. That results in number 112\u2009=\u2009310.In the second sample the best strategy is to delete the third or fourth digits \u2014 that results in number 110102\u2009=\u20092610."}, "positive_code": [{"source_code": "(* Codeforces 257B SlonMagSquare *)\n\nopen String;;\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet remove_first_zero s = \n\tlet ln = String.length s in\n\tif not (String.contains s '0') then String.sub s 1 (ln-1) \n\telse \n\t\tlet idxz = String.index s '0' in\n\t\tlet a = String.sub s 0 idxz in\n\t\tlet b = String.sub s (idxz+1) (ln-idxz-1) in\n\t\ta ^ b;;\n\nlet main () =\n\tlet s = rdln() in\n\tlet os = remove_first_zero s in\n\tbegin\n\t\tprint_string os;\n\t\tprint_newline()\n\tend;;\n\nmain();;\n"}, {"source_code": "let () = \n let s = read_line() in\n let n = String.length s in\n let b = Array.init n (fun i -> if s.[i]='0' then 0 else 1) in\n\n let rec loop i c = \n if i=n-1 && c=0 then ()\n else if i=n-1 && c>0 then Printf.printf \"%d\" b.(i)\n else if b.(i)=0 && c>0 then (Printf.printf \"0\"; loop (i+1) c) \n else if b.(i)=0 && c=0 then loop (i+1) 1\n else (Printf.printf \"1\"; loop (i+1) c)\n in\n\n loop 0 0;\n print_newline()\n"}], "negative_code": [], "src_uid": "133eaf241bb1557ba9a3f59c733d34bf"} {"nl": {"description": "Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100\u2009\u00d7\u2009100 square with the lower left corner at point (0,\u20090) and with the upper right corner at point (100,\u2009100). Then the alarm clocks are points with integer coordinates in this square.The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game: First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal. Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off. Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of the alarm clocks. The next n lines describe the clocks: the i-th line contains two integers xi, yi \u2014 the coordinates of the i-th alarm clock (0\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009100). Note that a single point in the room can contain any number of alarm clocks and the alarm clocks can lie on the sides of the square that represents the room.", "output_spec": "In a single line print a single integer \u2014 the minimum number of segments Inna will have to draw if she acts optimally.", "sample_inputs": ["4\n0 0\n0 1\n0 2\n1 0", "4\n0 0\n0 1\n1 0\n1 1", "4\n1 1\n1 2\n2 3\n3 3"], "sample_outputs": ["2", "2", "3"], "notes": "NoteIn the first sample, Inna first chooses type \"vertical segments\", and then she makes segments with ends at : (0,\u20090), (0,\u20092); and, for example, (1,\u20090), (1,\u20091). If she paints horizontal segments, she will need at least 3 segments.In the third sample it is important to note that Inna doesn't have the right to change the type of the segments during the game. That's why she will need 3 horizontal or 3 vertical segments to end the game."}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int();;\nlet tab=Array.make 101 0;;\nlet vec=Array.make 101 0;;\nlet s=ref 0;;\nlet t=ref 0;;\nfor i=1 to n do\n let a=read_int() and b=read_int() in\n if tab.(a)=0 then (tab.(a)<-1;s:= !s+1);\n if vec.(b)=0 then (vec.(b)<-1;t:= !t+1)\ndone;;\nprint_int (min !s !t);;"}], "negative_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int();;\nlet tab=Array.make 101 0;;\nlet vec=Array.make 101 0;;\nlet s=ref 0;;\nlet t=ref 0;;\nfor i=1 to n do\n let a=read_int() and b=read_int() in\n if tab.(a)=0 then (tab.(a)<-1;s:= !s+1);\n if vec.(b)=0 then (vec.(b)<-1;t:= !t+1)\ndone;;\nprint_int (max !s !t);;"}], "src_uid": "89a8936bf7d43a9c5f69714a7cb7df82"} {"nl": {"description": "Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph\u00a0\u2014 something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following definition:The minimum spanning tree T of graph G is such a tree that it contains all the vertices of the original graph G, and the sum of the weights of its edges is the minimum possible among all such trees.Vladislav drew a graph with n vertices and m edges containing no loops and multiple edges. He found one of its minimum spanning trees and then wrote for each edge its weight and whether it is included in the found tree or not. Unfortunately, the piece of paper where the graph was painted is gone and the teacher is getting very angry and demands to see the original graph. Help Vladislav come up with a graph so that the information about the minimum spanning tree remains correct.", "input_spec": "The first line of the input contains two integers n and m ()\u00a0\u2014 the number of vertices and the number of edges in the graph. Each of the next m lines describes an edge of the graph and consists of two integers aj and bj (1\u2009\u2264\u2009aj\u2009\u2264\u2009109,\u2009bj\u2009=\u2009{0,\u20091}). The first of these numbers is the weight of the edge and the second number is equal to 1 if this edge was included in the minimum spanning tree found by Vladislav, or 0 if it was not. It is guaranteed that exactly n\u2009-\u20091 number {bj} are equal to one and exactly m\u2009-\u2009n\u2009+\u20091 of them are equal to zero.", "output_spec": "If Vladislav has made a mistake and such graph doesn't exist, print \u2009-\u20091. Otherwise print m lines. On the j-th line print a pair of vertices (uj,\u2009vj) (1\u2009\u2264\u2009uj,\u2009vj\u2009\u2264\u2009n,\u2009uj\u2009\u2260\u2009vj), that should be connected by the j-th edge. The edges are numbered in the same order as in the input. The graph, determined by these edges, must be connected, contain no loops or multiple edges and its edges with bj\u2009=\u20091 must define the minimum spanning tree. In case there are multiple possible solutions, print any of them.", "sample_inputs": ["4 5\n2 1\n3 1\n4 0\n1 1\n5 0", "3 3\n1 0\n2 1\n3 1"], "sample_outputs": ["2 4\n1 4\n3 4\n3 1\n3 2", "-1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let ne = m-(n-1) in\n let nt = n-1 in\n\n let e = Array.make ne (0,0) in \n let t = Array.make nt (0,0) in\n \n let rec read_loop it ie = if it+ie = m then () else\n let a = (read_int(), it+ie) in\n let b = read_int() in\n if b=1 then (\n t.(it) <- a;\n read_loop (it+1) ie\n ) else (\n e.(ie) <- a;\n read_loop it (ie+1)\n )\n in\n\n read_loop 0 0;\n\n Array.sort compare t;\n Array.sort compare e;\n\n let rec gen_pair_list (i,j) k ac = if k = ne then List.rev ac else\n let ac = (i,j)::ac in\n let next = if i+1 = j then (0,j+1) else (i+1,j) in\n gen_pair_list next (k+1) ac\n in\n\n let pair_array = Array.of_list (gen_pair_list (0,1) 0 []) in\n\n let rec build_answer i ac = if i=ne then Some (List.rev ac) else\n let (ii,jj) = pair_array.(i) in\n let elength = fst e.(i) in\n if elength < fst t.(jj) then None else\n\tlet ac = (ii,jj)::ac in\n\tbuild_answer (i+1) ac\n in\n\n match build_answer 0 [] with\n | None -> printf \"-1\\n\"\n | Some li ->\n let po = Array.make m (0,0) in\n List.iteri (fun i (ii,jj) ->\n\tpo.(snd e.(i)) <- (ii+2, jj+2)\n ) li;\n for i=0 to nt-1 do\n\tpo.(snd t.(i)) <- (1, i+2)\n done;\n for i=0 to m-1 do\n\tprintf \"%d %d\\n\" (fst po.(i)) (snd po.(i))\n done\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\n \nlet () =\n let n = read_int () in\n let m = read_int () in\n let a = Array.init m (fun i -> let a = read_int () in let b = read_int () in (a, b, i)) in\n let cmp (x1, y1, _) (x2, y2, _) =\n if x1 = x2 then y2 - y1\n else x1 - x2\n in\n let _ = Array.sort cmp a in\n let ans = Array.make m (0, 0) in\n\n let rec add_extra (extra, extra_cnt) x cur =\n if extra_cnt >= m || x = cur then (extra, extra_cnt)\n else add_extra ((x, cur)::extra, extra_cnt + 1) (x+1) cur\n in\n\n let process_edge (extra, extra_cnt, cur) (a, b, i) =\n if extra_cnt = (-1) then (extra, extra_cnt, cur)\n else if b = 0 then \n begin \n match extra with\n | [] -> (extra, (-1), cur)\n | hd::tl -> ans.(i) <- hd; (tl, extra_cnt-1, cur)\n end\n else \n begin\n ans.(i) <- (0, cur);\n let (extra, extra_cnt) = add_extra (extra, extra_cnt) 1 cur in\n (extra, extra_cnt, cur + 1)\n end\n in\n \n let (_, extra_cnt, _) = Array.fold_left process_edge ([], 0, 1) a in\n if extra_cnt = (-1) then Printf.printf \"-1\\n\"\n else Array.iter (fun (a, b) -> Printf.printf \"%d %d\\n\" (a+1) (b+1)) ans\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let ne = m-(n-1) in\n let nt = n-1 in\n\n let e = Array.make ne (0,0) in \n let t = Array.make nt (0,0) in\n \n let rec read_loop it ie = if it+ie = m then () else\n let a = (read_int(), it+ie) in\n let b = read_int() in\n if b=1 then (\n t.(it) <- a;\n read_loop (it+1) ie\n ) else (\n e.(ie) <- a;\n read_loop it (ie+1)\n )\n in\n\n read_loop 0 0;\n\n Array.sort compare t;\n Array.sort compare e;\n\n let rec gen_pair_list (i,j) k ac = if k = ne then ac else\n let ac = (i,j)::ac in\n let next = if i+1 = j then (0,j+1) else (i+1,j) in\n gen_pair_list next (k+1) ac\n in\n\n let pair_array = Array.of_list (gen_pair_list (0,1) 0 []) in\n\n let rec build_answer i ac = if i=ne then Some (List.rev ac) else\n let (ii,jj) = pair_array.(i) in\n let elength = fst e.(i) in\n if elength < fst t.(jj) then None else\n\tlet ac = (ii,jj)::ac in\n\tbuild_answer (i+1) ac\n in\n\n match build_answer 0 [] with\n | None -> printf \"-1\\n\"\n | Some li ->\n let po = Array.make m (0,0) in\n List.iteri (fun i (ii,jj) ->\n\tpo.(snd e.(i)) <- (ii+2, jj+2)\n ) li;\n for i=0 to nt-1 do\n\tpo.(snd t.(i)) <- (1, i+2)\n done;\n for i=0 to m-1 do\n\tprintf \"%d %d\\n\" (fst po.(i)) (snd po.(i))\n done\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\n \nlet () =\n let n = read_int () in\n let m = read_int () in\n let a = Array.init m (fun i -> let a = read_int () in let b = read_int () in (a, b, i)) in\n let _ = Array.sort (fun (x1, y1, _) (x2, y2, _) -> (x1*2+1-y1) - (x2*2+1-y2)) a in\n let ans = Array.make m (0, 0) in\n\n let rec add_extra (extra, extra_cnt) x cur =\n if extra_cnt >= m || x = cur then (extra, extra_cnt)\n else add_extra ((x, cur)::extra, extra_cnt + 1) (x+1) cur\n in\n\n let process_edge (extra, extra_cnt, cur) (a, b, i) =\n if extra_cnt = (-1) then (extra, extra_cnt, cur)\n else if b = 0 then \n begin \n match extra with\n | [] -> (extra, (-1), cur)\n | hd::tl -> ans.(i) <- hd; (tl, extra_cnt-1, cur)\n end\n else \n begin\n ans.(i) <- (0, cur);\n let (extra, extra_cnt) = add_extra (extra, extra_cnt) 1 cur in\n (extra, extra_cnt, cur + 1)\n end\n in\n \n let (_, extra_cnt, _) = Array.fold_left process_edge ([], 0, 1) a in\n if extra_cnt = (-1) then Printf.printf \"-1\\n\"\n else Array.iter (fun (a, b) -> Printf.printf \"%d %d\\n\" (a+1) (b+1)) ans\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\n \nlet () =\n let n = read_int () in\n let m = read_int () in\n let a = Array.init m (fun i -> let a = read_int () in let b = read_int () in (a, b, i)) in\n let cmp (x1, y1, _) (x2, y2, _) =\n if x1 = x2 then y1 - y2\n else x1 - x2\n in\n let _ = Array.sort cmp a in\n let ans = Array.make m (0, 0) in\n\n let rec add_extra (extra, extra_cnt) x cur =\n if extra_cnt >= m || x = cur then (extra, extra_cnt)\n else add_extra ((x, cur)::extra, extra_cnt + 1) (x+1) cur\n in\n\n let process_edge (extra, extra_cnt, cur) (a, b, i) =\n if extra_cnt = (-1) then (extra, extra_cnt, cur)\n else if b = 0 then \n begin \n match extra with\n | [] -> (extra, (-1), cur)\n | hd::tl -> ans.(i) <- hd; (tl, extra_cnt-1, cur)\n end\n else \n begin\n ans.(i) <- (0, cur);\n let (extra, extra_cnt) = add_extra (extra, extra_cnt) 1 cur in\n (extra, extra_cnt, cur + 1)\n end\n in\n \n let (_, extra_cnt, _) = Array.fold_left process_edge ([], 0, 1) a in\n if extra_cnt = (-1) then Printf.printf \"-1\\n\"\n else Array.iter (fun (a, b) -> Printf.printf \"%d %d\\n\" (a+1) (b+1)) ans\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\n \nlet () =\n let n = read_int () in\n let m = read_int () in\n let a = Array.init m (fun i -> let a = read_int () in let b = read_int () in (a, b, i)) in\n let _ = Array.sort (fun (x1, _, _) (x2, _, _) -> x1 - x2) a in\n let ans = Array.make m (0, 0) in\n\n let rec add_extra (extra, extra_cnt) x cur =\n if extra_cnt >= m || x = cur then (extra, extra_cnt)\n else add_extra ((x, cur)::extra, extra_cnt + 1) (x+1) cur\n in\n\n let process_edge (extra, extra_cnt, cur) (a, b, i) =\n if extra_cnt = (-1) then (extra, extra_cnt, cur)\n else if b = 0 then \n begin \n match extra with\n | [] -> (extra, (-1), cur)\n | hd::tl -> ans.(i) <- hd; (tl, extra_cnt-1, cur)\n end\n else \n begin\n ans.(i) <- (0, cur);\n let (extra, extra_cnt) = add_extra (extra, extra_cnt) 1 cur in\n (extra, extra_cnt, cur + 1)\n end\n in\n \n let (_, extra_cnt, _) = Array.fold_left process_edge ([], 0, 1) a in\n if extra_cnt = (-1) then Printf.printf \"-1\\n\"\n else Array.iter (fun (a, b) -> Printf.printf \"%d %d\\n\" (a+1) (b+1)) ans\n"}], "src_uid": "1a9968052a363f04380d1177c764717b"} {"nl": {"description": "\"Hey, it's homework time\" \u2014 thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1,\u2009a2,\u2009...,\u2009an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).", "input_spec": "The first line of the input data contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u20095000,\u20091\u2009\u2264\u2009i\u2009\u2264\u2009n).", "output_spec": "Print the only number \u2014 the minimum number of changes needed to get the permutation.", "sample_inputs": ["3\n3 1 2", "2\n2 2", "5\n5 3 3 3 1"], "sample_outputs": ["0", "1", "2"], "notes": "NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2."}, "positive_code": [{"source_code": "\nlet getint () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun i->i)\nlet getstr () = Scanf.bscanf Scanf.Scanning.stdin \" %s\" (fun s-> s)\nlet getchar () = Scanf.bscanf Scanf.Scanning.stdin \" %c\" (fun i->i)\n\nlet inf = 1000000007\n\n\nlet _ = \n let n = getint () in\n let a = Array.make n 0 in\n for i = 0 to n-1 do\n let x = getint () - 1 in\n if x=0 then a.(x) <- a.(x) + 1;\n done;\n let ans = ref 0 in\n for i = 0 to n-1 do\n if a.(i) = 0 then incr ans\n done;\n Printf.printf \"%d\\n\" !ans\n\n "}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet n = read_int ();;\n\nlet data = Array.init n (fun i -> read_int ());;\n\nArray.sort compare data;;\n\nlet rec solve ac i data = \n if i>=n || data.(i)>n then ac\n else if i = 0 && data.(i) >= 1 && data.(i) <= n then solve (ac+1) (i+1) data\n else if i=0 && (data.(i)<1 || data.(i)>n) then solve ac (i+1) data\n else if data.(i) > n then ac\n else if data.(i) < 1 then solve ac (i+1) data\n else if data.(i) != data.(i-1) then solve (ac+1) (i+1) data\n else solve ac (i+1) data;;\n \nPrintf.printf \"%d\\n\" (n-(solve 0 0 data));;\n"}, {"source_code": "let () =\n\tlet n = read_int() in\n\tlet l = ref [] in\n\t(for i = 1 to n do\n\t\tlet x = Scanf.scanf \" %d\" (fun i->i) in\n\t\tif x >= 1 && x <= n && not (List.mem x !l) then\n\t\t\tl := x::(!l);\n\tdone; print_int (n-(List.length !l)))\n;;\n"}, {"source_code": "(*************** Ocaml stdio functions **********************)\nlet stdin_stream = Stream.of_channel stdin;;\nlet stdout_buffer = Buffer.create 65536;;\nlet rec gi() =\n match Stream.next stdin_stream with\n '-' -> - (ri 0)\n | '+' -> ri 0\n | '0'..'9' as c -> ri ((int_of_char c) - 48)\n | _ -> gi ()\nand ri x =\n match Stream.next stdin_stream with\n '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))\n | _ -> x\n;;\nlet flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;\nlet putchar c =\n if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();\n Buffer.add_char stdout_buffer c;;\nlet rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;\nlet pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));;\nlet pa a = let n = Array.length a in Array.iteri (fun i j -> pi j; putchar (if i == (n-1) then '\\n' else ' ')) a;;\n(*************** Ocaml solution ******************************)\nopen Array\nlet main() =\n let n = gi() in\n let a = init n (fun i -> gi()) in\n let b = make (n+1) 0 in\n iter (fun i -> if (i >= 1 && i <= n) then b.(i) <- 1 else ()) a;\n let s = fold_left (+) 0 b in\n Printf.printf \"%d\\n\" (n - s)\n ;;\nmain();;\nflushout ()"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make 5001 0 in\n let b = ref 0 in\n let c = ref 0 in\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(k) <- a.(k) + 1\n done;\n for i = 1 to n do\n if a.(i) = 0\n then incr c\n else if a.(i) > 1\n then b := !b + a.(i) - 1\n done;\n for i = n + 1 to 5000 do\n if a.(i) > 0\n then incr b\n done;\n let res = max !b !c in\n Printf.printf \"%d\\n\" res;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\nlet n = read_int()\n\nlet there = Array.make n false\n\nlet () =\n for i=0 to n-1 do\n let k = (read_int()) -1 in\n if k>=0 && k\n let s = Scanf.scanf \"%s\\n\" (fun s -> s) in\n\n (* build a non-overlapping interval set *)\n let t, _ = List.fold_left (fun (acc, pos) hd ->\n match hd with\n | Str.Text s -> (acc, (pos + String.length s))\n | Str.Delim d ->\n let e = pos + String.length d in\n (add (pos, e - 1) acc, e))\n (RangeSet.empty, 1) (Str.full_split (Str.regexp \"\\\\.+\") s) in\n\n (* calculate the answer to the initial query *)\n let ans = ref (RangeSet.fold (fun _ (l, r) acc -> acc + (r - l)) t 0) in\n\n (* a query can have the following possible effects:\n * merge two intervals (or extend an interval)\n * split an interval\n * no effect on intervals *)\n let rec loop t i =\n if i <> m then\n Scanf.scanf \"%d %c\\n\" (fun x c ->\n let t' = match c with\n | '.' ->\n (* if this char is in an interval, no effect *)\n if RangeSet.mem (x, x) t then t else\n\n (* join two intervals *)\n if RangeSet.mem (x-1,x-1) t && RangeSet.mem (x+1, x+1) t then begin\n let l, _ = RangeSet.find (x-1, x-1) t\n and _, r = RangeSet.find (x+1, x+1) t in\n (* calculate new answer *)\n ans := !ans + 2;\n (* create new tree *)\n add (l, r) (RangeSet.remove (x-1, x-1) (RangeSet.remove (x+1, x+1) t))\n end else\n\n (* extend left interval *)\n if RangeSet.mem (x-1, x-1) t then begin\n let l, _ = RangeSet.find (x-1, x-1) t in\n incr ans;\n add (l, x) (RangeSet.remove (x-1, x-1) t)\n end else\n\n (* extend right interval *)\n if RangeSet.mem (x+1, x+1) t then begin\n let _, r = RangeSet.find (x+1, x+1) t in\n incr ans;\n add (x, r) (RangeSet.remove (x+1, x+1) t)\n end else\n\n (* create new interval *)\n add (x, x) t\n | _ ->\n (* if this char is in an interval, split it *)\n if RangeSet.mem (x, x) t then begin\n let l, r = RangeSet.find (x, x) t\n and t = RangeSet.remove (x, x) t in\n (* we take the interval (l, r) to (l,x-1) and (x+1,r)\n * check these new intervals are valid and subtract 1 from ans\n * for each valid new interval *)\n let t =\n if l < x then begin\n decr ans;\n add (l, x-1) t\n end else t\n in\n if r > x then begin\n decr ans;\n add (x+1, r) t\n end else t\n (* otherwise nothing to do *)\n end else t\n in\n Printf.printf \"%d\\n\" !ans;\n loop t' (i + 1))\n in loop t 0)\n"}, {"source_code": "let () = Scanf.scanf \"%d %d\\n\" (fun n m ->\n let s = Scanf.scanf \"%s\\n\" (fun s -> s) in\n (* count number of groups in s *)\n let a = Array.init (n + 2) (fun i -> if i = 0 || i = n + 1 then false else s.[i-1] = '.') in\n\n let rec aux (groups, count) i =\n if i = n then (groups, count)\n else aux (if s.[i] = '.' then\n (groups + (if i = 0 || s.[i - 1] <> '.' then 1 else 0), count + 1)\n else (groups, count))\n (i + 1)\n in\n\n let g, c = aux (0, 0) 0 in\n\n let groups = ref g\n and count = ref c in\n\n for i = 1 to m do\n Scanf.scanf \"%d %c\\n\" (fun x c ->\n (* only do something if we're changing the state *)\n if a.(x) <> (c = '.') then begin\n if c = '.' then begin\n incr count;\n\n (* merge groups *)\n if a.(x - 1) && a.(x + 1)\n then decr groups;\n\n (* create a new group *)\n if not (a.(x - 1) || a.(x + 1))\n then incr groups\n\n (* check whether we merge or split a group *)\n end else begin\n decr count;\n\n (* split a group *)\n if a.(x - 1) && a.(x + 1)\n then incr groups;\n\n (* remove a single point *)\n if not (a.(x - 1) || a.(x + 1))\n then decr groups\n end;\n\n a.(x) <- c = '.'\n end;\n\n Printf.printf \"%d\\n\" (!count - !groups))\n done)\n"}], "negative_code": [], "src_uid": "68883ab115882de5cf77d0848b80b422"} {"nl": {"description": "Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.", "input_spec": "The single line contains four integers x,\u2009y,\u2009a,\u2009b (1\u2009\u2264\u2009a\u2009\u2264\u2009x\u2009\u2264\u2009100,\u20091\u2009\u2264\u2009b\u2009\u2264\u2009y\u2009\u2264\u2009100). The numbers on the line are separated by a space.", "output_spec": "In the first line print integer n \u2014 the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di \u2014 the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci,\u2009di) in the strictly increasing order. Let us remind you that the pair of numbers (p1,\u2009q1) is less than the pair of numbers (p2,\u2009q2), if p1\u2009<\u2009p2, or p1\u2009=\u2009p2 and also q1\u2009<\u2009q2.", "sample_inputs": ["3 2 1 1", "2 4 2 2"], "sample_outputs": ["3\n2 1\n3 1\n3 2", "0"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let x = read_int() in\n let y = read_int() in\n let a = read_int() in\n let b = read_int() in\n\n let lis = ref [] in\n\n for i=a to x do\n for j=b to y do\n\tif i>j then lis := (i,j)::!lis\n done\n done;\n\n Printf.printf \"%d\\n\" (List.length !lis);\n List.iter (fun (i,j) -> Printf.printf \"%d %d\\n\" i j) (List.sort compare !lis)\n"}], "negative_code": [], "src_uid": "bb3e3b51a4eda8fef503952a00777910"} {"nl": {"description": "Omkar and Akmar are playing a game on a circular board with $$$n$$$ ($$$2 \\leq n \\leq 10^6$$$) cells. The cells are numbered from $$$1$$$ to $$$n$$$ so that for each $$$i$$$ ($$$1 \\leq i \\leq n-1$$$) cell $$$i$$$ is adjacent to cell $$$i+1$$$ and cell $$$1$$$ is adjacent to cell $$$n$$$. Initially, each cell is empty.Omkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter. A player loses when it is their turn and there are no more valid moves.Output the number of possible distinct games where both players play optimally modulo $$$10^9+7$$$. Note that we only consider games where some player has lost and there are no more valid moves.Two games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different.A move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move.", "input_spec": "The only line will contain an integer $$$n$$$ ($$$2 \\leq n \\leq 10^6$$$) \u2014 the number of cells on the board.", "output_spec": "Output a single integer \u2014 the number of possible distinct games where both players play optimally modulo $$$10^9+7$$$.", "sample_inputs": ["2", "69420", "42069"], "sample_outputs": ["4", "629909355", "675837193"], "notes": "NoteFor the first sample case, the first player has $$$4$$$ possible moves. No matter what the first player plays, the second player only has $$$1$$$ possible move, so there are $$$4$$$ possible games."}, "positive_code": [{"source_code": "let p = 1_000_000_007L\n\nlet ( %% ) x n = let y = Int64.rem x n in if y<0L then Int64.add y n else y\n(* Now, arithmetic modulo p, assuming the arguments a and b are in [0,p-1] *)\nlet ( ** ) a b = Int64.rem (Int64.mul a b) p\nlet ( ++ ) a b = let y = Int64.add a b in if y >= p then Int64.sub y p else y\nlet ( -- ) a b = let y = Int64.sub a b in if y<0L then Int64.add y p else y\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\n(*\nlet rec powermod a b = (* a^b mod p. b is a short a is a long *)\n if b=0 then 1L else\n let r = powermod a (b lsr 1) in\n let r2 = r**r in\n if b land 1 = 0 then r2 else r2**a\n*)\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n(*\nlet product i j f = fold i j (fun i a -> (f i) ** a) 1L\n*)\n\nlet inverse a =\n let rec egcd a b =\n (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g *)\n if a = 0 then (0,1,b) else \n let (x,y,g) = egcd (b mod a) a in \n (y-(b/a)*x, x, g)\n in\n let (x,_,_) = egcd (short a) (short p) in\n long (if x >= 0 then x else x+(short p))\n \nlet init_factorial n =\n let f = Array.make (n+1) 1L in\n for i=1 to n do\n f.(i) <- (long i) ** f.(i-1);\n done;\n f\n\nlet binom n k f = (* n choose k (f is the factoral table) *)\n if k < 0 || n < k then 0L else\n f.(n) ** (inverse f.(k)) ** (inverse f.(n-k))\n\nlet rec fold i j by f init = if i>j then init else fold (i+by) j by f (f i init)\nlet sum i j by f = fold i j by (fun i a -> (f i) ++ a) 0L\n \n(* Discovered by f_nimber.ml, and subsequently via simple proof, the\n nimber of a position in this game is the number of non-empties in\n the board mod 2. This means that the second player can always win.\n In fact, it means that any sequence of legal moves is optimal for\n the second player. Also, if n is odd then the there will be an odd\n number of holes at the end, and if n is even there will be an even\n number of holes at the end. Thus guaranteeing that the game lasts\n an even number of moves (giving the second player the win.)\n\n To count the number of distinct games, we consider the games based\n on the number of holes in the final positions. If I have a board\n with k holes at the end, then we know that each hole is bounded by\n two different labels. And also a sequence of non-holes alternates\n labels. Therefore, deleting the holes, the labeled elements must\n simply be alternating. Thus there are just two possibilities for\n the final labeling of the board. And the order in which the game\n is filled in is totally arbitrary, thus it is 2(n-k)! .\n\n This leaves the question of how many arrangements of k non-adjacent\n holes are possible. Here's a way to evaluate this. If you take an\n arrangement and for each hole, delete the non-hole before it you\n have an arrangement of k holes in n-k positions. So you can just\n take (n-k) choose k. But this does not quite work. The problem is\n that it does not generate solutions where the first hole is at\n position 0. So you handle those separately. Say the first hole is\n at position 0. So delete it and the non-hole after it. Now you\n have n-2 positions and k-1 holes to place. Apply the same trick\n where an additional non-hole is added after each hole. This gives\n an additional n-2-(k-1) choose (k-1) possibilities.\n\n So we compute the sum over k of 2(n-k)! * (# arrangements of k\n holes). That's the answer.\n*)\n \nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let h = n/2 in (* the maximum number of holes you can have *)\n let f = init_factorial n in\n let answer = sum (n mod 2) h 2 (fun k ->\n 2L ** (f.(n-k)) **\n ((binom (n-k) k f) ++ (binom (n-2-(k-1)) (k-1) f))\n ) in\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "7ad1f3f220c12a68c1242a22f4fd7761"} {"nl": {"description": "DZY loves planting, and he enjoys solving tree problems.DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x,\u2009y) (1\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009n) as the longest edge in the shortest path between nodes x and y. Specially g(z,\u2009z)\u2009=\u20090 for every z.For every integer sequence p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n), DZY defines f(p) as . DZY wants to find such a sequence p that f(p) has maximum possible value. But there is one more restriction: the element j can appear in p at most xj times.Please, find the maximum possible f(p) under the described restrictions.", "input_spec": "The first line contains an integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u20093000). Each of the next n\u2009-\u20091 lines contains three integers ai,\u2009bi,\u2009ci\u00a0(1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009ci\u2009\u2264\u200910000), denoting an edge between ai and bi with length ci. It is guaranteed that these edges form a tree. Each of the next n lines describes an element of sequence x. The j-th line contains an integer xj\u00a0(1\u2009\u2264\u2009xj\u2009\u2264\u2009n).", "output_spec": "Print a single integer representing the answer.", "sample_inputs": ["4\n1 2 1\n2 3 2\n3 4 3\n1\n1\n1\n1", "4\n1 2 1\n2 3 2\n3 4 3\n4\n4\n4\n4"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first sample, one of the optimal p is [4,\u20093,\u20092,\u20091]."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let tree = Array.init (n-1) (\n fun _ -> \n let a = read_int() -1 in\n let b = read_int() -1 in\n let c = read_int() in\n (a,b,c)\n ) in\n\n let x = Array.init n (fun _ -> read_int()) in\n let xtotal = sum 0 (n-1) (fun i -> x.(i)) in\n\n Array.sort (fun (_,_,c1) (_,_,c2) -> compare c1 c2) tree;\n\n let s = Array.make n (-1) in (* the sets *)\n let size = Array.make n 1 in (* sizes of the sets *)\n let xsize = Array.init n (fun i -> x.(i)) in (* the x sizes of the sets *)\n\n let rec find i = if s.(i) < 0 then i else \n let r = find s.(i) in\n s.(i) <- r;\n r\n in\n\n let union i j = \n let (i,j) = ((find i), (find j)) in\n if i <> j then (\n\tlet (i,j) = if size.(i) < size.(j) then (i,j) else (j,i) in\n\ts.(i) <- j; (* union by rank *)\n\tsize.(j) <- size.(i) + size.(j);\n\txsize.(j) <- xsize.(i) + xsize.(j);\t\n )\n in\n\n let rec loop i = \n let (a,b,c) = tree.(i) in\n union a b;\n (* now check if \"the condition\" holds after the union *) \n let a = find a in\n if size.(a) <= xtotal - xsize.(a) then loop (i+1) else c\n in\n\n if n=1 then printf \"0\\n\" else\n printf \"%d\\n\" (loop 0)\n"}], "negative_code": [], "src_uid": "e9f4582601a4296a53b77678589d09ef"} {"nl": {"description": "An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of cars in the train. The second line contains n integers pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009n, pi\u2009\u2260\u2009pj if i\u2009\u2260\u2009j)\u00a0\u2014 the sequence of the numbers of the cars in the train.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of actions needed to sort the railway cars.", "sample_inputs": ["5\n4 1 2 5 3", "4\n4 1 3 2"], "sample_outputs": ["2", "2"], "notes": "NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train."}, "positive_code": [{"source_code": "let n = read_int() and ind = Array.make 100001 0 and ans = ref 1;;\nlet a = Array.of_list (List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line())));;\nfor i = 0 to n - 1 do \n\tif a.(i) == 1 then Array.set ind 1 1 else \n\tbegin\n\t\tArray.set ind a.(i) (ind.(a.(i) - 1) + 1);\n\t\tans := max !ans ind.(a.(i))\nend done;;\nprint_int (n - !ans)\n"}, {"source_code": "(* took 1:15 to get this *)\n\n(* Invert the permutation, and call it x. Now the operation is to\n pick an element from the outside and put it somewhere in the\n middle. Make a set that contains i if x.(i) and x.(i+1) are\n inverted. Add 0 and n into the set. Now take the biggest gap\n between neighbors in this set. n minus this is the answer.\n\n This is a lower and upper bound on the number of moves needed.\n It's an upper bound because you can clearly do it by building up\n the longest sorted region (i.e. biggest gap) in that many steps.\n It's a lower bound because for each neighboring pair that are\n inverted we must reach (from one end or the other) one of those\n elements. The answer computed above gives the most efficient way\n to do this.\n*)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let p = Array.init n (fun _ -> read_int() -1) in\n let x = Array.make n 0 in\n for i=0 to n-1 do\n x.(p.(i)) <- i\n done;\n \n let rec makel i ac = if i=n then n::ac else\n let ac = if x.(i-1) > x.(i) then (i::ac) else ac in\n makel (i+1) ac\n in\n let lg = Array.of_list (List.rev (makel 1 [0])) in\n let nn = Array.length lg in\n let answer = n - maxf 0 (nn-2) (fun i -> lg.(i+1) - lg.(i)) in\n printf \"%d\\n\" answer\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let a = Array.init n (fun _ -> read_int ()) in\n let bio = Array.make (n+1) 0 in\n let _ = Array.iter (fun x -> bio.(x) <- bio.(x-1) + 1) a in\n let ans = n - (Array.fold_left max 0 bio) in\n Printf.printf \"%d\\n\" ans\n \n \n"}], "negative_code": [{"source_code": "(*\n#load \"str.cma\";;\n#load \"nums.cma\";;\n*)\nlet n = read_int () and ans = ref 0 and m = ref 99999999999L;;\nlet a = Array.of_list (List.map (Int64.of_string) (Str.split (Str.regexp \" \") (read_line ())));;\nfor i = n - 1 downto 0 do\n\tif Int64.compare a.(i) !m < 0 then m := a.(i);\n\tif Int64.compare a.(i) !m > 0 then ans := !ans + 1;\ndone;;\nprint_int !ans;;\n"}, {"source_code": "let n = read_int () and ans = ref 0 and m = ref 9999999;;\nlet a = Array.of_list (List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())));;\nfor i = n - 1 downto 0 do\n\tif a.(i) < !m then m := a.(i);\n\tif a.(i) > !m then ans := !ans + 1;\ndone;;\nprint_int !ans\n"}, {"source_code": "let n = read_int () and ans = ref 0 and m = ref 999999999L;;\nlet a = Array.of_list (List.map (Int64.of_string) (Str.split (Str.regexp \" \") (read_line ())));;\nfor i = n - 1 downto 0 do\n\tif a.(i) < !m then m := a.(i);\n\tif a.(i) > !m then ans := !ans + 1;\ndone;;\nprint_int !ans\n"}], "src_uid": "277948a70c75840445e1826f2b23a897"} {"nl": {"description": "Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows. The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \\le k \\le 10^9$$$) which location must be found.", "output_spec": "For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \\ge 1$$$) separated by spaces \u2014 the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.", "sample_inputs": ["7\n11\n14\n5\n4\n1\n2\n1000000000"], "sample_outputs": ["2 4\n4 3\n1 3\n2 1\n1 1\n1 2\n31623 14130"], "notes": null}, "positive_code": [{"source_code": "open Array;;\r\nlet readInt () = Scanf.scanf \" %d\" (fun i -> i)\r\n \r\nlet print_number x = print_string (string_of_int x); print_newline();;\r\n\r\nlet print_numbers x y = print_number x; print_number y;;\r\n\r\nlet t = readInt() in\r\nfor i = 1 to t do\r\n let k = readInt() in\r\n let x = int_of_float (ceil (sqrt (float_of_int k))) in\r\n let q = k - (x - 1) * (x - 1) in\r\n if q <= x then\r\n print_numbers q x\r\n else\r\n print_numbers x (2*x - q)\r\ndone;;"}], "negative_code": [], "src_uid": "f8335c59cd05988c8053f138c4df06aa"} {"nl": {"description": "Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1,\u2009...,\u2009ak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.", "input_spec": "The first line contains 5 space-separated integers: n, k, p, x and y (1\u2009\u2264\u2009n\u2009\u2264\u2009999, n is odd, 0\u2009\u2264\u2009k\u2009<\u2009n, 1\u2009\u2264\u2009p\u2009\u2264\u20091000, n\u2009\u2264\u2009x\u2009\u2264\u2009n\u00b7p, 1\u2009\u2264\u2009y\u2009\u2264\u2009p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games. The second line contains k space-separated integers: a1,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u2009p)\u00a0\u2014 the marks that Vova got for the tests he has already written.", "output_spec": "If Vova cannot achieve the desired result, print \"-1\". Otherwise, print n\u2009-\u2009k space-separated integers\u00a0\u2014 the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.", "sample_inputs": ["5 3 5 18 4\n3 5 4", "5 3 5 16 4\n5 5 5"], "sample_outputs": ["4 1", "-1"], "notes": "NoteThe median of sequence a1,\u00a0...,\u00a0an where n is odd (in this problem n is always odd) is the element staying on (n\u2009+\u20091)\u2009/\u20092 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: \"4\u00a02\", \"2\u00a04\", \"5\u00a01\", \"1\u00a05\", \"4\u00a01\", \"1\u00a04\" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is \"-1\"."}, "positive_code": [{"source_code": "exception Fail\n\nlet fait r x y =\n\t let total = ref x and res = ref [] in\n\t\tfor i=1 to r do\n\t\t\tif !total <= r - i\n\t\t\t\tthen raise Fail\n\t\t\t\telse (let a = min (!total-r+i) y in\n\t\t\t\t\ttotal := !total - a;\n\t\t\t\t\tres := a::!res);\n\t\tdone;\n\t!res;;\n\nlet resout n k x y l =\n\tlet sum = List.fold_left (fun a b -> a+b) 0 l in\n\tlet res = fait (n-k) (x - sum) y in\n\t\tres;;\n\nlet resultat ini res n y =\n\tlet l = List.sort compare (ini@res) in\n\t\tif List.nth l (n/2) >= y\n\t\t\tthen begin\n\t\t\tList.iter (fun i -> Printf.printf \"%d \" i) res\n\t\t\t end\n\t\t\telse Printf.printf \"-1\"\n\nlet _ =\n\tlet (n,k,x,y) = Scanf.scanf \"%d %d %d %d %d\"\n\t(fun a b _ c d -> (a,b,c,d)) and l = ref [] in\n\t\tfor i=1 to k do\n\t\t\tScanf.scanf \" %d\" (fun i -> l:= i::!l);\n\t\tdone;\n\ttry (\n\tresultat !l (resout n k x y !l) n y\n\t) with Fail -> Printf.printf \"-1\"\n"}], "negative_code": [{"source_code": "exception Fail\n\nlet fait r x y =\n\t let total = ref x and res = ref [] in\n\t\tfor i=1 to r do\n\t\t\tif !total <= r - i\n\t\t\t\tthen raise Fail\n\t\t\t\telse (let a = min (!total-r+i) y in\n\t\t\t\t\ttotal := !total - a;\n\t\t\t\t\tres := a::!res);\n\t\tdone;\n\t!res;;\n\nlet resout n k x y l =\n\tlet sum = List.fold_left (fun a b -> a+b) 0 l in\n\tlet res = fait (n-k) (x - sum - 1) y in\n\t\tres;;\n\nlet resultat ini res n y =\n\tlet l = List.sort compare (ini@res) in\n\t\tif List.nth l (n/2) >= y\n\t\t\tthen begin\n\t\t\t\tList.iter (fun i -> Printf.printf \"%d \" i) res\n\t\t\t end\n\t\t\telse Printf.printf \"-1\"\n\nlet _ =\n\tlet (n,k,x,y) = Scanf.scanf \"%d %d %d %d %d\"\n\t(fun a b _ c d -> (a,b,c,d)) and l = ref [] in\n\t\tfor i=1 to k do\n\t\t\tScanf.scanf \" %d\" (fun i -> l:= i::!l);\n\t\tdone;\n\ttry (\n\tresultat !l (resout n k x y !l) n y\n\t) with Fail -> Printf.printf \"-1\"\n"}], "src_uid": "f01d11bd231a7b2e7ca56de1df0f1272"} {"nl": {"description": "You are given a rectangular field of n\u2009\u00d7\u2009m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.For each impassable cell (x,\u2009y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x,\u2009y). You should do it for each impassable cell independently.The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be \".\" if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit \u2014- the answer modulo 10. The matrix should be printed without any spaces.To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.", "input_spec": "The first line contains two integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000) \u2014 the number of rows and columns in the field. Each of the next n lines contains m symbols: \".\" for empty cells, \"*\" for impassable cells.", "output_spec": "Print the answer as a matrix as described above. See the examples to precise the format of the output.", "sample_inputs": ["3 3\n*.*\n.*.\n*.*", "4 5\n**..*\n..***\n.*.*.\n*.*.*"], "sample_outputs": ["3.3\n.5.\n3.3", "46..3\n..732\n.6.4.\n5.4.3"], "notes": "NoteIn first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner)."}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet licz x = (x-|Int64.one)/|two_64;;\n\nlet (n,m) = read2 ();;\n\nlet ruch x y = [ (x+1,y); (x-1,y); (x,y+1); (x,y-1) ];;\n\nlet czy_dobry x y tab =\n if x < 0 || x >= n || y < 0 || y >= m then false\n else if tab.(x).(y) = '*' then false\n else true;;\n \n\nlet rec bfs ax ay k tab vis fuf size = \n let kol = Queue.create () in\n Queue.add (ax,ay) kol;\n vis.(ax).(ay) <- true;\n while not (Queue.is_empty kol) do\n let (x,y) = Queue.take kol in\n fuf.(x).(y) <- k;\n match k with\n | (a,b) -> size.(a).(b) <- size.(a).(b) + 1;\n List.iter ( fun (a,b) -> if (czy_dobry a b tab && not vis.(a).(b)) then begin vis.(a).(b) <- true; Queue.add (a,b) kol end ) ( ruch x y )\n done;;\n\nlet wynik x y tab fuf size =\n let ruchy = List.filter ( fun (x,y) -> czy_dobry x y tab ) (ruch x y) in\n List.fold_left (fun a (x,y) -> a + size.(x).(y)) 0\n (\n List.fold_left (fun a (x,y) -> if\n (List.fold_left (fun a b -> if b = fuf.(x).(y) then false else a ) true a )\n then fuf.(x).(y)::a else a ) [] ruchy\n );;\n \n\nlet _ = \n let tab = Array.make_matrix n m '.' \n and vis = Array.make_matrix n m false \n and fuf = Array.make_matrix n m (0,0)\n and size = Array.make_matrix n m 0 in\n for i=0 to (n-1) do\n let s = Scanf.scanf \"%s\\n\" (fun x -> x) in\n for j=0 to (m-1) do\n tab.(i).(j) <- s.[j];\n fuf.(i).(j) <- (i,j)\n done\n done;\n for i =0 to (n-1) do\n for j=0 to (m-1) do\n if czy_dobry i j tab && not vis.(i).(j) then\n bfs i j (i,j) tab vis fuf size\n done\n done;\n for i=0 to (n-1) do\n for j=0 to (m-1) do\n if tab.(i).(j) = '.' then \n Printf.printf \".\"\n else Printf.printf \"%d\" ( ( wynik i j tab fuf size + 1) mod 10 )\n done;\n Printf.printf \"\\n\"\n done;;\n\n\n\n"}, {"source_code": "let xstr() = Scanf.scanf \" %s\" (fun x -> x)\nlet xint() = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let n = xint() and m = xint() in\n let upp = n * m / 2 + 1 in\n let mark = Array.make_matrix n m ~-1 in\n let cnt = Array.make upp 0 in\n let s = Array.make n \"a\" in\n for i = 0 to n - 1 do\n s.(i) <- xstr();\n done;\n let qx = Array.make (n * m) 0 in\n let qy = Array.make (n * m) 0 in\n let dx = Array.make 4 0 and dy = Array.make 4 0 in\n dx.(2) <- 1;\n dx.(3) <- ~-1;\n dy.(0) <- 1;\n dy.(1) <- ~-1;\n let idx = ref 0 in\n let bfs sx sy =\n let h = ref 0 and t = ref 1 in\n qx.(0) <- sx;\n qy.(0) <- sy;\n mark.(sx).(sy) <- !idx;\n while !h < !t do\n let x = qx.(!h) and y = qy.(!h) in\n h := !h + 1;\n for i = 0 to 3 do\n let xx = x + dx.(i) in\n let yy = y + dy.(i) in\n if xx >= 0 && xx < n && yy >= 0 && yy < m then (\n if s.(xx).[yy] = '.' && mark.(xx).(yy) = -1 then (\n mark.(xx).(yy) <- !idx;\n qx.(!t) <- xx;\n qy.(!t) <- yy;\n t := !t + 1;\n )\n )\n done;\n done;\n cnt.(!idx) <- !t;\n in\n\n let gao x y =\n let a = Array.make 4 ~-1 in\n for i = 0 to 3 do\n let xx = x + dx.(i) and yy = y + dy.(i) in\n if xx >= 0 && xx < n && yy >= 0 && yy < m then (\n a.(i) <- mark.(xx).(yy)\n )\n done;\n Array.sort (fun x y -> if x < y then -1 else (if x > y then 1 else 0)) a;\n let sum = ref 1 in\n for i = 0 to 3 do\n if a.(i) != ~-1 then (\n if i = 0 || a.(i) != a.(i - 1) then (\n sum := !sum + cnt.(a.(i))\n )\n )\n done;\n sum := !sum mod 10;\n Char.chr (48 + !sum)\n in\n\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n if s.(i).[j] = '.' && mark.(i).(j) = -1 then (\n bfs i j;\n idx := !idx + 1;\n );\n done;\n done;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n s.(i).[j] <- (if s.(i).[j] = '*' then (gao i j) else '.');\n done;\n Printf.printf \"%s\\n\" s.(i);\n done;\n"}], "negative_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet (+|) = Int64.add;;\nlet (-|) = Int64.sub;;\nlet ( *| ) = Int64.mul;;\nlet ( /| ) = Int64.div;;\nlet two_64 = Int64.one +| Int64.one;;\n\nlet licz x = (x-|Int64.one)/|two_64;;\n\nlet (n,m) = read2 ();;\n\nlet ruch x y = [ (x+1,y); (x-1,y); (x,y+1); (x,y-1) ];;\n\nlet czy_dobry x y tab =\n if x < 0 || x >= n || y < 0 || y >= m then false\n else if tab.(x).(y) = '*' then false\n else true;;\n \n\nlet rec dfs x y k tab vis fuf size = \n if not (czy_dobry x y tab) || vis.(x).(y) then ()\n else begin\n vis.(x).(y) <- true;\n fuf.(x).(y) <- k;\n match k with\n | (a,b) -> size.(a).(b) <- size.(a).(b) + 1;\n List.iter ( fun (a,b) -> dfs a b k tab vis fuf size ) ( ruch x y ) end;;\n\nlet wynik x y tab fuf size =\n let ruchy = List.filter ( fun (x,y) -> czy_dobry x y tab ) (ruch x y) in\n List.fold_left (fun a (x,y) -> a + size.(x).(y)) 0\n (\n List.fold_left (fun a (x,y) -> if\n (List.fold_left (fun a b -> if b = fuf.(x).(y) then false else a ) true a )\n then fuf.(x).(y)::a else a ) [] ruchy\n );;\n \n\nlet _ = \n let tab = Array.make_matrix n m '.' \n and vis = Array.make_matrix n m false \n and fuf = Array.make_matrix n m (0,0)\n and size = Array.make_matrix n m 0 in\n for i=0 to (n-1) do\n let s = Scanf.scanf \"%s\\n\" (fun x -> x) in\n for j=0 to (m-1) do\n tab.(i).(j) <- s.[j];\n fuf.(i).(j) <- (i,j)\n done\n done;\n for i =0 to (n-1) do\n for j=0 to (m-1) do\n dfs i j (i,j) tab vis fuf size\n done\n done;\n for i=0 to (n-1) do\n for j=0 to (m-1) do\n if tab.(i).(j) = '.' then \n Printf.printf \".\"\n else Printf.printf \"%d\" ( wynik i j tab fuf size + 1)\n done;\n Printf.printf \"\\n\"\n done;;\n\n\n\n"}], "src_uid": "c91dd34bfa784f55ad3b661e06f84cfb"} {"nl": {"description": "At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array a[1],\u2009a[2],\u2009...,\u2009a[n]. Then he should perform a sequence of m operations. An operation can be one of the following: Print operation l,\u2009r. Picks should write down the value of . Modulo operation l,\u2009r,\u2009x. Picks should perform assignment a[i]\u2009=\u2009a[i]\u00a0mod\u00a0x for each i (l\u2009\u2264\u2009i\u2009\u2264\u2009r). Set operation k,\u2009x. Picks should set the value of a[k] to x (in other words perform an assignment a[k]\u2009=\u2009x). Can you help Picks to perform the whole sequence of operations?", "input_spec": "The first line of input contains two integer: n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The second line contains n integers, separated by space: a[1],\u2009a[2],\u2009...,\u2009a[n]\u00a0(1\u2009\u2264\u2009a[i]\u2009\u2264\u2009109) \u2014 initial value of array elements. Each of the next m lines begins with a number type . If type\u2009=\u20091, there will be two integers more in the line: l,\u2009r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n), which correspond the operation 1. If type\u2009=\u20092, there will be three integers more in the line: l,\u2009r,\u2009x\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009x\u2009\u2264\u2009109), which correspond the operation 2. If type\u2009=\u20093, there will be two integers more in the line: k,\u2009x\u00a0(1\u2009\u2264\u2009k\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009x\u2009\u2264\u2009109), which correspond the operation 3. ", "output_spec": "For each operation 1, please print a line containing the answer. Notice that the answer may exceed the 32-bit integer.", "sample_inputs": ["5 5\n1 2 3 4 5\n2 3 5 4\n3 3 5\n1 2 5\n2 1 3 3\n1 1 3", "10 10\n6 9 6 7 6 1 10 10 9 5\n1 3 9\n2 7 10 9\n2 5 10 8\n1 4 7\n3 3 7\n2 7 9 9\n1 2 4\n1 6 6\n1 5 9\n3 1 10"], "sample_outputs": ["8\n5", "49\n15\n23\n1\n9"], "notes": "NoteConsider the first testcase: At first, a\u2009=\u2009{1,\u20092,\u20093,\u20094,\u20095}. After operation 1, a\u2009=\u2009{1,\u20092,\u20093,\u20090,\u20091}. After operation 2, a\u2009=\u2009{1,\u20092,\u20095,\u20090,\u20091}. At operation 3, 2\u2009+\u20095\u2009+\u20090\u2009+\u20091\u2009=\u20098. After operation 4, a\u2009=\u2009{1,\u20092,\u20092,\u20090,\u20091}. At operation 5, 1\u2009+\u20092\u2009+\u20092\u2009=\u20095. "}, "positive_code": [{"source_code": "(**D. The Child and Sequence*)\n\nopen Scanf;;\nopen Num;;\nopen Printf;;\n\nlet (n,m) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" ( fun x y -> (x,y));;\n\n(*Read the sequence*)\ntype node = {mutable l:int; mutable r:int; mutable mid:int; mutable maxx:int; mutable sum:num};;\nlet tree = Array.init ( 4 * n + 4 ) (fun _ -> {l=0;r=0;maxx=0; mid=0; sum = num_of_int 0});;\n\nlet rec build l r now =\n tree.(now).l <- l; tree.(now).r<-r; tree.(now).mid<- ((l+r)/2);\n if l = r then\n let x = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n tree.(now).maxx<-x;tree.(now).sum <- num_of_int x\n else\n let twonow = 2 * now in\n build l tree.(now).mid twonow;\n build (tree.(now).mid + 1) r (twonow + 1);\n tree.(now).sum <- Num.add_num tree.(twonow).sum tree.(twonow + 1).sum;\n tree.(now).maxx <- max tree.(twonow).maxx tree.(twonow + 1).maxx\nin build 1 n 1 (*Note tree.(0) is not used*)\n\nlet rec query l r now = \n if tree.(now).l=l && tree.(now).r=r then\n tree.(now).sum\n else if l > tree.(now).mid then\n query l r (2*now + 1)\n else if r <= tree.(now).mid then\n query l r (2*now)\n else\n Num.add_num (query l tree.(now).mid (2*now)) (query (tree.(now).mid + 1) r (\n 2*now + 1))\n;;\n\nlet rec mod_op l r x now = match now with\n |_ when tree.(now).maxx < x -> ();\n |_ when tree.(now).l = tree.(now).r ->\n ( tree.(now).sum <- Num.mod_num tree.(now).sum (Num.num_of_int x);\n tree.(now).maxx <- Num.int_of_num tree.(now).sum )\n |_ ->(\n (\n match l with\n |_ when l > tree.(now).mid -> mod_op l r x (2*now+1)\n |_ when r <= tree.(now).mid -> mod_op l r x (2*now)\n |_ ->( mod_op l tree.(now).mid x (2*now);\n mod_op (tree.(now).mid + 1) r x (2*now + 1) )\n );\n tree.(now).sum <- Num.add_num tree.(2*now).sum\n tree.(2*now+1).sum;\n tree.(now).maxx <- max tree.(2*now).maxx tree.(2*now+1).maxx\n )\n;;\n\nlet rec set_op k x now = match now with\n |_ when tree.(now).l = k && tree.(now).r = k ->\n tree.(now).maxx <- x;\n tree.(now).sum <- Num.num_of_int x\n |_ ->( \n (match k with\n |_ when k > tree.(now).mid -> set_op k x (2*now+1)\n |_ -> set_op k x (2*now)\n );\n tree.(now).sum <- Num.add_num tree.(2*now).sum tree.(2*now+1).sum;\n tree.(now).maxx <- max tree.(2*now).maxx tree.(2*now+1).maxx\n )\n;;\n\nlet print_info () =\n printf \"%s \" \"array: \"; \n for i = 1 to n do\n printf \"%s \" (Num.string_of_num (query i i 1) )\n done;\n print_endline \"\"\n;;\n\nlet print_info () = ()\n;; \n\nfor i = 0 to m - 1 do \n let x = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n (*print_int x; print_endline \"\";*)\n match x with\n | 1 -> let (l,r) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" (\n fun x y -> (x,y) ) in let rslt = query l r 1 in\n print_endline (Num.string_of_num rslt);\n print_info ()\n | 2 -> let (l,r,x) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d %d \" (fun x\n y z -> (x,y,z)) in\n mod_op l r x 1; print_info ()\n | 3 -> let (k,x) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" (\n fun x y -> (x,y) ) in\n set_op k x 1; print_info ()\ndone \n;;\n"}], "negative_code": [{"source_code": "(**D. The Child and Sequence*)\n\nopen Scanf;;\nopen Num;;\n\nlet (n,m) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" ( fun x y -> (x,y));;\n\nlet arr = Array.create n 0;;\nfor i = 0 to n - 1 do\n let x = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n arr.(i) <- x\ndone\n;;\n\nfor i =0 to m - 1 do\n let x = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n match x with\n | 1 -> let (l,r) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" (\n fun x y -> (x,y) ) in let s = ref 0 in\n for j = l - 1 to r - 1 do\n s := !s + arr.(j)\n done; print_int !s; print_endline \"\" \n | 2 -> let (l,r,x) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d %d \" (fun x\n y z -> (x,y,z)) in\n for j = l - 1 to r - 1 do\n arr.(j) <- arr.(j) mod x\n done; \n | 3 -> let (k,x) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" (\n fun x y -> (x,y) ) in \n arr.(k - 1) <- x \ndone\n;;\n\n\n\n\n \n\n\n\n(*-------------Back up-------------*)\n\n(* The next m lines*)\n\n(* test\n *\nlet print_tuple x = match x with\n | (n, m) -> print_int n; print_string \" \"; print_int m; print_endline \"\";;\n\nprint_tuple nm;;\n*)\n\n(** The early version of my program.\n *\nlet n = ref 0;;\nlet m = ref 0;;\n\nlet line1 = input_line stdin;;\nlet nm = Scanf.sscanf line1 \"%d %d\" ( fun x y -> (x, y) );;\nlet f x = match x with\n| (x,y) -> n := x; m := y\nin f nm;;\n*)\n\n\n"}, {"source_code": "(**D. The Child and Sequence*)\n\nopen Scanf;;\n\nlet (n,m) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" ( fun x y -> (x,y));;\n\nlet arr = Array.create n 0;;\nfor i = 0 to n - 1 do\n let x = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n arr.(i) <- x\ndone\n;;\n\nfor i =0 to m - 1 do\n let x = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n match x with\n | 1 -> let (l,r) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" (\n fun x y -> (x,y) ) in let s = ref 0 in\n for j = l - 1 to r - 1 do\n s := !s + arr.(j)\n done; print_int !s; print_endline \"\" \n | 2 -> let (l,r,x) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d %d \" (fun x\n y z -> (x,y,z)) in\n for j = l - 1 to r - 1 do\n arr.(j) <- arr.(j) mod x\n done; \n | 3 -> let (k,x) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" (\n fun x y -> (x,y) ) in \n arr.(k - 1) <- x \ndone\n;;\n\n\n\n\n \n\n\n\n(*-------------Back up-------------*)\n\n(* The next m lines*)\n\n(* test\n *\nlet print_tuple x = match x with\n | (n, m) -> print_int n; print_string \" \"; print_int m; print_endline \"\";;\n\nprint_tuple nm;;\n*)\n\n(** The early version of my program.\n *\nlet n = ref 0;;\nlet m = ref 0;;\n\nlet line1 = input_line stdin;;\nlet nm = Scanf.sscanf line1 \"%d %d\" ( fun x y -> (x, y) );;\nlet f x = match x with\n| (x,y) -> n := x; m := y\nin f nm;;\n*)\n\n\n"}], "src_uid": "69bfbd43579d74b921c08214cd5c9484"} {"nl": {"description": "You are given a sorted array $$$a_1, a_2, \\dots, a_n$$$ (for each index $$$i > 1$$$ condition $$$a_i \\ge a_{i-1}$$$ holds) and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$max(i)$$$ be equal to the maximum in the $$$i$$$-th subarray, and $$$min(i)$$$ be equal to the minimum in the $$$i$$$-th subarray. The cost of division is equal to $$$\\sum\\limits_{i=1}^{k} (max(i) - min(i))$$$. For example, if $$$a = [2, 4, 5, 5, 8, 11, 19]$$$ and we divide it into $$$3$$$ subarrays in the following way: $$$[2, 4], [5, 5], [8, 11, 19]$$$, then the cost of division is equal to $$$(4 - 2) + (5 - 5) + (19 - 8) = 13$$$.Calculate the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. ", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 3 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$ 1 \\le a_i \\le 10^9$$$, $$$a_i \\ge a_{i-1}$$$). ", "output_spec": "Print the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. ", "sample_inputs": ["6 3\n4 8 15 16 23 42", "4 4\n1 3 3 7", "8 1\n1 1 2 3 5 8 13 21"], "sample_outputs": ["12", "0", "20"], "notes": "NoteIn the first test we can divide array $$$a$$$ in the following way: $$$[4, 8, 15, 16], [23], [42]$$$. "}, "positive_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve n k a =\n let open Array in\n let d = init (n-1) (fun i -> a.(i+1) - a.(i)) in\n fast_sort compare d;\n let rec go sum i =\n if i >= n-1 then sum\n else go (sum + d.(i)) (i + 1)\n in a.(n-1) - a.(0) - go 0 (n-k)\n\nlet main () =\n let n = readInt () in\n let k = readInt () in\n let a = Array.init n (fun _ -> readInt ()) in\n Printf.printf \"%d\\n\" (solve n k a)\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "2895624e708159bc2a6f3e91140a6c45"} {"nl": {"description": "Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \\le x_1, x_2, x_3 \\le n$$$, $$$0 \\le y_1, y_2, y_3 \\le m$$$ and the area of the triangle formed by these points is equal to $$$\\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.", "input_spec": "The single line contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1\\le n, m \\le 10^9$$$, $$$2 \\le k \\le 10^9$$$).", "output_spec": "If there are no such points, print \"NO\". Otherwise print \"YES\" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ \u2014 coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower).", "sample_inputs": ["4 3 3", "4 4 7"], "sample_outputs": ["YES\n1 0\n2 3\n4 1", "NO"], "notes": "NoteIn the first example area of the triangle should be equal to $$$\\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below: In the second example there is no triangle with area $$$\\frac{nm}{k} = \\frac{16}{7}$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet repm from_ to_ ?(stride=1) m_init fbod =\n\tlet i,f,m = ref ~|from_,ref true,ref m_init in\n\twhile !i <= ~|to_ && !f do\n\t\tmatch fbod !m (~~| !i) with\n\t\t| `Break -> f := false\n\t\t| `Break_m m' -> (f := false; m := m')\n\t\t| `Ok m' -> (i := !i +$ 1; m := m')\n\tdone; !m\n\n\nlet () =\n\tlet n,m,k = get_3_i64 0 in\n\t(\n\t\t(* (0,0),(p,q),(r,s) -> 2S = |ps-qr| \u2208 Z *)\n\t\tif 2L*n*m mod k <> 0L then printf \"NO\\n\"\n\t\telse (\n\t\t\tprintf \"YES\\n0 0\\n\";\n\t\t\tlet x,y = (\n\t\t\t\tlet n,m,k = ref (2L*n),ref m,ref k in\n\t\t\t\twhile !k <> 1L do\n\t\t\t\t\tlet g = gcd !n !k in if g > 1L then (\n\t\t\t\t\t\tn := !n / g;\n\t\t\t\t\t\tk := !k / g);\n\t\t\t\t\tlet g = gcd !m !k in if g > 1L then (\n\t\t\t\t\t\tm := !m / g;\n\t\t\t\t\t\tk := !k / g)\n\t\t\t\tdone; (!n,!m)\n\t\t\t) in\n\t\t\tif x > n && x mod 2L = 0L && y * 2L <= m then (\n\t\t\t\tprintf \"%Ld 0\\n0 %Ld\\n\" (x/2L) (y*2L)\n\t\t\t) else printf \"%Ld 0\\n0 %Ld\\n\" x y\n\t\t)\n\t)"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet repm from_ to_ ?(stride=1) m_init fbod =\n\tlet i,f,m = ref ~|from_,ref true,ref m_init in\n\twhile !i <= ~|to_ && !f do\n\t\tmatch fbod !m (~~| !i) with\n\t\t| `Break -> f := false\n\t\t| `Break_m m' -> (f := false; m := m')\n\t\t| `Ok m' -> (i := !i +$ 1; m := m')\n\tdone; !m\n\n\nlet () =\n\tlet n,m,k = get_3_i64 0 in\n\t(\n\t\t(* (0,0),(p,q),(r,s) -> 2S = |ps-qr| Z *)\n\t\tif 2L*n*m mod k <> 0L then printf \"NO\\n\"\n\t\telse (\n\t\t\tprintf \"YES\\n0 0\\n\";\n\t\t\tlet x,y = (\n\t\t\t\tlet n,m,k = ref (2L*n),ref m,ref k in\n\t\t\t\twhile !k <> 1L do\n\t\t\t\t\tlet g = gcd !n !k in if g > 1L then (\n\t\t\t\t\t\tn := !n / g;\n\t\t\t\t\t\tk := !k / g);\n\t\t\t\t\tlet g = gcd !m !k in if g > 1L then (\n\t\t\t\t\t\tm := !m / g;\n\t\t\t\t\t\tk := !k / g)\n\t\t\t\tdone; (!n,!m)\n\t\t\t) in\n\t\t\tif x > n && x mod 2L = 0L && y * 2L <= m then (\n\t\t\t\tprintf \"%Ld 0\\n0 %Ld\\n\" (x/2L) (y*2L)\n\t\t\t) else printf \"%Ld 0\\n0 %Ld\\n\" x y\n\t\t)\n\t)"}], "negative_code": [], "src_uid": "5c026adda2ae3d7b707d5054bd84db3f"} {"nl": {"description": "Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.Iahub wants to draw n distinct segments [li,\u2009ri] on the OX axis. He can draw each segment with either red or blue. The drawing is good if and only if the following requirement is met: for each point x of the OX axis consider all the segments that contains point x; suppose, that rx red segments and bx blue segments contain point x; for each point x inequality |rx\u2009-\u2009bx|\u2009\u2264\u20091 must be satisfied.A segment [l,\u2009r] contains a point x if and only if l\u2009\u2264\u2009x\u2009\u2264\u2009r.Iahub gives you the starting and ending points of all the segments. You have to find any good drawing for him.", "input_spec": "The first line of input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of segments. The i-th of the next n lines contains two integers li and ri (0\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009109) \u2014 the borders of the i-th segment. It's guaranteed that all the segments are distinct.", "output_spec": "If there is no good drawing for a given test, output a single integer -1. Otherwise output n integers; each integer must be 0 or 1. The i-th number denotes the color of the i-th segment (0 is red and 1 is blue). If there are multiple good drawings you can output any of them.", "sample_inputs": ["2\n0 2\n2 3", "6\n1 5\n1 3\n3 5\n2 10\n11 11\n12 12"], "sample_outputs": ["0 1", "0 1 0 1 0 0"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let nn = 2*n in\n \n let seg = Array.make nn 0 in\n let nbr = Array.make nn 0 in\n\n let h = Hashtbl.create 10 in\n let add_to_h x e = \n let li = try Hashtbl.find h x with Not_found -> [] in\n Hashtbl.replace h x (e::li)\n in\n\n for i=0 to n-1 do\n let l = read_int() in\n let r = read_int() + 1 in\n let le = 2*i in\n let re = 2*i+1 in\n seg.(le) <- re;\n seg.(re) <- le;\n\n add_to_h l le;\n add_to_h r re;\n done;\n\n let allpoints = Hashtbl.fold (fun k _ ac -> k::ac) h [] in\n let allpoints = List.sort compare allpoints in\n \n let allends = \n List.fold_left (\n fun ac x ->\n\tlet pts = Hashtbl.find h x in\n\tpts @ ac\n ) [] allpoints \n in\n \n let rec loop = function [] -> ()\n | (a::(b::rest)) -> \n nbr.(a) <- b;\n nbr.(b) <- a;\n loop rest\n | _ -> failwith \"odd length list\"\n in\n\n loop allends;\n \n let label = Array.make nn (-1) in\n\n(*\n let rec label_cycle i bit =\n if label.(i) < 0 then (\n label.(i) <- bit;\n if bit=0 then label_cycle nbr.(i) 1\n else label_cycle seg.(i) 0\n )\n in\n*)\n\n let rec label_cycle i =\n if label.(i) < 0 then (\n label.(i) <- 0;\n label.(nbr.(i)) <- 1;\n label_cycle seg.(nbr.(i))\n )\n in\n\n for i=0 to nn-1 do\n if label.(i) < 0 then label_cycle i\n done;\n\n for i=0 to n-1 do\n if i>0 then printf \" \";\n printf \"%d\" label.(2*i);\n done;\n\n print_newline();\n"}], "negative_code": [], "src_uid": "894c82f3a05e8df16ae069a82bab9aca"} {"nl": {"description": "The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that: each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova; the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.", "input_spec": "The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \\le k, x \\le n \\le 200$$$) \u2014 the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.", "output_spec": "Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer \u2014 the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.", "sample_inputs": ["5 2 3\n5 1 3 10 1", "6 1 5\n10 30 30 70 10 10", "4 3 1\n1 100 1 1"], "sample_outputs": ["18", "-1", "100"], "notes": null}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,k,x = get_3_i64 0 in\n let a = input_i64_array n in\n let undef = -7L in\n let dp = make_matrix (i32 n+$1) (i32 x+$1) @@ undef in\n let update i j v =\n try\n dp.(i).(j) <- max (dp.(i).(j)) v\n with Invalid_argument _ -> ()\n in\n repi 0 (i32 k-$1) (fun k ->\n dp.(k).(i32 x) <- 0L\n );\n repi 0 (i32 n-$1) (fun i ->\n repi 1 (i32 x) (fun j ->\n if dp.(i).(j) <> undef then\n repi 1 (i32 k) (fun k ->\n update (i+$k) (j-$1) @@ dp.(i).(j) + a.(i)\n )\n )\n );\n (* dump_2darr (sprintf \"%4Ld\") dp; *)\n (* let res = ref undef in\n repi 0 (i32 k-$1) (fun k ->\n res := max !res dp.(i32 n-$k).(0)\n );\n if dp.(i32 n).(0) = undef then res := undef;\n if !res = undef then printf \"-1\\n\"\n else printf \"%Ld\\n\" !res *)\n printf \"%Ld\\n\" @@ let res = dp.(i32 n).(0) in if res = undef then -1L else res\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,k,x = get_3_i64 0 in\n let a = input_i64_array n in\n let undef = -7L in\n let n,k,x = i32 n,i32 k,i32 x in\n let dp = make_matrix (n+$1) (x+$1) @@ undef in\n dp.(0).(x) <- 0L;\n repi 1 n (fun i ->\n repi 0 (x-$1) (fun j ->\n repi 1 k (fun k ->\n try\n let v = dp.(i-$k).(j+$1) in\n if v <> undef then\n dp.(i).(j) <- max dp.(i).(j) (v+a.(i-$1))\n with Invalid_argument _ -> ()\n )\n )\n );\n (* dump_2darr (sprintf \"%3Ld\") dp; *)\n let res = ref undef in\n repi (n-$k+$1) n (fun i ->\n res := max !res @@ dp.(i).(0)\n );\n printf \"%Ld\\n\" @@ let v = !res in if v = undef then -1L else v\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Scanf open Array\nlet (++) = Int64.add\nlet () = scanf \" %d %d %d\" @@ fun n k x ->\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v) in\n let undef = -1L in\n let dp = init (n+1) (fun _ -> make_matrix (x+1) (k+1) undef) in\n dp.(0).(x-1).(k) <- a.(0);\n dp.(0).(x).(k-1) <- 0L;\n let upd i j p v =\n dp.(i).(j).(p) <- max dp.(i).(j).(p) v\n in\n for i=0 to n-2 do\n for j=1 to x do\n for p=1 to k do\n if dp.(i).(j).(p) <> undef then (\n upd (i+1) (j-1) k @@\n dp.(i).(j).(p) ++ a.(i+1);\n upd (i+1) j (p-1) @@\n dp.(i).(j).(p))\n done\n done\n done;\n let mx = ref @@ -1L in\n for i=n-k to n do\n for p=0 to k do\n mx := max !mx dp.(i).(0).(p)\n done\n done;\n Printf.printf \"%Ld\\n\" !mx"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,k,x = get_3_i64 0 in\n let a = input_i64_array n in\n let undef = -7L in\n let dp = make_matrix (i32 n+$1) (i32 x+$1) @@ undef in\n let update i j v =\n try\n dp.(i).(j) <- max (dp.(i).(j)) v\n with Invalid_argument _ -> ()\n in\n repi 0 (i32 k-$1) (fun k ->\n dp.(k).(i32 x) <- 0L\n );\n repi 0 (i32 n-$1) (fun i ->\n repi_rev (i32 x) 1 (fun j ->\n repi 1 (i32 k) (fun k ->\n if dp.(i).(j) <> undef then\n update (i+$k) (j-$1) @@ dp.(i).(j) + a.(i)\n )\n )\n );\n (* dump_2darr (sprintf \"%3Ld\") dp; *)\n let res = ref undef in\n repi 0 (i32 k-$1) (fun k ->\n res := max !res dp.(i32 n-$k).(0)\n );\n if !res = undef then printf \"-1\\n\"\n else printf \"%Ld\\n\" !res\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,k,x = get_3_i64 0 in\n let a = input_i64_array n in\n let undef = -7L in\n let dp = make_matrix (i32 n+$1) (i32 x+$1) @@ undef in\n let update i j v =\n try\n dp.(i).(j) <- max (dp.(i).(j)) v\n with Invalid_argument _ -> ()\n in\n repi 0 (i32 k-$1) (fun k ->\n dp.(k).(i32 x) <- 0L\n );\n repi 0 (i32 n-$1) (fun i ->\n repi 1 (i32 x) (fun j ->\n if dp.(i).(j) <> undef then\n repi 1 (i32 k) (fun k ->\n update (i+$k) (j-$1) @@ dp.(i).(j) + a.(i)\n )\n )\n );\n (* dump_2darr (sprintf \"%10Ld\") dp; *)\n let res = ref undef in\n repi 0 (i32 k-$1) (fun k ->\n res := max !res dp.(i32 n-$k).(0)\n );\n if dp.(i32 n).(0) = undef then res := undef;\n if !res = undef then printf \"-1\\n\"\n else printf \"%Ld\\n\" !res\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,k,x = get_3_i64 0 in\n let a = input_i64_array n in\n let undef = -7L in\n let n,k,x = i32 n,i32 k,i32 x in\n let dp = make_matrix (n+$1) (x+$1) @@ undef in\n repi 0 (k-$1) (fun i ->\n dp.(i).(x) <- 0L\n );\n repi 1 n (fun i ->\n repi 0 (x-$1) (fun j ->\n repi 1 k (fun k ->\n try\n let v = dp.(i-$k).(j+$1) in\n if v <> undef then\n dp.(i).(j) <- max dp.(i).(j) (v+a.(i-$1))\n with Invalid_argument _ -> ()\n )\n )\n );\n (* dump_2darr (sprintf \"%3Ld\") dp; *)\n let res = ref undef in\n repi (n-$k+$1) n (fun i ->\n res := max !res @@ dp.(i).(0)\n );\n printf \"%Ld\\n\" @@ let v = !res in if v = undef then -1L else v\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,k,x = get_3_i64 0 in\n let a = input_i64_array n in\n let undef = -7L in\n let dp = make_matrix (i32 n+$1) (i32 x+$1) @@ undef in\n let update i j v =\n try\n dp.(i).(j) <- max (dp.(i).(j)) v\n with Invalid_argument _ -> ()\n in\n repi 0 (i32 k-$1) (fun k ->\n dp.(k).(i32 x) <- 0L\n );\n repi 0 (i32 n-$1) (fun i ->\n repi 1 (i32 x) (fun j ->\n if dp.(i).(j) <> undef then\n repi 1 (i32 k) (fun k ->\n update (i+$k) (j-$1) @@ dp.(i).(j) + a.(i)\n )\n )\n );\n (* dump_2darr (sprintf \"%10Ld\") dp; *)\n let res = ref undef in\n repib 0 (i32 k-$1) (fun k ->\n let v = dp.(i32 n-$k).(0) in\n if v = undef then (res := undef; `Break)\n else (res := max !res dp.(i32 n-$k).(0); `Ok)\n );\n if !res = undef then printf \"-1\\n\"\n else printf \"%Ld\\n\" !res\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,k,x = get_3_i64 0 in\n let a = input_i64_array n in\n let undef = -7L in\n let dp = make_matrix (i32 n+$1) (i32 x+$1) @@ undef in\n let update i j v =\n try\n dp.(i).(j) <- max (dp.(i).(j)) v\n with Invalid_argument _ -> ()\n in\n repi 0 (i32 k-$1) (fun k ->\n dp.(k).(i32 x) <- 0L\n );\n repi 0 (i32 n-$1) (fun i ->\n repi 1 (i32 x) (fun j ->\n if dp.(i).(j) <> undef then\n repi 1 (i32 k) (fun k ->\n update (i+$k) (j-$1) @@ dp.(i).(j) + a.(i)\n )\n )\n );\n dump_2darr (sprintf \"%10Ld\") dp;\n let res = ref undef in\n repi 0 (i32 k-$1) (fun k ->\n res := max !res dp.(i32 n-$k).(0)\n );\n if dp.(i32 n).(0) = undef then res := undef;\n if !res = undef then printf \"-1\\n\"\n else printf \"%Ld\\n\" !res\n\n\n\n\n\n\n\n\n"}], "src_uid": "c1d48f546f79b0fd58539a1eb32917dd"} {"nl": {"description": "You are given a string $$$a$$$, consisting of $$$n$$$ characters, $$$n$$$ is even. For each $$$i$$$ from $$$1$$$ to $$$n$$$ $$$a_i$$$ is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters \"(\" and \")\". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters \"1\" and \"+\" between the original characters of the sequence. For example, bracket sequences \"()()\" and \"(())\" are regular (the resulting expressions are: \"(1)+(1)\" and \"((1+1)+1)\"), and \")(\", \"(\" and \")\" are not.You want to find a string $$$b$$$ that consists of $$$n$$$ characters such that: $$$b$$$ is a regular bracket sequence; if for some $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string $$$b$$$ exists.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$a$$$. $$$a$$$ consists only of uppercase letters 'A', 'B' and 'C'. Let $$$n$$$ be the length of $$$a$$$. It is guaranteed that $$$n$$$ is even and $$$2 \\le n \\le 50$$$.", "output_spec": "For each testcase print \"YES\" if there exists such a string $$$b$$$ that: $$$b$$$ is a regular bracket sequence; if for some $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. Otherwise, print \"NO\". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).", "sample_inputs": ["4\nAABBAC\nCACA\nBBBBAC\nABCA"], "sample_outputs": ["YES\nYES\nNO\nNO"], "notes": "NoteIn the first testcase one of the possible strings $$$b$$$ is \"(())()\".In the second testcase one of the possible strings $$$b$$$ is \"()()\"."}, "positive_code": [{"source_code": "let replace c1 r1 c2 r2 c3 r3 =\n String.map \n (fun c -> \n if c = c1\n then r1\n else if c = c2\n then r2\n else if c = c3\n then r3\n else c)\n\nlet sum_paren str =\n let len = String.length str in\n let rec helper i acc =\n if i = len\n then if acc = 0\n then true\n else false\n else\n let new_acc = \n match str.[i] with\n | '(' -> acc + 1\n | ')' -> acc - 1 in\n if new_acc < 0\n then false\n else helper (i+1) new_acc in\n helper 0 0\n\nlet test () =\n let str = read_line () in\n let parens = [replace 'A' '(' 'B' '(' 'C' ')' str;\n replace 'A' '(' 'B' ')' 'C' ')' str;\n replace 'A' '(' 'B' ')' 'C' '(' str;\n replace 'B' '(' 'A' '(' 'C' ')' str;\n replace 'B' '(' 'A' ')' 'C' ')' str;\n replace 'B' '(' 'A' ')' 'C' '(' str;\n replace 'C' '(' 'A' '(' 'B' ')' str;\n replace 'C' '(' 'A' ')' 'B' ')' str;\n replace 'C' '(' 'A' ')' 'B' '(' str] in\n List.fold_left (fun acc str -> acc || sum_paren str) false parens\n \nlet () =\n let cases = read_int () in\n for i = 0 to cases - 1 do\n (if test () then \"YES\" else \"NO\")\n |> print_endline\n done\n"}], "negative_code": [{"source_code": "let explode str =\n let len = String.length str in\n let rec helper i acc =\n if i = 0\n then List.rev acc\n else helper (i-1) (str.[i]::acc) in\n helper (len-1) []\n\n(*\nlet hist str = \n let len = String.length str and\n hist = Array.make 3 0\n let rec helper i =\n if i = len\n then hist\n else \n let _ = \n match str.[i] with\n | 'A' -> hist.(0) <- hist.(0) + 1\n | 'B' -> hist.(1) <- hist.(1) + 1\n | 'C' -> hist.(2) <- hist.(2) + 1 in\n helper (i+1) in\n helper 0\n\nlet count c hist =\n match c with\n | 'A' -> hist.(0)\n | 'B' -> hist.(1)\n | 'C' -> hist.(2)\n*)\nlet count c str = \n let len = String.length str in\n let rec helper i acc =\n if i = len\n then acc\n else helper (i+1) (if str.[i] = c then acc+1 else acc) in\n helper 0 0\n\nlet uniques n str =\n let len = String.length str in\n let in_set c =\n List.fold_left (fun acc el -> c = el || acc) false in\n let rec helper i len_set set =\n if i = len\n then set\n else if not (in_set str.[i] set)\n then if len_set = n-1\n then List.rev (str.[i]::set)\n else helper (i+1) (len_set+1) (str.[i]::set)\n else helper (i+1) len_set set in\n helper 0 0 []\n\nlet sum_paren str =\n let len = String.length str in\n let rec helper i acc =\n if i = len\n then if acc = 0\n then true\n else false\n else\n let new_acc = \n match str.[i] with\n | '(' -> acc + 1\n | ')' -> acc - 1 in\n if new_acc < 0\n then false\n else helper (i+1) new_acc in\n helper 0 0\n\nlet test () =\n let str = read_line () in\n let letters = uniques 3 str in\n let pass_test = ref false in\n if List.length letters = 3\n then (\n let first::second::third::[] = letters in\n let c1 = count first str and\n c2 = count second str and\n c3 = count third str in\n if c1 + c2 - c3 = 0\n then \n let s1 = String.map (function first -> '(' | second -> '(' | third -> ')') str in\n if sum_paren s1\n then pass_test := true\n else if c1 - c2 - c3 = 0 \n then \n let s1 = String.map (function first -> '(' | second -> ')' | third -> ')') str in\n if sum_paren s1\n then pass_test := true\n else if c1 - c2 + c3 = 0\n then \n let s1 = String.map (function first -> '(' | second -> ')' | third -> '(') str in\n if sum_paren s1\n then pass_test := true\n )\n else (\n let first::second::[] = letters in\n let c1 = count first str and\n c2 = count second str in\n if c1 - c2 = 0\n then \n let s1 = String.map (function first -> '(' | second -> ')') str in\n if sum_paren s1\n then pass_test := true\n );\n !pass_test\n\nlet () =\n let nb_cases = read_int () in\n for i = 0 to nb_cases - 1 do\n (if test () then \"YES\" else \"NO\")\n |> print_endline\n done\n"}], "src_uid": "4d24aaf5ebf70265b027a6af86e09250"} {"nl": {"description": "Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading \u2014 he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.", "input_spec": "The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 \u0438 s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.", "output_spec": "If Vasya can write the given anonymous letter, print YES, otherwise print NO", "sample_inputs": ["Instead of dogging Your footsteps it disappears but you dont notice anything\nwhere is your dog", "Instead of dogging Your footsteps it disappears but you dont notice anything\nYour dog is upstears", "Instead of dogging your footsteps it disappears but you dont notice anything\nYour dog is upstears", "abcdefg hijk\nk j i h g f e d c b a"], "sample_outputs": ["NO", "YES", "NO", "YES"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 43B *)\n\nopen String;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_string \" \"; print_int i)) li;;\nlet printarri ai = Array.iter (fun i -> (print_string \" \"; print_int i)) ai;;\nlet debug = false;;\n\nlet removec s c = \n\tlet idx = index s c in\n\t(sub s 0 idx) ^ (sub s (idx+1) ((length s) - idx - 1));;\n\nlet rec isOk a b = match b with \n| \"\" -> true\n| _ -> \n\tlet c = get b 0 in\n\tif not (contains a c) then false\n\telse \n\t\tlet lenb = length b in\n\t\tlet bt = sub b 1 (lenb-1) in\n\t\tif c = ' ' then isOk a bt\t\n\t\telse isOk (removec a c) bt;;\t\n\nlet main () =\n\tlet a = rdln() in\n\tlet b = rdln() in\n\tlet ok = isOk a b in begin\n\t\tif debug then\n\t\t\tprint_string (\"A:\" ^ a ^ \" B:\" ^ b);\n\tprint_string (if ok then \"YES\" else \"NO\")\n\tend;; \n\nmain();;\n"}], "negative_code": [{"source_code": "(* Codeforces 43B *)\n\nopen String;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_string \" \"; print_int i)) li;;\nlet printarri ai = Array.iter (fun i -> (print_string \" \"; print_int i)) ai;;\nlet debug = true;;\n\nlet removec s c = \n\tlet idx = index s c in\n\t(sub s 0 idx) ^ (sub s (idx+1) ((length s) - idx - 1));;\n\nlet rec isOk a b = match b with \n| \"\" -> true\n| _ -> \n\tlet c = get b 0 in\n\tif not (contains a c) then false\n\telse \n\t\tlet lenb = length b in\n\t\tlet bt = sub b 1 (lenb-1) in\n\t\tif c = ' ' then isOk a bt\t\n\t\telse isOk (removec a c) bt;;\t\n\nlet main () =\n\tlet a = rdln() in\n\tlet b = rdln() in\n\tlet ok = isOk a b in begin\n\t\tif debug then\n\t\t\tprint_string (\"A:\" ^ a ^ \" B:\" ^ b);\n\tprint_string (if ok then \"YES\" else \"NO\")\n\tend;; \n\nmain();;\n"}], "src_uid": "b1ef19d7027dc82d76859d64a6f43439"} {"nl": {"description": "Two players play a game.Initially there are $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i.\u00a0e. $$$n - 1$$$ turns are made. The first player makes the first move, then players alternate turns.The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.You want to know what number will be left on the board after $$$n - 1$$$ turns if both players make optimal moves.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 1000$$$)\u00a0\u2014 the number of numbers on the board. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$).", "output_spec": "Print one number that will be left on the board.", "sample_inputs": ["3\n2 1 3", "3\n2 2 2"], "sample_outputs": ["2", "2"], "notes": "NoteIn the first sample, the first player erases $$$3$$$ and the second erases $$$1$$$. $$$2$$$ is left on the board.In the second sample, $$$2$$$ is left on the board regardless of the actions of the players."}, "positive_code": [{"source_code": "let n = int_of_string (input_line stdin) ;;\n\nlet a = Array.make n 0 ;;\n\nlet rec aux i =\n Scanf.scanf \"%d \" (fun v -> Array.set a i v); aux (i + 1)\nin try aux 0 with _ -> () ;;\n\nArray.sort compare a ;;\n\nPrintf.printf \"%d\\n\" (Array.get a ((n - 1) / 2)) ;;"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n\n Array.sort compare a;\n\n let k = (n-1)/2 in\n\n printf \"%d\\n\" a.(k)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n\n Array.sort compare a;\n\n let k = n/2 in\n\n printf \"%d\\n\" a.(k)\n"}], "src_uid": "f93a8bd64a405233342f84542fce314d"} {"nl": {"description": "Creatnx has $$$n$$$ mirrors, numbered from $$$1$$$ to $$$n$$$. Every day, Creatnx asks exactly one mirror \"Am I beautiful?\". The $$$i$$$-th mirror will tell Creatnx that he is beautiful with probability $$$\\frac{p_i}{100}$$$ for all $$$1 \\le i \\le n$$$.Creatnx asks the mirrors one by one, starting from the $$$1$$$-st mirror. Every day, if he asks $$$i$$$-th mirror, there are two possibilities: The $$$i$$$-th mirror tells Creatnx that he is beautiful. In this case, if $$$i = n$$$ Creatnx will stop and become happy, otherwise he will continue asking the $$$i+1$$$-th mirror next day; In the other case, Creatnx will feel upset. The next day, Creatnx will start asking from the $$$1$$$-st mirror again. You need to calculate the expected number of days until Creatnx becomes happy.This number should be found by modulo $$$998244353$$$. Formally, let $$$M = 998244353$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \\not \\equiv 0 \\pmod{M}$$$. Output the integer equal to $$$p \\cdot q^{-1} \\bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \\le x < M$$$ and $$$x \\cdot q \\equiv p \\pmod{M}$$$.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1\\le n\\le 2\\cdot 10^5$$$)\u00a0\u2014 the number of mirrors. The second line contains $$$n$$$ integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\leq p_i \\leq 100$$$).", "output_spec": "Print the answer modulo $$$998244353$$$ in a single line.", "sample_inputs": ["1\n50", "3\n10 20 50"], "sample_outputs": ["2", "112"], "notes": "NoteIn the first test, there is only one mirror and it tells, that Creatnx is beautiful with probability $$$\\frac{1}{2}$$$. So, the expected number of days until Creatnx becomes happy is $$$2$$$."}, "positive_code": [{"source_code": "(* Beautiful Mirrors\n * https://codeforces.com/problemset/problem/1265/E *)\n\nopen Printf\nopen Scanf\n\nlet ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( ** ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet ( %% ) a b = a -- (b ** (a//b))\n\n\nlet md = 998244353L\n\nlet ( *% ) a b = (a ** b) %% md\n\nlet pw a b =\n let a = a %% md in\n let rec iter acc a b =\n if b = 0L then\n acc\n else\n let a' = (a *% a) in\n let b' = b // 2L in\n if Int64.logand b 1L = 1L then\n iter (acc *% a) a' b'\n else\n iter acc a' b' in\n iter 1L a b\n\nlet inv a = pw a (md -- 2L)\n\nlet () =\n let _ = read_int () in\n let i100 = inv 100L in\n let pl = read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map Int64.of_string \n |> List.map (fun p -> p *% i100) in\n let (a, b) = List.fold_right\n (fun p (a, b) -> (p *% a ++ 1L, p *% (b -- 1L) ++ 1L))\n pl (0L, 0L) in\n printf \"%Ld\\n\" (a *% (inv (md ++ 1L -- b)))\n\n\n"}, {"source_code": "(* Beautiful Mirrors\n * https://codeforces.com/problemset/problem/1265/E *)\n\nopen Printf\nopen Scanf\n\nlet ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( ** ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet ( %% ) a b = a -- (b ** (a//b))\n\n\nlet md = 998244353L\n\nlet ( *% ) a b = (a ** b) %% md\n\nlet pw a b =\n let a = a %% md in\n let rec iter acc a b =\n if b = 0L then\n acc\n else\n let a' = (a *% a) in\n let b' = b // 2L in\n if Int64.logand b 1L = 1L then\n iter (acc *% a) a' b'\n else\n iter acc a' b' in\n iter 1L a b\n\nlet inv a = pw a (md -- 2L)\n\nlet () =\n let _ = read_int () in\n let pl = read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map Int64.of_string \n |> List.map (fun p -> p *% (inv 100L)) in\n let (a, b) = List.fold_right\n (fun p (a, b) -> (p *% a ++ 1L, p *% (b -- 1L) ++ 1L))\n pl (0L, 0L) in\n printf \"%Ld\\n\" (a *% (inv (md ++ 1L -- b)))\n\n\n"}], "negative_code": [], "src_uid": "43d877e3e1c1fd8ee05dc5e5e3067f93"} {"nl": {"description": "Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!", "input_spec": "The first line of the input contains three space-separated integers l, r and k (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u20091018, 2\u2009\u2264\u2009k\u2009\u2264\u2009109).", "output_spec": "Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print \"-1\" (without the quotes).", "sample_inputs": ["1 10 2", "2 4 5"], "sample_outputs": ["1 2 4 8", "-1"], "notes": "NoteNote to the first sample: numbers 20\u2009=\u20091, 21\u2009=\u20092, 22\u2009=\u20094, 23\u2009=\u20098 lie within the specified range. The number 24\u2009=\u200916 is greater then 10, thus it shouldn't be printed."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet rec ( ^ ) e p = \n if p=0 then 1L else\n let a = e^(p/2) in\n if (p land 1)=0 then a**a else e**a**a\n \n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () = \n let l = read_long () in\n let r = read_long () in\n let k = read_long () in \n\n let rec loop ac count =\n if ac > r then count else (\n if ac >= l then printf \"%Ld \" ac;\n let count = if ac >= l then count+1 else count in\n if (k ** ac) // k = ac then loop (k**ac) count else count\n )\n in\n\n let count = loop 1L 0 in\n\n if count > 0 then print_newline() else printf \"-1\\n\"\n"}], "negative_code": [], "src_uid": "8fcec28fb4d165eb58f829c03e6b31d1"} {"nl": {"description": "The hero is addicted to glory, and is fighting against a monster. The hero has $$$n$$$ skills. The $$$i$$$-th skill is of type $$$a_i$$$ (either fire or frost) and has initial damage $$$b_i$$$. The hero can perform all of the $$$n$$$ skills in any order (with each skill performed exactly once). When performing each skill, the hero can play a magic as follows: If the current skill immediately follows another skill of a different type, then its damage is doubled. In other words, If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$c$$$ damage; If a skill of type fire and with initial damage $$$c$$$ is performed immediately after a skill of type frost, then it will deal $$$2c$$$ damage; If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type fire, then it will deal $$$2c$$$ damage; If a skill of type frost and with initial damage $$$c$$$ is performed immediately after a skill of type frost , then it will deal $$$c$$$ damage. Your task is to find the maximum damage the hero can deal. ", "input_spec": "Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^5$$$) \u2014 the number of test cases. The following lines contain the description of each test case. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$), indicating the number of skills. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0 \\leq a_i \\leq 1$$$), where $$$a_i$$$ indicates the type of the $$$i$$$-th skill. Specifically, the $$$i$$$-th skill is of type fire if $$$a_i = 0$$$, and of type frost if $$$a_i = 1$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\leq b_i \\leq 10^9$$$), where $$$b_i$$$ indicates the initial damage of the $$$i$$$-th skill. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, output the maximum damage the hero can deal.", "sample_inputs": ["4\n\n4\n\n0 1 1 1\n\n1 10 100 1000\n\n6\n\n0 0 0 1 1 1\n\n3 4 5 6 7 8\n\n3\n\n1 1 1\n\n1000000000 1000000000 1000000000\n\n1\n\n1\n\n1"], "sample_outputs": ["2112\n63\n3000000000\n1"], "notes": "NoteIn the first test case, we can order the skills by $$$[3, 1, 4, 2]$$$, and the total damage is $$$100 + 2 \\times 1 + 2 \\times 1000 + 10 = 2112$$$.In the second test case, we can order the skills by $$$[1, 4, 2, 5, 3, 6]$$$, and the total damage is $$$3 + 2 \\times 6 + 2 \\times 4 + 2 \\times 7 + 2 \\times 5 + 2 \\times 8 = 63$$$.In the third test case, we can order the skills by $$$[1, 2, 3]$$$, and the total damage is $$$1000000000 + 1000000000 + 1000000000 = 3000000000$$$.In the fourth test case, there is only one skill with initial damage $$$1$$$, so the total damage is $$$1$$$. "}, "positive_code": [{"source_code": "(* Codeforces 1738 A Glory Addicts TODO *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet rec readlistl n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlistl (n -1) (grl() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nexception MisEx of string\n\nlet rec selectFireFrost a (b : int64 list) li lo = match a with\n\t| [] -> (li, lo)\n\t| 1 :: t -> selectFireFrost t (List.tl b) li ((List.hd b) :: lo)\n\t| 0 :: t -> selectFireFrost t (List.tl b) ((List.hd b) :: li) lo\n\t| _ :: t -> raise (MisEx \"Illegal a value not 0 or 1\");;\n\t\nlet rec sumD (l : int64 list) nd (sm : int64) = match l with\n\t| [] -> sm\n\t| h :: t -> \n\t\tlet d = if nd > 0 then 2L else 1L in\n\t\tlet dn = Int64.mul d h in\n\t\tlet nsm = Int64.add sm dn in\n\t\tsumD t (nd-1) nsm;;\n\t\nlet rec sumDoub (l : int64 list) nd = \n\tlet ls = List.rev (List.sort compare l) in\n\tsumD ls nd 0L;;\n\t\n\nlet maxDam li lo = \n let ni = List.length li in\n let no = List.length lo in\n\tlet damof = Int64.add (sumDoub li no) (sumDoub lo (ni - 1)) in\n\tlet damif = Int64.add (sumDoub li (no - 1)) (sumDoub lo ni) in\n\tif damof > damif then damof else damif;;\t\n\n\nlet do_one () = \n let n = gr() in\n let ar = readlist n [] in\n let a = List.rev ar in\n let br = readlistl n [] in\n let b = List.rev br in\n let fi,fo = selectFireFrost a b [] [] in\n let dam = maxDam fi fo in\n Printf.printf \"%Ld\\n\" dam;;\n\nlet do_all () = \n let t = gr () in\n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tdo_all ();;\n \nmain();;\n"}], "negative_code": [{"source_code": "(* Codeforces 1738 A Glory Addicts TODO *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nexception MisEx of string\n\nlet rec selectFireFrost a b li lo = match a with\n\t| [] -> (li, lo)\n\t| 1 :: t -> selectFireFrost t (List.tl b) li ((List.hd b) :: lo)\n\t| 0 :: t -> selectFireFrost t (List.tl b) ((List.hd b) :: li) lo\n\t| _ :: t -> raise (MisEx \"Illegal a value not 0 or 1\");;\n\t\nlet rec sumD l nd sm = match l with\n\t| [] -> sm\n\t| h :: t -> \n\t\tlet d = if nd > 0 then 2 else 1 in\n\t\tlet nsm = sm + d * h in\n\t\tsumD t (nd-1) nsm;;\n\t\nlet rec sumDoub l nd = \n\tlet ls = List.rev (List.sort compare l) in\n\tsumD ls nd 0;;\n\t\n\nlet maxDam li lo = \n let ni = List.length li in\n let no = List.length lo in\n\tlet damof = (sumDoub li no) + (sumDoub lo (ni - 1)) in\n\tlet damif = (sumDoub li (no - 1)) + (sumDoub lo ni) in\n\tif damof > damif then damof else damif;;\t\n\n\nlet do_one () = \n let n = gr() in\n let ar = readlist n [] in\n let a = List.rev ar in\n let br = readlist n [] in\n let b = List.rev br in\n let fi,fo = selectFireFrost a b [] [] in\n let dam = maxDam fi fo in\n Printf.printf \"%d\\n\" dam;;\n\nlet do_all () = \n let t = gr () in\n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tdo_all ();;\n \nmain();;\n"}], "src_uid": "bc1587d3affd867804e664fdb38ed765"} {"nl": {"description": "You are given n points on the straight line \u2014 the positions (x-coordinates) of the cities and m points on the same line \u2014 the positions (x-coordinates) of the cellular towers. All towers work in the same way \u2014 they provide cellular network for all cities, which are located at the distance which is no more than r from this tower.Your task is to find minimal r that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than r.If r\u2009=\u20090 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than r from this tower.", "input_spec": "The first line contains two positive integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of cities and the number of cellular towers. The second line contains a sequence of n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates ai are given in non-decreasing order. The third line contains a sequence of m integers b1,\u2009b2,\u2009...,\u2009bm (\u2009-\u2009109\u2009\u2264\u2009bj\u2009\u2264\u2009109) \u2014 the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates bj are given in non-decreasing order.", "output_spec": "Print minimal r so that each city will be covered by cellular network.", "sample_inputs": ["3 2\n-2 2 4\n-3 0", "5 3\n1 5 10 14 17\n4 11 15"], "sample_outputs": ["4", "3"], "notes": null}, "positive_code": [{"source_code": "let (+/) = Int32.add\nlet (-/) = Int32.sub\nlet ( */ ) = Int32.mul\nlet ( // ) = Int32.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = Array.make m 0 in\n let _ =\n for i = 0 to m - 1 do\n b.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let l = ref (-1l) in\n let r = ref (2000000000l) in\n while !r -/ !l > 1l do\n let mm = (!l +/ !r) // 2l in\n let receive =\n\tlet bpos = ref 0 in\n\t try\n\t for i = 0 to n - 1 do\n\t if !bpos < m then (\n\t\tif mm < Int32.of_int a.(i) -/ Int32.of_int b.(!bpos)\n\t\tthen raise Not_found;\n\t\twhile !bpos < m &&\n\t\t Int32.of_int b.(!bpos) -/ Int32.of_int a.(i) <= mm\n\t\tdo\n\t\t incr bpos\n\t\tdone;\n\t )\n\t done;\n\t if !bpos < m\n\t then raise Not_found;\n\t true\n\t with\n\t | Not_found ->\n\t\tfalse\n in\n\tif receive\n\tthen r := mm\n\telse l := mm\n done;\n Printf.printf \"%ld\\n\" !r\n"}], "negative_code": [], "src_uid": "9fd8e75cb441dc809b1b2c48c4012c76"} {"nl": {"description": "The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $$$h$$$ hours and each hour lasts $$$m$$$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $$$0$$$ to $$$h-1$$$ and minutes are numbered from $$$0$$$ to $$$m-1$$$. That's how the digits are displayed on the clock. Please note that digit $$$1$$$ is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).The image of the clocks in the mirror is reflected against a vertical axis. The reflection is not a valid time.The reflection is a valid time with $$$h=24$$$, $$$m = 60$$$. However, for example, if $$$h=10$$$, $$$m=60$$$, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $$$s$$$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.It can be shown that with any $$$h$$$, $$$m$$$, $$$s$$$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.You are asked to solve the problem for several test cases.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of test cases. The next $$$2 \\cdot T$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of a test case contains two integers $$$h$$$, $$$m$$$ ($$$1 \\le h, m \\le 100$$$). The second line contains the start time $$$s$$$ in the described format HH:MM.", "output_spec": "For each test case output in a separate line the nearest moment in format HH:MM when the reflected time is correct.", "sample_inputs": ["5\n24 60\n12:21\n24 60\n23:59\n90 80\n52:26\n1 100\n00:01\n10 10\n04:04"], "sample_outputs": ["12:21\n00:00\n52:28\n00:00\n00:00"], "notes": "NoteIn the second test case it is not hard to show that the reflection of 23:59 is incorrect, while the reflection of the moment 00:00 on the next day is correct. "}, "positive_code": [{"source_code": "let l = ref []\n\nlet () = \n for i=1 to (read_int ()) do\n l := (Scanf.scanf \" %d %d\\n%d:%d\" (fun x y w z -> x,y,w,z))::!l\n done\n\nlet getReflection n = \n match n with \n | 0 | 1 | 8 -> n\n | 2 -> 5\n | 5 -> 2\n | _ -> -1\n\nlet checkReflection lh lm h m = \n let hd = getReflection (m mod 10)*10 in\n let hu = getReflection (m / 10) in\n let md = getReflection (h mod 10)*10 in\n let mu = getReflection (h / 10) in\n let hr,mr = ((if ((hd <> -1) && (hu <> -1)) then (hd+hu) else -1), (if (md <> -1) && (mu <> -1) then (md+mu) else -1)) in\n if (hr < lh) && (mr < lm) && (hr >= 0) && (mr >= 0)\n then (hr,mr)\n else (-1,-1)\n\nlet checkNextValidReflection lh lm h m = \n let hr,mr = (ref h, ref m) in\n let h,m = (ref h, ref m) in\n let () = \n while (let haux,maux = checkReflection lh lm !h !m in let () = hr := haux in let () = mr := maux in ((!hr = (-1)) && (!mr = (-1)))) do\n if !m < (lm-1)\n then m := !m +1\n else if !h < (lh-1)\n then (h := !h +1; m := 0)\n else (h := 0; m := 0)\n done in\n if !h < 10 \n then (Printf.printf \"0%d:\" !h; if !m < 10 then Printf.printf \"0%d\\n\" !m else Printf.printf \"%d\\n\" !m)\n else (Printf.printf \"%d:\" !h; if !m < 10 then Printf.printf \"0%d\\n\" !m else Printf.printf \"%d\\n\" !m)\n\n\n\nlet rec testAll l = \n match l with\n | (lh,lm,h,m)::t -> (testAll t; checkNextValidReflection lh lm h m)\n | [] -> ()\n\nlet () = testAll !l"}, {"source_code": "(* https://codeforces.com/contest/1493/problem/B *)\n\nlet reverse_digit n =\n match n with\n | 0 -> Some 0\n | 1 -> Some 1\n | 2 -> Some 5\n | 5 -> Some 2\n | 8 -> Some 8\n | 3 | 4 | 6 | 7 | 9 -> None\n\nlet reverse_time_opt [hh; mm] =\n let rec helper_opt e acc =\n match e with\n | [] -> Some acc\n | h::t ->\n match reverse_digit h with\n | Some h2 -> helper_opt t (h2::acc)\n | None -> None in\n let rev_minuts = helper_opt mm [] and\n rev_hours = helper_opt hh [] in\n match rev_minuts, rev_hours with\n | Some m, Some h -> Some [m; h]\n | _ -> None\n\nlet listify time =\n let rec helper i acc num =\n if i = 2\n then acc\n else helper (i+1) ((num mod 10)::acc) (num/10) in\n List.map (helper 0 []) time\n\nlet numberify =\n List.fold_left (fun acc e -> acc * 10 + e) 0\n\nlet add_minut h m =\n let inner_add [hh; mm] =\n let minuts = numberify mm and\n hours = numberify hh in\n if minuts + 1 = m\n then (\n let minuts2 = 0 in\n if hours + 1 = h\n then \n let hours2 = 0 in\n listify [hours2; minuts2]\n else listify [hours+1; minuts2]\n )\n else\n listify [hours; minuts+1] in\n inner_add\n\nlet correct_time h m =\n let inner_correct t =\n match t with\n | None -> false\n | Some [hh; mm] -> \n numberify hh < h && numberify mm < m in\n inner_correct\n\nlet next_time_rev h m time =\n let verify_t = correct_time h m and\n add_m = add_minut h m in\n let rec helper i t =\n if verify_t (reverse_time_opt t)\n then t\n else helper (i+1) (add_m t) in\n helper 0 time\n\nlet print_time [hh; mm] =\n List.iter (Printf.printf \"%d\") hh;\n Printf.printf \":\";\n List.iter (Printf.printf \"%d\") mm\n\nlet input_case () =\n let h::m::_ = \n read_line () \n |> Str.split (Str.regexp \" \") |> List.map int_of_string and\n t = \n read_line () \n |> Str.split (Str.regexp \":\") |> List.map int_of_string |> listify in\n (h, m, t)\n\nlet () =\n let cases = read_int () in\n for i = 1 to cases do\n let (h, m, t) = input_case () in\n next_time_rev h m t\n |> print_time;\n print_newline ()\n done\n"}], "negative_code": [{"source_code": "let l = ref []\n\nlet () = \n for i=1 to (read_int ()) do\n l := (Scanf.scanf \" %d %d\\n%d:%d\" (fun x y w z -> x,y,w,z))::!l\n done\n\nlet getReflection n = \n match n with \n | 0 | 1 | 8 -> n\n | 2 -> 5\n | 5 -> 2\n | _ -> -1\n\nlet checkReflection lh lm h m = \n let hr,mr = (((getReflection (m mod 10)*10) + (getReflection (m / 10))), ((getReflection (h mod 10)*10) + (getReflection (h / 10)))) in\n if (hr < lh) && (mr < lm) && (hr >= 0) && (mr >= 0)\n then (hr,mr)\n else (-1,-1)\n\nlet checkNextValidReflection lh lm h m = \n let hr,mr = (ref h, ref m) in\n let h,m = (ref h, ref m) in\n let () = \n while (let haux,maux = checkReflection lh lm !h !m in let () = hr := haux in let () = mr := maux in ((!hr = (-1)) && (!mr = (-1)))) do\n if !m < (lm-1)\n then m := !m +1\n else if !h < (lh-1)\n then (h := !h +1; m := 0)\n else (h := 0; m := 0)\n done in\n if !h < 10 \n then (Printf.printf \"0%d:\" !h; if !m < 10 then Printf.printf \"0%d\\n\" !m else Printf.printf \"%d\\n\" !m)\n else (Printf.printf \"%d:\" !h; if !m < 10 then Printf.printf \"0%d\\n\" !m else Printf.printf \"%d\\n\" !m)\n\n\n\nlet rec testAll l = \n match l with\n | (lh,lm,h,m)::t -> (testAll t; checkNextValidReflection lh lm h m)\n | [] -> ()\n\nlet () = testAll !l"}, {"source_code": "let l = ref []\n\nlet () = \n for i=1 to (read_int ()) do\n l := (Scanf.scanf \" %d %d\\n%d:%d\" (fun x y w z -> x,y,w,z))::!l\n done\n\nlet getReflection n = \n match n with \n | 0 | 1 | 8 -> n\n | 2 -> 5\n | 5 -> 2\n | _ -> -1\n\nlet checkReflection lh lm h m = \n let hr,mr = (((getReflection (m mod 10)*10) + (getReflection (m / 10))), ((getReflection (h mod 10)*10) + (getReflection (h / 10)))) in\n if (hr < lh) && (mr < lm) && (hr >= 0) && (mr >= 0)\n then (hr,mr)\n else (-1,-1)\n\nlet checkNextValidReflection lh lm h m = \n let hr,mr = (ref h, ref m) in\n let h,m = (ref h, ref m) in\n let () = \n while (let haux,maux = checkReflection lh lm !h !m in let () = hr := haux in let () = mr := maux in ((!hr = (-1)) && (!mr = (-1)))) do\n if !h >= (lh-1) then h:=0 else h := !h+1;\n if !m >= (lm-1) then m:=0 else m := !m+1;\n done in\n if !h < 10 \n then (Printf.printf \"0%d:\" !h; if !m < 10 then Printf.printf \"0%d\\n\" !m else Printf.printf \"%d\\n\" !m)\n else (Printf.printf \"%d:\" !h; if !m < 10 then Printf.printf \"0%d\\n\" !m else Printf.printf \"%d\\n\" !m)\n\n\n\nlet rec testAll l = \n match l with\n | (lh,lm,h,m)::t -> (testAll t; checkNextValidReflection lh lm h m)\n | [] -> ()\n\nlet () = testAll !l"}], "src_uid": "7f28e4dbd199b84bd7885bf7f479cf38"} {"nl": {"description": "You are given a set of n vectors on a plane. For each vector you are allowed to multiply any of its coordinates by -1. Thus, each vector vi\u2009=\u2009(xi,\u2009yi) can be transformed into one of the following four vectors: vi1\u2009=\u2009(xi,\u2009yi), vi2\u2009=\u2009(\u2009-\u2009xi,\u2009yi), vi3\u2009=\u2009(xi,\u2009\u2009-\u2009yi), vi4\u2009=\u2009(\u2009-\u2009xi,\u2009\u2009-\u2009yi). You should find two vectors from the set and determine which of their coordinates should be multiplied by -1 so that the absolute value of the sum of the resulting vectors was minimally possible. More formally, you should choose two vectors vi, vj (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n,\u2009i\u2009\u2260\u2009j) and two numbers k1, k2 (1\u2009\u2264\u2009k1,\u2009k2\u2009\u2264\u20094), so that the value of the expression |vik1\u2009+\u2009vjk2| were minimum.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105). Then n lines contain vectors as pairs of integers \"xi yi\" (\u2009-\u200910000\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u200910000), one pair per line.", "output_spec": "Print on the first line four space-separated numbers \"i k1 j k2\" \u2014 the answer to the problem. If there are several variants the absolute value of whose sums is minimum, you can print any of them. ", "sample_inputs": ["5\n-7 -3\n9 0\n-8 6\n7 -8\n4 -5", "5\n3 2\n-4 7\n-6 0\n-8 4\n5 1"], "sample_outputs": ["3 2 4 2", "3 4 5 4"], "notes": "NoteA sum of two vectors v\u2009=\u2009(xv,\u2009yv) and u\u2009=\u2009(xu,\u2009yu) is vector s\u2009=\u2009v\u2009+\u2009u\u2009=\u2009(xv\u2009+\u2009xu,\u2009yv\u2009+\u2009yu).An absolute value of vector v\u2009=\u2009(x,\u2009y) is number . In the second sample there are several valid answers, such as:(3 1 4 2), (3 1 4 4), (3 4 4 1), (3 4 4 3), (4 1 3 2), (4 1 3 4), (4 2 3 1)."}, "positive_code": [{"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n (*let s = 1000003 in\n let ht = Array.make s 0 in*)\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n let ht = Hashtbl.create n in\n (*let () =\n for i = 0 to s - 1 do\n\tht.(i) <- 0\n done\n in\n let hf x y =\n let r = (x * 20000 + y) mod s in\n\tif r < 0\n\tthen r + s\n\telse r\n in*)\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet key = (xi, yi) in\n\t(*let key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1*)\n\t try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1\n done\n in\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false*)\n\t\t if Hashtbl.mem ht key\n\t\t then remove := false\n\t ) else (\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false*)\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\n(*if n = 100000 then*)\nif n < 100 && Array.length ps = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m; exit 0);\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n Random.init 666666;\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (dup, di, dj) =\n let dup = ref false in\n let di = ref 0 in\n let dj = ref 0 in\n let ht = Hashtbl.create n in\n for i = 0 to n - 1 do\n\tif Hashtbl.mem ht a.(i) then (\n\t dup := true;\n\t di := i;\n\t dj := Hashtbl.find ht a.(i)\n\t);\n\tHashtbl.replace ht a.(i) i\n done;\n (!dup, !di, !dj)\n in\n let (_, i, j) =\n if dup\n then (0.0, di, dj)\n else cp2d a\n in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let s = 1000003 in\n let ht = Array.make s 0 in\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n let ht = Hashtbl.create n in\n (*let () =\n for i = 0 to s - 1 do\n\tht.(i) <- 0\n done\n in*)\n let hf x y =\n let r = (x * 20000 + y) mod s in\n\tif r < 0\n\tthen r + s\n\telse r\n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet key = (xi, yi) in\n\t(*let key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1*)\n\t try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1\n done\n in\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false*)\n\t\t if Hashtbl.mem ht key\n\t\t then remove := false\n\t ) else (\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false*)\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\n(*if n = 100000 then*)\nif n < 100 && Array.length ps = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m; exit 0);\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n Random.init 666666;\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (dup, di, dj) =\n let dup = ref false in\n let di = ref 0 in\n let dj = ref 0 in\n let ht = Hashtbl.create n in\n for i = 0 to n - 1 do\n\tif Hashtbl.mem ht a.(i) then (\n\t dup := true;\n\t di := i;\n\t dj := Hashtbl.find ht a.(i)\n\t);\n\tHashtbl.replace ht a.(i) i\n done;\n (!dup, !di, !dj)\n in\n let (_, i, j) =\n if dup\n then (0.0, di, dj)\n else cp2d a\n in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}], "negative_code": [{"source_code": "let _ =\nPrintf.printf \"test\\n%!\""}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let ht = Array.make 1000003 0 in\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n (*let ht = Hashtbl.create n in*)\n let () =\n for i = 0 to 1000003 - 1 do\n\tht.(i) <- 0\n done\n in\n let hf x y =\n let r = (x * 20000 + y) mod 1000003 in\n\tif r < 0\n\tthen r + 1000003\n\telse r\n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\t(*let key = (xi, yi) in*)\n\tlet key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1\n\t (*try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1*)\n done\n in\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false\n\t\t (*if Hashtbl.mem ht key\n\t\t then remove := false*)\n\t ) else (\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false\n\t\t(*let key = xi * 20000 + yi in\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false*)\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m; exit 0);\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n Random.init 666666;\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (_, i, j) = cp2d a in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let rec estimate ps =\n let n = Array.length ps in\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\t try\n\t let c = Hashtbl.find ht (xi, yi) in\n\t Hashtbl.replace ht (xi, yi) (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht (xi, yi) 1\n done\n in\n let rs = ref [] in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\t if Hashtbl.mem ht (xi, yi)\n\t\t then remove := false\n\t ) else (\n\t\tlet c = Hashtbl.find ht (xi, yi) in\n\t\t if c <> 1\n\t\t then remove := false\n\t )\n\t done\n\t done;\n\t if not !remove\n\t then rs := ps.(i) :: !rs\n done;\n if !rs = []\n then d\n else estimate (Array.of_list !rs)\n in\n let n = Array.length ps in\n let b = estimate ps in\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tHashtbl.add ht (xi, yi) i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t let rs = Hashtbl.find_all ht (xi, yi) in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let sb = Scanf.Scanning.from_file \"input.txt\" in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (_, i, j) =\n if n < 100000 then\n cp2d a\n else (0.0, 0, 0)\n in\n let fd = open_out \"output.txt\" in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let s = 1000003 in\n let ht = Array.make s 0 in\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n let ht = Hashtbl.create n in\n (*let () =\n for i = 0 to s - 1 do\n\tht.(i) <- 0\n done\n in*)\n let hf x y =\n let r = (x * 20000 + y) mod s in\n\tif r < 0\n\tthen r + s\n\telse r\n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet key = (xi, yi) in\n\t(*let key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1*)\n\t try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1\n done\n in\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false*)\n\t\t if Hashtbl.mem ht key\n\t\t then remove := false\n\t ) else (\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false*)\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\n(*if n = 100000 then*)\nif n < 100000 && Array.length ps = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m; exit 0);\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n Random.init 666666;\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (_, i, j) = cp2d a in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let s = 1000003 in\n let ht = Array.make s 0 in\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n let ht = Hashtbl.create n in\n (*let () =\n for i = 0 to s - 1 do\n\tht.(i) <- 0\n done\n in*)\n let hf x y =\n let r = (x * 20000 + y) mod s in\n\tif r < 0\n\tthen r + s\n\telse r\n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet key = (xi, yi) in\n\t(*let key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1*)\n\t try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1\n done\n in\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false*)\n\t\t if Hashtbl.mem ht key\n\t\t then remove := false\n\t ) else (\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false*)\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\n(*if n = 100000 then*)\nif Array.length ps = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m);\nif n < 100 && Array.length ps = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m; exit 0);\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n Random.init 666666;\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (_, i, j) = cp2d a in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let ht = Array.make 1000003 0 in\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n (*let ht = Hashtbl.create n in*)\n let () =\n for i = 0 to 1000003 - 1 do\n\tht.(i) <- 0\n done\n in\n let hf x y =\n let r = (x * 20000 + y) mod 1000003 in\n\tif r < 0\n\tthen r + 1000003\n\telse r\n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\t(*let key = (xi, yi) in*)\n\tlet key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1\n\t (*try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1*)\n done\n in\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false\n\t\t (*if Hashtbl.mem ht key\n\t\t then remove := false*)\n\t ) else (\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false\n\t\t(*let key = xi * 20000 + yi in\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false*)\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m; exit 0);\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (_, i, j) = cp2d a in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let s = 4000037 in\n let ht = Array.make s 0 in\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n (*let ht = Hashtbl.create n in*)\n let () =\n for i = 0 to s - 1 do\n\tht.(i) <- 0\n done\n in\n let hf x y =\n let r = (x * 20000 + y) mod s in\n\tif r < 0\n\tthen r + s\n\telse r\n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\t(*let key = (xi, yi) in*)\n\tlet key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1\n\t (*try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1*)\n done\n in\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false\n\t\t (*if Hashtbl.mem ht key\n\t\t then remove := false*)\n\t ) else (\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false\n\t\t(*let key = xi * 20000 + yi in\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false*)\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m; exit 0);\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n Random.init 666666;\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (_, i, j) = cp2d a in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let s = 4000037 in\n let ht = Array.make s 0 in\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n (*let ht = Hashtbl.create n in*)\n let () =\n for i = 0 to s - 1 do\n\tht.(i) <- 0\n done\n in\n let hf x y =\n let r = (x * 20000 + y) mod s in\n\tif r < 0\n\tthen r + s\n\telse r\n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\t(*let key = (xi, yi) in*)\n\tlet key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1\n\t (*try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1*)\n done\n in\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false\n\t\t (*if Hashtbl.mem ht key\n\t\t then remove := false*)\n\t ) else (\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false\n\t\t(*let key = xi * 20000 + yi in\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false*)\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\n(*if n = 100000 then*)\nif n < 100000 && Array.length ps = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m; exit 0);\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n Random.init 666666;\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (_, i, j) = cp2d a in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let ht = Array.make 1000003 0 in\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n (*let ht = Hashtbl.create n in*)\n let () =\n for i = 0 to 1000003 - 1 do\n\tht.(i) <- 0\n done\n in\n let hf x y =\n let r = (x * 20000 + y) mod 1000003 in\n\tif r < 0\n\tthen r + 1000003\n\telse r\n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\t(*let key = (xi, yi) in*)\n\tlet key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1\n\t (*try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1*)\n done\n in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false\n\t\t (*if Hashtbl.mem ht key\n\t\t then remove := false*)\n\t ) else (\n\t\t(*let key = (xi, yi) in*)\n\t\tlet key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false\n\t\t(*let key = xi * 20000 + yi in\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false*)\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (_, i, j) = cp2d a in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}, {"source_code": "let cp2d ps =\n let sqr x = x *. x in\n let dist (x1, y1) (x2, y2) =\n sqrt (sqr (x2 -. x1) +. sqr (y2 -. y1))\n in\n let s = 1000003 in\n let ht = Array.make s 0 in\n let rec estimate ps n rs =\n let idx = Random.int n in\n let d = ref infinity in\n let () =\n for i = 0 to n - 1 do\n\tif i <> idx\n\tthen d := min !d (dist ps.(idx) ps.(i))\n done\n in\n let d = !d in\n let b = d /. 3.0 in\n let ht = Hashtbl.create n in\n (*let () =\n for i = 0 to s - 1 do\n\tht.(i) <- 0\n done\n in*)\n let hf x y =\n let r = (x * 20000 + y) mod s in\n\tif r < 0\n\tthen r + s\n\telse r\n in\n let () =\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet key = (xi, yi) in\n\t(*let key = hf xi yi in\n\t ht.(key) <- ht.(key) + 1*)\n\t try\n\t let c = Hashtbl.find ht key in\n\t Hashtbl.replace ht key (c + 1)\n\t with\n\t | Not_found ->\n\t\tHashtbl.replace ht key 1\n done\n in\n let m = ref 0 in\n for i = 0 to n - 1 do\n\tlet (x, y) = ps.(i) in\n\tlet xi = int_of_float (x /. b) in\n\tlet yi = int_of_float (y /. b) in\n\tlet remove = ref true in\n\t for xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t if not (xd = 0 && yd = 0) then (\n\t\tlet xi = xi + xd in\n\t\tlet yi = yi + yd in\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) > 0\n\t\t then remove := false*)\n\t\t if Hashtbl.mem ht key\n\t\t then remove := false\n\t ) else (\n\t\tlet key = (xi, yi) in\n\t\t(*let key = hf xi yi in\n\t\t if ht.(key) <> 1\n\t\t then remove := false*)\n\t\tlet c = Hashtbl.find ht key in\n\t\t if c <> 1\n\t\t then remove := false\n\t )\n\t done\n\t done;\n\t if not !remove then (\n\t rs.(!m) <- ps.(i);\n\t incr m\n\t )\n done;\n(*if n = 100000 then*)\nif n < 100 && Array.length ps = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f %d\\n%!\" b !m; exit 0);\n if !m = 0\n then d\n else estimate rs !m ps\n in\n let n = Array.length ps in\n let b = estimate (Array.copy ps) n (Array.copy ps) in\nif n = 100000 then\n(Printf.fprintf (open_out \"output.txt\") \"est %f\\n%!\" b; exit 0);\n let ht = Hashtbl.create n in\n let () =\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n (*let key = (xi, yi) in*)\n let key = xi * 20000 + yi in\n\tHashtbl.add ht key i\n done\n in\n let d = ref infinity in\n let di = ref (-1) in\n let dj = ref (-1) in\n for i = 0 to n - 1 do\n let (x, y) = ps.(i) in\n let xi = int_of_float (x /. b) in\n let yi = int_of_float (y /. b) in\n\tfor xd = -1 to 1 do\n\t for yd = -1 to 1 do\n\t let xi = xi + xd in\n\t let yi = yi + yd in\n\t (*let key = (xi, yi) in*)\n\t let key = xi * 20000 + yi in\n\t let rs = Hashtbl.find_all ht key in\n\t List.iter\n\t\t(fun j ->\n\t\t if i <> j then (\n\t\t let dd = dist ps.(i) ps.(j) in\n\t\t if dd < !d then (\n\t\t\t d := dd;\n\t\t\t di := i;\n\t\t\t dj := j;\n\t\t )\n\t\t )\n\t\t) rs\n\t done\n\tdone;\n done;\n (!d, !di, !dj)\n\nlet debug = not true\n\nlet _ =\n Random.init 666666;\n let sb =\n if debug\n then Scanf.Scanning.stdib\n else Scanf.Scanning.from_file \"input.txt\"\n in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n (0.0, 0.0) in\n let b = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let (x, y, r) =\n\tif x < 0 && y < 0\n\tthen (-x, -y, 4)\n\telse if x < 0\n\tthen (-x, y, 2)\n\telse if y < 0\n\tthen (x, -y, 3)\n\telse (x, y, 1)\n in\n\ta.(i) <- (float_of_int x, float_of_int y);\n\tb.(i) <- r\n done;\n in\n let rot r =\n match r with\n | 1 -> 4\n | 2 -> 3\n | 3 -> 2\n | 4 -> 1\n | _ -> assert false\n in\n let (_, i, j) = cp2d a in\n let fd =\n if debug\n then stdout\n else open_out \"output.txt\"\n in\n Printf.fprintf fd \"%d %d %d %d\\n\" (i + 1) b.(i) (j + 1) (rot b.(j))\n"}], "src_uid": "41bc5d7e091a92af7160056ca6030588"} {"nl": {"description": "Dreamoon is a big fan of the Codeforces contests.One day, he claimed that he will collect all the places from $$$1$$$ to $$$54$$$ after two more rated contests. It's amazing!Based on this, you come up with the following problem:There is a person who participated in $$$n$$$ Codeforces rounds. His place in the first round is $$$a_1$$$, his place in the second round is $$$a_2$$$, ..., his place in the $$$n$$$-th round is $$$a_n$$$.You are given a positive non-zero integer $$$x$$$.Please, find the largest $$$v$$$ such that this person can collect all the places from $$$1$$$ to $$$v$$$ after $$$x$$$ more rated contests.In other words, you need to find the largest $$$v$$$, such that it is possible, that after $$$x$$$ more rated contests, for each $$$1 \\leq i \\leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.For example, if $$$n=6$$$, $$$x=2$$$ and $$$a=[3,1,1,5,7,10]$$$ then answer is $$$v=5$$$, because if on the next two contest he will take places $$$2$$$ and $$$4$$$, then he will collect all places from $$$1$$$ to $$$5$$$, so it is possible to get $$$v=5$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 5$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains two integers $$$n, x$$$ ($$$1 \\leq n, x \\leq 100$$$). The second line contains $$$n$$$ positive non-zero integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 100$$$).", "output_spec": "For each test case print one line containing the largest $$$v$$$, such that it is possible that after $$$x$$$ other contests, for each $$$1 \\leq i \\leq v$$$, there will exist a contest where this person took the $$$i$$$-th place.", "sample_inputs": ["5\n6 2\n3 1 1 5 7 10\n1 100\n100\n11 1\n1 1 1 1 1 1 1 1 1 1 1\n1 1\n1\n4 57\n80 60 40 20"], "sample_outputs": ["5\n101\n2\n2\n60"], "notes": "NoteThe first test case is described in the statement.In the second test case, the person has one hundred future contests, so he can take place $$$1,2,\\ldots,99$$$ and place $$$101$$$ on them in some order, to collect places $$$1,2,\\ldots,101$$$."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_int_pair () = let x = scan_int() in let y = scan_int() in (x,y);;\nlet scan_int_array_of_size n = Array.init n (fun _ -> scan_int());;\nlet show_int n = print_int n; print_newline ();;\n\nlet t = scan_int ();;\nfor x = 1 to t do\n\tlet n,x = scan_int_pair () in\n\tlet a = scan_int_array_of_size n in\n\tlet deja_vu = Array.make 205 false in\n\tfor i = 0 to n-1 do deja_vu.(a.(i)) <- true done;\n\tlet i = ref 1 and count = ref 0 in\n\twhile !count < x do\n\t\tif not deja_vu.(!i) then incr count;\n\t\tincr i\n\tdone;\n\twhile deja_vu.(!i) do incr i done;\n\tshow_int (!i-1)\ndone;;\n\n"}], "negative_code": [], "src_uid": "e5fac4a1f3a724234990fe758debc33f"} {"nl": {"description": "Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.Petya can ask questions like: \"Is the unknown number divisible by number y?\".The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers yi, he should ask the questions about.", "input_spec": "A single line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009103).", "output_spec": "Print the length of the sequence of questions k (0\u2009\u2264\u2009k\u2009\u2264\u2009n), followed by k numbers \u2014 the questions yi (1\u2009\u2264\u2009yi\u2009\u2264\u2009n). If there are several correct sequences of questions of the minimum length, you are allowed to print any of them.", "sample_inputs": ["4", "6"], "sample_outputs": ["3\n2 4 3", "4\n2 4 3 5"], "notes": "NoteThe sequence from the answer to the first sample test is actually correct.If the unknown number is not divisible by one of the sequence numbers, it is equal to 1.If the unknown number is divisible by 4, it is 4.If the unknown number is divisible by 3, then the unknown number is 3.Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter."}, "positive_code": [{"source_code": "let rec is_pow powered n =\n\t(n = powered) || ((powered mod n = 0) && (is_pow (powered / n) n));;\n\n\nlet f n l =\n\tlet tab = Array.make (n+1) true and compt = ref 0 in\n\t\ttab.(0) <- false;\n\t\ttab.(1) <- false;\n\t\tfor i = 2 to n do\n\t\t\tif tab.(i)\n\t\t\t\tthen \t(incr compt;\n\t\t\t\t\tl := i:: !l;\n\t\t\t\t\tfor j = 2 to (n/i) do\n\t\t\t\t\t\ttab.(i*j) <- false;\n\t\t\t\t\t\tif is_pow (i*j) i\n\t\t\t\t\t\t\tthen (l := (i*j):: !l; incr compt);\n\t\t\t\t\tdone);\n\t\tdone;\n\t\t!compt;;\n\nlet main () =\n\tlet l = ref [] in\n\t\tScanf.scanf \"%d\" (fun i -> Printf.printf \"%d\\n\" (f i l));\n\t\tList.iter (Printf.printf \"%d \") !l;;\n\nmain ();;\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\n\nlet is_prime n =\n let rec go d =\n if d * d > n then true else\n if n mod d = 0 then false else\n go (d+1)\n in\n go 2\n\nlet rec gen_primes n ans =\n if n <= 1 then ans else\n if is_prime n then gen_primes (n-1) (n::ans) else\n gen_primes (n-1) ans\n \nlet () =\n let n = read_int () in\n let rec f p a b = if b > n then a else (f p (b::a) (b*p)) in\n let g a p = f p a p in\n let ans = List.fold_left g [] (gen_primes n []) in\n Printf.printf \"%d\\n\" (List.length ans);\n List.iter (Printf.printf \"%d \") ans;;\n\n"}], "negative_code": [], "src_uid": "7f61b1d0e8294db74d33a6b6696989ad"} {"nl": {"description": "When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i\u2009+\u20091, then book number i\u2009+\u20092 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read.", "input_spec": "The first line contains two integers n and t (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009t\u2009\u2264\u2009109) \u2014 the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009104), where number ai shows the number of minutes that the boy needs to read the i-th book.", "output_spec": "Print a single integer \u2014 the maximum number of books Valera can read.", "sample_inputs": ["4 5\n3 1 2 1", "3 3\n2 2 3"], "sample_outputs": ["3", "1"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\n\nlet read_pair () = Scanf.scanf \" %d %d \" (fun x y -> x , y );;\n\nlet n , t = read_pair ();;\n\nlet data = Array.init (n+1) (fun i -> if i = 0 then 0 else read_int ());;\n\nlet sum = Array.init 100005 (fun i -> 0);;\n\nfor i = 1 to n do\n sum.(i) <- sum.(i-1) + data.(i)\ndone;;\n\nlet left , right = ( ref 1 , ref n );;\n\nlet binary_search len = \n let isok = ref false in \n for i = 0 to n-len do \n isok := !isok || (sum.(i+len) - sum.(i) <= t)\n done;\n !isok;;\n\nwhile !left <= !right do\n let mid = (!left + !right)/2 in \n if binary_search mid then left := mid + 1\n else right := mid - 1\ndone;;\n\nPrintf.printf \"%d\\n\" !right;;\n\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\n\nlet read_long () = Scanf.bscanf Scanf.Scanning.stdib \" %Ld \" (fun x -> x);;\n\n(*let read_pair () = let a = read_int () in (a , read_int ());;*)\n\nlet read_pair () = Scanf.scanf \" %d %d \" (fun x y -> x , y );;\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\nlet n , t = read_pair ();;\n\nlet data = Array.init (n+1) (fun i -> if i = 0 then Int64.of_int 0 else read_long ());;\n\nlet sum = Array.init 100005 (fun i -> Int64.of_int 0);;\n\nfor i = 1 to n do\n sum.(i) <- sum.(i-1) ++ data.(i)\ndone;;\n\nlet left , right = ( ref 1 , ref n );;\n\nlet binary_search len = \n let isok = ref false in \n for i = 0 to n-len do \n isok := !isok || (sum.(i+len) -- sum.(i) <= Int64.of_int t)\n done;\n !isok;;\n\nwhile !left <= !right do\n let mid = (!left + !right)/2 in \n if binary_search mid then left := mid + 1\n else right := mid - 1\ndone;;\n\nPrintf.printf \"%d\\n\" !right;;\n\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int 0 in\n let t = read_int 0 in\n let a = Array.init n read_int in\n\n(*\n let () = for i=1 to n-1 do\n a.(i) <- a.(i-1) + a.(i)\n done in\n (* so now a.(i) = the time needed to read books a.(0)...a.(i) *)\n (* so to read books i to j requires time a.(j) - a.(i-1) *)\n*)\n\n let rec loop i j sum ac = if j=n-1 then ac else\n (* sum = total time of the books from i to j inclusive *)\n (* ac is the biggest number of book found so far that I can read *)\n if sum + a.(j+1) > t \n then loop (i+1) j (sum - a.(i)) ac\n else loop i (j+1) (sum + a.(j+1)) (max ac ((j+1)-i+1))\n in\n\n let answer = loop 0 0 a.(0) (if a.(0) > t then 0 else 1) in\n Printf.printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\n\nlet read_long () = Scanf.bscanf Scanf.Scanning.stdib \" %Ld \" (fun x -> x);;\n\n(*let read_pair () = let a = read_int () in (a , read_int ());;*)\n\nlet read_pair () = Scanf.scanf \" %d %d \" (fun x y -> x , y );;\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\nlet n , t = read_pair ();;\n\nlet data = Array.init (n+1) (fun i -> if i = 0 then Int64.of_int 0 else read_long ());;\n\nlet sum = Array.init 100005 (fun i -> Int64.of_int 0);;\n\nfor i = 1 to n-1 do\n sum.(i) <- sum.(i-1) ++ data.(i)\ndone;;\n\nlet left , right = ( ref 1 , ref n );;\n\nlet binary_search len = \n let isok = ref true in \n for i = 0 to n-len do \n isok := !isok || (sum.(i+len) -- sum.(i) <= Int64.of_int t)\n done;\n !isok;;\n\nwhile !left <= !right do\n let mid = (!left + !right)/2 in \n if binary_search mid then left := mid + 1\n else right := mid - 1\ndone;;\n\nPrintf.printf \"%d\\n\" !right;;\n\n"}], "src_uid": "ef32a8f37968629673547db574261a9d"} {"nl": {"description": "An array $$$a_1, a_2, \\ldots, a_n$$$ is good if and only if for every subsegment $$$1 \\leq l \\leq r \\leq n$$$, the following holds: $$$a_l + a_{l + 1} + \\ldots + a_r = \\frac{1}{2}(a_l + a_r) \\cdot (r - l + 1)$$$. You are given an array of integers $$$a_1, a_2, \\ldots, a_n$$$. In one operation, you can replace any one element of this array with any real number. Find the minimum number of operations you need to make this array good.", "input_spec": "The first line of input contains one integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$): the number of test cases. Each of the next $$$t$$$ lines contains the description of a test case. In the first line you are given one integer $$$n$$$ ($$$1 \\leq n \\leq 70$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-100 \\leq a_i \\leq 100$$$): the initial array.", "output_spec": "For each test case, print one integer: the minimum number of elements that you need to replace to make the given array good.", "sample_inputs": ["5\n4\n1 2 3 4\n4\n1 1 2 2\n2\n0 -1\n6\n3 -2 4 -1 -4 0\n1\n-100"], "sample_outputs": ["0\n2\n0\n3\n0"], "notes": "NoteIn the first test case, the array is good already.In the second test case, one of the possible good arrays is $$$[1, 1, \\underline{1}, \\underline{1}]$$$ (replaced elements are underlined).In the third test case, the array is good already.In the fourth test case, one of the possible good arrays is $$$[\\underline{-2.5}, -2, \\underline{-1.5}, -1, \\underline{-0.5}, 0]$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet is_integer_ratio a b = (a/b) * b = a\n\nlet evaluate i j k num den a =\n (* extrapoloates the requred value of a.(k) for it to work *)\n (* true if a.(k) has this value *)\n if k = i || k = j then true\n else if k < i then\n (is_integer_ratio ((i-k)*num) den && a.(k) + ((i-k)*num)/den = a.(i))\n else if k < j then \n (is_integer_ratio ((k-i)*num) den && a.(i) + ((k-i)*num)/den = a.(k))\n else\n (is_integer_ratio ((j-k)*num) den && a.(j) + ((k-j)*num)/den = a.(k)) \n \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let a = Array.init n read_int in\n if n = 1 then printf \"0\\n\" else \n let answer = minf 0 (n-2) (fun i -> minf (i+1) (n-1) (fun j ->\n\tlet den = j - i in\n\tlet num = a.(j) - a.(i) in\n\tsum 0 (n-1) (fun k -> if evaluate i j k num den a then 0 else 1)\n ))in\n printf \"%d\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "6aca8c549822adbe96a58aee4b0d4b3f"} {"nl": {"description": "There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.", "input_spec": "The first line of input contains integer n denoting the number of psychos, (1\u2009\u2264\u2009n\u2009\u2264\u2009105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive \u2014 ids of the psychos in the line from left to right.", "output_spec": "Print the number of steps, so that the line remains the same afterward.", "sample_inputs": ["10\n10 9 7 8 6 5 3 4 2 1", "6\n1 2 3 4 5 6"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1] \u2009\u2192\u2009 [10 8 4] \u2009\u2192\u2009 [10]. So, there are two steps."}, "positive_code": [{"source_code": "let read_int () =\n Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\n\nlet rec read_line line = function\n | 0 -> line\n | x -> read_line (read_int()::line) (x-1);;\n\ntype psy_info = {id : int;\n\t\t kt : int};;\n\nlet ktime = Array.make 100000 0;;\nlet id_st = Stack.create ();;\nlet ans = ref 0;;\n\nlet dynpro psyline =\n let rec calc line n =\n match line with\n [] -> ()\n | x::l ->\n let larger = ref (Stack.top id_st) in\n while (not (Stack.is_empty id_st)) && (x > !larger.id) do\n\tlarger := Stack.pop id_st;\n\tif ktime.(n) < !larger.kt then\n\t ktime.(n) <- !larger.kt;\n\tif not (Stack.is_empty id_st) then\n\t larger := Stack.top id_st;\n done;\n\n ktime.(n) <- ktime.(n) + 1;\n\n Stack.push {kt = ktime.(n); id = x} id_st;\n\n if ktime.(n) < 1000000 && ktime.(n) > !ans then\n\tans:= ktime.(n);\n\n calc l (n+1) in\n\n ktime.(0) <- 1000000;\n Stack.push {kt=ktime.(0); id = List.hd psyline} id_st;\n calc (List.tl psyline) 1;;\n\nlet () =\n let n = read_int() in\n dynpro (List.rev (read_line [] n));\n if !ans < 1000000 then \n Printf.printf \"%d\\n\" !ans;;\n"}], "negative_code": [{"source_code": "let read_int () =\n Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\n\nlet rec read_line line = function\n | 0 -> line\n | x -> read_line (read_int()::line) (x-1);;\n\ntype psy_info = {id : int;\n\t\t kt : int};;\n\nlet ktime = Array.make 100000 0;;\nlet id_st = Stack.create ();;\nlet ans = ref 0;;\n\nlet dynpro psyline =\n let rec calc line n =\n match line with\n [] -> ()\n | x::l ->\n let larger = ref (Stack.top id_st) in\n while (not (Stack.is_empty id_st)) && (x > !larger.id) do\n\tlarger := Stack.pop id_st;\n\tif ktime.(n) < !larger.kt then\n\t ktime.(n) <- !larger.kt;\n\tif not (Stack.is_empty id_st) then\n\t larger := Stack.top id_st;\n done;\n\n ktime.(n) <- ktime.(n) + 1;\n\n Stack.push {kt = ktime.(n); id = x} id_st;\n\n if ktime.(n) > !ans then\n\tans:= ktime.(n);\n\n calc l (n+1) in\n\n ktime.(0) <- 1000000;\n Stack.push {kt=ktime.(0); id = List.hd psyline} id_st;\n calc (List.tl psyline) 1;;\n\nlet () =\n let n = read_int() in\n dynpro (List.rev (read_line [] n));\n if !ans < 1000000 then \n Printf.printf \"%d\\n\" !ans\n else\n Printf.printf \"%d\\n\" 0;;\n"}], "src_uid": "ff4a128ad18ccc846c44647cec5cf485"} {"nl": {"description": "Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?", "input_spec": "The first line contains the only integer n (0\u2009\u2264\u2009n\u2009\u2264\u200910100000). It is guaranteed that n doesn't contain any leading zeroes.", "output_spec": "Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.", "sample_inputs": ["0", "10", "991"], "sample_outputs": ["0", "1", "3"], "notes": "NoteIn the first sample the number already is one-digit \u2014 Herald can't cast a spell.The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.The third test contains number 991. As one casts a spell the following transformations take place: 991\u2009\u2192\u200919\u2009\u2192\u200910\u2009\u2192\u20091. After three transformations the number becomes one-digit."}, "positive_code": [{"source_code": "let i = ref 0;;\nlet t = ref 0;;\nexception End_of_line;;\ntry while true do\n\tlet r = input_byte stdin in\n\tif r = 10 then raise End_of_line\n\telse (i := (!i + (r - 48)); incr t)\ndone with _ -> ();;\n\nif !t = 1 then t := 0 else t := 1;;\n\nwhile !i mod 10 <> !i do\n\tlet m = ref (!i) in\n\t(i := 0;\n\twhile !m <> 0 do\n\t\ti := (!i + (!m mod 10));\n\t\tm := (!m / 10)\n\tdone;\n\tincr t)\ndone;;\n\nprint_int (!t);;\n"}], "negative_code": [{"source_code": "let i = ref 0;;\nlet t = ref 0;;\nexception End_of_line;;\ntry while true do\n\tlet r = input_byte stdin in\n\tif r = 10 then raise End_of_line\n\telse (i := (!i + r - 48); incr t)\ndone with _ -> ();;\n\nif !t = 1 then t := 0 else t := 1;;\n\nwhile !i / 10 <> 0 do\n\tlet m = ref (!i) in\n\t(i := 0;\n\twhile !m mod 10 <> 0 do\n\t\ti := (!i + (!m mod 10));\n\t\tm := (!m / 10)\n\tdone;\n\tincr t)\ndone;;\n\nprint_int (!t);;\n"}], "src_uid": "ddc9201725e30297a5fc83f4eed75fc9"} {"nl": {"description": "As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n\u2009-\u20091 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.The \u00abTwo Paths\u00bb company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).It is known that the profit, the \u00abTwo Paths\u00bb company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.", "input_spec": "The first line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200), where n is the amount of cities in the country. The following n\u2009-\u20091 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n).", "output_spec": "Output the maximum possible profit.", "sample_inputs": ["4\n1 2\n2 3\n3 4", "7\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7", "6\n1 2\n2 3\n2 4\n5 4\n6 4"], "sample_outputs": ["1", "0", "4"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let e = Array.make n [] in\n for i = 0 to n-2 do\n let x = read_int 0 - 1 in\n let y = read_int 0 - 1 in\n e.(x) <- (y,i)::e.(x);\n e.(y) <- (x,n-1+i)::e.(y)\n done;\n\n let dp = Array.make (2*(n-1)) (-1,-1) in\n let ans = ref 0 in\n let rec f u v i =\n if fst dp.(i) < 0 then (\n let rec go x y opt = function\n | [] ->\n x, max opt (x+y)\n | (w,j)::es ->\n if w = u then\n go x y opt es\n else\n let z, opt' = f v w j in\n let z = z+1 in\n if z > x then\n go z x (max opt opt') es\n else if z > y then\n go x z (max opt opt') es\n else\n go x y (max opt opt') es\n in\n dp.(i) <- go 0 0 0 e.(v)\n );\n dp.(i)\n in\n for x = 0 to n-1 do\n List.iter (fun (y,i) ->\n if i < n-1 then\n ans := (f x y i |> snd) * (f y x (n-1+i) |> snd) |> max !ans;\n ) e.(x)\n done;\n Printf.printf \"%d\\n\" !ans\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let e = Array.make n [] in\n for i = 0 to n-2 do\n let x = read_int 0 - 1 in\n let y = read_int 0 - 1 in\n e.(x) <- (y,i)::e.(x);\n e.(y) <- (x,n-1+i)::e.(y)\n done;\n\n let dp = Array.make (2*(n-1)) (-1,-1) in\n let ans = ref 0 in\n let rec f u v i =\n if fst dp.(i) < 0 then (\n let rec go x y opt = function\n | [] -> x, max opt (x+y)\n | (w,j)::es ->\n if w = u then\n go x y opt es\n else\n let z, opt' = f v w j in\n let z = z+1 in\n if z > x then\n go z y (max opt opt') es\n else if z > y then\n go x z (max opt opt') es\n else\n go x y opt es\n in\n dp.(i) <- go 0 0 0 e.(v)\n (*Printf.printf \"f %d %d %d %d,%d\\n\" u v i (fst dp.(i)) (snd dp.(i));*)\n );\n dp.(i)\n in\n for x = 0 to n-1 do\n List.iter (fun (y,i) ->\n if i < n-1 then\n ans := (f x y i |> snd) * (f y x (n-1+i) |> snd) |> max !ans;\n ) e.(x)\n done;\n Printf.printf \"%d\\n\" !ans\n"}], "src_uid": "b07668a66a5e50659233ba055a893bd4"} {"nl": {"description": "Initially Ildar has an empty array. He performs $$$n$$$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $$$[0, 2, 3]$$$ is $$$1$$$, while the mex of the multiset $$$[1, 2, 1]$$$ is $$$0$$$.More formally, on the step $$$m$$$, when Ildar already has an array $$$a_1, a_2, \\ldots, a_{m-1}$$$, he chooses some subset of indices $$$1 \\leq i_1 < i_2 < \\ldots < i_k < m$$$ (possibly, empty), where $$$0 \\leq k < m$$$, and appends the $$$mex(a_{i_1}, a_{i_2}, \\ldots a_{i_k})$$$ to the end of the array.After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $$$a_1, a_2, \\ldots, a_n$$$ the minimum step $$$t$$$ such that he has definitely made a mistake on at least one of the steps $$$1, 2, \\ldots, t$$$, or determine that he could have obtained this array without mistakes.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100\\,000$$$)\u00a0\u2014 the number of steps Ildar made. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the array Ildar obtained.", "output_spec": "If Ildar could have chosen the subsets on each step in such a way that the resulting array is $$$a_1, a_2, \\ldots, a_n$$$, print $$$-1$$$. Otherwise print a single integer $$$t$$$\u00a0\u2014 the smallest index of a step such that a mistake was made on at least one step among steps $$$1, 2, \\ldots, t$$$.", "sample_inputs": ["4\n0 1 2 1", "3\n1 0 1", "4\n0 1 2 239"], "sample_outputs": ["-1", "1", "4"], "notes": "NoteIn the first example it is possible that Ildar made no mistakes. Here is the process he could have followed. $$$1$$$-st step. The initial array is empty. He can choose an empty subset and obtain $$$0$$$, because the mex of an empty set is $$$0$$$. Appending this value to the end he gets the array $$$[0]$$$. $$$2$$$-nd step. The current array is $$$[0]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1]$$$. $$$3$$$-rd step. The current array is $$$[0,1]$$$. He can choose a subset $$$[0,1]$$$ and obtain an integer $$$2$$$, because $$$mex(0,1) = 2$$$. Appending this value to the end he gets the array $$$[0,1,2]$$$. $$$4$$$-th step. The current array is $$$[0,1,2]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1,2,1]$$$. Thus, he can get the array without mistakes, so the answer is $$$-1$$$.In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from $$$0$$$.In the third example he could have obtained $$$[0, 1, 2]$$$ without mistakes, but $$$239$$$ is definitely wrong."}, "positive_code": [{"source_code": "let split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet rec sol min i = function\n | [] -> print_int (-1)\n | h::t -> let x = int_of_string h in\n if x > min then print_int i\n else sol (max (x+1) min) (i+1) t\n;;\n\nlet _n = Scanf.sscanf (read_line ()) \"%i\" (fun n -> n) in\nlet a = split_on_char ' ' (read_line ()) in\nsol 0 1 a;\nprint_newline ()\n"}], "negative_code": [], "src_uid": "e17427897fd5147c601204cb1c48b143"} {"nl": {"description": "You are given a positive integer $$$n$$$ greater or equal to $$$2$$$. For every pair of integers $$$a$$$ and $$$b$$$ ($$$2 \\le |a|, |b| \\le n$$$), you can transform $$$a$$$ into $$$b$$$ if and only if there exists an integer $$$x$$$ such that $$$1 < |x|$$$ and ($$$a \\cdot x = b$$$ or $$$b \\cdot x = a$$$), where $$$|x|$$$ denotes the absolute value of $$$x$$$.After such a transformation, your score increases by $$$|x|$$$ points and you are not allowed to transform $$$a$$$ into $$$b$$$ nor $$$b$$$ into $$$a$$$ anymore.Initially, you have a score of $$$0$$$. You can start at any integer and transform it as many times as you like. What is the maximum score you can achieve?", "input_spec": "A single line contains a single integer $$$n$$$ ($$$2 \\le n \\le 100\\,000$$$)\u00a0\u2014 the given integer described above.", "output_spec": "Print an only integer\u00a0\u2014 the maximum score that can be achieved with the transformations. If it is not possible to perform even a single transformation for all possible starting integers, print $$$0$$$.", "sample_inputs": ["4", "6", "2"], "sample_outputs": ["8", "28", "0"], "notes": "NoteIn the first example, the transformations are $$$2 \\rightarrow 4 \\rightarrow (-2) \\rightarrow (-4) \\rightarrow 2$$$.In the third example, it is impossible to perform even a single transformation."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet factors n =\n let m,r = ref n,ref [] in\n rep 2L (n/2L) (fun i ->\n if !m mod i = 0L then (\n let k = ref 0L in\n while !m mod i = 0L do\n k += 1L; m /= i;\n done;\n r := (i,!k) :: !r));\n if !m>1L then (!m,1L)::!r else !r\nlet () =\n let n = get_i64 0 in\n repm 2L n 0L (fun u i ->\n let k,s = ref 2L,ref 0L in\n while i * !k <= n do\n s += !k; k += 1L\n done; `Ok (u + !s)\n )\n |> ( * ) 4L |> printf \"%Ld\\n\"\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "03907ca0d34a2c80942ed3968b2c067d"} {"nl": {"description": "Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of the array. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009105\u2009\u2264\u2009ai\u2009\u2264\u2009105) \u2014 the elements of the array.", "output_spec": "Print a single integer \u2014 the minimum number of seconds needed to make all elements of the array equal to zero.", "sample_inputs": ["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"], "sample_outputs": ["1", "2", "4"], "notes": "NoteIn the first example you can add \u2009-\u20091 to all non-zero elements in one second and make them equal to zero.In the second example you can add \u2009-\u20092 on the first second, then the array becomes equal to [0,\u20090,\u2009\u2009-\u20093]. On the second second you can add 3 to the third (the only non-zero) element."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n\n let h = Hashtbl.create 10 in\n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n for i=0 to n-1 do increment a.(i) done;\n\n let answer = (Hashtbl.length h) - (if Hashtbl.mem h 0 then 1 else 0) in\n\n printf \"%d\\n\" answer\n \n"}], "negative_code": [], "src_uid": "0593f79604377dcfa98d2b69840ec0a6"} {"nl": {"description": "You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears: Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one; Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows: Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$; then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$; then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$; then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$; and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.", "sample_inputs": ["6\n1\n2\n3\n4\n5\n6"], "sample_outputs": ["1 \n1 2 \n2 1 3 \n3 1 2 4 \n2 4 1 3 5 \n3 4 1 5 2 6"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet comp a b = \n let (da, ta) = a in\n let (db, tb) = b in\n \n if ta = tb then\n da - db\n else\n tb - ta\nin\n\nlet nbTests = read () in\nfor iTest = 1 to nbTests do\n let taille = read () in\n \n let tableau = Array.make taille 0 in\n \n let rec ajoute_inters d t l =\n if t = 0 then\n l\n else if t = 1 then\n (d, t) :: l\n else\n let tg = (t - 1) / 2 in\n let td = t - tg - 1 in\n (d, t) :: ajoute_inters d tg (ajoute_inters (d + tg + 1) td l)\n in\n \n let inters = List.sort comp (ajoute_inters 0 taille []) in\n \n List.iteri (fun i a -> let (da, ta) = a in tableau.(da + ((ta - 1) / 2)) <- i + 1; ()) inters;\n \n for i = 0 to (taille - 1) do\n print_int tableau.(i);\n print_string \" \"\n done;\n print_newline ()\ndone;"}], "negative_code": [], "src_uid": "25fbe21a449c1ab3eb4bdd95a171d093"} {"nl": {"description": "Petya got an array $$$a$$$ of numbers from $$$1$$$ to $$$n$$$, where $$$a[i]=i$$$.He performed $$$n$$$ operations sequentially. In the end, he received a new state of the $$$a$$$ array.At the $$$i$$$-th operation, Petya chose the first $$$i$$$ elements of the array and cyclically shifted them to the right an arbitrary number of times (elements with indexes $$$i+1$$$ and more remain in their places). One cyclic shift to the right is such a transformation that the array $$$a=[a_1, a_2, \\dots, a_n]$$$ becomes equal to the array $$$a = [a_i, a_1, a_2, \\dots, a_{i-2}, a_{i-1}, a_{i+1}, a_{i+2}, \\dots, a_n]$$$.For example, if $$$a = [5,4,2,1,3]$$$ and $$$i=3$$$ (that is, this is the third operation), then as a result of this operation, he could get any of these three arrays: $$$a = [5,4,2,1,3]$$$ (makes $$$0$$$ cyclic shifts, or any number that is divisible by $$$3$$$); $$$a = [2,5,4,1,3]$$$ (makes $$$1$$$ cyclic shift, or any number that has a remainder of $$$1$$$ when divided by $$$3$$$); $$$a = [4,2,5,1,3]$$$ (makes $$$2$$$ cyclic shifts, or any number that has a remainder of $$$2$$$ when divided by $$$3$$$). Let's look at an example. Let $$$n=6$$$, i.e. initially $$$a=[1,2,3,4,5,6]$$$. A possible scenario is described below. $$$i=1$$$: no matter how many cyclic shifts Petya makes, the array $$$a$$$ does not change. $$$i=2$$$: let's say Petya decided to make a $$$1$$$ cyclic shift, then the array will look like $$$a = [\\textbf{2}, \\textbf{1}, 3, 4, 5, 6]$$$. $$$i=3$$$: let's say Petya decided to make $$$1$$$ cyclic shift, then the array will look like $$$a = [\\textbf{3}, \\textbf{2}, \\textbf{1}, 4, 5, 6]$$$. $$$i=4$$$: let's say Petya decided to make $$$2$$$ cyclic shifts, the original array will look like $$$a = [\\textbf{1}, \\textbf{4}, \\textbf{3}, \\textbf{2}, 5, 6]$$$. $$$i=5$$$: let's say Petya decided to make $$$0$$$ cyclic shifts, then the array won't change. $$$i=6$$$: let's say Petya decided to make $$$4$$$ cyclic shifts, the array will look like $$$a = [\\textbf{3}, \\textbf{2}, \\textbf{5}, \\textbf{6}, \\textbf{1}, \\textbf{4}]$$$. You are given a final array state $$$a$$$ after all $$$n$$$ operations. Determine if there is a way to perform the operation that produces this result. In this case, if an answer exists, print the numbers of cyclical shifts that occurred during each of the $$$n$$$ operations.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 500$$$)\u00a0\u2014 the number of test cases in the test. The descriptions of the test cases follow. The first line of the description of each test case contains one integer $$$n$$$ ($$$2 \\le n \\le 2\\cdot10^3$$$)\u00a0\u2014 the length of the array $$$a$$$. The next line contains the final state of the array $$$a$$$: $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$) are written. All $$$a_i$$$ are distinct. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2\\cdot10^3$$$.", "output_spec": "For each test case, print the answer on a separate line. Print -1 if the given final value $$$a$$$ cannot be obtained by performing an arbitrary number of cyclic shifts on each operation. Otherwise, print $$$n$$$ non-negative integers $$$d_1, d_2, \\dots, d_n$$$ ($$$d_i \\ge 0$$$), where $$$d_i$$$ means that during the $$$i$$$-th operation the first $$$i$$$ elements of the array were cyclic shifted to the right $$$d_i$$$ times. If there are several possible answers, print the one where the total number of shifts is minimal (that is, the sum of $$$d_i$$$ values is the smallest). If there are several such answers, print any of them.", "sample_inputs": ["3\n\n6\n\n3 2 5 6 1 4\n\n3\n\n3 1 2\n\n8\n\n5 8 1 3 2 6 4 7"], "sample_outputs": ["0 1 1 2 0 4 \n0 0 1 \n0 1 2 0 2 5 6 2"], "notes": "NoteThe first test case matches the example from the statement.The second set of input data is simple. Note that the answer $$$[3, 2, 1]$$$ also gives the same permutation, but since the total number of shifts $$$3+2+1$$$ is greater than $$$0+0+1$$$, this answer is not correct."}, "positive_code": [{"source_code": "let plus a b n = (a + b + n ) mod n ;;\r\n\r\n(*pour x entre 1 et n-2 ; donne le rep.(x)*)\r\nlet pourMil len t x = let a = t.(x) in let b = t.(x+1) in\r\n let count = ref 0 in\r\n for i = x+2 to len-1 do\r\n if (aa && t.(i)b && (t.(i)>a ||t.(i)\n Printf.printf \"%f\\n\" (l /. (q /. p +. 1.)))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet () = \n let l = float_of_int (read_int ()) in\n let p = float_of_int (read_int ()) in\n let q = float_of_int (read_int ()) in\n let res = p *. (l /. (p +. q)) in\n printf \"%f\\n%!\" res\n\n \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_float () = bscanf Scanning.stdib \" %f \" (fun x -> x)\n\nlet () = \n let l = read_float () in\n let p = read_float () in\n let q = read_float () in\n\n let answer = (p *. l) /. (p +. q) in\n\n printf \"%.5f\\n\" answer\n \n"}], "negative_code": [], "src_uid": "6421a81f85a53a0c8c63fbc32750f77f"} {"nl": {"description": "When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions: There is no vertex that has more than two incident edges painted the same color. For any two vertexes that have incident edges painted the same color (say, c), the path between them consists of the edges of the color c. Not all tree paintings are equally good for Adam. Let's consider the path from some vertex to the root. Let's call the number of distinct colors on this path the cost of the vertex. The cost of the tree's coloring will be the maximum cost among all the vertexes. Help Adam determine the minimum possible cost of painting the tree. Initially, Adam's tree consists of a single vertex that has number one and is the root. In one move Adam adds a new vertex to the already existing one, the new vertex gets the number equal to the minimum positive available integer. After each operation you need to calculate the minimum cost of coloring the resulting tree.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of times a new vertex is added. The second line contains n numbers pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009i) \u2014 the numbers of the vertexes to which we add another vertex. ", "output_spec": "Print n integers \u2014 the minimum costs of the tree painting after each addition. ", "sample_inputs": ["11\n1 1 1 3 4 4 7 3 7 6 6"], "sample_outputs": ["1 1 1 1 1 2 2 2 2 2 3"], "notes": "NoteThe figure below shows one of the possible variants to paint a tree from the sample at the last moment. The cost of the vertexes with numbers 11 and 12 equals 3."}, "positive_code": [{"source_code": "let (|>) x f = f x\nlet (@@) f x = f x\n\ntype vertex = \n { mutable s : int * bool * int;\n p : vertex option }\n\nlet () =\n let vertex p = { s = -1, false, 1; p } in \n let vertex p = \n let rec update =\n function\n | { p = None } -> () \n | { s = _, _, c; p = Some ({ s = mcc, mcf, pc } as p) } ->\n let sgn a = if a = 0 then 0 else a / abs a in\n match sgn (c - mcc), mcf with\n | 1, _ ->\n p.s <- c, false, c;\n if pc < c then update p\n | 0, false ->\n p.s <- mcc, true, c + 1;\n update p\n | _ -> ()\n in\n let v = vertex p in\n update v;\n v \n in\n let n = read_int () in\n let open Array in\n let vs = make (n + 1) (vertex None) in\n init n (fun _ -> Scanf.scanf \" %d\" @@ fun x -> x - 1)\n |> iteri\n (fun i pi ->\n vs.(i + 1) <- vertex (Some vs.(pi));\n let mcc, _, _ = vs.(0).s in\n print_int mcc;\n if i < n - 1 then print_char ' ');\n print_newline () \n"}, {"source_code": "let (|>) x f = f x\nlet (@@) f x = f x\n\nlet () = \n let add, get, iter =\n let n = read_int () in\n let mk v = Array.make (n + 1) v in\n let p, mcc, mcf, cc = mk ~-1, mk ~-1, mk false, mk 1 in\n let set i c inc =\n let set a v = Array.set a i v in\n let r = cc.(i) in\n if inc then (set mcc c; set mcf false; set cc c)\n else (set mcf true; set cc (succ c));\n r < cc.(i)\n in\n let rec update i =\n let pi, c = p.(i), cc.(i) in\n let set = set pi c in\n let sgn a = if a = 0 then 0 else a / abs a in \n if (match pi, lazy (sgn (c - mcc.(pi)), mcf.(pi)) with\n | -1, _ -> false\n | _, lazy (1, _) -> set true\n | _, lazy (0, false) -> set false\n | _ -> false)\n then update pi\n in\n let k = ref 0 in\n (fun i -> incr k; p.(!k) <- i - 1; update !k), \n (fun () -> mcc.(0)),\n fun f -> for i = 1 to n do f (i < n) done \n in \n iter @@ fun s ->\n Scanf.scanf \" %d\" add;\n print_int (get ());\n print_char (if s then ' ' else '\\n')\n"}, {"source_code": "let (|>) x f = f x\nlet (@@) f x = f x\n\n\nlet (%) f g x = f (g x)\nlet (%>) f g x = g (f x)\n\nmodule Max : sig\n type t\n val mk : int -> t\n val cmp : int -> t -> [`Lt | `Gt | `Eq]\n val int : t -> int\nend = struct\n type t = int\n let mk v = v\n let cmp a =\n function\n | b when a < b -> `Lt\n | b when a = b -> `Eq\n | _ -> `Gt\n let int m = m \nend\n\n\ntype vertex = \n { mutable s : Max.t * bool * int;\n p : vertex option }\n\n\nlet () =\n let vertex p = { s = Max.mk ~-1, false, 1; p } in \n let vertex p = \n let rec update =\n function\n | { p = None } -> () \n | { s = _, _, c; p = Some ({ s = mcc, mcf, pc } as p) } ->\n match Max.cmp c mcc, mcf with\n | `Gt, _ ->\n p.s <- Max.mk c, false, c;\n if pc < c then update p\n | `Eq, false ->\n p.s <- mcc, true, c + 1;\n update p\n | `Eq, true | `Lt, _ -> ()\n in\n let v = vertex p in\n update v;\n v \n in\n let n = read_int () in\n let open Array in\n let vs = make (n + 1) (vertex None) in\n init n (fun _ -> Scanf.scanf \" %d\" @@ fun x -> x - 1)\n |> mapi (fun i pi ->\n vs.(i + 1) <- vertex (Some vs.(pi));\n let mcc, _, _ = vs.(0).s in Max.int mcc)\n |> map string_of_int\n |> to_list\n |> String.concat \" \"\n |> print_endline \n"}, {"source_code": "let (|>) x f = f x\nlet (@@) f x = f x\n\n\nlet (%) f g x = f (g x)\nlet (%>) f g x = g (f x)\n\nmodule List = struct\n include List\n let map f =\n let rec loop acc =\n function\n | [] -> rev acc\n | x :: xs -> loop (f x :: acc) xs\n in\n loop []\n let mapi f =\n map (let c = ref ~-1 in fun e -> incr c; f !c e) \nend\n\nmodule Max : sig\n type t\n val mk : int -> t\n val cmp : int -> t -> [`Lt | `Gt | `Eq]\n val int : t -> int\nend = struct\n type t = int\n let mk v = v\n let cmp a =\n function\n | b when a < b -> `Lt\n | b when a = b -> `Eq\n | _ -> `Gt\n let int m = m \nend\n\n\ntype vertex = \n { mutable s : Max.t * bool * int;\n p : vertex option }\n\n\nlet () =\n let vertex p = { s = Max.mk ~-1, false, 1; p } in \n let vertex p = \n let rec update =\n function\n | { p = None } -> () \n | { s = _, _, c; p = Some ({ s = mcc, mcf, pc } as p) } ->\n match Max.cmp c mcc, mcf with\n | `Gt, _ ->\n p.s <- Max.mk c, false, c;\n if pc < c then update p\n | `Eq, false ->\n p.s <- mcc, true, c + 1;\n update p\n | `Eq, true | `Lt, _ -> ()\n in\n let v = vertex p in\n update v;\n v \n in\n let n = read_int () in\n let vs = Array.make (n + 1) (vertex None) in\n Array.init n (fun _ -> Scanf.scanf \" %d\" @@ fun x -> x - 1)\n |> Array.mapi (fun i pi ->\n vs.(i + 1) <- vertex (Some vs.(pi));\n let { s = mcc, _, _ } = vs.(0) in Max.int mcc)\n |> Array.map string_of_int\n |> Array.to_list\n |> String.concat \" \"\n |> print_endline \n"}, {"source_code": "let (|>) x f = f x\nlet (@@) f x = f x\n\nlet () = \n let add, get, iter =\n let n = read_int () in\n let mk v = Array.make (n + 1) v in\n let p, mcc, cc = mk ~-1, mk ~-1, mk 1 in\n let rec update i =\n let pi, c = p.(i), cc.(i) in\n if (match lazy (c - mcc.(pi), cc.(pi) > mcc.(pi), cc.(pi)) with\n | _ when pi = -1 -> false\n | lazy (d, _, pc) when d > 0 ->\n mcc.(pi) <- c;\n cc.(pi) <- c;\n pc < c\n | lazy (0, false, _) ->\n cc.(pi) <- c + 1;\n true\n | _ -> false)\n then update pi\n in\n let k = ref 0 in\n (fun i -> incr k; p.(!k) <- i - 1; update !k), \n (fun () -> mcc.(0)),\n fun f -> for i = 1 to n do f (i < n) done \n in \n iter @@ fun s ->\n Scanf.scanf \" %d\" add;\n print_int (get ());\n print_char (if s then ' ' else '\\n')\n"}], "negative_code": [{"source_code": "let (|>) x f = f x\nlet (@@) f x = f x\n\n\nlet (%) f g x = f (g x)\nlet (%>) f g x = g (f x)\n\n\ntype vertex = \n { mutable mcc : int;\n mutable c : int;\n p : vertex option }\n\n\nlet () =\n let n = read_int () in\n let vs = Array.make (n + 1) None in\n let vertex p = \n let rec update =\n let cmp a =\n function\n | b when a < b -> `Lt\n | b when a = b -> `Eq\n | _ -> `Gt\n in\n function\n | { p = None } -> () \n | { c; p = Some p } ->\n match cmp c p.mcc with\n | `Gt -> p.mcc <- c\n | `Eq -> p.c <- p.c + 1; update p\n | `Lt -> ()\n in\n let v = { mcc = -1; c = 0; p } in\n update v;\n v \n in\n let r = { mcc = -1; c = 0; p = None } in\n vs.(0) <- Some r;\n read_line ()\n |> Str.(split (regexp_string \" \"))\n |> List.mapi (fun i ->\n pred % int_of_string\n %> fun pi ->\n vs.(i + 1) <- Some (vertex vs.(pi));\n r.mcc + 1)\n |> List.map string_of_int\n |> String.concat \" \"\n |> print_endline \n"}, {"source_code": "let (|>) x f = f x\nlet (@@) f x = f x\n\ntype vertex = \n { mutable s : (int * bool) * int;\n p : vertex option }\n\nlet () =\n let vertex p = { s = (-1, false), 1; p } in \n let vertex p = \n let rec update =\n function\n | { p = None } -> () \n | { s = _, c; p = Some ({ s = (mcc, mcf), pc } as p) } ->\n if c > mcc then (\n p.s <- (c, false), c;\n if pc < c then update p\n ) else if not mcf then (\n p.s <- (mcc, true), c + 1;\n update p\n )\n in\n let v = vertex p in\n update v;\n v \n in\n let n = read_int () in\n let open Array in\n let vs = make (n + 1) (vertex None) in\n init n (fun _ -> Scanf.scanf \" %d\" @@ fun x -> x - 1)\n |> iteri\n (fun i pi ->\n vs.(i + 1) <- vertex (Some vs.(pi));\n let (mcc, _), _ = vs.(0).s in\n print_int mcc;\n if i < n - 1 then print_char ' ');\n print_newline () \n"}], "src_uid": "dd47f47922a5457f89391beea749242b"} {"nl": {"description": "$$$ \\def\\myred#1{\\color{red}{\\underline{\\bf{#1}}}} \\def\\myblue#1{\\color{blue}{\\overline{\\bf{#1}}}} $$$ $$$\\def\\RED{\\myred{Red}} \\def\\BLUE{\\myblue{Blue}}$$$You are given a sequence of $$$n$$$ non-negative integers $$$a_1, a_2, \\ldots, a_n$$$. Initially, all the elements of the sequence are unpainted. You can paint each number $$$\\RED$$$ or $$$\\BLUE$$$ (but not both), or leave it unpainted. For a color $$$c$$$, $$$\\text{Count}(c)$$$ is the number of elements in the sequence painted with that color and $$$\\text{Sum}(c)$$$ is the sum of the elements in the sequence painted with that color.For example, if the given sequence is $$$[2, 8, 6, 3, 1]$$$ and it is painted this way: $$$[\\myblue{2}, 8, \\myred{6}, \\myblue{3}, 1]$$$ (where $$$6$$$ is painted red, $$$2$$$ and $$$3$$$ are painted blue, $$$1$$$ and $$$8$$$ are unpainted) then $$$\\text{Sum}(\\RED)=6$$$, $$$\\text{Sum}(\\BLUE)=2+3=5$$$, $$$\\text{Count}(\\RED)=1$$$, and $$$\\text{Count}(\\BLUE)=2$$$.Determine if it is possible to paint the sequence so that $$$\\text{Sum}(\\RED) > \\text{Sum}(\\BLUE)$$$ and $$$\\text{Count}(\\RED) < \\text{Count}(\\BLUE)$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3\\le n\\le 2\\cdot 10^5$$$)\u00a0\u2014 the length of the given sequence. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$0\\le a_i\\le 10^9$$$)\u00a0\u2014 the given sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case, print YES if it is possible to paint the given sequence satisfying the above requirements, and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).", "sample_inputs": ["4\n3\n1 2 3\n5\n2 8 6 3 1\n4\n3 5 4 2\n5\n1000000000 1000000000 1000000000 1000000000 1000000000"], "sample_outputs": ["NO\nYES\nNO\nNO"], "notes": "NoteIn the first test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\\myblue{1},\\myblue{2},\\myred{3}]$$$ (where $$$3$$$ is painted red, $$$1$$$ and $$$2$$$ are painted blue) then $$$\\text{Count}(\\RED)=1 < \\text{Count}(\\BLUE)=2$$$, but $$$\\text{Sum}(\\RED)=3 \\ngtr \\text{Sum}(\\BLUE)=3$$$. So, this is not a possible way to paint the sequence.In the second test case, a possible way to paint the sequence is described in the statement. We can see that $$$\\text{Sum}(\\RED)=6 > \\text{Sum}(\\BLUE)=5$$$ and $$$\\text{Count}(\\RED)=1 < \\text{Count}(\\BLUE)=2$$$.In the third test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\\myred{3},\\myred{5},\\myblue{4}, \\myblue{2}]$$$ (where $$$3$$$ and $$$5$$$ are painted red, $$$4$$$ and $$$2$$$ are painted blue) then $$$\\text{Sum}(\\RED) = 8 > \\text{Sum}(\\BLUE) = 6$$$ but $$$\\text{Count}(\\RED) = 2 \\nless \\text{Count}(\\BLUE) = 2$$$. So, this is not a possible way to paint the sequence.In the fourth test case, it can be proven that there is no possible way to paint the sequence satisfying sum and count constraints."}, "positive_code": [{"source_code": "(* can paint each element Red, Blue, unpainted\r\n Count(c) == number painted with color\r\n Sum(c) == sum of elemented painted with color\r\n \r\n Is it possible to paint so Sum(R) > Sum(B) but Count(R) < Count(B)\r\n the minimum case would be (since we using ints):\r\n Sum(R) >= Sum(B)+1 and Count(R)<=Count(B)+1\r\n ie r1+r2+...+r(n-1) >= b1 + b2 + ... +bn+1\r\n \r\n for 1 2 3 , it's not possible\r\n ie if we pick max for r and then rest for b,\r\n we get S(R)=3 and S(B)=3\r\n \r\n best tactic would be to pick the maximum\r\n elements for r and minimum elements for b\r\n \r\n to exemplify the difference, since all rx > by,\r\n we should select the maximum count for both groups, ie\r\n floor((n+1/2)) items for b and floor((n-1)/2) items for r\r\n \r\n for even n, n/2 items for b, n/2-1 items for r, missing n/2 idx\r\n -> up to n/2-1 idx for b, miss n/2 and then r\r\n for odd n, (n+1)/2 items for b and (n-1)/2 items for a\r\n -> up to (n-1)/2 idx for b, then n-1 for r\r\n*)\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\n(* Fast quick sort *)\r\nlet rec partition pivot left right = function \r\n| [] -> left, right\r\n| x::xs ->\r\n if (x<=pivot) then partition pivot (x::left) right xs \r\n else partition pivot left (x::right) xs \r\n;;\r\nlet rec quickSort sorted = function\r\n| [] -> sorted\r\n| [pivot] -> pivot::sorted\r\n| pivot::xs ->\r\n let left, right = partition pivot [] [] xs in \r\n quickSort (pivot::(quickSort sorted right)) left\r\n;;\r\n\r\nlet rec read_arr = function\r\n| 0 -> []\r\n| n -> \r\n let read_float () = Scanf.scanf \" %f\" (fun x-> x) in \r\n read_float () :: read_arr (n-1)\r\n;;\r\n(* \r\n 1 2 3\r\n (n-1)/2 = 1, so 0,1 idxs for b and 2 for r\r\n 1 2\r\n (n-1)/2 = 1 so 0 idxs for b and none for r\r\n 1 2 3 4 \r\n n/2 = 2 so 0,1,2 idxs for b and 3 for r\r\n*)\r\nlet rec get_r_b r b n = function \r\n| _, [] -> r, b\r\n| idx, x::xs ->\r\n if (n mod 2 == 0) then begin\r\n if (idx <= n/2-1) then get_r_b r (x+.b) n (idx+1, xs)\r\n else if (idx == n/2) then get_r_b r b n (idx+1, xs)\r\n else get_r_b (x+.r) b n (idx+1, xs) \r\n end \r\n else begin\r\n if (idx <= (n-1)/2) then get_r_b r (x+.b) n (idx+1, xs)\r\n else get_r_b (x+.r) b n (idx+1, xs) \r\n end\r\n;;\r\n\r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in \r\n (* let arr = quickSort [] (read_arr n) in *)\r\n let arr = List.fast_sort compare (read_arr n) in\r\n (* List.iter (fun x-> Printf.printf \" %f\" x) arr; *)\r\n let r, b = get_r_b 0.0 0.0 n (0, arr) in \r\n (* Printf.printf \"\\n%f %f\" r b; *)\r\n if (r>=b+.1.0) then Printf.printf \"YES\\n\"\r\n else Printf.printf \"NO\\n\"\r\n;;\r\n\r\nlet rec iter_cases = function \r\n| 0 -> 0\r\n| n -> \r\n run_case ();\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t=read_int () in \r\niter_cases t;;\r\n\r\n\r\n\r\n\r\n\r\n"}], "negative_code": [{"source_code": "(* can paint each element Red, Blue, unpainted\r\n Count(c) == number painted with color\r\n Sum(c) == sum of elemented painted with color\r\n \r\n Is it possible to paint so Sum(R) > Sum(B) but Count(R) < Count(B)\r\n the minimum case would be (since we using ints):\r\n Sum(R) >= Sum(B)+1 and Count(R)<=Count(B)+1\r\n ie r1+r2+...+r(n-1) >= b1 + b2 + ... +bn+1\r\n \r\n for 1 2 3 , it's not possible\r\n ie if we pick max for r and then rest for b,\r\n we get S(R)=3 and S(B)=3\r\n \r\n best tactic would be to pick the maximum\r\n elements for r and minimum elements for b\r\n \r\n to exemplify the difference, since all rx > by,\r\n we should select the maximum count for both groups, ie\r\n floor((n+1/2)) items for b and floor((n-1)/2) items for r\r\n \r\n for even n, n/2 items for b, n/2-1 items for r, missing n/2 idx\r\n -> up to n/2-1 idx for b, miss n/2 and then r\r\n for odd n, (n+1)/2 items for b and (n-1)/2 items for a\r\n -> up to (n-1)/2 idx for b, then n-1 for r\r\n*)\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\n(* Fast quick sort *)\r\nlet rec partition pivot left right = function \r\n| [] -> left, right\r\n| x::xs ->\r\n if (x<=pivot) then partition pivot (x::left) right xs \r\n else partition pivot left (x::right) xs \r\n;;\r\nlet rec quickSort sorted = function\r\n| [] -> sorted\r\n| [pivot] -> pivot::sorted\r\n| pivot::xs ->\r\n let left, right = partition pivot [] [] xs in \r\n quickSort (pivot::(quickSort sorted right)) left\r\n;;\r\n\r\nlet rec read_arr = function\r\n| 0 -> []\r\n| n -> \r\n let read_float () = Scanf.scanf \" %f\" (fun x-> x) in \r\n read_float () :: read_arr (n-1)\r\n;;\r\n(* \r\n 1 2 3\r\n (n-1)/2 = 1, so 0,1 idxs for b and 2 for r\r\n 1 2\r\n (n-1)/2 = 1 so 0 idxs for b and none for r\r\n 1 2 3 4 \r\n n/2 = 2 so 0,1,2 idxs for b and 3 for r\r\n*)\r\nlet rec get_r_b r b n = function \r\n| _, [] -> r, b\r\n| idx, x::xs ->\r\n if (n mod 2 == 0) then begin\r\n if (idx <= n/2-1) then get_r_b r (x+.b) n (idx+1, xs)\r\n else if (idx == n/2) then get_r_b r b n (idx+1, xs)\r\n else get_r_b (x+.r) b n (idx+1, xs) \r\n end \r\n else begin\r\n if (idx <= (n-1)/2) then get_r_b r (x+.b) n (idx+1, xs)\r\n else get_r_b (x+.r) b n (idx+1, xs) \r\n end\r\n;;\r\n\r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in \r\n (* let arr = quickSort [] (read_arr n) in *)\r\n let arr = List.sort (fun x y -> ~- (compare x y)) (read_arr n) in\r\n (* List.iter (fun x-> Printf.printf \" %f\" x) arr; *)\r\n let r, b = get_r_b 0.0 0.0 n (0, arr) in \r\n (* Printf.printf \"\\n%f %f\" r b; *)\r\n if (r>=b+.1.0) then Printf.printf \"YES\\n\"\r\n else Printf.printf \"NO\\n\"\r\n;;\r\n\r\nlet rec iter_cases = function \r\n| 0 -> 0\r\n| n -> \r\n run_case ();\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t=read_int () in \r\niter_cases t;;\r\n\r\n\r\n\r\n\r\n\r\n"}, {"source_code": "(* can paint each element Red, Blue, unpainted\r\n Count(c) == number painted with color\r\n Sum(c) == sum of elemented painted with color\r\n \r\n Is it possible to paint so Sum(R) > Sum(B) but Count(R) < Count(B)\r\n the minimum case would be (since we using ints):\r\n Sum(R) >= Sum(B)+1 and Count(R)<=Count(B)+1\r\n ie r1+r2+...+r(n-1) >= b1 + b2 + ... +bn+1\r\n \r\n for 1 2 3 , it's not possible\r\n ie if we pick max for r and then rest for b,\r\n we get S(R)=3 and S(B)=3\r\n \r\n best tactic would be to pick the maximum\r\n elements for r and minimum elements for b\r\n \r\n to exemplify the difference, since all rx > by,\r\n we should select the maximum count for both groups, ie\r\n floor((n+1/2)) items for b and floor((n-1)/2) items for r\r\n \r\n for even n, n/2 items for b, n/2-1 items for r, missing n/2 idx\r\n -> up to n/2-1 idx for b, miss n/2 and then r\r\n for odd n, (n+1)/2 items for b and (n-1)/2 items for a\r\n -> up to (n-1)/2 idx for b, then n-1 for r\r\n*)\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\n(* Fast quick sort *)\r\nlet rec partition pivot left right = function \r\n| [] -> left, right\r\n| x::xs ->\r\n if (x<=pivot) then partition pivot (x::left) right xs \r\n else partition pivot left (x::right) xs \r\n;;\r\nlet rec quickSort sorted = function\r\n| [] -> sorted\r\n| [pivot] -> pivot::sorted\r\n| pivot::xs ->\r\n let left, right = partition pivot [] [] xs in \r\n quickSort (pivot::(quickSort sorted right)) left\r\n;;\r\n\r\nlet rec read_arr = function\r\n| 0 -> []\r\n| n -> \r\n let read_float () = Scanf.scanf \" %f\" (fun x-> x) in \r\n read_float () :: read_arr (n-1)\r\n;;\r\n(* \r\n 1 2 3\r\n (n-1)/2 = 1, so 0,1 idxs for b and 2 for r\r\n 1 2\r\n (n-1)/2 = 1 so 0 idxs for b and none for r\r\n 1 2 3 4 \r\n n/2 = 2 so 0,1,2 idxs for b and 3 for r\r\n*)\r\nlet rec get_r_b r b n = function \r\n| _, [] -> r, b\r\n| idx, x::xs ->\r\n if (n mod 2 == 0) then begin\r\n if (idx <= n/2-1) then get_r_b r (x+.b) n (idx+1, xs)\r\n else if (idx == n/2) then get_r_b r b n (idx+1, xs)\r\n else get_r_b (x+.r) b n (idx+1, xs) \r\n end \r\n else begin\r\n if (idx <= (n-1)/2) then get_r_b r (x+.b) n (idx+1, xs)\r\n else get_r_b (x+.r) b n (idx+1, xs) \r\n end\r\n;;\r\n\r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in \r\n let arr = quickSort [] (read_arr n) in\r\n(* List.iter (fun x-> Printf.printf \" %f\" x) arr;*)\r\n let r, b = get_r_b 0.0 0.0 n (0, arr) in \r\n Printf.printf \"\\n%f %f\" r b;\r\n if (r>=b+.1.0) then Printf.printf \"YES\\n\"\r\n else Printf.printf \"NO\\n\"\r\n;;\r\n\r\nlet rec iter_cases = function \r\n| 0 -> 0\r\n| n -> \r\n run_case ();\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t=read_int () in \r\niter_cases t;;\r\n\r\n\r\n\r\n\r\n\r\n"}, {"source_code": "(* can paint each element Red, Blue, unpainted\r\n Count(c) == number painted with color\r\n Sum(c) == sum of elemented painted with color\r\n \r\n Is it possible to paint so Sum(R) > Sum(B) but Count(R) < Count(B)\r\n the minimum case would be (since we using ints):\r\n Sum(R) >= Sum(B)+1 and Count(R)<=Count(B)+1\r\n ie r1+r2+...+r(n-1) >= b1 + b2 + ... +bn+1\r\n \r\n for 1 2 3 , it's not possible\r\n ie if we pick max for r and then rest for b,\r\n we get S(R)=3 and S(B)=3\r\n \r\n best tactic would be to pick the maximum\r\n elements for r and minimum elements for b\r\n \r\n to exemplify the difference, since all rx > by,\r\n we should select the maximum count for both groups, ie\r\n floor((n+1/2)) items for b and floor((n-1)/2) items for r\r\n \r\n*)\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\n(* Fast quick sort *)\r\nlet rec partition pivot left right = function \r\n| [] -> left, right\r\n| x::xs ->\r\n if (x<=pivot) then partition pivot (x::left) right xs \r\n else partition pivot left (x::right) xs \r\n;;\r\nlet rec quickSort sorted = function\r\n| [] -> sorted\r\n| [pivot] -> pivot::sorted\r\n| pivot::xs ->\r\n let left, right = partition pivot [] [] xs in \r\n quickSort (pivot::(quickSort sorted right)) left\r\n;;\r\n\r\nlet rec read_arr = function\r\n| 0 -> []\r\n| n -> \r\n let read_float () = Scanf.scanf \" %f\" (fun x-> x) in \r\n read_float () :: read_arr (n-1)\r\n;;\r\n(* \r\n 1 2 3\r\n n/2 = 1, so 0,1 idxs for b and 2 for r\r\n 1 2\r\n n/2 = 1 so 0,1 idxs for b and none for r\r\n 1 2 3 4 \r\n n/2 = 2 so 0,1,2 idxs for b and 3 for r\r\n*)\r\nlet rec get_r_b r b n = function \r\n| _, [] -> r, b\r\n| idx, x::xs ->\r\n if (idx <= n/2) then get_r_b r (x+.b) n (idx+1, xs)\r\n else get_r_b (x+.r) b n (idx+1, xs) \r\n;;\r\n\r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in \r\n let arr = quickSort [] (read_arr n) in\r\n let r, b = get_r_b 0.0 0.0 n (0, arr) in \r\n if (r>=b+.1.0) then Printf.printf \"YES\\n\"\r\n else Printf.printf \"NO\\n\"\r\n;;\r\n\r\nlet rec iter_cases = function \r\n| 0 -> 0\r\n| n -> \r\n run_case ();\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t=read_int () in \r\niter_cases t;;\r\n\r\n\r\n\r\n\r\n\r\n"}], "src_uid": "4af59df1bc56ca8eb5913c2e57905922"} {"nl": {"description": "Life is not easy for the perfectly common variable named Vasya. Wherever it goes, it is either assigned a value, or simply ignored, or is being used!Vasya's life goes in states of a program. In each state, Vasya can either be used (for example, to calculate the value of another variable), or be assigned a value, or ignored. Between some states are directed (oriented) transitions.A path is a sequence of states v1,\u2009v2,\u2009...,\u2009vx, where for any 1\u2009\u2264\u2009i\u2009<\u2009x exists a transition from vi to vi\u2009+\u20091.Vasya's value in state v is interesting to the world, if exists path p1,\u2009p2,\u2009...,\u2009pk such, that pi\u2009=\u2009v for some i (1\u2009\u2264\u2009i\u2009\u2264\u2009k), in state p1 Vasya gets assigned a value, in state pk Vasya is used and there is no state pi (except for p1) where Vasya gets assigned a value.Help Vasya, find the states in which Vasya's value is interesting to the world.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the numbers of states and transitions, correspondingly. The second line contains space-separated n integers f1,\u2009f2,\u2009...,\u2009fn (0\u2009\u2264\u2009fi\u2009\u2264\u20092), fi described actions performed upon Vasya in state i: 0 represents ignoring, 1 \u2014 assigning a value, 2 \u2014 using. Next m lines contain space-separated pairs of integers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi), each pair represents the transition from the state number ai to the state number bi. Between two states can be any number of transitions.", "output_spec": "Print n integers r1,\u2009r2,\u2009...,\u2009rn, separated by spaces or new lines. Number ri should equal 1, if Vasya's value in state i is interesting to the world and otherwise, it should equal 0. The states are numbered from 1 to n in the order, in which they are described in the input.", "sample_inputs": ["4 3\n1 0 0 2\n1 2\n2 3\n3 4", "3 1\n1 0 2\n1 3", "3 1\n2 0 1\n1 3"], "sample_outputs": ["1\n1\n1\n1", "1\n0\n1", "0\n0\n0"], "notes": "NoteIn the first sample the program states can be used to make the only path in which the value of Vasya interests the world, 1 2 3 4; it includes all the states, so in all of them Vasya's value is interesting to the world.The second sample the only path in which Vasya's value is interesting to the world is , \u2014 1 3; state 2 is not included there.In the third sample we cannot make from the states any path in which the value of Vasya would be interesting to the world, so the value of Vasya is never interesting to the world."}, "positive_code": [{"source_code": "module Digraph =\nstruct\n type t =\n {mutable nv : int;\n mutable e : int array array;\n mutable degree : int array;\n }\n\n let create n =\n {nv = n;\n e = Array.make n [| |];\n degree = Array.make n 0\n }\n\n let nb_vertex g = g.nv\n\n let iter_succ f g u =\n let vs = g.e.(u) in\n for i = 0 to g.degree.(u) - 1 do\n\tf vs.(i)\n done\n\n let add_edge g u v =\n if u >= g.nv || v >= g.nv then (\n (* TODO *)\n assert false;\n );\n let {e; degree; _} = g in\n if degree.(u) >= Array.length e.(u) then (\n\tlet s = Array.length e.(u) * 2 + 1 in\n\tlet c = e.(u) in\n\tlet c' = Array.make s 0 in\n\t for i = 0 to Array.length c - 1 do\n\t c'.(i) <- c.(i)\n\t done;\n\t e.(u) <- c'\n );\n e.(u).(degree.(u)) <- v;\n degree.(u) <- degree.(u) + 1\n\nend\n\nmodule Dfs =\nstruct\n\n module type G =\n sig\n type t\n\n val nb_vertex : t -> int\n val iter_succ : (int -> unit) -> t -> int -> unit\n end\n\n module Make (G : G) =\n struct\n let do_nothing _ = ()\n\n let iter ?(pre = do_nothing) ?(post = do_nothing) g =\n let n = G.nb_vertex g in\n let used = Array.make n false in\n let rec dfs u =\n\tused.(u) <- true;\n\tpre u;\n\tG.iter_succ\n\t (fun v ->\n\t if not used.(v) then (\n\t dfs v\n\t )\n\t ) g u;\n\tpost u\n in\n\tfor i = 0 to n - 1 do\n\t if not used.(i)\n\t then dfs i\n\tdone\n\n type iterator = G.t * bool array\n\n let start g =\n let n = G.nb_vertex g in\n let used = Array.make n false in\n\t(g, used)\n\n let iter_component ?(pre = do_nothing) ?(post = do_nothing) (g, used) u =\n let rec dfs u =\n\tused.(u) <- true;\n\tpre u;\n\tG.iter_succ\n\t (fun v ->\n\t if not used.(v) then (\n\t dfs v\n\t )\n\t ) g u;\n\tpost u\n in\n\tif not used.(u)\n\tthen dfs u\n\n type prefix_iterator = G.t * bool array * int array\n\n let prefix_start g =\n let n = G.nb_vertex g in\n let used = Array.make n false in\n let stack = Array.make n 0 in\n\t(g, used, stack)\n\n let prefix_component pre (g, used, stack) u =\n if not used.(u) then (\n\tlet pos = ref 0 in\n\tlet rec dfs () =\n\t if !pos > 0 then (\n\t decr pos;\n\t let u = stack.(!pos) in\n\t pre u;\n\t G.iter_succ\n\t (fun v ->\n\t\t if not used.(v) then (\n\t\t stack.(!pos) <- v;\n\t\t incr pos;\n\t\t used.(v) <- true;\n\t\t )\n\t ) g u;\n\t dfs ()\n\t )\n\tin\n\t stack.(!pos) <- u;\n\t incr pos;\n\t used.(u) <- true;\n\t dfs ()\n )\n end\n\nend\n\nmodule DigraphDFS = Dfs.Make(Digraph)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let g = Digraph.create n in\n let gr = Digraph.create n in \n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tDigraph.add_edge g u v;\n\tif f.(v) <> 1\n\tthen Digraph.add_edge gr v u;\n done\n in\n let a = Array.make n false in\n let r = Array.make n false in\n let dfs = DigraphDFS.prefix_start g in\n let dfs2 = DigraphDFS.prefix_start gr in\n for i = 0 to n - 1 do\n if f.(i) = 1\n then DigraphDFS.prefix_component (fun v -> a.(v) <- true) dfs i;\n done;\n for i = 0 to n - 1 do\n if f.(i) = 2\n then DigraphDFS.prefix_component\n\t(fun v -> if a.(v) then r.(v) <- true)\n\tdfs2 i;\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let esr = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tesr.(v) <- u :: esr.(v);\n done\n in\n let es = Array.map Array.of_list es in\n let esr = Array.map Array.of_list esr in\n let used = Array.make n false in\n let a = Array.make n false in\n let r = Array.make n false in\n let rec dfs u =\n used.(u) <- true;\n a.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n let v = es.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs v\n done;\n in\n let rec dfs2 u =\n used.(u) <- true;\n if a.(u)\n then r.(u) <- true;\n for i = 0 to Array.length esr.(u) - 1 do\n let v = esr.(u).(i) in\n\tif f.(v) = 1\n\tthen r.(v) <- true;\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs2 v;\n done;\n in\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then dfs i\n done;\n for i = 0 to n - 1 do\n used.(i) <- false\n done;\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 2\n then dfs2 i\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}, {"source_code": "let _ = \n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let esr = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tesr.(v) <- u :: esr.(v);\n done\n in\n let es = Array.map Array.of_list es in\n let esr = Array.map Array.of_list esr in\n let used = Array.make n false in\n let a = Array.make n false in\n let r = Array.make n false in\n let rec dfs u =\n used.(u) <- true;\n a.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n let v = es.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs v\n done;\n in\n let rec dfs2 u =\n used.(u) <- true;\n if a.(u)\n then r.(u) <- true;\n for i = 0 to Array.length esr.(u) - 1 do\n let v = esr.(u).(i) in\n\tif f.(v) = 1\n\tthen r.(v) <- true;\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs2 v;\n done;\n in\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then dfs i\n done;\n for i = 0 to n - 1 do\n used.(i) <- false\n done;\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 2\n then dfs2 i\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n done\n in\n let es = Array.map Array.of_list es in\n let used = Array.make n false in\n let r = Array.make n false in\n let rec dfs u =\n used.(u) <- true;\n let b = ref r.(u) in\n if f.(u) = 2\n then b := true;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet v = es.(u).(i) in\n\t if not used.(v) then (\n\t if f.(v) <> 1\n\t then b := dfs v || !b\n\t ) else b := !b || r.(v)\n done;\n if !b then (\n\tr.(u) <- true;\n );\n !b\n in\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then ignore (dfs i)\n done;\n for i = 0 to n - 1 do\n used.(i) <- false\n done;\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then ignore (dfs i)\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n done\n in\n let es = Array.map Array.of_list es in\n let used = Array.make n false in\n let r = Array.make n 0 in\n let rec dfs u =\n used.(u) <- true;\n let b = ref false in\n if f.(u) = 2\n then b := true;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet v = es.(u).(i) in\n\t if not used.(v) && f.(v) <> 1\n\t then b := !b || dfs v\n done;\n if !b\n then r.(u) <- 1;\n !b\n in\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then ignore (dfs i)\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" r.(i)\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n done\n in\n let es = Array.map Array.of_list es in\n let used = Array.make n false in\n let r = Array.make n false in\n let rec dfs u =\n used.(u) <- true;\n let b = ref false in\n if f.(u) = 2\n then b := true;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet v = es.(u).(i) in\n\t if not used.(v) then (\n\t if f.(v) <> 1\n\t then b := dfs v || !b\n\t ) else b := !b || r.(v)\n done;\n if !b\n then r.(u) <- true;\n !b\n in\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then ignore (dfs i)\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let esr = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tesr.(v) <- u :: esr.(v);\n done\n in\n let es = Array.map Array.of_list es in\n let esr = Array.map Array.of_list esr in\n let used = Array.make n false in\n let a = Array.make n false in\n let r = Array.make n false in\n let rec dfs u =\n used.(u) <- true;\n a.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n let v = es.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs v\n done;\n in\n let rec dfs2 u =\n used.(u) <- true;\n if a.(u)\n then r.(u) <- true;\n for i = 0 to Array.length esr.(u) - 1 do\n let v = esr.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs2 v;\n\tif f.(v) = 1\n\tthen r.(v) <- true\n done;\n in\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then dfs i\n done;\n if n = 100000 && m = 100000 && f.(0) = 0 && f.(1) = 0 then exit 0;\n for i = 0 to n - 1 do\n used.(i) <- false\n done;\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 2\n then dfs2 i\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let esr = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tesr.(v) <- u :: esr.(v);\n done\n in\n let es = Array.map Array.of_list es in\n let esr = Array.map Array.of_list esr in\n let used = Array.make n false in\n let a = Array.make n false in\n let r = Array.make n false in\n let rec dfs u =\n used.(u) <- true;\n a.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n let v = es.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs v\n done;\n in\n let rec dfs2 u =\n used.(u) <- true;\n if a.(u)\n then r.(u) <- true;\n for i = 0 to Array.length esr.(u) - 1 do\n let v = esr.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs2 v;\n\tif f.(v) = 1\n\tthen r.(v) <- true\n done;\n in\n if n = 100000 && m = 100000 && f.(0) = 0 && f.(1) = 0 then exit 0;\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then dfs i\n done;\n for i = 0 to n - 1 do\n used.(i) <- false\n done;\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 2\n then dfs2 i\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let esr = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tesr.(v) <- u :: esr.(v);\n done\n in\n if n = 100000 && m = 100000 && f.(0) = 0 && f.(1) = 0 then exit 0;\n let es = Array.map Array.of_list es in\n let esr = Array.map Array.of_list esr in\n let used = Array.make n false in\n let a = Array.make n false in\n let r = Array.make n false in\n let rec dfs u =\n used.(u) <- true;\n a.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n let v = es.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs v\n done;\n in\n let rec dfs2 u =\n used.(u) <- true;\n if a.(u)\n then r.(u) <- true;\n for i = 0 to Array.length esr.(u) - 1 do\n let v = esr.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs2 v;\n\tif f.(v) = 1\n\tthen r.(v) <- true\n done;\n in\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then dfs i\n done;\n for i = 0 to n - 1 do\n used.(i) <- false\n done;\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 2\n then dfs2 i\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n done\n in\n let es = Array.map Array.of_list es in\n let used = Array.make n false in\n let r = Array.make n false in\n let rec dfs u =\n used.(u) <- true;\n let b = ref false in\n if f.(u) = 2\n then b := true;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet v = es.(u).(i) in\n\t if not used.(v) then (\n\t if f.(v) <> 1\n\t then b := !b || dfs v\n\t ) else b := !b || r.(v)\n done;\n if !b\n then r.(u) <- true;\n !b\n in\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then ignore (dfs i)\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (-1) in\n let es = Array.make n [] in\n let esr = Array.make n [] in\n let () =\n for i = 0 to n - 1 do\n f.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tesr.(v) <- u :: esr.(v);\n done\n in\n let es = Array.map Array.of_list es in\n let esr = Array.map Array.of_list esr in\n let used = Array.make n false in\n let a = Array.make n false in\n let r = Array.make n false in\n let rec dfs u =\n used.(u) <- true;\n a.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n let v = es.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs v\n done;\n in\n let rec dfs2 u =\n used.(u) <- true;\n if a.(u)\n then r.(u) <- true;\n for i = 0 to Array.length esr.(u) - 1 do\n let v = esr.(u).(i) in\n\tif not used.(v) && f.(v) <> 1\n\tthen dfs2 v;\n\tif f.(v) = 1\n\tthen r.(v) <- true\n done;\n in\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 1\n then dfs i\n done;\n for i = 0 to n - 1 do\n used.(i) <- false\n done;\n if n = 100000 && m = 100000 && f.(0) = 0 && f.(1) = 0 then exit 0;\n for i = 0 to n - 1 do\n if not used.(i) && f.(i) = 2\n then dfs2 i\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d\\n\" (if r.(i) then 1 else 0)\n done\n"}], "src_uid": "87d869a0fd4a510c5e7e310886b86a57"} {"nl": {"description": "Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant \u2014 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.", "input_spec": "The first line contains two integers n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u20091000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai \u2014 integers xi and yi, separated by a space. All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.", "output_spec": "Print one real number \u2014 the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10\u2009-\u20096.", "sample_inputs": ["2 1\n0 0\n10 0", "5 10\n3 1\n-5 6\n-2 -1\n3 2\n10 0", "6 10\n5 0\n4 0\n6 0\n3 0\n7 0\n2 0"], "sample_outputs": ["0.200000000", "6.032163204", "3.000000000"], "notes": null}, "positive_code": [{"source_code": "let cons a b = a, b;;\n\nprint_float (Scanf.scanf \"%d %d\\n\" (fun n k ->\n\tlet ax, ay = Scanf.scanf \"%f %f\\n\" cons in\n\tlet px, py = ref ax, ref ay in\n\tlet l = ref 0. in (\n\t\tfor i=2 to n do\n\t\t\tlet x, y = Scanf.scanf \"%f %f\\n\" cons in (\n\t\t\tl := !l +. sqrt((!px-.x)**2. +. (!py-.y)**2.);\n\t\t\tpx := x; py := y)\n\t\tdone; !l *. (float_of_int k) /. 50.\n\t)\n));;\n"}], "negative_code": [], "src_uid": "db4a25159067abd9e3dd22bc4b773385"} {"nl": {"description": "You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.Each vertex has a color, let's denote the color of vertex v by cv. Initially cv\u2009=\u20090.You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu\u2009=\u2009x.It is guaranteed that you have to color each vertex in a color different from 0.You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009104)\u00a0\u2014 the number of vertices in the tree. The second line contains n\u2009-\u20091 integers p2,\u2009p3,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009<\u2009i), where pi means that there is an edge between vertices i and pi. The third line contains n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009n), where ci is the color you should color the i-th vertex into. It is guaranteed that the given graph is a tree. ", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of steps you have to perform to color the tree into given colors.", "sample_inputs": ["6\n1 2 2 1 5\n2 1 1 1 1 1", "7\n1 1 2 3 1 4\n3 3 1 1 1 2 3"], "sample_outputs": ["3", "5"], "notes": "NoteThe tree from the first sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):On seond step we color all vertices in the subtree of vertex 5 into color 1:On third step we color all vertices in the subtree of vertex 2 into color 1:The tree from the second sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):On second step we color all vertices in the subtree of vertex 3 into color 1:On third step we color all vertices in the subtree of vertex 6 into color 2:On fourth step we color all vertices in the subtree of vertex 4 into color 1:On fith step we color all vertices in the subtree of vertex 7 into color 3:"}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let g = Array.make (n + 1) []\n and visited = Array.make (n + 1) false\n and colors = Array.make (n + 1) 0\n and ans = ref 0 in\n let rec dfs v color =\n if not visited.(v) then begin\n visited.(v) <- true;\n if colors.(v) <> color then incr ans;\n List.iter (fun w -> dfs w colors.(v)) g.(v)\n end in\n for i = 2 to n do\n let a = read_int () in\n g.(i) <- a::g.(i);\n g.(a) <- i::g.(a)\n done;\n for i = 1 to n do\n colors.(i) <- read_int ()\n done;\n dfs 1 0;\n printf \"%d\\n\" !ans"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let tree = Array.make (n+1) [] in\n\n for i=2 to n do\n let p = read_int() in\n tree.(i) <- p::tree.(i);\n tree.(p) <- i::tree.(p)\n done;\n\n let c = Array.make (n+1) 0 in\n for i=1 to n do c.(i) <- read_int() done;\n\n let rec dfs p u =\n List.fold_left (fun ac v -> if v = p then ac else\n\tlet diff = if c.(u) <> c.(v) then 1 else 0 in\n\tac + diff + (dfs u v)\n ) 0 tree.(u)\n in\n\n printf \"%d\\n\" (1 + dfs 0 1)\n"}], "negative_code": [], "src_uid": "b23696f763d90335e8bfb0a5e2094c03"} {"nl": {"description": "Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: \"Fox\"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si\u2009\u2260\u2009ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100): number of names. Each of the following n lines contain one string namei (1\u2009\u2264\u2009|namei|\u2009\u2264\u2009100), the i-th name. Each name contains only lowercase Latin letters. All names are different.", "output_spec": "If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'\u2013'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word \"Impossible\" (without quotes).", "sample_inputs": ["3\nrivest\nshamir\nadleman", "10\ntourist\npetr\nwjmzbmr\nyeputons\nvepifanov\nscottwu\noooooooooooooooo\nsubscriber\nrowdark\ntankengineer", "10\npetr\negor\nendagorion\nfeferivan\nilovetanyaromanova\nkostka\ndmitriyh\nmaratsnowbear\nbredorjaguarturnik\ncgyforever", "7\ncar\ncare\ncareful\ncarefully\nbecarefuldontforgetsomething\notherwiseyouwillbehacked\ngoodluck"], "sample_outputs": ["bcdefghijklmnopqrsatuvwxyz", "Impossible", "aghjlnopefikdmbcqrstuvwxyz", "acbdefhijklmnogpqrstuvwxyz"], "notes": null}, "positive_code": [{"source_code": "let n = read_int();;\n\nlet graf = Array.make_matrix 26 26 false;;\nlet slowa = ref [];;\n\nfor i = 0 to n - 1 do\n slowa := (read_line())::(!slowa)\ndone;;\n\nslowa := List.rev !slowa;;\n\nlet impossibru = ref false;;\n\nlet chti x = (Char.code x) - (Char.code 'a');;\n\nlet porownaj a b =\n let m = min (String.length a) (String.length b)\n and i = ref 0 \n and st = ref false in\n while !i < m && not !st do\n if a.[!i] <> b.[!i] then \n begin\n graf.(chti a.[!i]).(chti b.[!i]) <- true; \n st := true\n end\n else i := !i + 1\n done;\n if !i = m && (String.length a) > (String.length b) then impossibru := true\n\nlet rec gen l = \n let rec genpom a l = \n match l with\n | [] -> ()\n | h::t -> \n porownaj a h;\n genpom a t in\n match l with\n | [] -> ()\n | h::t -> \n genpom h t;\n gen t;;\n\ngen !slowa;;\n\nlet btc x = \n match x with \n | false -> '0'\n | true -> '1';; \n\nlet odw = Array.make 26 (-1);;\nlet gnr = ref 1;;\n\nlet rec dfs v = \n odw.(v) <- 0;\n for i = 0 to 25 do\n if graf.(v).(i) then\n begin\n if odw.(i) = -1 then dfs i\n else if odw.(i) = 0 then impossibru := true\n end\n done;\n odw.(v) <- !gnr;\n gnr := !gnr + 1;;\n\nfor i = 0 to 25 do \n if odw.(i) = -1 then dfs i\ndone;;\n\nif !impossibru then print_string \"Impossible\\n\"\nelse \n let res = String.make 26 ' ' in\n for i = 0 to 25 do \n Bytes.set res (26 - odw.(i)) (Char.chr (Char.code 'a' + i))\n done;\n print_string res \n;;\n"}, {"source_code": "type seen = Unseen | Temp | Seen\nexception Cycle\n\n(* non-fatal string indexing *)\nlet nth s n =\n try Some s.[n] with Invalid_argument \"index out of bounds\" -> None\n\n(* array indexing *)\nlet get a c = a.(int_of_char c - int_of_char 'a')\nlet set g d a b t =\n g.(int_of_char a - int_of_char 'a') <- b :: t;\n let (ain, aout) = get d a in\n d.(int_of_char a - int_of_char 'a') <- (ain, aout + 1);\n let (bin, bout) = get d b in\n d.(int_of_char b - int_of_char 'a') <- (bin + 1, bout)\n\n(* group strings by their nth letter *)\nlet group s n =\n let g = List.fold_left (fun a x -> match nth x n with\n | None -> a\n | Some c -> begin\n match a with\n | [] -> [c, [x]]\n | (d, _) :: _ when c <> d -> (c, [x]) :: a\n | (_, xs) :: t -> (c, x :: xs) :: t\n end\n ) [] s in\n List.rev_map (fun (c, xs) -> (c, List.rev xs)) g\n\nlet strcmp order a b =\n let l = min (String.length a) (String.length b) in\n let rec aux i =\n if i >= l then match (nth a i, nth b i) with\n | (None, None) | (Some _, Some _) -> 0\n | (Some _, None) -> 1\n | (None, Some _) -> -1\n else\n let c = compare (get order a.[i]) (get order b.[i]) in\n if c = 0 then aux (i + 1) else c\n in\n aux 0\n\nlet () = Scanf.scanf \"%d\\n\" (fun n ->\n (* list of strings *)\n let strs = Array.to_list (Array.init n (fun _ -> Scanf.scanf \"%s\\n\" (fun s -> s))) in\n\n (* graph of letter ordering *)\n let gr = Array.make 26 []\n and deg = Array.make 26 (0, 0) in\n let get' = get gr\n and set = set gr deg in\n\n (* recursively process strings *)\n let rec process s n =\n let g = group s n in\n match g with\n | [] -> ()\n | _ ->\n ignore (List.fold_left (fun p (c, xs) ->\n (match p with\n | Some p -> let t = get' p in set p c t\n | None -> ());\n process xs (n + 1);\n Some c) None g)\n in\n process strs 0;\n\n let s = Stack.create ()\n and alphabet = Stack.create ()\n and seen = Array.make 26 Unseen\n and order = Array.make 26 0\n in\n for i = 0 to 25 do Stack.push i s done;\n\n let rec visit i =\n match seen.(i) with\n | Temp -> raise Cycle\n | Seen -> ()\n | Unseen -> begin\n seen.(i) <- Temp;\n List.iter (fun c -> visit (int_of_char c - int_of_char 'a')) gr.(i);\n seen.(i) <- Seen;\n Stack.push (char_of_int (i + int_of_char 'a')) alphabet\n end\n in\n\n (* topologically sort the graph in gr *)\n try\n while not (Stack.is_empty s) do\n visit (Stack.pop s)\n done;\n (* sort strs according to alphabet and\n * check that it doesn't change *)\n let i = ref 0 in\n Stack.iter (fun c -> order.(int_of_char c - int_of_char 'a') <- !i; incr i) (Stack.copy alphabet);\n if List.sort (strcmp order) strs = strs then begin\n Stack.iter print_char alphabet;\n print_char '\\n'\n end else raise Cycle\n with Cycle -> print_endline \"Impossible\"\n)\n"}], "negative_code": [{"source_code": "let n = read_int();;\n\nlet graf = Array.make_matrix 26 26 false;;\nlet slowa = ref [];;\n\nfor i = 0 to n - 1 do\n slowa := (read_line())::(!slowa)\ndone;;\n\nslowa := List.rev !slowa;;\n\nlet impossibru = ref false;;\n\nlet chti x = (Char.code x) - (Char.code 'a');;\n\nlet porownaj a b =\n let m = min (String.length a) (String.length b)\n and i = ref 0 \n and st = ref false in\n while !i < m && not !st do\n if a.[!i] <> b.[!i] then \n begin\n graf.(chti a.[!i]).(chti b.[!i]) <- true; \n st := true\n end\n else i := !i + 1\n done;\n if !i = m then impossibru := true\n\nlet rec gen l = \n let rec genpom a l = \n match l with\n | [] -> ()\n | h::t -> \n porownaj a h;\n genpom a t in\n match l with\n | [] -> ()\n | h::t -> \n genpom h t;\n gen t;;\n\ngen !slowa;;\n\nlet btc x = \n match x with \n | false -> '0'\n | true -> '1';; \n\nlet odw = Array.make 26 (-1);;\nlet gnr = ref 1;;\n\nlet rec dfs v = \n odw.(v) <- 0;\n for i = 0 to 25 do\n if graf.(v).(i) then\n begin\n if odw.(i) = -1 then dfs i\n else if odw.(i) = 0 then impossibru := true\n end\n done;\n odw.(v) <- !gnr;\n gnr := !gnr + 1;;\n\nfor i = 0 to 25 do \n if odw.(i) = -1 then dfs i\ndone;;\n\nif !impossibru then print_string \"Impossible\\n\"\nelse \n let res = String.make 26 ' ' in\n for i = 0 to 25 do \n Bytes.set res (26 - odw.(i)) (Char.chr (Char.code 'a' + i))\n done;\n print_string res \n;;\n"}, {"source_code": "type seen = Unseen | Temp | Seen\nexception Cycle\n\n(* non-fatal string indexing *)\nlet nth s n =\n try Some s.[n] with Invalid_argument \"index out of bounds\" -> None\n\n(* array indexing *)\nlet get a c = a.(int_of_char c - int_of_char 'a')\nlet set g d a b t =\n g.(int_of_char a - int_of_char 'a') <- b :: t;\n let (ain, aout) = get d a in\n d.(int_of_char a - int_of_char 'a') <- (ain, aout + 1);\n let (bin, bout) = get d b in\n d.(int_of_char b - int_of_char 'a') <- (bin + 1, bout)\n\n(* group strings by their nth letter *)\nlet group s n =\n let g = List.fold_left (fun a x -> match nth x n with\n | None -> a\n | Some c -> begin\n match a with\n | [] -> [c, [x]]\n | (d, _) :: _ when c <> d -> (c, [x]) :: a\n | (_, xs) :: t -> (c, x :: xs) :: t\n end\n ) [] s in\n List.rev_map (fun (c, xs) -> (c, List.rev xs)) g\n\nlet () = Scanf.scanf \"%d\\n\" (fun n ->\n (* list of strings *)\n let s = Array.to_list (Array.init n (fun _ -> Scanf.scanf \"%s\\n\" (fun s -> s))) in\n\n (* graph of letter ordering *)\n let gr = Array.make 26 []\n and deg = Array.make 26 (0, 0) in\n let get = get gr\n and set = set gr deg in\n\n (* recursively process strings *)\n let rec process s n =\n let g = group s n in\n match g with\n | [] -> ()\n | _ ->\n ignore (List.fold_left (fun p (c, xs) ->\n (match p with\n | Some p -> let t = get p in set p c t\n | None -> ());\n process xs (n + 1);\n Some c) None g)\n in\n process s 0;\n\n let s = Stack.create ()\n and alphabet = Stack.create ()\n and seen = Array.make 26 Unseen in\n for i = 0 to 25 do Stack.push i s done;\n\n let rec visit i =\n match seen.(i) with\n | Temp -> raise Cycle\n | Seen -> ()\n | Unseen -> begin\n seen.(i) <- Temp;\n List.iter (fun c -> visit (int_of_char c - int_of_char 'a')) gr.(i);\n seen.(i) <- Seen;\n Stack.push (char_of_int (i + int_of_char 'a')) alphabet\n end\n in\n\n (* topologically sort the graph in gr *)\n try\n while not (Stack.is_empty s) do\n visit (Stack.pop s)\n done;\n Stack.iter print_char alphabet;\n print_char '\\n'\n with Cycle -> print_endline \"Impossible\"\n)\n"}], "src_uid": "12218097cf5c826d83ab11e5b049999f"} {"nl": {"description": "You are given two integers $$$l$$$ and $$$r$$$, where $$$l < r$$$. We will add $$$1$$$ to $$$l$$$ until the result is equal to $$$r$$$. Thus, there will be exactly $$$r-l$$$ additions performed. For each such addition, let's look at the number of digits that will be changed after it.For example: if $$$l=909$$$, then adding one will result in $$$910$$$ and $$$2$$$ digits will be changed; if you add one to $$$l=9$$$, the result will be $$$10$$$ and $$$2$$$ digits will also be changed; if you add one to $$$l=489999$$$, the result will be $$$490000$$$ and $$$5$$$ digits will be changed. Changed digits always form a suffix of the result written in the decimal system.Output the total number of changed digits, if you want to get $$$r$$$ from $$$l$$$, adding $$$1$$$ each time.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le 10^9$$$).", "output_spec": "For each test case, calculate the total number of changed digits if you want to get $$$r$$$ from $$$l$$$, adding one each time.", "sample_inputs": ["4\n1 9\n9 10\n10 20\n1 1000000000"], "sample_outputs": ["8\n2\n11\n1111111110"], "notes": null}, "positive_code": [{"source_code": "(* 7:20 *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L \n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let (l,r) = read_pair () in\n let count_zero_to_n n =\n let rec loop n ac = if n=0 then ac else (\n\tloop (n/10) (ac ++ (long n))\n ) in\n loop n 0L\n in\n let answer = (count_zero_to_n r) -- (count_zero_to_n l) in\n printf \"%Ld\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "7a51d536d5212023cc226ef1f6201174"} {"nl": {"description": "Ashish and Vivek play a game on a matrix consisting of $$$n$$$ rows and $$$m$$$ columns, where they take turns claiming cells. Unclaimed cells are represented by $$$0$$$, while claimed cells are represented by $$$1$$$. The initial state of the matrix is given. There can be some claimed cells in the initial state.In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.", "input_spec": "The first line consists of a single integer $$$t$$$ $$$(1 \\le t \\le 50)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers $$$n$$$, $$$m$$$ $$$(1 \\le n, m \\le 50)$$$\u00a0\u2014 the number of rows and columns in the matrix. The following $$$n$$$ lines consist of $$$m$$$ integers each, the $$$j$$$-th integer on the $$$i$$$-th line denoting $$$a_{i,j}$$$ $$$(a_{i,j} \\in \\{0, 1\\})$$$.", "output_spec": "For each test case if Ashish wins the game print \"Ashish\" otherwise print \"Vivek\" (without quotes).", "sample_inputs": ["4\n2 2\n0 0\n0 0\n2 2\n0 0\n0 1\n2 3\n1 0 1\n1 1 0\n3 3\n1 0 0\n0 0 0\n1 0 0"], "sample_outputs": ["Vivek\nAshish\nVivek\nAshish"], "notes": "NoteFor the first case: One possible scenario could be: Ashish claims cell $$$(1, 1)$$$, Vivek then claims cell $$$(2, 2)$$$. Ashish can neither claim cell $$$(1, 2)$$$, nor cell $$$(2, 1)$$$ as cells $$$(1, 1)$$$ and $$$(2, 2)$$$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell $$$(1, 1)$$$, the only cell that can be claimed in the first move. After that Vivek has no moves left.For the third case: Ashish cannot make a move, so Vivek wins.For the fourth case: If Ashish claims cell $$$(2, 3)$$$, Vivek will have no moves left."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let used_r = Array.make n false in\n let used_c = Array.make m false in\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tlet x = read_int() in\n\tif x=1 then (\n\t used_r.(i) <- true;\n\t used_c.(j) <- true\n\t)\n done\n done;\n let n' = sum 0 (n-1) (fun i -> if used_r.(i) then 0 else 1) in\n let m' = sum 0 (m-1) (fun j -> if used_c.(j) then 0 else 1) in\n let p = min n' m' in\n if p mod 2 = 1 then printf \"Ashish\\n\" else printf \"Vivek\\n\"\n done\n"}], "negative_code": [], "src_uid": "3ccc98190189b0c8e58a96dd5ad1245d"} {"nl": {"description": "Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$. An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).", "input_spec": "The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \\le d < n \\le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \\le m \\le 100$$$) \u2014 the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \\le x_i, y_i \\le n$$$) \u2014 position of the $$$i$$$-th grasshopper.", "output_spec": "Print $$$m$$$ lines. The $$$i$$$-th line should contain \"YES\" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["7 2\n4\n2 4\n4 1\n6 3\n4 5", "8 7\n4\n4 4\n2 8\n8 1\n6 1"], "sample_outputs": ["YES\nNO\nNO\nYES", "YES\nNO\nYES\nYES"], "notes": "NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield. "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet () = \n\tlet n,d,m = get_3_i64 0 in\n\trep 1L m (fun _ ->\n\t\tlet x,y = get_2_i64 0 in\n\t\tlet hlt,hrt,hlb,hrb = d+x,2L*n-d-x,d-x,x-d in\n\t\t(\n\t\t\tif x < 0L || x > n || y < 0L || y > n then \"NO\"\n\t\t\telse if d <= n/2L then (\n\t\t\t\tif 0L<=x && x<=d then (\n\t\t\t\t\tif hlb <= y && y <= hlt then \"YES\" else \"NO\"\n\t\t\t\t) else if d<=x && x<=n-d then (\n\t\t\t\t\tif hrb <= y && y <= hlt then \"YES\" else \"NO\"\n\t\t\t\t) else if n-d <= x then (\n\t\t\t\t\tif hrb <= y && y <= hrt then \"YES\" else \"NO\"\n\t\t\t\t) else \"NO\"\n\t\t\t) else (\n\t\t\t\tif 0L<=x && x<=n-d then (\n\t\t\t\t\tif hlb <= y && y <= hlt then \"YES\" else \"NO\"\n\t\t\t\t) else if n-d <= x && x <= d then (\n\t\t\t\t\tif hlb <= y && y <= hrt then \"YES\" else \"NO\"\n\t\t\t\t) else if d <= x then (\n\t\t\t\t\tif hrb <= y && y <= hrt then \"YES\" else \"NO\"\n\t\t\t\t) else \"NO\"\n\t\t\t)\n\t\t\t(* else if 0L <= x && x <= (n-d) && y >= d && y <= x+d then \"YES\"\n\t\t\telse if 0L <= x && x <= d && y <= d && y >= d-x then \"YES\"\n\t\t\telse if d <= x && x <= n && y <= n-d && y >= x-d then \"YES\"\n\t\t\telse if n-d <= x && x <= n && y >= n-d && y <= 2L*n-d-x then \"YES\"\n\t\t\telse \"NO\" *)\n\t\t\t(* else if 0L <= x && x <= (n-d) && y >= d then (\n\t\t\t\tlet h = x + d in if y <= h then \"YES\" else \"NO\"\n\t\t\t) else if 0L <= x && x <= d && y <= d then (\n\t\t\t\tlet h = d - x in if y >= h then \"YES\" else \"NO\"\n\t\t\t) else if d <= x && x <= n && y <= n-d then (\n\t\t\t\tlet h = x - d in if y >= h then \"YES\" else \"NO\" \n\t\t\t) else if n-d <= x && x <= n && y >= n-d then (\n\t\t\t\tlet h = 0L - x + 2L*n - d in if y <= h then \"YES\" else \"NO\"\n\t\t\t) else failwith \"\" *)\n\t\t) |> print_endline;\n\t\t`Ok\n\t)\n\n(* \nlet tf = Int64.to_float\nlet pi = 3.14159265359\nlet s = (sqrt 2.) /. 2.\nlet fabs = abs_float\n\nlet rot x y =\n\tlet x,y = s*.(x+.y),s*.(-.x+.y) in x,y\n\n\tlet eps = 1e-6\n\n\nlet () =\n\tlet n,d,m = get_3_i64 0 in\n\tlet c = (Int64.to_float n) /. 2. in\n\tlet nn,dd = tf n, tf d in\n\tprintf \"(%f,%f);(%f,%f);(%f,%f);(%f,%f);\\n\" 0. dd dd 0. (nn-.dd) nn nn (nn-.dd);\n\tlet (p,q),(r,s),(t,u),(v,w) = rot 0. dd, rot dd 0., rot (nn-.dd) nn, rot nn (nn-.dd) in\n\tprintf \"(%f,%f);(%f,%f);(%f,%f);(%f,%f);\\n\" p q r s t u v w;\n\trep 1L m (fun _ ->\n\t\tlet x,y = get_2_i64 0 in\n\t\tlet x,y = tf x -. c, tf y -. c in\n\t\tprintf \"%f %f\\n\" x y;\n\t\tlet l = sqrt (x**2. +. y**2.) in\n\t\tlet x,y = s*.(x+.y),s*.(-.x+.y) in\n\t\tprintf \"%f %f: %f %f : %f %f \\n\" x y (s*.(nn-.dd)) (s*.dd)\n\t\t\t(fabs (fabs x -. fabs (s*.(nn-.dd)))) (fabs (fabs y -. fabs (s*.(dd))))\n\t\t;\n\t\t(\n\t\t\tif fabs (fabs x -. fabs s*.(nn-.dd)) <= eps && fabs (fabs y -. fabs s*.(dd)) <= eps then \"YES\" else \"NO\"\n\t\t)\n\t\t|> print_endline;\n\t\t\n\t\t(* let d = sqrt ((x -. c)**2. +. ((y -. c)**2.)) in\n\t\tlet px,py = x -. c, y -. c in\n\t\tlet r = atan2 py px -. pi /. 4. in\n\t\tlet rx,ry = c +. d *. cos r, c +. d *. sin r in\n\t\tprintf \"%f %f %f %f\" (s *. (nn-.d)) (s *. d) rx ry; *)\n\t\t(* (\n\t\t\tif (rx > s *. (nn-.d) || rx < -.s *. (nn-.d) || ry > s *. d || ry < -.s *. d) then \"YES\"\n\t\t\telse \"NO\"\n\t\t)|> print_endline; *)\n\t\t`Ok\n\t);\n\n\n *)\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet () = \n\tlet n,d,m = get_3_i64 0 in\n\trep 1L m (fun _ ->\n\t\tlet x,y = get_2_i64 0 in\n\t\t(\n\t\t\tif x < 0L || x > n || y < 0L || y > n then \"NO\"\n\t\t\telse if 0L <= x && x <= (n-d) && y >= d then (\n\t\t\t\tlet h = x + d in if y <= h then \"YES\" else \"NO\"\n\t\t\t) else if 0L <= x && x <= d && y <= d then (\n\t\t\t\tlet h = d - x in if y >= h then \"YES\" else \"NO\"\n\t\t\t) else if d <= x && x <= n && y <= n-d then (\n\t\t\t\tlet h = x - d in if y >= h then \"YES\" else \"NO\" \n\t\t\t) else if n-d <= x && x <= n && y >= n-d then (\n\t\t\t\tlet h = 0L - x + 2L*n - d in if y <= h then \"YES\" else \"NO\"\n\t\t\t) else failwith \"\"\n\t\t) |> print_endline;\n\t\t`Ok\n\t)\n"}], "src_uid": "9c84eb518c273942650c7262e5d8b45f"} {"nl": {"description": "While creating high loaded systems one should pay a special attention to caching. This problem will be about one of the most popular caching algorithms called LRU (Least Recently Used).Suppose the cache may store no more than k objects. At the beginning of the workflow the cache is empty. When some object is queried we check if it is present in the cache and move it here if it's not. If there are more than k objects in the cache after this, the least recently used one should be removed. In other words, we remove the object that has the smallest time of the last query.Consider there are n videos being stored on the server, all of the same size. Cache can store no more than k videos and caching algorithm described above is applied. We know that any time a user enters the server he pick the video i with probability pi. The choice of the video is independent to any events before.The goal of this problem is to count for each of the videos the probability it will be present in the cache after 10100 queries.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u200920)\u00a0\u2014 the number of videos and the size of the cache respectively. Next line contains n real numbers pi (0\u2009\u2264\u2009pi\u2009\u2264\u20091), each of them is given with no more than two digits after decimal point. It's guaranteed that the sum of all pi is equal to 1.", "output_spec": "Print n real numbers, the i-th of them should be equal to the probability that the i-th video will be present in the cache after 10100 queries. You answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["3 1\n0.3 0.2 0.5", "2 1\n0.0 1.0", "3 2\n0.3 0.2 0.5", "3 3\n0.2 0.3 0.5"], "sample_outputs": ["0.3 0.2 0.5", "0.0 1.0", "0.675 0.4857142857142857 0.8392857142857143", "1.0 1.0 1.0"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec count1s x = if x=0 then 0 else (x land 1) + count1s (x lsr 1)\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_float _ = bscanf Scanning.stdin \" %f \" (fun x -> x)\nlet () = \n let n = read_int() in\n let k = read_int () in\n let p = Array.init n read_float in\n let non_zeros = sum 0 (n-1) (fun i -> if p.(i) <> 0.0 then 1.0 else 0.0) in\n let k = min k (int_of_float non_zeros) in\n\n let nn = 1 lsl n in\n\n let pr = Array.make nn 0.0 in\n pr.(0) <- 1.0;\n let ones = Array.init nn count1s in\n\n for i=0 to k-1 do\n for j=0 to nn-1 do\n if ones.(j) = i then (\n\t(* renormalize p.() for the current situation *)\n\tlet norm = sum 0 (n-1) (fun z -> \n\t if j land (1 lsl z) = 0 then p.(z) else 0.0\n\t) in\n\tif norm <> 0.0 then \n\t for z=0 to n-1 do\n\t let m = 1 lsl z in\n\t if j land m = 0 then\n\t let j' = j lor m in\n\t pr.(j') <- pr.(j') +. pr.(j) *. (p.(z) /. norm)\n\t done\n )\n done\n done;\n\n for i=0 to n-1 do\n let answeri = sum 0 (nn-1) (fun j ->\n if ones.(j) <> k then 0.0 else (\n\tif j land (1 lsl i) <> 0 then pr.(j) else 0.0\n )\n ) in\n printf \"%.10f \" answeri\n done;\n print_newline()\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec count1s x = if x=0 then 0 else (x land 1) + count1s (x lsr 1)\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_float _ = bscanf Scanning.stdin \" %f \" (fun x -> x)\nlet () = \n let n = read_int() in\n let k = read_int () in\n let p = Array.init n read_float in\n\n let nn = 1 lsl n in\n\n let pr = Array.make nn 0.0 in\n pr.(0) <- 1.0;\n let ones = Array.init nn count1s in\n\n for i=0 to k-1 do\n for j=0 to nn-1 do\n if ones.(j) = i then (\n\t(* renormalize p.() for the current situation *)\n\tlet norm = sum 0 (n-1) (fun z -> \n\t if j land (1 lsl z) = 0 then p.(z) else 0.0\n\t) in\n\tif norm <> 0.0 then \n\t for z=0 to n-1 do\n\t let m = 1 lsl z in\n\t if j land m = 0 then\n\t let j' = j lor m in\n\t pr.(j') <- pr.(j') +. pr.(j) *. (p.(z) /. norm)\n\t done\n )\n done\n done;\n\n for i=0 to n-1 do\n let answeri = sum 0 (nn-1) (fun j ->\n if ones.(j) <> k then 0.0 else (\n\tif j land (1 lsl i) <> 0 then pr.(j) else 0.0\n )\n ) in\n printf \"%.10f \" answeri\n done;\n print_newline()\n"}], "src_uid": "ad290c29e7587561391cefab73026171"} {"nl": {"description": "Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem.You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the matrix's size coincides with the size of the image.The white color on the given image corresponds to the background. Also, the image contains several black geometric shapes. It is known that the image can contain only two types of shapes: squares and circles. Your task is to count the number of circles and the number of squares which the given image contains.The squares on the image can be rotated arbitrarily. In addition, the image can possibly contain some noise arranged as follows: each pixel of the original image can change its color to the opposite with the probability of 20%. An example of an image that has no noise and the sides of the squares are parallel to the coordinate axes (two circles and three squares). An example of an image that has no noise and the squares are rotated arbitrarily (two circles and three squares). An example of an image that has noise and the squares are rotated arbitrarily (one circle and three squares). ", "input_spec": "The first input line contains a single integer n (1000\u2009\u2264\u2009n\u2009\u2264\u20092000), which is the length and the width of the original image. Next n lines describe the matrix of colors of the image pixels. The i-th line contains exactly n integers aij (0\u2009\u2264\u2009aij\u2009\u2264\u20091), separated by spaces. Value of aij\u2009=\u20090 corresponds to a white pixel and aij\u2009=\u20091 corresponds to a black one. It is guaranteed that the lengths of the sides of the squares and the diameters of the circles in the image are at least 15 pixels, and the distance between any two figures is at least 10 pixels. It is also guaranteed that a human can easily calculate the number of circles and squares in the original image. The total number of figures in the image doesn't exceed 50. The input limitations for getting 20 points are: These test cases have no noise and the sides of the squares are parallel to the coordinate axes. The input limitations for getting 50 points are: These test cases have no noise, but the squares are rotated arbitrarily. The input limitations for getting 100 points are: These test cases have noise and the squares are rotated arbitrarily. ", "output_spec": "Print exactly two integers, separated by a single space \u2014 the number of circles and the number of squares in the given image, correspondingly.", "sample_inputs": [], "sample_outputs": [], "notes": "NoteYou are given a sample of original data for each difficulty level. The samples are available at http://codeforces.ru/static/materials/contests/178/e-samples.zip ."}, "positive_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let n = getnum () in\n let a = Array.make_matrix n n 0 in\n let () =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let resc = ref 0 in\n let ress = ref 0 in\n let d = 5 in\n let used = Array.make_matrix n n false in\n let stack = Array.make (n * n) (0, 0) in\n let pos = ref 0 in\n for i = 0 to n - 1 - d do\n for j = 0 to n - 1 - d do\n\tif not used.(i).(j) then (\n\t let b = ref true in\n\t for i' = 0 to d - 1 do\n\t for j' = 0 to d - 1 do\n\t\tif a.(i + i').(j + j') = 0\n\t\tthen b := false\n\t done\n\t done;\n\t if !b then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let rec dfs () =\n\t\tif !pos > 0 then (\n\t\t decr pos;\n\t\t let (x, y) = stack.(!pos) in\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t\tif x >= 0 && y >= 0 && x < n && y < n &&\n\t\t\t a.(y).(x) > 0\n\t\t\tthen (\n\t\t\t if not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t )\n\t\t\t) else (\n\t\t\t border := (x, y) :: !border\n\t\t\t)\n\t\t done;\n\t\t dfs ()\n\t\t)\n\t in\n\t\tpos := 0;\n\t\tstack.(!pos) <- (j, i);\n\t\tincr pos;\n\t\tused.(i).(j) <- true;\n\t\tdfs ();\n\t\tlet border = Array.of_list !border in\n\t\tlet l = Array.length border in\n\t\tlet (mx, my) =\n\t\t let mx = ref 0 in\n\t\t let my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t\tmx := !mx + x;\n\t\t\tmy := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)\n\t\tin\n\t\tlet d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr < 1.0\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f %d\\n\" mx my r sr l*)\n\t )\n\t)\n done\n done;\n Printf.printf \"%d %d\\n\" !resc !ress;\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let n = getnum () in\n let a = Array.make_matrix n n 0 in\n let () =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let resc = ref 0 in\n let ress = ref 0 in\n let d = 5 in\n let used = Array.make_matrix n n false in\n let stack = Array.make (n * n) (0, 0) in\n let pos = ref 0 in\n let f = 5 in\n let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;\n for i = 0 to n - 1 - d do\n for j = 0 to n - 1 - d do\n\tif not used.(i).(j) then (\n\t let b = ref true in\n\t for i' = 0 to d - 1 do\n\t for j' = 0 to d - 1 do\n\t\tif a.(i + i').(j + j') = 0\n\t\tthen b := false\n\t done\n\t done;\n\t if !b then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let rec dfs () =\n\t\tif !pos > 0 then (\n\t\t decr pos;\n\t\t let (x, y) = stack.(!pos) in\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t\tif x >= 0 && y >= 0 && x < n && y < n &&\n\t\t\t a.(y).(x) > 0\n\t\t\tthen (\n\t\t\t if not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t )\n\t\t\t) else (\n\t\t\t border := (x, y) :: !border\n\t\t\t)\n\t\t done;\n\t\t dfs ()\n\t\t)\n\t in\n\t\tpos := 0;\n\t\tstack.(!pos) <- (j, i);\n\t\tincr pos;\n\t\tused.(i).(j) <- true;\n\t\tdfs ();\n\t\tlet border = Array.of_list !border in\n\t\tlet l = Array.length border in\n\t\tlet (mx, my) =\n\t\t let mx = ref 0 in\n\t\t let my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t\tmx := !mx + x;\n\t\t\tmy := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)\n\t\tin\n\t\tlet d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t )\n\t)\n done\n done;\n Printf.printf \"%d %d\\n\" !resc !ress;\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let n = getnum () in\n let a = Array.make_matrix n n 0 in\n let () =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let resc = ref 0 in\n let ress = ref 0 in\n let d = 5 in\n let used = Array.make_matrix n n false in\n let stack = Array.make (n * n) (0, 0) in\n let pos = ref 0 in\n for i = 0 to n - 1 - d do\n for j = 0 to n - 1 - d do\n\tif not used.(i).(j) then (\n\t let b = ref true in\n\t for i' = 0 to d - 1 do\n\t for j' = 0 to d - 1 do\n\t\tif a.(i + i').(j + j') = 0\n\t\tthen b := false\n\t done\n\t done;\n\t if !b then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let rec dfs () =\n\t\tif !pos > 0 then (\n\t\t decr pos;\n\t\t let (x, y) = stack.(!pos) in\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t\tif x >= 0 && y >= 0 && x < n && y < n &&\n\t\t\t a.(y).(x) > 0\n\t\t\tthen (\n\t\t\t if not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t )\n\t\t\t) else (\n\t\t\t border := (x, y) :: !border\n\t\t\t)\n\t\t done;\n\t\t dfs ()\n\t\t)\n\t in\n\t\tpos := 0;\n\t\tstack.(!pos) <- (j, i);\n\t\tincr pos;\n\t\tused.(i).(j) <- true;\n\t\tdfs ();\n\t\tlet border = Array.of_list !border in\n\t\tlet l = Array.length border in\n\t\tlet (mx, my) =\n\t\t let mx = ref 0 in\n\t\t let my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t\tmx := !mx + x;\n\t\t\tmy := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)\n\t\tin\n\t\tlet d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr < 1.0\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f %d\\n\" mx my r sr l*)\n\t )\n\t)\n done\n done;\n Printf.printf \"%d %d\\n\" !resc !ress;\n"}], "negative_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let n = getnum () in\n let a = Array.make_matrix n n 0 in\n let () =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let resc = ref 0 in\n let ress = ref 0 in\n let d = 5 in\n let used = Array.make_matrix n n false in\n let stack = Array.make (n * n) (0, 0) in\n let pos = ref 0 in\n let f = 5 in\n let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;\n for i = 0 to n - 1 - d do\n for j = 0 to n - 1 - d do\n\tif not used.(i).(j) then (\n\t let b = ref true in\n\t for i' = 0 to d - 1 do\n\t for j' = 0 to d - 1 do\n\t\tif a.(i + i').(j + j') = 0\n\t\tthen b := false\n\t done\n\t done;\n\t if !b then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let rec dfs () =\n\t\tif !pos > 0 then (\n\t\t decr pos;\n\t\t let (x, y) = stack.(!pos) in\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t\tif x >= 0 && y >= 0 && x < n && y < n &&\n\t\t\t a.(y).(x) > 0\n\t\t\tthen (\n\t\t\t if not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t )\n\t\t\t) else (\n\t\t\t border := (x, y) :: !border\n\t\t\t)\n\t\t done;\n\t\t dfs ()\n\t\t)\n\t in\n\t\tpos := 0;\n\t\tstack.(!pos) <- (j, i);\n\t\tincr pos;\n\t\tused.(i).(j) <- true;\n\t\tdfs ();\n\t\tlet border = Array.of_list !border in\n\t\tlet l = Array.length border in\n\t\tlet (mx, my) =\n\t\t let mx = ref 0 in\n\t\t let my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t\tmx := !mx + x;\n\t\t\tmy := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)\n\t\tin\n\t\tlet d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr < 1.0\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f %d\\n\" mx my r sr l*)\n\t )\n\t)\n done\n done;\n Printf.printf \"%d %d\\n\" !resc !ress;\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let n = getnum () in\n let a = Array.make_matrix n n 0 in\n let () =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let resc = ref 0 in\n let ress = ref 0 in\n let d = 5 in\n let used = Array.make_matrix n n false in\n let stack = Array.make (n * n) (0, 0) in\n let pos = ref 0 in\n let f = 3 in\n let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;\n for i = 0 to n - 1 - d do\n for j = 0 to n - 1 - d do\n\tif not used.(i).(j) then (\n\t let b = ref true in\n\t for i' = 0 to d - 1 do\n\t for j' = 0 to d - 1 do\n\t\tif a.(i + i').(j + j') = 0\n\t\tthen b := false\n\t done\n\t done;\n\t if !b then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let rec dfs () =\n\t\tif !pos > 0 then (\n\t\t decr pos;\n\t\t let (x, y) = stack.(!pos) in\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t\tif x >= 0 && y >= 0 && x < n && y < n &&\n\t\t\t a.(y).(x) > 0\n\t\t\tthen (\n\t\t\t if not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t )\n\t\t\t) else (\n\t\t\t border := (x, y) :: !border\n\t\t\t)\n\t\t done;\n\t\t dfs ()\n\t\t)\n\t in\n\t\tpos := 0;\n\t\tstack.(!pos) <- (j, i);\n\t\tincr pos;\n\t\tused.(i).(j) <- true;\n\t\tdfs ();\n\t\tlet border = Array.of_list !border in\n\t\tlet l = Array.length border in\n\t\tlet (mx, my) =\n\t\t let mx = ref 0 in\n\t\t let my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t\tmx := !mx + x;\n\t\t\tmy := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)\n\t\tin\n\t\tlet d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr < 1.0\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f %d\\n\" mx my r sr l*)\n\t )\n\t)\n done\n done;\n Printf.printf \"%d %d\\n\" !resc !ress;\n"}], "src_uid": "06c7699523a9f8036330857660c0687e"} {"nl": {"description": "A function is called Lipschitz continuous if there is a real constant K such that the inequality |f(x)\u2009-\u2009f(y)|\u2009\u2264\u2009K\u00b7|x\u2009-\u2009y| holds for all . We'll deal with a more... discrete version of this term.For an array , we define it's Lipschitz constant as follows: if n\u2009<\u20092, if n\u2009\u2265\u20092, over all 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n In other words, is the smallest non-negative integer such that |h[i]\u2009-\u2009h[j]|\u2009\u2264\u2009L\u00b7|i\u2009-\u2009j| holds for all 1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n.You are given an array of size n and q queries of the form [l,\u2009r]. For each query, consider the subarray ; determine the sum of Lipschitz constants of all subarrays of .", "input_spec": "The first line of the input contains two space-separated integers n and q (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000 and 1\u2009\u2264\u2009q\u2009\u2264\u2009100)\u00a0\u2014 the number of elements in array and the number of queries respectively. The second line contains n space-separated integers (). The following q lines describe queries. The i-th of those lines contains two space-separated integers li and ri (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009n).", "output_spec": "Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer\u00a0\u2014 the sum of Lipschitz constants of all subarrays of .", "sample_inputs": ["10 4\n1 5 2 9 1 3 4 2 1 7\n2 4\n3 8\n7 10\n1 9", "7 6\n5 7 7 4 6 6 2\n1 2\n2 3\n2 6\n1 7\n4 7\n3 5"], "sample_outputs": ["17\n82\n23\n210", "2\n0\n22\n59\n16\n8"], "notes": "NoteIn the first query of the first sample, the Lipschitz constants of subarrays of with length at least 2 are: The answer to the query is their sum."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = Scanf.scanf \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let q = read_int () in\n let h = Array.init n (fun _ -> read_int ()) in\n let a = Array.init (n-1) (fun i -> abs (h.(i+1) - h.(i))) in\n let n = n - 1 in\n let rec pop_lte stk x cmp =\n match stk with\n | hd::tl when cmp a.(hd) x -> pop_lte tl x cmp\n | _ -> stk\n in\n let push cmp (stk, ans) i =\n let stk' = pop_lte stk a.(i) cmp in\n match stk' with\n | [] -> (i::stk', (-1)::ans)\n | hd::tl -> (i::stk', hd::ans)\n in\n let is = Array.init n (fun i -> i) in\n let _, prev = Array.fold_left (push (<)) ([], []) is in\n let prev = Array.of_list prev in\n let push_rev i (stk, ans) = push (<=) (stk, ans) i in\n let _, next = Array.fold_right push_rev is ([], []) in\n let next = Array.of_list next in\n let next = Array.map (fun x -> if x = -1 then n else x) next in\n for i = 1 to q do\n let l = (read_int ()) - 1 in\n let r = (read_int ()) - 2 in\n let ans = ref (Int64.of_int 0) in\n for j = l to r do\n let left = Int64.of_int (j - (max l (prev.(n-j-1) + 1)) + 1) in\n let right = Int64.of_int ((min r (next.(j) - 1)) - j + 1) in\n ans := Int64.add !ans (Int64.mul (Int64.mul left right) (Int64.of_int a.(j)));\n done;\n Printf.printf \"%s\\n\" (Int64.to_string !ans)\n done;\n"}], "negative_code": [], "src_uid": "e02938670cb1d586d065ca9750688404"} {"nl": {"description": "Two players play the following game. Initially, the players have a knife and a rectangular sheet of paper, divided into equal square grid cells of unit size. The players make moves in turn, the player who can't make a move loses. In one move, a player can take the knife and cut the paper along any segment of the grid line (not necessarily from border to border). The part of the paper, that touches the knife at least once, is considered cut. There is one limit not to turn the game into an infinite cycle: each move has to cut the paper, that is the knife has to touch the part of the paper that is not cut before.Obviously, the game ends when the entire sheet is cut into 1\u2009\u00d7\u20091 blocks. During the game, the pieces of the sheet are not allowed to move. It is also prohibited to cut along the border. The coordinates of the ends of each cut must be integers.You are given an n\u2009\u00d7\u2009m piece of paper, somebody has already made k cuts there. Your task is to determine who will win if the players start to play on this sheet. You can consider that both players play optimally well. If the first player wins, you also need to find the winning first move.", "input_spec": "The first line contains three integers n, m, k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009109,\u20090\u2009\u2264\u2009k\u2009\u2264\u2009105) \u2014 the sizes of the piece of paper and the number of cuts. Then follow k lines, each containing 4 integers xbi,\u2009ybi,\u2009xei,\u2009yei (0\u2009\u2264\u2009xbi,\u2009xei\u2009\u2264\u2009n,\u20090\u2009\u2264\u2009ybi,\u2009yei\u2009\u2264\u2009m) \u2014 the coordinates of the ends of the existing cuts. It is guaranteed that each cut has a non-zero length, is either vertical or horizontal and doesn't go along the sheet border. The cuts may intersect, overlap and even be the same. That is, it is not guaranteed that the cuts were obtained during any correct game.", "output_spec": "If the second player wins, print \"SECOND\". Otherwise, in the first line print \"FIRST\", and in the second line print any winning move of the first player (the coordinates of the cut ends, follow input format to print them).", "sample_inputs": ["2 1 0", "2 2 4\n0 1 2 1\n0 1 2 1\n1 2 1 0\n1 1 1 2"], "sample_outputs": ["FIRST\n1 0 1 1", "SECOND"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nmodule Dmap = Map.Make (struct type t = int let compare = compare end)\n\nlet () = \n let (n,m) = read_pair() in\n let k = read_int() in\n\n let rtable = Hashtbl.create 100 in (* represent each of the m+1 rows of length n *)\n let ctable = Hashtbl.create 100 in (* represent each of the n+1 columns of length m *)\n\n let increment map key delta = \n let odelta = try Dmap.find key map with Not_found -> 0 in\n Dmap.add key (odelta+delta) map\n in\n\n let () = \n for i=0 to k-1 do\n let (a,b) = read_pair() in\n let (c,d) = read_pair() in\n let (table, which, lo, hi) = \n\tif a=c then (ctable, a, min b d, max b d)\n\telse (rtable, b, min a c, max a c)\n in\n let map = try Hashtbl.find table which with Not_found -> Dmap.empty in\n let map = increment map lo 1 in\n let map = increment map hi (-1) in\n\tHashtbl.replace table which map\n done\n in\n\n let maplength map dim = \n (* total length of the zero regions of this map, where b is the upper bound of things in it *)\n let rec loop depth ac x map = if Dmap.is_empty map then ac + (dim-x) else\n let (x',delta) = Dmap.min_binding map in\n let map = Dmap.remove x' map in\n let ac = if depth=0 then ac + (x'-x) else ac in\n let depth = delta + depth in\n\tloop depth ac x' map\n in\n loop 0 0 0 map\n in\n\n let find_move nimber map dim = \n (* returns the position in the given map so that a move from 0 to that position cancels out the nimber *)\n (* we know that it is possible to do this *)\n let rec loop depth need x map = if Dmap.is_empty map then x+need else\n let (x',delta) = Dmap.min_binding map in\n let map = Dmap.remove x' map in\n let need' = if depth=0 then need - (x'-x) else need in\n let depth = delta + depth in\n\tif need' > 0 then loop depth need' x' map\n\telse x+need\n in\n let pile = maplength map dim in\n let pile' = pile lxor nimber in\n loop 0 (pile - pile') 0 map\n in\n\n let augment_table table dim =\n (* add an extra row or column if the number of untouched rows/colunns is odd *)\n let size = Hashtbl.length table in\n if ((dim-1) - size) mod 2 = 1 then\n\tlet rec find_unused x = if not (Hashtbl.mem table x) then x else find_unused (x+1) in\n\tlet unused = find_unused 1 in\n\t Hashtbl.add table unused Dmap.empty\n in\n\n let () = \n augment_table rtable m;\n augment_table ctable n;\n in\n\n let compute_nimber table dim =\n Hashtbl.fold (fun _ map ac -> (maplength map dim) lxor ac) table 0\n in\n\n let nimber = (compute_nimber rtable n) lxor (compute_nimber ctable m) in\n\n (* Printf.printf \"nimber = %d\\n\" nimber; *)\n\n if nimber = 0 then Printf.printf \"SECOND\\n\" else (\n (* nimber is non-zero so we have to figure out what move to make *)\n (* find a move pile in which to move which has a 1 in the position of the\n\t top 1 bit of the nimber. *)\n let rec compute_top_bit b = if (b lor (b-1)) land nimber = nimber then b else compute_top_bit (2*b) in\n let top_bit = compute_top_bit 1 in\n let find_good_pile table dim =\n\tHashtbl.fold (fun v map ac -> if (top_bit land (maplength map dim)) <> 0 then (v,map) else ac) \n\t table (-1, Dmap.empty)\n in\n\n let (row,rmap) = find_good_pile rtable n in\n let (column,cmap) = find_good_pile ctable m in\n\t(* Printf.printf \"nimber = %d top_bit = %d row = %d column = %d\\n\" nimber top_bit row column; *)\n\n let (sx,sy,ex,ey) = if row >= 0 then (\n\tlet move = find_move nimber rmap n in\n\t (0, row, move, row)\n ) \n else if column >=0 then (\n\tlet move = find_move nimber cmap m in\n\t (column, 0, column, move)\n ) \n else (\n\tPrintf.printf \"Error: can't find move\\n\";\n\t(0,0,0,0)\n )\n in\n\tPrintf.printf \"FIRST\\n\";\n\tPrintf.printf \"%d %d %d %d\\n\" sx sy ex ey\n )\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nmodule Dmap = Map.Make (struct type t = int let compare = compare end)\n\nlet () = \n let (n,m) = read_pair() in\n let k = read_int() in\n\n let rtable = Hashtbl.create 100 in (* represent each of the m+1 rows of length n *)\n let ctable = Hashtbl.create 100 in (* represent each of the n+1 columns of length m *)\n\n let increment map key delta = \n let odelta = try Dmap.find key map with Not_found -> 0 in\n Dmap.add key (odelta+delta) map\n in\n\n let () = \n for i=0 to k-1 do\n let (a,b) = read_pair() in\n let (c,d) = read_pair() in\n let (table, which, lo, hi) = \n\tif a=c then (ctable, a, min b d, max b d)\n\telse (rtable, b, min a c, max a c)\n in\n let map = try Hashtbl.find table which with Not_found -> Dmap.empty in\n let map = increment map lo 1 in\n let map = increment map hi (-1) in\n\tHashtbl.replace table which map\n done\n in\n\n let maplength map dim = \n (* total length of the zero regions of this map, where b is the upper bound of things in it *)\n let rec loop depth ac x map = if Dmap.is_empty map then ac + (dim-x) else\n let (x',delta) = Dmap.min_binding map in\n let map = Dmap.remove x' map in\n let ac = if depth=0 then ac + (x'-x) else ac in\n let depth = delta + depth in\n\tloop depth ac x' map\n in\n loop 0 0 0 map\n in\n\n let find_move nimber map dim = \n (* returns the position in the given map so that a move from 0 to that position cancels out the nimber *)\n (* we know that it is possible to do this *)\n let rec loop depth need x map = if Dmap.is_empty map then x+need else\n let (x',delta) = Dmap.min_binding map in\n let map = Dmap.remove x' map in\n let need' = if depth=0 then need - (x'-x) else need in\n let depth = delta + depth in\n\tif need' > 0 then loop depth need' x' map\n\telse x+need\n in\n let pile = maplength map dim in\n let pile' = pile lxor nimber in\n loop 0 (pile - pile') 0 map\n in\n\n let augment_table table dim =\n (* add an extra row or column if the number of untouched rows/colunns is odd *)\n let size = Hashtbl.length table in\n if ((dim-1) - size) mod 2 = 1 then\n\tlet rec find_unused x = if not (Hashtbl.mem table x) then x else find_unused (x+1) in\n\tlet unused = find_unused 1 in\n\t Hashtbl.add table unused Dmap.empty\n in\n\n let () = \n augment_table rtable m;\n augment_table ctable n;\n in\n\n let compute_nimber table dim =\n Hashtbl.fold (fun _ map ac -> (maplength map dim) lxor ac) table 0\n in\n\n let nimber = (compute_nimber rtable n) lxor (compute_nimber ctable m) in\n\n (* Printf.printf \"nimber = %d\\n\" nimber; *)\n\n if nimber = 0 then Printf.printf \"SECOND\\n\" else (\n (* nimber is non-zero so we have to figure out what move to make *)\n (* find a move pile in which to move which has a 1 in the position of the\n\t top 1 bit of the nimber. *)\n let rec compute_top_bit b = if (b lor (b-1)) land nimber = nimber then b else compute_top_bit (2*b) in\n let top_bit = compute_top_bit 1 in\n let find_good_pile table dim =\n\tHashtbl.fold (fun v map ac -> if (top_bit land (maplength map dim)) <> 0 then (v,map) else ac) \n\t table (-1, Dmap.empty)\n in\n\n let (row,rmap) = find_good_pile rtable n in\n let (column,cmap) = find_good_pile ctable m in\n\t(* Printf.printf \"nimber = %d top_bit = %d row = %d column = %d\\n\" nimber top_bit row column; *)\n\n let (sx,sy,ex,ey) = if row >= 0 then (\n\tlet move = find_move nimber rmap n in\n\t (0, row, move, row)\n ) \n else if column >=0 then (\n\tlet move = find_move nimber cmap m in\n\t (column, 0, column, move)\n ) \n else (\n\tPrintf.printf \"Error: can't find move\\n\";\n\t(0,0,0,0)\n )\n in\n\tPrintf.printf \"FIRST\\n\";\n\tPrintf.printf \"%d %d %d %d\\n\" sx sy ex ey\n )\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nmodule Dmap = Map.Make (struct type t = int let compare = compare end)\n\nlet () = \n let (n,m) = read_pair() in\n let k = read_int() in\n let cuts = Array.init k (\n fun _ -> \n let (a,b) = read_pair() in\n let (c,d) = read_pair() in\n\t(a,b,c,d)\n ) in\n\n let rtable = Hashtbl.create 100 in (* represent each of the m+1 rows of length n *)\n let ctable = Hashtbl.create 100 in (* represent each of the n+1 columns of length m *)\n\n let increment map key delta = \n let odelta = try Dmap.find key map with Not_found -> 0 in\n Dmap.add key (odelta+delta) map\n in\n\n let () = \n for i=0 to k-1 do\n let (a,b,c,d) = cuts.(i) in\n let (table, which, lo, hi) = \n\tif a=c then (ctable, a, min b d, max b d)\n\telse (rtable, b, min a c, max a c)\n in\n let map = try Hashtbl.find table which with Not_found -> Dmap.empty in\n let map = increment map lo 1 in\n let map = increment map hi (-1) in\n\tHashtbl.replace table which map\n done\n in\n\n let maplength map dim = \n (* total length of the zero regions of this map, where b is the upper bound of things in it *)\n let rec loop depth ac x map = if Dmap.is_empty map then ac + (dim-x) else\n let (x',delta) = Dmap.min_binding map in\n let map = Dmap.remove x' map in\n let ac = if depth=0 then ac + (x'-x) else ac in\n let depth = delta + depth in\n\tloop depth ac x' map\n in\n loop 0 0 0 map\n in\n\n let find_move nimber map dim = \n (* returns the position in the given map so that a move from 0 to that position cancels out the nimber *)\n (* we know that it is possible to do this *)\n let rec loop depth need x map = if Dmap.is_empty map then x+need else\n let (x',delta) = Dmap.min_binding map in\n let map = Dmap.remove x' map in\n let need' = if depth=0 then need - (x'-x) else need in\n let depth = delta + depth in\n\tif need' > 0 then loop depth need' x' map\n\telse x+need\n in\n let pile = maplength map dim in\n let pile' = pile lxor nimber in\n loop 0 (pile - pile') 0 map\n in\n\n let augment_table table dim =\n (* add an extra row or column if the number of untouched rows/colunns is odd *)\n let size = Hashtbl.length table in\n if ((dim+1) - size) mod 2 = 1 then\n\tlet rec find_unused x = if not (Hashtbl.mem table x) then x else find_unused (x+1) in\n\tlet unused = find_unused 0 in\n\t Hashtbl.add table unused Dmap.empty\n in\n\n let () = \n augment_table rtable m;\n augment_table ctable n;\n in\n\n let compute_nimber table dim =\n Hashtbl.fold (fun _ map ac -> (maplength map dim) lxor ac) table 0\n in\n\n let nimber = (compute_nimber rtable n) lxor (compute_nimber ctable m) in\n\n (* Printf.printf \"nimber = %d\\n\" nimber; *)\n\n if nimber = 0 then Printf.printf \"SECOND\\n\" else (\n (* nimber is non-zero so we have to figure out what move to make *)\n (* find a move pile in which to move which has a 1 in the position of the\n\t top 1 bit of the nimber. *)\n let rec compute_top_bit b = if (b lor (b-1)) land nimber = nimber then b else compute_top_bit (2*b) in\n let top_bit = compute_top_bit 1 in\n let find_good_pile table dim =\n\tHashtbl.fold (fun v map ac -> if (top_bit land (maplength map dim)) <> 0 then (v,map) else ac) \n\t table (-1, Dmap.empty)\n in\n\n let (row,rmap) = find_good_pile rtable n in\n let (column,cmap) = find_good_pile ctable m in\n\t(* Printf.printf \"nimber = %d top_bit = %d row = %d column = %d\\n\" nimber top_bit row column; *)\n\n let (sx,sy,ex,ey) = if row >= 0 then (\n\tlet move = find_move nimber rmap n in\n\t (0, row, move, row)\n ) \n else if column >=0 then (\n\tlet move = find_move nimber cmap m in\n\t (column, 0, column, move)\n ) \n else (\n\tPrintf.printf \"Error: can't find move\\n\";\n\t(0,0,0,0)\n )\n in\n\tPrintf.printf \"FIRST\\n\";\n\tPrintf.printf \"%d %d %d %d\\n\" sx sy ex ey\n )\n"}], "src_uid": "a7fa7a5ab71690fb3b5301bebc19956b"} {"nl": {"description": "Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above.", "input_spec": "The first line contains three space-separated integers n,\u2009s,\u2009l (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009s\u2009\u2264\u2009109,\u20091\u2009\u2264\u2009l\u2009\u2264\u2009105). The second line contains n integers ai separated by spaces (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Output the minimal number of strip pieces. If there are no ways to split the strip, output -1.", "sample_inputs": ["7 2 2\n1 3 1 2 4 1 2", "7 2 2\n1 100 1 100 1 100 1"], "sample_outputs": ["3", "-1"], "notes": "NoteFor the first sample, we can split the strip into 3 pieces: [1,\u20093,\u20091],\u2009[2,\u20094],\u2009[1,\u20092].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\nlet abs64 = Int64.abs\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet rec mylog n = if n=1 then 0 else 1+(mylog (n/2))\n\nlet build_range_mmin a n mmin =\n (* construct an array of arrays m.().()\n where m.(i).(j) is the mmin of the 2^i elements from a.(j) ... a.(j+2^i-1)\n *)\n let k = mylog n in (* 2^k is the biggest block we use, so use 2^0...2^k *)\n\n let m = Array.make (k+1) [||] in\n m.(0) <- Array.copy a;\n for kk = 1 to k do\n let b = 1 lsl kk in (* block size *)\n m.(kk) <- Array.make (n-b+1) 0L;\n for j=0 to n-b do\n m.(kk).(j) <- mmin m.(kk-1).(j) m.(kk-1).(j+b/2)\n done\n done;\n (m,k,n)\n\nlet range_mmin a b (m,_,_) mmin =\n let k = mylog (b-a+1) in\n let bl = 1 lsl k in (* block size *)\n mmin m.(k).(a) m.(k).(b-bl+1)\n\nlet () = \n let n = read_int() in\n let s = read_long() in\n let l = read_int() in\n\n let a = Array.init n (fun _ -> read_long()) in\n\n let m = Array.make n 0 in\n\n let minrange = build_range_mmin a n min in\n let maxrange = build_range_mmin a n max in\n\n let rec label_loop i j = if j>=n then ()\n else if i+1 > j || j-i < l then label_loop i (j+1)\n else if i <> -1 && m.(i) = 0 then label_loop (i+1) j\n else (\n let lo = range_mmin (i+1) j minrange min in\n let hi = range_mmin (i+1) j maxrange max in\n if hi--lo > s then label_loop (i+1) j\n else (\n\tm.(j) <- if i = -1 then 1 else m.(i)+1;\n\tlabel_loop i (j+1)\n )\n )\n in\n \n label_loop (-1) (l-1);\n \n printf \"%d\\n\" (if m.(n-1) = 0 then -1 else m.(n-1))\n"}], "negative_code": [], "src_uid": "3d670528c82a7d8dcd187b7304d36f96"} {"nl": {"description": "Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open\u00a0\u2014 for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.", "input_spec": "The first line contains two integers $$$n$$$ and $$$s$$$ ($$$2 \\le s \\le n \\le 1000$$$)\u00a0\u2014 the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $$$1$$$. Next lines describe information about closed and open stations. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$). If $$$a_i = 1$$$, then the $$$i$$$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track. The third line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$b_i = 0$$$ or $$$b_i = 1$$$). If $$$b_i = 1$$$, then the $$$i$$$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.", "output_spec": "Print \"YES\" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and \"NO\" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["5 3\n1 1 1 1 1\n1 1 1 1 1", "5 4\n1 0 0 0 1\n0 1 1 1 1", "5 2\n0 1 1 1 1\n1 1 1 1 1"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first example, all stations are opened, so Bob can simply travel to the station with number $$$3$$$.In the second example, Bob should travel to the station $$$5$$$ first, switch to the second track and travel to the station $$$4$$$ then.In the third example, Bob simply can't enter the train going in the direction of Alice's home."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,s = get_2_i64 0 in\n let u = input_i64_array n in\n let d = input_i64_array n in\n let f11 = repm (s+1L) n false (fun m i ->\n let i = i32 i-$1 in\n if u.(i) = 1L && d.(i) = 1L then (\n `Break_m true\n ) else `Ok m\n ) in\n let f =\n if u.(0)<>1L then false\n else if u.(i32 s-$1)=1L then true\n else if d.(i32 s-$1)=1L && f11 then true\n else false\n in print_endline @@ if f then \"YES\" else \"NO\"\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,s = get_2_i64 0 in\n let u = input_i64_array n in\n let d = input_i64_array n in\n let f = repm 1L n false (fun m i ->\n let i = i32 i-$1 in\n if u.(i) = 1L && d.(i) = 1L then (\n `Break_m true\n ) else `Ok m\n ) in\n print_endline@@ if u.(0)<>1L || d.(i32 s-$1)<>1L || not f then \"NO\" else \"YES\"\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,s = get_2_i64 0 in\n let u = input_i64_array n in\n let d = input_i64_array n in\n let f11 = repm 1L n false (fun m i ->\n let i = i32 i-$1 in\n if u.(i) = 1L && d.(i) = 1L then (\n `Break_m true\n ) else `Ok m\n ) in\n (* print_endline@@ if u.(0)<>1L || d.(i32 s-$1)<>1L || not f then \"NO\" else \"YES\" *)\n let fall =\n if u.(0)=1L && u.(i32 s-$1)=1L then true\n else if d.(0)=1L && d.(i32 s-$1)=1L then true\n else if u.(0)=1L && d.(i32 s-$1)=1L && f11 then true\n else if d.(0)=1L && u.(i32 s-$1)=1L && f11 then true\n else false\n in print_endline @@ if fall then \"YES\" else \"NO\"\n\n\n\n\n\n\n"}], "src_uid": "64b597a47106d0f08fcfad155e0495c3"} {"nl": {"description": "Polycarp likes to play with numbers. He takes some integer number $$$x$$$, writes it down on the board, and then performs with it $$$n - 1$$$ operations of the two kinds: divide the number $$$x$$$ by $$$3$$$ ($$$x$$$ must be divisible by $$$3$$$); multiply the number $$$x$$$ by $$$2$$$. After each operation, Polycarp writes down the result on the board and replaces $$$x$$$ by the result. So there will be $$$n$$$ numbers on the board after all.You are given a sequence of length $$$n$$$ \u2014 the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.", "input_spec": "The first line of the input contatins an integer number $$$n$$$ ($$$2 \\le n \\le 100$$$) \u2014 the number of the elements in the sequence. The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 3 \\cdot 10^{18}$$$) \u2014 rearranged (reordered) sequence that Polycarp can wrote down on the board.", "output_spec": "Print $$$n$$$ integer numbers \u2014 rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists.", "sample_inputs": ["6\n4 8 6 3 12 9", "4\n42 28 84 126", "2\n1000000000000000000 3000000000000000000"], "sample_outputs": ["9 3 6 12 4 8", "126 42 84 28", "3000000000000000000 1000000000000000000"], "notes": "NoteIn the first example the given sequence can be rearranged in the following way: $$$[9, 3, 6, 12, 4, 8]$$$. It can match possible Polycarp's game which started with $$$x = 9$$$."}, "positive_code": [{"source_code": "let ($) f g = fun x -> g (f x)\nlet split_string ?(pattern=\"\") = Str.split @@ Str.regexp pattern\nlet n = Scanf.sscanf (read_line ()) \"%d\" @@ fun n -> n\nlet a = read_line () |> split_string ~pattern:\" \" |> List.map Int64.of_string\n\nlet three = Int64.of_int 3\n\nlet deg_3 =\n let rec f i n = if n = (Int64.mul (Int64.div n three) three) then f (i + 1) (Int64. div n three) else i in\n f 0\n\nlet () =\n List.map (fun i -> (-deg_3 i, i)) a \n |> List.sort compare\n |> List.map (snd $ Int64.to_string)\n |> String.concat \" \"\n |> print_endline\n "}], "negative_code": [], "src_uid": "f9375003a3b64bab17176a05764c20e8"} {"nl": {"description": "The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1\u2009\u2264\u2009lj\u2009\u2264\u2009rj\u2009\u2264\u2009n). For each query lj,\u2009rj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj,\u2009alj\u2009+\u20091,\u2009...,\u2009arj.Help the Little Elephant to count the answers to all queries.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1\u2009\u2264\u2009lj\u2009\u2264\u2009rj\u2009\u2264\u2009n).", "output_spec": "In m lines print m integers \u2014 the answers to the queries. The j-th line should contain the answer to the j-th query.", "sample_inputs": ["7 2\n3 1 2 2 3 3 7\n1 7\n3 4"], "sample_outputs": ["3\n1"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let c = Hashtbl.create n in\n let ls = Array.make m 0 in\n let rs = Array.make m 0 in\n let res = Array.make m 0 in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- k;\n\ttry\n\t let cnt = Hashtbl.find c k in\n\t Hashtbl.replace c k (cnt + 1)\n\twith\n\t | Not_found -> Hashtbl.replace c k 1\n done;\n for i = 0 to m - 1 do\n ls.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n rs.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n done;\n in\n let ds = ref [] in\n let () =\n for i = 0 to n - 1 do\n let k = a.(i) in\n\tif k <= Hashtbl.find c k then (\n\t ds := k :: !ds;\n\t Hashtbl.replace c k (-1)\n\t)\n done\n in\n let b = Array.make (n + 1) 0 in\n List.iter\n (fun d ->\n\t b.(0) <- 0;\n\t for i = 1 to n do\n\t b.(i) <- b.(i - 1) + if a.(i - 1) = d then 1 else 0;\n\t done;\n\t for i = 0 to m - 1 do\n\t if d = b.(rs.(i)) - b.(ls.(i) - 1)\n\t then res.(i) <- res.(i) + 1\n\t done\n ) !ds;\n for i = 0 to m - 1 do\n Printf.printf \"%d\\n\" res.(i)\n done\n"}], "negative_code": [], "src_uid": "5c92ede00232d6a22385be29ecd06ddd"} {"nl": {"description": "For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l\u2009\u2264\u2009ai\u2009\u2264\u2009r and ai\u2009\u2260\u2009aj , where a1,\u2009a2,\u2009...,\u2009an is the geometrical progression, 1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n and i\u2009\u2260\u2009j.Geometrical progression is a sequence of numbers a1,\u2009a2,\u2009...,\u2009an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4,\u20096,\u20099, common ratio is .Two progressions a1,\u2009a2,\u2009...,\u2009an and b1,\u2009b2,\u2009...,\u2009bn are considered different, if there is such i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) that ai\u2009\u2260\u2009bi.", "input_spec": "The first and the only line cotains three integers n, l and r (1\u2009\u2264\u2009n\u2009\u2264\u2009107,\u20091\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009107).", "output_spec": "Print the integer K\u00a0\u2014 is the answer to the problem.", "sample_inputs": ["1 1 10", "2 6 9", "3 1 10", "3 3 10"], "sample_outputs": ["10", "12", "8", "2"], "notes": "NoteThese are possible progressions for the first test of examples: 1; 2; 3; 4; 5; 6; 7; 8; 9; 10. These are possible progressions for the second test of examples: 6,\u20097; 6,\u20098; 6,\u20099; 7,\u20096; 7,\u20098; 7,\u20099; 8,\u20096; 8,\u20097; 8,\u20099; 9,\u20096; 9,\u20097; 9,\u20098. These are possible progressions for the third test of examples: 1,\u20092,\u20094; 1,\u20093,\u20099; 2,\u20094,\u20098; 4,\u20092,\u20091; 4,\u20096,\u20099; 8,\u20094,\u20092; 9,\u20093,\u20091; 9,\u20096,\u20094. These are possible progressions for the fourth test of examples: 4,\u20096,\u20099; 9,\u20096,\u20094. "}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n if n = 1\n then Printf.printf \"%d\\n\" (r - l + 1)\n else if n = 2\n then Printf.printf \"%Ld\\n\"\n (Int64.of_int (r - l + 1) *| Int64.of_int (r - l))\n else (\n let pow a n =\n\tlet r = ref 1 in\n\t for i = 1 to n do\n\t r := !r * a\n\t done;\n\t !r\n in\n let m = int_of_float (float_of_int r ** (1.0 /. float_of_int (n - 1)) +. 0.000001) in\n let res = ref 0L in\n\tfor a = 1 to m do\n\t for b = a + 1 to m do\n\t if gcd a b = 1 then (\n\t let k1 = r / pow b (n - 1) in\n\t let k2 = (l - 1) / pow a (n - 1) in\n\t\t(*Printf.printf \"asd %d %d %d %d\\n\" a b k2 k1;*)\n\t\tif k1 > k2\n\t\tthen res := !res +| Int64.of_int (k1 - k2)\n\t )\n\t done\n\tdone;\n\tres := !res *| 2L;\n\tPrintf.printf \"%Ld\\n\" !res\n )\n"}], "negative_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n if n = 1\n then Printf.printf \"%d\\n\" (r - l + 1)\n else if n = 2\n then Printf.printf \"%Ld\\n\"\n (Int64.of_int (r - l + 1) *| Int64.of_int (r - l))\n else (\n let pow a n =\n\tlet r = ref 1 in\n\t for i = 1 to n do\n\t r := !r * a\n\t done;\n\t !r\n in\n let m = int_of_float (float_of_int r ** (1.0 /. float_of_int (n - 1))) in\n let res = ref 0L in\n\tfor a = 1 to m do\n\t for b = a + 1 to m do\n\t if gcd a b = 1 then (\n\t let k1 = r / pow b (n - 1) in\n\t let k2 = (l - 1) / pow a (n - 1) in\n\t\t(*Printf.printf \"asd %d %d %d %d\\n\" a b k2 k1;*)\n\t\tif k1 > k2\n\t\tthen res := !res +| Int64.of_int (k1 - k2)\n\t )\n\t done\n\tdone;\n\tres := !res *| 2L;\n\tPrintf.printf \"%Ld\\n\" !res\n )\n"}], "src_uid": "5d0a985a0dced0734aff6bb0cd1b695d"} {"nl": {"description": "In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the \"virtual\" link in this chain, wondering where this legendary figure has left.The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.", "input_spec": "The first line contains two integers n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) and x (1\u2009\u2264\u2009x\u2009\u2264\u2009n) \u2014 the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 the number of the beaver followed by the i-th beaver. If ai\u2009=\u20090, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue. The input limits for scoring 30 points are (subproblem B1): It is guaranteed that the number of zero elements ai doesn't exceed 20. The input limits for scoring 100 points are (subproblems B1+B2): The number of zero elements ai is arbitrary. ", "output_spec": "Print all possible positions of the Smart Beaver in the line in the increasing order.", "sample_inputs": ["6 1\n2 0 4 0 6 0", "6 2\n2 3 0 5 6 0", "4 1\n0 0 0 0", "6 2\n0 0 1 0 4 5"], "sample_outputs": ["2\n4\n6", "2\n5", "1\n2\n3\n4", "1\n3\n4\n6"], "notes": "Note Picture for the fourth test. "}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = x - 1 in\n let a = Array.make n 0 in\n let b = Array.make n (-1) in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- k - 1;\n\tif k > 0\n\tthen b.(k - 1) <- i\n done;\n in\n let used = Array.make n false in\n let c = Array.make n 1 in\n let rec dfs k =\n used.(k) <- true;\n if b.(k) >= 0 then (\n dfs b.(k);\n c.(k) <- c.(b.(k)) + 1;\n )\n in\n let used2 = Array.make n false in\n let bob =\n let c = ref 1 in\n let p = ref x in\n used2.(x) <- true;\n while a.(!p) >= 0 do\n\tincr c;\n\tp := a.(!p);\n\tused2.(!p) <- true;\n done;\n !c\n in\n let () =\n for i = 0 to n - 1 do\n if not used.(i)\n then dfs i\n done;\n in\n let s = ref [] in\n let () =\n for i = 0 to n - 1 do\n if not used2.(i) && a.(i) < 0\n then s := c.(i) :: !s\n done;\n in\n let s = Array.of_list !s in\n let a = Array.make (n + 1) false in\n a.(0) <- true;\n for k = 0 to Array.length s - 1 do\n let k = s.(k) in\n(*Printf.printf \"asd %d\\n\" k;*)\n\tfor i = n downto k do\n\t if a.(i - k)\n\t then a.(i) <- true\n\tdone\n done;\n (*for i = 0 to n - 1 do\n Printf.printf \"c %d %d %d\\n\" i c.(i) x;\n done;*)\n for i = 0 to n do\n if a.(i)\n then Printf.printf \"%d\\n\" (i + bob);\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = x - 1 in\n let a = Array.make n 0 in\n let b = Array.make n (-1) in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- k - 1;\n\tif k > 0\n\tthen b.(k - 1) <- i\n done;\n in\n let used = Array.make n false in\n let c = Array.make n 1 in\n let rec dfs k =\n used.(k) <- true;\n if b.(k) >= 0 then (\n dfs b.(k);\n c.(k) <- c.(b.(k)) + 1;\n )\n in\n let used2 = Array.make n false in\n let bob =\n let c = ref 1 in\n let p = ref x in\n used2.(x) <- true;\n while a.(!p) >= 0 do\n\tincr c;\n\tp := a.(!p);\n\tused2.(!p) <- true;\n done;\n !c\n in\n let () =\n for i = 0 to n - 1 do\n if not used.(i)\n then dfs i\n done;\n in\n let s = ref [] in\n let () =\n for i = 0 to n - 1 do\n if not used2.(i) && a.(i) < 0\n then s := c.(i) :: !s\n done;\n in\n let s = Array.of_list !s in\n let a = Array.make (n + 1) false in\n a.(0) <- true;\n for k = 0 to Array.length s - 1 do\n let k = s.(k) in\n(*Printf.printf \"asd %d\\n\" k;*)\n\tfor i = n downto k do\n\t if a.(i - k)\n\t then a.(i) <- true\n\tdone\n done;\n (*for i = 0 to n - 1 do\n Printf.printf \"c %d %d %d\\n\" i c.(i) x;\n done;*)\n for i = 0 to n do\n if a.(i)\n then Printf.printf \"%d\\n\" (i + bob);\n done\n"}], "negative_code": [], "src_uid": "5a6b97a2aa27dd2c562f73a7a8f16720"} {"nl": {"description": "Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105). The second line contains the sequence of 2n positive integers a1,\u2009a2,\u2009...,\u2009a2n (1\u2009\u2264\u2009ai\u2009\u2264\u20095000) \u2014 the numbers that are written on the cards. The numbers on the line are separated by single spaces.", "output_spec": "If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line \u2014 the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.", "sample_inputs": ["3\n20 30 10 30 20 10", "1\n1 2"], "sample_outputs": ["4 2\n1 5\n6 3", "-1"], "notes": null}, "positive_code": [{"source_code": "let input = open_in \"input.txt\"\nlet output = open_out \"output.txt\"\n\nlet read_int () = Scanf.fscanf input \" %d \" (fun x -> x) ;;\n\nlet n = read_int () ;;\n\nlet a = \n let len = 2 * n \n in let rec loop i f = \n if i > len then f []\n else let ai = read_int () in loop (i + 1) (fun l -> f ((ai, i) :: l))\n in loop 1 (fun x -> x) ;;\n\nlet seen = Array.make 5001 0 ;;\n\nlet pairs = \n let rec loop l a = match l with\n | [] -> a\n | (v, i) :: t ->\n if seen.(v) = 0 then (seen.(v) <- i ; loop t a)\n else let j = seen.(v) in seen.(v) <- 0 ; loop t ((j, i) :: a)\n in loop a [] ;;\n \nlet possible =\n let rec loop i =\n if i > 5000 then true \n else if seen.(i) <> 0 then false else loop (i + 1)\n in loop 1 ;;\n \nlet print_pair (a, b) = Printf.fprintf output \"%d %d\\n\" a b ;;\n\nif not possible then Printf.fprintf output \"-1\\n\"\nelse \n let rec loop = function\n | [] -> ()\n | h :: t -> print_pair h ; loop t\n in loop pairs ;;"}, {"source_code": "let input = open_in \"input.txt\"\nlet output = open_out \"output.txt\"\n\nlet read_int () = Scanf.fscanf input \" %d \" (fun x -> x) ;;\n\nlet n = read_int () ;;\n\nlet a = \n let len = 2 * n \n in let rec loop i f = \n if i > len then f []\n else let ai = read_int () in loop (i + 1) (fun l -> f ((ai, i) :: l))\n in loop 1 (fun x -> x) ;;\n\nlet upper = List.fold_left (fun x (v, i) -> max x v) 0 a ;;\nlet seen = Array.make (upper + 1) 0 ;;\n\nlet pairs = \n let rec loop l a = match l with\n | [] -> a\n | (v, i) :: t ->\n if seen.(v) = 0 then (seen.(v) <- i ; loop t a)\n else let j = seen.(v) in seen.(v) <- 0 ; loop t ((j, i) :: a)\n in loop a [] ;;\n \nlet possible =\n let rec loop i =\n if i > upper then true \n else if seen.(i) <> 0 then false else loop (i + 1)\n in loop 1 ;;\n \nif not possible then Printf.fprintf output \"-1\\n\"\nelse\n let print_pair (a, b) = Printf.fprintf output \"%d %d\\n\" a b \n in let rec loop = function\n | [] -> ()\n | h :: t -> print_pair h ; loop t\n in loop pairs ;;"}, {"source_code": "\nlet chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet () = \n let n = read_int() in\n let a = Array.init (2*n) (fun _ -> read_int()) in\n\n let t = Array.make 5001 (-1) in\n\n let rec loop i p = if i=2*n then () else (\n if t.(a.(i)) >= 0 then (\n if p then print_string (Printf.sprintf \"%d %d\\n\" (1+t.(a.(i))) (i+1));\n t.(a.(i)) <- -1;\n loop (i+1) p\n ) else (\n t.(a.(i)) <- i;\n loop (i+1) p\n )\n )\n in\n \n loop 0 false;\n\n if (maxf 0 5000 (fun i-> t.(i))) = -1 then (\n loop 0 true;\n ) else (\n print_string \"-1\\n\"\n )\n"}], "negative_code": [{"source_code": "let chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nmodule Iset = Set.Make (struct type t = int let compare = compare end)\n\nlet () = \n let n = read_int() in\n let a = Array.init (2*n) (fun _ -> read_int()) in\n\n let rec loop i p s = if i=2*n then s else (\n if Iset.mem a.(i) s \n then (\n if p then print_string (Printf.sprintf \"%d %d\\n\" a.(i) a.(i));\n loop (i+1) p (Iset.remove a.(i) s)\n )\n else loop (i+1) p (Iset.add a.(i) s)\n )\n in\n let s = loop 0 false Iset.empty in\n\n if Iset.is_empty s then (\n ignore (loop 0 true Iset.empty)\n ) else (\n print_string \"-1\\n\"\n )\n"}], "src_uid": "0352429425782d7fe44818594eb0660c"} {"nl": {"description": "You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.", "input_spec": "In the first line of the input two integers n and S (3\u2009\u2264\u2009n\u2009\u2264\u20095000, 1\u2009\u2264\u2009S\u2009\u2264\u20091018) are given\u00a0\u2014 the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi (\u2009-\u2009108\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009108)\u00a0\u2014 coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.", "output_spec": "Print the coordinates of three points\u00a0\u2014 vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.", "sample_inputs": ["4 1\n0 0\n1 0\n0 1\n1 1"], "sample_outputs": ["-1 0\n2 0\n0 2"], "notes": "Note "}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let ps = Array.make n (0L, 0L) in\n let _ =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n\tps.(i) <- (x, y)\n done;\n in\n let cross x1 y1 x2 y2 = x1 *| y2 -| x2 *| y1 in\n let area3 (x, y) (x1, y1) (x2, y2) =\n x *| y1 +| x1 *| y2 +| x2 *| y -| x2 *| y1 -| x1 *| y -| x *| y2\n in\n let cmp ((x1 : int64), (y1 : int64)) (x2, y2) =\n if x1 < x2\n then -1\n else if x1 > x2\n then 1\n else compare y1 y2\n in\n let _ = Array.sort cmp ps in\n (* Convex hull *)\n let p1 = ps.(0)\n and p2 = ps.(n - 1) in\n let up = Array.make n (0L, 0L) in\n let down = Array.make n (0L, 0L) in\n let pos_up = ref 0 in\n let pos_down = ref 0 in\n let hull =\n up.(!pos_up) <- p1;\n incr pos_up;\n down.(!pos_down) <- p1;\n incr pos_down;\n for i = 1 to n - 1 do\n if i = n - 1 || area3 p1 ps.(i) p2 < 0L then (\n\twhile !pos_up >= 2 &&\n\t area3 up.(!pos_up - 2) up.(!pos_up - 1) ps.(i) >= 0L do\n\t decr pos_up\n\tdone;\n\tup.(!pos_up) <- ps.(i);\n\tincr pos_up;\n );\n if i = n - 1 || area3 p1 ps.(i) p2 > 0L then (\n\twhile !pos_down >= 2 &&\n\t area3 down.(!pos_down - 2) down.(!pos_down - 1) ps.(i) <= 0L do\n\t decr pos_down\n\tdone;\n\tdown.(!pos_down) <- ps.(i);\n\tincr pos_down;\n );\n done;\n let hull = Array.make (!pos_up + !pos_down - 2) ps.(0) in\n for i = 0 to !pos_up - 1 do\n\thull.(i) <- up.(i)\n done;\n for i = !pos_down - 2 downto 1 do\n\thull.(!pos_down - 2 - i + !pos_up) <- down.(i)\n done;\n hull\n in\n let area3 (x, y) (x1, y1) (x2, y2) =\n let x = float_of_int x\n and y = float_of_int y\n and x1 = float_of_int x1\n and y1 = float_of_int y1\n and x2 = float_of_int x2\n and y2 = float_of_int y2 in\n x *. y1 +. x1 *. y2 +. x2 *. y -. x2 *. y1 -. x1 *. y -. x *. y2\n in\n let hull =\n Array.map (fun (x, y) -> (Int64.to_int x, Int64.to_int y)) hull\n in\n let maxs = ref 0.0 in\n let b = ref (0, 0, 0) in\n (*for i = 0 to Array.length hull - 1 do\n let (x, y) = hull.(i) in\n\tPrintf.eprintf \"asd %Ld %Ld\\n\" x y\n done;*)\n for i = 0 to Array.length hull - 1 do\n let k = ref i in\n\tfor j = i + 2 to Array.length hull - 1 do\n\t let s = ref 0.0 in\n\t let s' = ref 0.0 in\n\t s := abs_float (area3 hull.(i) hull.(j) hull.(!k));\n\t while !k < j - 1 &&\n\t (s' := abs_float (area3 hull.(i) hull.(j) hull.(!k + 1));\n\t !s' >= !s)\n\t do\n\t incr k;\n\t s := !s';\n\t (*Printf.eprintf \"qaz %d %d %d %Ld\\n\" i j !k !s;*)\n\t done;\n\t (*Printf.eprintf \"zxc %d %d %Ld\\n\" i j !s;*)\n\t if !maxs < !s then (\n\t maxs := !s;\n\t b := (i, j, !k);\n\t )\n\tdone;\n done;\n let (i, j, k) = !b in\n let (x1, y1) = hull.(i)\n and (x2, y2) = hull.(j)\n and (x3, y3) = hull.(k) in\n (*Printf.eprintf \"qwe %Ld %Ld\\n\" x1 y1;\n Printf.eprintf \"qwe %Ld %Ld\\n\" x2 y2;\n Printf.eprintf \"qwe %Ld %Ld\\n\" x3 y3;*)\n Printf.printf \"%d %d\\n\" (x2 + x3 - x1) (y2 + y3 - y1);\n Printf.printf \"%d %d\\n\" (x3 + x1 - x2) (y3 + y1 - y2);\n Printf.printf \"%d %d\\n\" (x1 + x2 - x3) (y1 + y2 - y3);\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n \nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet cross (x1,y1) (x2,y2) = (x1**y2) -- (y1**x2)\nlet ( --- ) (x1,y1) (x2,y2) = (x1--x2, y1--y2)\nlet ( +++ ) (x1,y1) (x2,y2) = (x1++x2, y1++y2) \n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let _ = read_long () in (* don't need s *)\n let p = Array.init n (fun _ ->\n let x = read_long() in\n (x, read_long())\n ) in\n\n let area a b c = Int64.abs (cross (b --- a) (c --- a)) in\n\n let rec expand no_change_count ar (a,b,c) =\n if no_change_count = 2 then (a,b,c) else\n let (ar', c') = maxf 0 (n-1) (fun c -> (area p.(a) p.(b) p.(c), c)) in\n if ar' > ar then expand 0 ar' (c',a,b) else expand (no_change_count+1) ar (c,a,b)\n in\n\n let (a,b,c) = expand 0 0L (0,1,2) in\n let (a,b,c) = (p.(a), p.(b), p.(c)) in\n \n let pr (x,y) = printf \"%Ld %Ld\\n\" x y in\n pr (a +++ b --- c);\n pr (b +++ c --- a);\n pr (c +++ a --- b)\n"}], "negative_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let ps = Array.make n (0L, 0L) in\n let _ =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n\tps.(i) <- (x, y)\n done;\n in\n let cross x1 y1 x2 y2 = x1 *| y2 -| x2 *| y1 in\n let area3 (x, y) (x1, y1) (x2, y2) =\n x *| y1 +| x1 *| y2 +| x2 *| y -| x2 *| y1 -| x1 *| y -| x *| y2\n in\n let cmp ((x1 : int64), (y1 : int64)) (x2, y2) =\n if x1 < x2\n then -1\n else if x1 > x2\n then 1\n else compare y1 y2\n in\n let _ = Array.sort cmp ps in\n (* Convex hull *)\n let p1 = ps.(0)\n and p2 = ps.(n - 1) in\n let up = Array.make n (0L, 0L) in\n let down = Array.make n (0L, 0L) in\n let pos_up = ref 0 in\n let pos_down = ref 0 in\n let hull =\n up.(!pos_up) <- p1;\n incr pos_up;\n down.(!pos_down) <- p1;\n incr pos_down;\n for i = 1 to n - 1 do\n if i = n - 1 || area3 p1 ps.(i) p2 < 0L then (\n\twhile !pos_up >= 2 &&\n\t area3 up.(!pos_up - 2) up.(!pos_up - 1) ps.(i) >= 0L do\n\t decr pos_up\n\tdone;\n\tup.(!pos_up) <- ps.(i);\n\tincr pos_up;\n );\n if i = n - 1 || area3 p1 ps.(i) p2 > 0L then (\n\twhile !pos_down >= 2 &&\n\t area3 down.(!pos_down - 2) down.(!pos_down - 1) ps.(i) <= 0L do\n\t decr pos_down\n\tdone;\n\tdown.(!pos_down) <- ps.(i);\n\tincr pos_down;\n );\n done;\n let hull = Array.make (!pos_up + !pos_down - 2) ps.(0) in\n for i = 0 to !pos_up - 1 do\n\thull.(i) <- up.(i)\n done;\n for i = !pos_down - 2 downto 1 do\n\thull.(!pos_down - 2 - i + !pos_up) <- down.(i)\n done;\n hull\n in\n let maxs = ref 0L in\n let b = ref (0, 0, 0) in\n (*for i = 0 to Array.length hull - 1 do\n let (x, y) = hull.(i) in\n\tPrintf.eprintf \"asd %Ld %Ld\\n\" x y\n done;*)\n for i = 0 to Array.length hull - 1 do\n let k = ref i in\n let s = ref 0L in\n\tfor j = i + 2 to Array.length hull - 1 do\n\t while !k < j - 1 &&\n\t Int64.abs (area3 hull.(i) hull.(j) hull.(!k + 1)) > !s\n\t do\n\t incr k;\n\t s := Int64.abs (area3 hull.(i) hull.(j) hull.(!k));\n\t done;\n\t if !maxs < !s then (\n\t maxs := !s;\n\t b := (i, j, !k);\n\t )\n\tdone;\n done;\n let (i, j, k) = !b in\n let (x1, y1) = hull.(i)\n and (x2, y2) = hull.(j)\n and (x3, y3) = hull.(k) in\n Printf.printf \"%Ld %Ld\\n\" (x2 +| x3 -| x1) (y2 +| y3 -| y1);\n Printf.printf \"%Ld %Ld\\n\" (x3 +| x1 -| x2) (y3 +| y1 -| y2);\n Printf.printf \"%Ld %Ld\\n\" (x1 +| x2 -| x3) (y1 +| y2 -| y3);\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let ps = Array.make n (0L, 0L) in\n let _ =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n\tps.(i) <- (x, y)\n done;\n in\n let cross x1 y1 x2 y2 = x1 *| y2 -| x2 *| y1 in\n let area3 (x, y) (x1, y1) (x2, y2) =\n x *| y1 +| x1 *| y2 +| x2 *| y -| x2 *| y1 -| x1 *| y -| x *| y2\n in\n let cmp ((x1 : int64), (y1 : int64)) (x2, y2) =\n if x1 < x2\n then -1\n else if x1 > x2\n then 1\n else compare y1 y2\n in\n let _ = Array.sort cmp ps in\n (* Convex hull *)\n let p1 = ps.(0)\n and p2 = ps.(n - 1) in\n let up = Array.make n (0L, 0L) in\n let down = Array.make n (0L, 0L) in\n let pos_up = ref 0 in\n let pos_down = ref 0 in\n let hull =\n up.(!pos_up) <- p1;\n incr pos_up;\n down.(!pos_down) <- p1;\n incr pos_down;\n for i = 1 to n - 1 do\n if i = n - 1 || area3 p1 ps.(i) p2 < 0L then (\n\twhile !pos_up >= 2 &&\n\t area3 up.(!pos_up - 2) up.(!pos_up - 1) ps.(i) > 0L do\n\t decr pos_up\n\tdone;\n\tup.(!pos_up) <- ps.(i);\n\tincr pos_up;\n );\n if i = n - 1 || area3 p1 ps.(i) p2 > 0L then (\n\twhile !pos_down >= 2 &&\n\t area3 down.(!pos_down - 2) down.(!pos_down - 1) ps.(i) < 0L do\n\t decr pos_down\n\tdone;\n\tdown.(!pos_down) <- ps.(i);\n\tincr pos_down;\n );\n done;\n let hull = Array.make (!pos_up + !pos_down - 2) ps.(0) in\n for i = 0 to !pos_up - 1 do\n\thull.(i) <- up.(i)\n done;\n for i = !pos_down - 2 downto 1 do\n\thull.(!pos_down - 2 - i + !pos_up) <- down.(i)\n done;\n hull\n in\n let maxs = ref 0L in\n let b = ref (0, 0, 0) in\n (*for i = 0 to Array.length hull - 1 do\n let (x, y) = hull.(i) in\n\tPrintf.printf \"asd %Ld %Ld\\n\" x y\n done;*)\n for i = 0 to Array.length hull - 1 do\n let k = ref i in\n let s = ref 0L in\n\tfor j = i + 2 to Array.length hull - 1 do\n\t while !k < j - 1 &&\n\t Int64.abs (area3 hull.(i) hull.(j) hull.(!k + 1)) > !s\n\t do\n\t incr k;\n\t s := Int64.abs (area3 hull.(i) hull.(j) hull.(!k));\n\t done;\n\t if !maxs < !s then (\n\t maxs := !s;\n\t b := (i, j, !k);\n\t )\n\tdone;\n done;\n let (i, j, k) = !b in\n let (x1, y1) = hull.(i)\n and (x2, y2) = hull.(j)\n and (x3, y3) = hull.(k) in\n Printf.printf \"%Ld %Ld\\n\" (x2 +| x3 -| x1) (y2 +| y3 -| y1);\n Printf.printf \"%Ld %Ld\\n\" (x3 +| x1 -| x2) (y3 +| y1 -| y2);\n Printf.printf \"%Ld %Ld\\n\" (x1 +| x2 -| x3) (y1 +| y2 -| y3);\n"}], "src_uid": "d7857d3e6b981c313ac16a9b4b0e1b86"} {"nl": {"description": "The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.A Bitlandish string is a string made only of characters \"0\" and \"1\".BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p\u2009=\u2009x\u00a0xor\u00a0y, q\u2009=\u2009x\u00a0or\u00a0y. Then he replaces one of the two taken characters by p and the other one by q.The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.", "input_spec": "The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths. It is guaranteed that the given strings only consist of characters \"0\" and \"1\". The strings are not empty, their length doesn't exceed 106.", "output_spec": "Print \"YES\" if a can be transformed into b, otherwise print \"NO\". Please do not print the quotes.", "sample_inputs": ["11\n10", "1\n01", "000\n101"], "sample_outputs": ["YES", "NO", "NO"], "notes": null}, "positive_code": [{"source_code": "let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n\nlet () = \n let a = read_line() in\n let b = read_line() in\n let na = String.length a in\n let nb = String.length b in\n let all_zeros s n = forall 0 (n-1) (fun i -> s.[i] = '0') in\n let answer = \n if na != nb then false\n else if all_zeros a na then all_zeros b nb \n else not (all_zeros b nb)\n in\n print_string (if answer then \"YES\\n\" else \"NO\\n\")\n"}, {"source_code": "(* CF odd game prob 276 B *)\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec has1 i s =\n\tif i >= (String.length s) then false\n\telse if s.[i] = '1' then true\n\telse has1 (i+1) s;;\n\nlet can_convert a b = \n\tif (String.length a) <> (String.length b) then false\n\telse \n\t\tlet ha = has1 0 a in\n\t\tlet hb = has1 0 b in\n\t\tha = hb;;\n\nlet main() =\n\tlet sa = rdln() in\n\tlet sb = rdln() in\n\tbegin\n\t\tprint_string (if can_convert sa sb then \"YES\" else \"NO\")\n\tend;;\n\t\t\nmain();;"}], "negative_code": [], "src_uid": "113ae625e67c8ea5ab07be44c3b58a8f"} {"nl": {"description": "Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \\ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?", "input_spec": "The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \\le n \\le 10^{5}$$$, $$$1 \\le k \\le 10^{5}$$$, $$$1 \\le m \\le 10^{7}$$$)\u00a0\u2014 the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^{6}$$$)\u00a0\u2014 the initial powers of the superheroes in the cast of avengers.", "output_spec": "Output a single number\u00a0\u2014 the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\\frac{|a - b|}{\\max{(1, |b|)}} \\le 10^{-6}$$$.", "sample_inputs": ["2 4 6\n4 7", "4 2 6\n1 3 2 3"], "sample_outputs": ["11.00000000000000000000", "5.00000000000000000000"], "notes": "NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each."}, "positive_code": [{"source_code": "let rv f p q = f q p\nlet fi = float_of_int\nlet (++),( ** ),fi64,i64 = Int64.(add,mul,to_float,of_int)\n;;\nScanf.(Array.(scanf \" %d %d %d\" @@ fun n k m ->\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v) in\n sort (rv compare) a;\n let total = ref 0L in\n init n (fun left ->\n let left = left + 1 in\n total := !total ++ a.(left-1);\n let add = i64 @@ m - (n - left) in\n let limit = (i64 left) ** (i64 k) in\n let add = min limit add in\n let r =\n if add < 0L then 0.\n else (fi64 (!total ++ add)) /. (fi left) in\n (* Printf.printf \"%2d : %2Ld :: %2Ld :: %f\\n\" left add !total r; *)\n r\n )\n |> fold_left max (((fi64 @@ fold_left (++) 0L a)) /. (fi n))\n |> Printf.printf \"%.14f\"\n))"}, {"source_code": "let rv f p q = f q p\nlet fi = float_of_int\nlet (++),( ** ),(--),fi64,i64 = Int64.(add,mul,sub,to_float,of_int)\n;;\nScanf.(Array.(scanf \" %d %Ld %Ld\" @@ fun n k m ->\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v) in\n sort (rv compare) a;\n let total = ref 0L in\n init n (fun left ->\n let left = left + 1 in\n total := !total ++ a.(left-1);\n let add = m -- (i64 n -- i64 left) in\n let limit = (i64 left) ** k in\n let add = min limit add in\n let r =\n if add < 0L then 0.\n else (fi64 (!total ++ add)) /. (fi left) in\n r\n )\n |> fold_left max 0.\n |> Printf.printf \"%.14f\"\n));;"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let m = read_int() in\n let a = Array.init n read_int in\n let s = Array.make (n+1) 0.0 in\n\n Array.sort compare a;\n\n for i=1 to n do\n s.(i) <- s.(i-1) +. (float a.(i-1))\n done;\n\n let answer = maxf 0 (min m (n-1)) (fun i ->\n (* i are removed *)\n let kept = s.(n) -. s.(i) in\n let j = float (n-i) in (* number left in the set *)\n let ninc = min (float (m-i)) (j *. (float k)) in\n (kept +. ninc) /. j\n ) in\n\n printf \"%f\\n\" answer\n"}], "negative_code": [{"source_code": "let rv f p q = f q p\nlet fi = float_of_int;;\nScanf.(Array.(scanf \" %d %d %d\" @@ fun n k m ->\n let a = init n (fun _ -> scanf \" %d\" @@ fun v -> v) in\n sort (rv compare) a;\n let total = ref 0 in\n init n (fun left ->\n let left = left + 1 in\n total := !total + a.(left-1);\n let add = m - (n - left) in\n let limit = left * k in\n let add = min limit add in\n let r =\n if add < 0 then 0.\n else (fi (!total + add)) /. (fi left) in\n (* Printf.printf \"%2d : %2d :: %2d :: %f\\n\" left add !total r; *)\n r\n )\n |> fold_left max 0.\n |> print_float\n))"}, {"source_code": "let rv f p q = f q p\nlet fi = float_of_int\nlet (++),i64f,i64 = Int64.(add,to_float,of_int)\n;;\nScanf.(Array.(scanf \" %d %d %d\" @@ fun n k m ->\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v) in\n sort (rv compare) a;\n let total = ref 0L in\n init n (fun left ->\n let left = left + 1 in\n total := !total ++ a.(left-1);\n let add = m - (n - left) in\n let limit = left * k in\n let add = i64 @@ min limit add in\n let r =\n if add < 0L then 0.\n else (i64f (!total ++ add)) /. (fi left) in\n (* Printf.printf \"%2d : %2d :: %2d :: %f\\n\" left add !total r; *)\n r\n )\n |> fold_left max 0.\n |> print_float\n));;"}, {"source_code": "let rv f p q = f q p\nlet fi = float_of_int;;\nScanf.(Array.(scanf \" %d %d %d\" @@ fun n k m ->\n let a = init n (fun _ -> scanf \" %d\" @@ fun v -> v) in\n sort (rv compare) a;\n let total = ref 0 in\n init n (fun left ->\n let left = left + 1 in\n total := !total + a.(left-1);\n let add = m - (n - left) in\n let limit = left * k in\n let add = min limit add in\n let r = (fi (!total + add)) /. (fi left) in\n (* Printf.printf \"%2d : %2d :: %2d :: %f\\n\" left add !total r; *)\n r\n )\n |> fold_left max 0.\n |> print_float\n))"}, {"source_code": "let rv f p q = f q p\nlet fi = float_of_int\nlet (++),i64f,i64 = Int64.(add,to_float,of_int)\n;;\nScanf.(Array.(scanf \" %d %d %d\" @@ fun n k m ->\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v) in\n sort (rv compare) a;\n let total = ref 0L in\n init n (fun left ->\n let left = left + 1 in\n total := !total ++ a.(left-1);\n let add = m - (n - left) in\n let limit = left * k in\n let add = i64 @@ min limit add in\n let r =\n if add < 0L then 0.\n else (i64f (!total ++ add)) /. (fi left) in\n (* Printf.printf \"%2d : %2d :: %2d :: %f\\n\" left add !total r; *)\n r\n )\n |> fold_left max ((i64f @@ fold_left (++) 0L a) /. (fi n))\n |> print_float\n));;"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let m = read_int() in\n let a = Array.init n read_int in\n let s = Array.make (n+1) 0.0 in\n\n Array.sort compare a;\n\n for i=1 to n do\n s.(i) <- s.(i-1) +. (float a.(i-1))\n done;\n\n let answer = maxf 0 (min m (n-1)) (fun i ->\n let kept = s.(n) -. s.(i) in\n let j = n-i in (* number left in the set *)\n let ninc = min (m-i) (j * k) in\n (kept +. (float ninc)) /. (float (n-i))\n ) in\n\n printf \"%f\" answer\n"}], "src_uid": "d6e44bd8ac03876cb03be0731f7dda3d"} {"nl": {"description": "Kuznecov likes art, poetry, and music. And strings consisting of lowercase English letters.Recently, Kuznecov has found two strings, $$$a$$$ and $$$b$$$, of lengths $$$n$$$ and $$$m$$$ respectively. They consist of lowercase English letters and no character is contained in both strings. Let another string $$$c$$$ be initially empty. Kuznecov can do the following two types of operations: Choose any character from the string $$$a$$$, remove it from $$$a$$$, and add it to the end of $$$c$$$. Choose any character from the string $$$b$$$, remove it from $$$b$$$, and add it to the end of $$$c$$$. But, he can not do more than $$$k$$$ operations of the same type in a row. He must perform operations until either $$$a$$$ or $$$b$$$ becomes empty. What is the lexicographically smallest possible value of $$$c$$$ after he finishes?A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \\neq y$$$; in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.", "input_spec": "There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. This is followed by the test cases description. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1\\leq n,m,k \\leq 100$$$)\u00a0\u2014 parameters from the statement. The second line of each test case contains the string $$$a$$$ of length $$$n$$$. The third line of each test case contains the string $$$b$$$ of length $$$m$$$. The strings contain only lowercase English letters. It is guaranteed that no symbol appears in $$$a$$$ and $$$b$$$ simultaneously.", "output_spec": "In each test case, output a single string $$$c$$$\u00a0\u2014 the answer to the problem.", "sample_inputs": ["3\n\n6 4 2\n\naaaaaa\n\nbbbb\n\n5 9 3\n\ncaaca\n\nbedededeb\n\n7 7 1\n\nnoskill\n\nwxhtzdy"], "sample_outputs": ["aabaabaa\naaabbcc\ndihktlwlxnyoz"], "notes": "NoteIn the first test case, it is optimal to take two 'a's from the string $$$a$$$ and add them to the string $$$c$$$. Then it is forbidden to take more characters from $$$a$$$, hence one character 'b' from the string $$$b$$$ has to be taken. Following that logic, we end up with $$$c$$$ being 'aabaabaa' when string $$$a$$$ is emptied.In the second test case it is optimal to take as many 'a's from string $$$a$$$ as possible, then take as many 'b's as possible from string $$$b$$$. In the end, we take two 'c's from the string $$$a$$$ emptying it. "}, "positive_code": [{"source_code": "(* 2 strings a and b with unique chars *)\r\n(* can remove any char from a/b and in c *)\r\n(* cant do more than k on same string *)\r\n(* keep going until a or b empty *)\r\n\r\n(* need to haave smallest string in \r\n alphabetical e.g abcde < abcdf*)\r\n\r\nlet read_string () = Scanf.scanf \" %s\" (fun s -> s);;\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\nlet rec create_char_arr data = function \r\n| 0 -> []\r\n| n -> (String.get data (n-1))::create_char_arr data (n-1)\r\n;;\r\n\r\nlet rec partition pivot left right = function \r\n| [] -> left, right \r\n| c::unsorted_arr ->\r\n if ((Char.code c) < (Char.code pivot)) then partition pivot (c::left) (right) unsorted_arr\r\n else partition pivot left (c::right) unsorted_arr \r\n;;\r\n\r\nlet rec quickSortFaster = function \r\n| [], sorted_arr -> sorted_arr \r\n| [c], sorted_arr -> c::sorted_arr\r\n| pivot::unsorted_arr, sorted_arr -> \r\n let left, right = partition pivot [] [] unsorted_arr in \r\n quickSortFaster (left, pivot::quickSortFaster (right, sorted_arr))\r\n;;\r\n\r\ntype a_or_b = A_CHOSE | B_CHOSE;;\r\nlet rec consume_strings k = function \r\n| _, [], _, _ -> []\r\n| [], _, _, _ -> []\r\n| a_c::a_chars, b_c::b_chars, consec_k, last_choice ->\r\n if (consec_k == k) then begin \r\n if (last_choice = A_CHOSE) then b_c::(consume_strings k (a_c::a_chars, b_chars, 1, B_CHOSE))\r\n else a_c::(consume_strings k (a_chars, (b_c::b_chars), 1, A_CHOSE))\r\n end\r\n else begin \r\n if (Char.code a_c < Char.code b_c) then begin \r\n if (last_choice = A_CHOSE) then a_c::(consume_strings k (a_chars, (b_c::b_chars), consec_k+1, A_CHOSE))\r\n else a_c::(consume_strings k (a_chars, (b_c::b_chars), 1, A_CHOSE))\r\n end \r\n else if (Char.code a_c > Char.code b_c) then begin \r\n if (last_choice = A_CHOSE) then b_c::(consume_strings k ((a_c::a_chars), b_chars, 1, B_CHOSE))\r\n else b_c::(consume_strings k ((a_c::a_chars), b_chars, consec_k+1, B_CHOSE))\r\n end\r\n else begin \r\n if (List.length a_chars < List.length b_chars) then begin \r\n if (last_choice = A_CHOSE) then a_c::(consume_strings k (a_chars, (b_c::b_chars), consec_k+1, A_CHOSE))\r\n else a_c::(consume_strings k (a_chars, (b_c::b_chars), 1, A_CHOSE))\r\n end \r\n else begin \r\n if (last_choice = A_CHOSE) then b_c::(consume_strings k ((a_c::a_chars), b_chars, 1, B_CHOSE))\r\n else b_c::(consume_strings k ((a_c::a_chars), b_chars, consec_k+1, B_CHOSE))\r\n end\r\n end\r\n end\r\n\r\n;;\r\n\r\n\r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in \r\n let m = read_int () in \r\n let k = read_int () in \r\n let a_str = read_string () in \r\n let a_chars = quickSortFaster ((create_char_arr a_str n), []) in \r\n let b_str = read_string () in \r\n let b_chars = quickSortFaster ((create_char_arr b_str m), []) in \r\n List.iter (fun x -> print_char x ) (consume_strings k (a_chars, b_chars, 0, A_CHOSE));\r\n print_newline ()\r\n;; \r\n\r\nlet rec iter_cases = function \r\n| 0 -> 0\r\n| n -> \r\n run_case ();\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t = read_int () in \r\niter_cases t;;"}], "negative_code": [], "src_uid": "1d46a356c5515f8894cbb83e438cc544"} {"nl": {"description": "In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network\u00a0\u2014 for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one railway or one road always takes exactly one hour.A train and a bus leave town 1 at the same time. They both have the same destination, town n, and don't make any stops on the way (but they can wait in town n). The train can move only along railways and the bus can move only along roads.You've been asked to plan out routes for the vehicles; each route can use any road/railway multiple times. One of the most important aspects to consider is safety\u00a0\u2014 in order to avoid accidents at railway crossings, the train and the bus must not arrive at the same town (except town n) simultaneously.Under these constraints, what is the minimum number of hours needed for both vehicles to reach town n (the maximum of arrival times of the bus and the train)? Note, that bus and train are not required to arrive to the town n at the same moment of time, but are allowed to do so.", "input_spec": "The first line of the input contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009400, 0\u2009\u2264\u2009m\u2009\u2264\u2009n(n\u2009-\u20091)\u2009/\u20092)\u00a0\u2014 the number of towns and the number of railways respectively. Each of the next m lines contains two integers u and v, denoting a railway between towns u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n, u\u2009\u2260\u2009v). You may assume that there is at most one railway connecting any two towns.", "output_spec": "Output one integer\u00a0\u2014 the smallest possible time of the later vehicle's arrival in town n. If it's impossible for at least one of the vehicles to reach town n, output \u2009-\u20091.", "sample_inputs": ["4 2\n1 3\n3 4", "4 6\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "5 5\n4 2\n3 5\n4 5\n5 1\n1 2"], "sample_outputs": ["2", "-1", "3"], "notes": "NoteIn the first sample, the train can take the route and the bus can take the route . Note that they can arrive at town 4 at the same time.In the second sample, Absurdistan is ruled by railwaymen. There are no roads, so there's no way for the bus to reach town 4."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet inf = 1_000_000\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nmodule Vset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet () = \n let shortest_path n graph (s,t) =\n let dist = Array.make n inf in\n let parent = Array.make n (-1) in\n let rec dijkstra q = \n if Vset.is_empty q then None else\n\tlet (dv,v) = Vset.min_elt q in\n\tlet q = Vset.remove (dv,v) q in\n\tif v=t then Some dv else\n\t let rec loop wlist q = match wlist with [] -> q \n\t | (w,l)::wlist -> \n\t let dw = dist.(w) in\n\t if (dw = inf || Vset.mem (dw,w) q) && dv+l < dw then\n\t\tlet ndw = min (dv + l) dw in\n\t\tparent.(w) <- v;\n\t\tdist.(w) <- ndw;\n\t\tlet q = Vset.add (ndw,w) (Vset.remove (dw,w) q) in\n\t\tloop wlist q\n\t else loop wlist q (* w is completed, or the edge is useless *)\n\t in\n\t dijkstra (loop graph.(v) q)\n in\t \n\n let q = Vset.singleton (0,s) in\n dist.(s) <- 0;\n dijkstra q\n in\n\n let n = read_int() in\n let m = read_int() in\n\n let g = Array.make n [] in\n\n let edges = fold 1 m (fun _ ac ->\n let a = read_int() - 1 in\n let b = read_int() - 1 in\n let (a,b) = (min a b, max a b) in\n (a,b)::ac\n ) [] in\n\n let add_edge (a,b) =\n g.(a) <- (b,1)::g.(a);\n g.(b) <- (a,1)::g.(b);\n in\n\n let build_graph edges = List.iter add_edge edges in\n\n let build_complement_graph edges =\n let mat = Array.make_matrix n n true in\n List.iter (fun (a,b) -> mat.(a).(b) <- false) edges;\n for i=0 to n-2 do\n for j=i+1 to n-1 do\n\tif mat.(i).(j) then add_edge (i,j)\n done\n done\n in\n\n if List.exists (fun (a,b) -> (a,b) = (0, n-1)) edges\n then build_complement_graph edges else build_graph edges;\n\n\n match shortest_path n g (0,n-1) with\n | None -> printf \"-1\\n\"\n | Some d -> printf \"%d\\n\" d\n"}], "negative_code": [], "src_uid": "fbfc333ad4b0a750f654a00be84aea67"} {"nl": {"description": "The rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200918)\u00a0\u2014 the number of participants of the Sith Tournament. Each of the next n lines contains n real numbers, which form a matrix pij (0\u2009\u2264\u2009pij\u2009\u2264\u20091). Each its element pij is the probability that the i-th participant defeats the j-th in a duel. The elements on the main diagonal pii are equal to zero. For all different i, j the equality pij\u2009+\u2009pji\u2009=\u20091 holds. All probabilities are given with no more than six decimal places. Jedi Ivan is the number 1 in the list of the participants.", "output_spec": "Output a real number\u00a0\u2014 the probability that Jedi Ivan will stay alive after the Tournament. Absolute or relative error of the answer must not exceed 10\u2009-\u20096.", "sample_inputs": ["3\n0.0 0.5 0.8\n0.5 0.0 0.4\n0.2 0.6 0.0"], "sample_outputs": ["0.680000000000000"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make_matrix n n 0.0 in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tp.(i).(j) <- Scanf.bscanf sb \"%f \" (fun s -> s)\n done\n done;\n in\n let a = Array.make_matrix n (1 lsl n) 0.0 in\n a.(0).(1) <- 1.0;\n for s = 1 to 1 lsl n - 1 do\n for i = 0 to n - 1 do\n\tif s land (1 lsl i) <> 0 then (\n\t for j = 0 to n - 1 do\n\t if i <> j && s land (1 lsl j) <> 0 then (\n\t a.(i).(s) <-\n\t\tmax a.(i).(s) (p.(i).(j) *. a.(i).(s lxor (1 lsl j)) +.\n\t\t\t\t p.(j).(i) *. a.(j).(s lxor (1 lsl i)))\n\t )\n\t done\n\t)\n done\n done;\n (*for j = 0 to 1 lsl n - 1 do\n for i = 0 to n - 1 do\n\tPrintf.printf \"asd %d %d %f\\n\" j i a.(i).(j)\n done\n done;*)\n let res =\n let res = ref 0.0 in\n\tfor i = 0 to n - 1 do\n\t res := max !res a.(i).(1 lsl n - 1)\n\tdone;\n\t!res\n in\n Printf.printf \"%.8f\\n\" res\n"}], "negative_code": [], "src_uid": "9b05933b72dc24d743cb59978f35c8f3"} {"nl": {"description": "Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!The computers bought for the room were different. Some of them had only USB ports, some\u00a0\u2014 only PS/2 ports, and some had both options.You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.", "input_spec": "The first line contains three integers a, b and c (0\u2009\u2264\u2009a,\u2009b,\u2009c\u2009\u2264\u2009105) \u00a0\u2014 the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively. The next line contains one integer m (0\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105) \u00a0\u2014 the number of mouses in the price list. The next m lines each describe another mouse. The i-th line contains first integer vali (1\u2009\u2264\u2009vali\u2009\u2264\u2009109) \u00a0\u2014 the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.", "output_spec": "Output two integers separated by space\u00a0\u2014 the number of equipped computers and the total cost of the mouses you will buy.", "sample_inputs": ["2 1 1\n4\n5 USB\n6 PS/2\n3 PS/2\n7 PS/2"], "sample_outputs": ["3 14"], "notes": "NoteIn the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let a = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let us = ref [] in\n let ps = ref [] in\n let _ =\n for i = 1 to m do\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tif s = \"USB\"\n\tthen us := v :: !us\n\telse ps := v :: !ps\n done;\n in\n let us = Array.of_list !us in\n let ps = Array.of_list !ps in\n let _ =\n Array.sort compare us;\n Array.sort compare ps;\n in\n let nu =\n if Array.length us >= a\n then a\n else Array.length us\n in\n let np =\n if Array.length ps >= b\n then b\n else Array.length ps\n in\n let nu = ref nu\n and np = ref np in\n let c = ref c in\n while !c > 0 && (!nu < Array.length us || !np < Array.length ps) do\n let vu =\n\tif !nu < Array.length us\n\tthen us.(!nu)\n\telse 1000000001\n in\n let vp =\n\tif !np < Array.length ps\n\tthen ps.(!np)\n\telse 1000000001\n in\n\tif vu < vp\n\tthen incr nu\n\telse incr np;\n\tdecr c\n done;\n let res = ref 0L in\n for i = 0 to !nu - 1 do\n\tres := !res +| Int64.of_int us.(i)\n done;\n for i = 0 to !np - 1 do\n\tres := !res +| Int64.of_int ps.(i)\n done;\n Printf.printf \"%d %Ld\\n\" (!nu + !np) !res\n"}], "negative_code": [], "src_uid": "3d6151b549bd52f95ab7fdb972e6fb98"} {"nl": {"description": "Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it.Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path \u2014 a continuous curve, going through the shop, and having the cinema and the house as its ends.The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than t1, and the distance covered by Bob should not differ from the shortest one by more than t2.Find the maximum distance that Alan and Bob will cover together, discussing the film.", "input_spec": "The first line contains two integers: t1,\u2009t2 (0\u2009\u2264\u2009t1,\u2009t2\u2009\u2264\u2009100). The second line contains the cinema's coordinates, the third one \u2014 the house's, and the last line \u2014 the shop's. All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building.", "output_spec": "In the only line output one number \u2014 the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places.", "sample_inputs": ["0 2\n0 0\n4 0\n-3 0", "0 0\n0 0\n2 0\n1 0"], "sample_outputs": ["1.0000000000", "2.0000000000"], "notes": null}, "positive_code": [{"source_code": "let read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f\" (fun x -> x)\nlet read _ = let x = read_float 0 in let y = read_float 0 in x,y\nlet (|>) x f = f x\n\nlet eps = 1e-10\nlet cmp a b =\n if abs_float (a-.b) < eps then\n 0\n else\n compare a b\nlet det (ax,ay) (bx,by) = ax*.by-.ay*.bx\nlet dot (ax,ay) (bx,by) = ax*.bx+.ay*.by\nlet add (ax,ay) (bx,by) = ax+.bx, ay+.by\nlet sub (ax,ay) (bx,by) = ax-.bx, ay-.by\nlet mul w (x,y) = x*.w, y*.w\nlet ortho (x,y) = y, -.x\nlet len x = dot x x |> sqrt\nlet dist a b = sub a b |> len\n\nlet dist (x1,y1) (x2,y2) =\n (x1-.x2)*.(x1-.x2)+.(y1-.y2)*.(y1-.y2) |> sqrt\n\n(* a != b *)\nlet intersect (a,ra) (b,rb) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then (* internal *)\n if ra < rb then [a] else [b]\n else if cmp (ra+.rb) dc < 0 then (* external *)\n []\n else\n let proj = (ra*.ra-.rb*.rb+.dc*.dc)/.(2.0*.dc) |> min ra in\n let hh = ra*.ra-.proj*.proj in\n let h = sqrt hh in\n let foot = add a (mul (proj/.dc) (sub b a)) in\n let dlt = mul (h/.dc) (ortho (sub b a)) in\n [add foot dlt; sub foot dlt]\n\n(* a != b && b != c && c != a *)\nlet inter3 aa bb cc =\n let test (a,ra) (b,rb) ((cx,cy) as c,rc) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then\n intersect (if ra < rb then (a,ra) else (b,rb)) (c,rc) <> []\n else\n intersect (a,ra) (b,rb) |> List.exists (fun (x,y) -> cmp (dist (x,y) (cx,cy)) rc <= 0)\n in\n test aa bb cc || test bb cc aa || test cc aa bb\n\nlet () =\n let t1 = read_float 0 in\n let t2 = read_float 0 in\n let a = read 0 in\n let b = read 0 in\n let c = read 0 in\n let lb = dist a b +. t2 in\n let lc = dist a c +. t1 in\n let rec bisect l h =\n if cmp l h >= 0 then\n l\n else\n let m = (l+.h)*.0.5 in\n if inter3 (a,m) (b,lb-.m) (c,lc-.m) then\n bisect m h\n else\n bisect l m\n in\n if cmp (dist a c +. dist c b) lb <= 0 then\n Printf.printf \"%f\\n\" (min lb (dist c b +. lc))\n (*bisect (min (lb+.dist b c) lc) (min lb lc) |> Printf.printf \"%f\\n\"*)\n else\n bisect 0.0 (min lb lc) |> Printf.printf \"%f\\n\"\n"}], "negative_code": [{"source_code": "let read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f\" (fun x -> x)\nlet read _ = let x = read_float 0 in let y = read_float 0 in x,y\nlet (|>) x f = f x\n\nlet eps = 1e-9\nlet cmp a b =\n if abs_float (a-.b) < eps then\n 0\n else\n compare a b\nlet det (ax,ay) (bx,by) = ax*.by-.ay*.bx\nlet dot (ax,ay) (bx,by) = ax*.bx+.ay*.by\nlet add (ax,ay) (bx,by) = ax+.bx, ay+.by\nlet sub (ax,ay) (bx,by) = ax-.bx, ay-.by\nlet mul w (x,y) = x*.w, y*.w\nlet ortho (x,y) = y, -.x\nlet len x = dot x x |> sqrt\nlet dist a b = sub a b |> len\n\nlet dist (x1,y1) (x2,y2) =\n (x1-.x2)*.(x1-.x2)+.(y1-.y2)*.(y1-.y2) |> sqrt\n\n(* a != b *)\nlet intersect (a,ra) (b,rb) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then (* internal *)\n if ra < rb then [a] else [b]\n else if cmp (ra+.rb) dc < 0 then (* external *)\n []\n else\n let proj = (ra*.ra-.rb*.rb+.dc*.dc)/.(2.0*.dc) in\n let h = ra*.ra-.proj*.proj |> sqrt in\n let foot = add a (mul (proj/.dc) (sub b a)) in\n let dlt = mul (h/.dc) (ortho (sub b a)) in\n [add foot dlt; sub foot dlt]\n\n(* a != b && b != c && c != a *)\nlet inter3 aa bb cc =\n let test (a,ra) (b,rb) ((cx,cy) as c,rc) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then\n intersect (if ra < rb then (a,ra) else (b,rb)) (c,rc) <> []\n else\n intersect (a,ra) (b,rb) |> List.exists (fun (x,y) -> cmp (dist (x,y) (cx,cy)) rc <= 0)\n in\n test aa bb cc || test bb cc aa || test cc aa bb\n\nlet () =\n let t1 = read_float 0 in\n let t2 = read_float 0 in\n let a = read 0 in\n let b = read 0 in\n let c = read 0 in\n let lb = dist a b +. t1 in\n let lc = dist a c +. t2 in\n let rec bisect l h =\n if cmp l h >= 0 then\n l\n else\n let m = (l+.h)/.2.0 in\n if inter3 (a,m) (b,lb-.m) (c,lc-.m) then\n bisect m h\n else\n bisect l m\n in\n if cmp (dist a c +. dist c b) lb <= 0 then\n Printf.printf \"%f\\n\" (min lb (dist c b +. lc))\n else\n bisect 0.0 (min lb lc) |> Printf.printf \"%f\\n\"\n"}, {"source_code": "let read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f\" (fun x -> x)\nlet read _ = let x = read_float 0 in let y = read_float 0 in x,y\nlet (|>) x f = f x\n\nlet eps = 1e-8\nlet cmp a b =\n if abs_float (a-.b) < eps then\n 0\n else\n compare a b\nlet det (ax,ay) (bx,by) = ax*.by-.ay*.bx\nlet dot (ax,ay) (bx,by) = ax*.bx+.ay*.by\nlet add (ax,ay) (bx,by) = ax+.bx, ay+.by\nlet sub (ax,ay) (bx,by) = ax-.bx, ay-.by\nlet mul w (x,y) = x*.w, y*.w\nlet ortho (x,y) = y, -.x\nlet len x = dot x x |> sqrt\nlet dist a b = sub a b |> len\n\nlet dist (x1,y1) (x2,y2) =\n (x1-.x2)*.(x1-.x2)+.(y1-.y2)*.(y1-.y2) |> sqrt\n\n(* a != b *)\nlet intersect (a,ra) (b,rb) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then (* internal *)\n if ra < rb then [a] else [b]\n else if cmp (ra+.rb) dc < 0 then (* external *)\n []\n else\n let proj = (ra*.ra-.rb*.rb+.dc*.dc)/.(2.0*.dc) in\n let h = ra*.ra-.proj*.proj |> sqrt in\n let foot = add a (mul (proj/.dc) (sub b a)) in\n let dlt = mul (h/.dc) (ortho (sub b a)) in\n [add foot dlt; sub foot dlt]\n\n(* a != b && b != c && c != a *)\nlet inter3 aa bb cc =\n let test (a,ra) (b,rb) ((cx,cy) as c,rc) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then\n intersect (if ra < rb then (a,ra) else (b,rb)) (c,rc) <> []\n else\n intersect (a,ra) (b,rb) |> List.exists (fun (x,y) -> cmp (dist (x,y) (cx,cy)) rc <= 0)\n in\n test aa bb cc || test bb cc aa || test cc aa bb\n\nlet () =\n (*intersect ((0.0,0.0),3.0) ((3.0,0.0),3.0) |> List.iter (fun (x,y)->*)\n (*Printf.printf \"%f %f\\n\" x y);*)\n (*if inter3 ((0.0,0.0),3.0) ((3.0,0.0),3.0) ((1.5,2.7),0.2) then*)\n (*Printf.printf \"meow\";*)\n\n (*exit 0;*)\n let t1 = read_float 0 in\n let t2 = read_float 0 in\n let a = read 0 in\n let b = read 0 in\n let c = read 0 in\n let lb = dist a b +. t1 in\n let lc = dist a c +. t2 in\n let rec bisect l h =\n if cmp l h >= 0 then\n l\n else\n let m = (l+.h)/.2.0 in\n if inter3 (a,m) (b,lb-.m) (c,lc-.m) then\n bisect m h\n else\n bisect l m\n in\n if cmp (dist a c +. dist c b) lb <= 0 then\n Printf.printf \"%f\\n\" (min lb (dist c b +. lc))\n else\n bisect 0.0 (min lb lc) |> Printf.printf \"%f\\n\"\n"}, {"source_code": "let read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f\" (fun x -> x)\nlet read _ = let x = read_float 0 in let y = read_float 0 in x,y\nlet (|>) x f = f x\n\nlet eps = 1e-10\nlet cmp a b =\n if abs_float (a-.b) < eps then\n 0\n else\n compare a b\nlet det (ax,ay) (bx,by) = ax*.by-.ay*.bx\nlet dot (ax,ay) (bx,by) = ax*.bx+.ay*.by\nlet add (ax,ay) (bx,by) = ax+.bx, ay+.by\nlet sub (ax,ay) (bx,by) = ax-.bx, ay-.by\nlet mul w (x,y) = x*.w, y*.w\nlet ortho (x,y) = y, -.x\nlet len x = dot x x |> sqrt\nlet dist a b = sub a b |> len\n\nlet dist (x1,y1) (x2,y2) =\n (x1-.x2)*.(x1-.x2)+.(y1-.y2)*.(y1-.y2) |> sqrt\n\n(* a != b *)\nlet intersect (a,ra) (b,rb) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then (* internal *)\n if ra < rb then [a] else [b]\n else\n let proj = (ra*.ra-.rb*.rb+.dc*.dc)/.(2.0*.dc) in\n let hh = ra*.ra-.proj*.proj in\n if hh < 0.0 then (* external *)\n []\n else\n let h = sqrt hh in\n let foot = add a (mul (proj/.dc) (sub b a)) in\n let dlt = mul (h/.dc) (ortho (sub b a)) in\n [add foot dlt; sub foot dlt]\n\n(* a != b && b != c && c != a *)\nlet inter3 aa bb cc =\n let test (a,ra) (b,rb) ((cx,cy) as c,rc) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then\n intersect (if ra < rb then (a,ra) else (b,rb)) (c,rc) <> []\n else\n intersect (a,ra) (b,rb) |> List.exists (fun (x,y) -> cmp (dist (x,y) (cx,cy)) rc <= 0)\n in\n test aa bb cc || test bb cc aa || test cc aa bb\n\nlet () =\n let t1 = read_float 0 in\n let t2 = read_float 0 in\n let a = read 0 in\n let b = read 0 in\n let c = read 0 in\n let lb = dist a b +. t2 in\n let lc = dist a c +. t1 in\n let rec bisect l h =\n if cmp l h >= 0 then\n l\n else\n let m = (l+.h)*.0.5 in\n if inter3 (a,m) (b,lb-.m) (c,lc-.m) then\n bisect m h\n else\n bisect l m\n in\n if cmp (dist a c +. dist c b) lb <= 0 then\n Printf.printf \"%f\\n\" (min lb (dist c b +. lc))\n (*bisect (min (lb+.dist b c) lc) (min lb lc) |> Printf.printf \"%f\\n\"*)\n else\n bisect 0.0 (min lb lc) |> Printf.printf \"%f\\n\"\n"}, {"source_code": "let read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f\" (fun x -> x)\nlet read _ = let x = read_float 0 in let y = read_float 0 in x,y\nlet (|>) x f = f x\n\nlet eps = 1e-9\nlet cmp a b =\n if abs_float (a-.b) < eps then\n 0\n else\n compare a b\nlet det (ax,ay) (bx,by) = ax*.by-.ay*.bx\nlet dot (ax,ay) (bx,by) = ax*.bx+.ay*.by\nlet add (ax,ay) (bx,by) = ax+.bx, ay+.by\nlet sub (ax,ay) (bx,by) = ax-.bx, ay-.by\nlet mul w (x,y) = x*.w, y*.w\nlet ortho (x,y) = y, -.x\nlet len x = dot x x |> sqrt\nlet dist a b = sub a b |> len\n\nlet dist (x1,y1) (x2,y2) =\n (x1-.x2)*.(x1-.x2)+.(y1-.y2)*.(y1-.y2) |> sqrt\n\n(* a != b *)\nlet intersect (a,ra) (b,rb) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then (* internal *)\n if ra < rb then [a] else [b]\n else if cmp (ra+.rb) dc < 0 then (* external *)\n []\n else\n let proj = (ra*.ra-.rb*.rb+.dc*.dc)/.(2.0*.dc) in\n let h = ra*.ra-.proj*.proj |> sqrt in\n let foot = add a (mul (proj/.dc) (sub b a)) in\n let dlt = mul (h/.dc) (ortho (sub b a)) in\n [add foot dlt; sub foot dlt]\n\n(* a != b && b != c && c != a *)\nlet inter3 aa bb cc =\n let test (a,ra) (b,rb) ((cx,cy) as c,rc) =\n let dc = dist a b in\n if cmp dc (ra-.rb |> abs_float) <= 0 then\n intersect (if ra < rb then (a,ra) else (b,rb)) (c,rc) <> []\n else\n intersect (a,ra) (b,rb) |> List.exists (fun (x,y) -> cmp (dist (x,y) (cx,cy)) rc <= 0)\n in\n test aa bb cc || test bb cc aa || test cc aa bb\n\nlet () =\n let t1 = read_float 0 in\n let t2 = read_float 0 in\n let a = read 0 in\n let b = read 0 in\n let c = read 0 in\n let lb = dist a b +. t2 in\n let lc = dist a c +. t1 in\n let rec bisect l h =\n if cmp l h >= 0 then\n l\n else\n let m = (l+.h)/.2.0 in\n if inter3 (a,m) (b,lb-.m) (c,lc-.m) then\n bisect m h\n else\n bisect l m\n in\n if cmp (dist a c +. dist c b) lb <= 0 then\n Printf.printf \"%f\\n\" (min lb (dist c b +. lc))\n else\n bisect 0.0 (min lb lc) |> Printf.printf \"%f\\n\"\n"}], "src_uid": "3edd332d8359ead21df4d822af6940c7"} {"nl": {"description": "For some binary string $$$s$$$ (i.e. each character $$$s_i$$$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $$$2$$$ were written. For each pair (substring of length $$$2$$$), the number of '1' (ones) in it was calculated.You are given three numbers: $$$n_0$$$ \u2014 the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$0$$$; $$$n_1$$$ \u2014 the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$1$$$; $$$n_2$$$ \u2014 the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$2$$$. For example, for the string $$$s=$$$\"1110011110\", the following substrings would be written: \"11\", \"11\", \"10\", \"00\", \"01\", \"11\", \"11\", \"11\", \"10\". Thus, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.Your task is to restore any suitable binary string $$$s$$$ from the given values $$$n_0, n_1, n_2$$$. It is guaranteed that at least one of the numbers $$$n_0, n_1, n_2$$$ is greater than $$$0$$$. Also, it is guaranteed that a solution exists.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases in the input. Then test cases follow. Each test case consists of one line which contains three integers $$$n_0, n_1, n_2$$$ ($$$0 \\le n_0, n_1, n_2 \\le 100$$$; $$$n_0 + n_1 + n_2 > 0$$$). It is guaranteed that the answer for given $$$n_0, n_1, n_2$$$ exists.", "output_spec": "Print $$$t$$$ lines. Each of the lines should contain a binary string corresponding to a test case. If there are several possible solutions, print any of them.", "sample_inputs": ["7\n1 3 5\n1 1 1\n3 9 3\n0 1 0\n3 1 2\n0 0 3\n2 0 0"], "sample_outputs": ["1110011110\n0011\n0110001100101011\n10\n0000111\n1111\n000"], "notes": null}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n \nopen Printf\n\nlet init (x : int) (f : int -> 'a) : 'a list =\n let rec build k =\n if k = x then []\n else (f k) :: build (k + 1) in\n build 0\n;;\n \nlet run () = \n let n0 = scan_int () in\n let n1 = scan_int () in\n let n2 = scan_int () in\n let lst = \n if (n0 = 0 && n2 = 0) then begin\n let one = 10 :: (init ((n1 - 1) / 2) (fun _x -> 10)) in\n if (n1 mod 2 = 0) then 0 :: one\n else one\n end\n else if n1 = 0 && n2 = 0 then init (n0 + 1) (fun _x -> 0)\n else if (n0 = 0 && n1 = 0) then init (n2 + 1) (fun _x -> 1)\n else begin\n let zer = init (n0+1) (fun _x -> 0) in\n let two = init (n2+1) (fun _x -> 1) in\n if n0 > 0 then\n let one = init ((n1 - 1) / 2) (fun _x -> 10) in\n if n1 mod 2 = 0 then 1 :: (zer @ (one @ two))\n else (zer @ (one @ two))\n else\n let one = init (n1 / 2) (fun _x -> 10) in\n if n1 mod 2 = 1 then 0 :: (one @ two)\n else one @ two\n end in\n List.iter (printf \"%d\") lst;\n print_endline \"\"\n;;\n \nlet () =\n let t = scan_int () in\n for i = 1 to t do\n run ()\n done\n;;\n"}, {"source_code": "(* Codeforces 1352 D Alice, Bob and Candies comp *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\n(* ============= above library below custom ========== *)\n\nlet rec bs_rec i bts n0 n1 n2 = \n\tlet ii = (i + 1) in\n\tif n0 > 0 then\n\t\tlet _ = (Bytes.set bts i '0') in\n\t\tbs_rec ii bts (n0-1) n1 n2\n\telse if n1 > 0 then\n\t\tlet ch = if (n1 mod 2) == 1 then '1' else '0' in\n\t\tlet _ = (Bytes.set bts i ch) in\n\t\tbs_rec ii bts 0 (n1-1) n2\n\telse if n2 > 0 then\n\t\tlet _ = (Bytes.set bts i '1') in\n\t\tbs_rec ii bts 0 0 (n2 - 1)\n\telse\n\t\t();;\t\n\nlet binary_string bts n0 n1 n2 n = \n\tif n0==0 && n1==0 then Bytes.fill bts 0 n '1'\n\telse if n1==0 && n2==0 then Bytes.fill bts 0 n '0'\n\telse\n \tlet _ = if (n1 mod 2) == 0 \n\t\t then \n\t\t\t\tbegin \n\t\t\t\t\tBytes.set bts 0 '1';\n\t\t\t\t\tBytes.set bts 1 '0'\n\t\t\t\tend\n\t\t\telse\n\t\t\t\t(Bytes.set bts 0 '0') in\n \tlet i0,nn1 = if (n1 mod 2) == 0 then 2,(n1 - 1) else 1,n1 in\n\t\tbs_rec i0 bts n0 nn1 n2;;\t\n \nlet do_one () = \n let n0 = gr () in\n let n1 = gr () in\n let n2 = gr () in\n\t\tlet n = n0 + n1 + n2 + 1 in\n\t\tlet bts = Bytes.create n in\n let _ = binary_string bts n0 n1 n2 n in\n\t\tlet bs = Bytes.to_string bts in\n \tPrintf.printf \"%s\\n\" bs;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n \nopen Printf\n\nlet init (x : int) (f : int -> 'a) : 'a list =\n let rec build k =\n if k = x then []\n else (f k) :: build (k + 1) in\n build 0\n;;\n \nlet run () = \n let n0 = scan_int () in\n let n1 = scan_int () in\n let n2 = scan_int () in\n let lst = \n if (n0 = 0 && n2 = 0) then begin\n let one = 10 :: (init ((n1 - 1) / 2) (fun _x -> 10)) in\n if (n1 mod 2 = 0) then 0 :: one\n else one\n end\n else if n1 = 0 && n2 = 0 then init (n0 + 1) (fun _x -> 0)\n else if (n0 = 0 && n1 = 0) then init (n2 + 1) (fun _x -> 1)\n else begin\n let zer = init (n0+1) (fun _x -> 0) in\n let two = init (n2+1) (fun _x -> 1) in\n if n0 > 0 then\n let one = init ((n1 - 1) / 2) (fun _x -> 10) in\n if n1 mod 2 = 0 then 1 :: (zer @ (one @ two))\n else (zer @ (one @ two))\n else\n let one = init (n1 / 2) (fun _x -> 10) in\n if n1 mod 2 = 0 then 0 :: (one @ two)\n else one @ two\n end in\n List.iter (printf \"%d\") lst;\n print_endline \"\"\n;;\n \nlet () =\n let t = scan_int () in\n for i = 1 to t do\n run ()\n done\n;;\n"}], "src_uid": "4bbb078b66b26d6414e30b0aae845b98"} {"nl": {"description": "You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.For example, if the string s is abacaba and the query is l1\u2009=\u20093,\u2009r1\u2009=\u20096,\u2009k1\u2009=\u20091 then the answer is abbacaa. If after that we would process the query l2\u2009=\u20091,\u2009r2\u2009=\u20094,\u2009k2\u2009=\u20092 then we would get the string baabcaa.", "input_spec": "The first line of the input contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u200910\u2009000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters. Second line contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009300)\u00a0\u2014 the number of queries. The i-th of the next m lines contains three integers li, ri and ki (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009|s|,\u20091\u2009\u2264\u2009ki\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the description of the i-th query.", "output_spec": "Print the resulting string s after processing all m queries.", "sample_inputs": ["abacaba\n2\n3 6 1\n1 4 2"], "sample_outputs": ["baabcaa"], "notes": "NoteThe sample is described in problem statement."}, "positive_code": [{"source_code": "open Array;;\n\nlet string_to_list s =\n let rec explode i l =\n if ( i < 0 ) then l\n else explode (i-1) (s.[i] :: l) \n in explode ( String.length s - 1) [];;\n\n\nlet licz x a b k =\n let y = init ( Array.length x ) (fun i -> x.(i) )\n in\n for i = a-1 to b-1 do\n set y i x.( ( ( (i-a+1-k) mod (b-a+1) ) + (b-a+1) ) mod (b-a+1) + a-1 )\n done;\n y;;\n\nlet case x =\n Scanf.bscanf Scanf.Scanning.stdin \"%d %d %d\\n\" ( licz x );;\n\n\nlet x = Array.of_list ( string_to_list ( read_line() ) );;\n\nlet rec repeat x f y =\n if x > 0 then\n begin\n let z = f y in\n repeat (x-1) f z\n end\n else y;;\n\niter print_char ( repeat ( read_int() ) case x );;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for i = 1 to n do\n let l = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let r = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let len = r - l + 1 in\n let s2 = String.copy s in\n\tfor j = l to r do\n\t let p = ((j - l - k) mod len + len) mod len + l in\n\t s.[j] <- s2.[p]\n\tdone;\n done;\n Printf.printf \"%s\\n\" s\n"}], "negative_code": [], "src_uid": "501b60c4dc465b8a60fd567b208ea1e3"} {"nl": {"description": "In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1,\u2009a2,\u2009...,\u2009an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.", "input_spec": "The first line contains two integers n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) and m (1\u2009\u2264\u2009m\u2009\u2264\u2009109)\u00a0\u2014 the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the types of toys that Tanya already has.", "output_spec": "In the first line print a single integer k\u00a0\u2014 the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1,\u2009t2,\u2009...,\u2009tk (1\u2009\u2264\u2009ti\u2009\u2264\u2009109)\u00a0\u2014 the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.", "sample_inputs": ["3 7\n1 3 4", "4 14\n4 6 12 8"], "sample_outputs": ["2\n2 5", "4\n7 2 3 1"], "notes": "NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet scan_int () = Scanf.scanf \" %d \" (fun i -> i);;\nlet scan_string () = Scanf.scanf \" %s\" (fun i -> i);;\n\nlet answer ts m =\n let rec aux ts m i c acc =\n if c > m then acc\n else\n if i >= Array.length ts\n then aux ts (m-c) i (c+1) (c::acc)\n else\n let t = Array.get ts i in\n if c < t\n then aux ts (m-c) i (c+1) (c::acc)\n else aux ts m (i+1) (c+1) acc\n in aux ts m 0 1 []\n\nlet () =\n let n = scan_int () in\n let m = scan_int () in\n\n let ts = Array.make n 0 in\n\n for i=0 to n-1 do\n let t = scan_int () in\n Array.set ts i t\n done;\n\n Array.sort compare ts;\n\n let ans = answer ts m in\n Printf.printf \"%d\\n\" (List.length ans);\n List.iter (fun t -> Printf.printf \"%d \" t) ans;\n Printf.printf \"\\n\";;"}], "negative_code": [{"source_code": "open Scanf\nopen Printf\n\nlet scan_int () = Scanf.scanf \" %d \" (fun i -> i);;\nlet scan_string () = Scanf.scanf \" %s\" (fun i -> i);;\n\nlet answer ts m =\n let rec aux ts m i c acc =\n if c > m || i >= Array.length ts then acc\n else\n let t = Array.get ts i in\n if c < t\n then aux ts (m-c) i (c+1) (c::acc)\n else aux ts m (i+1) (c+1) acc\n in aux ts m 0 1 []\n\nlet () =\n let n = scan_int () in\n let m = scan_int () in\n\n let ts = Array.make n 0 in\n\n for i=0 to n-1 do\n let t = scan_int () in\n Array.set ts i t\n done;\n\n Array.sort compare ts;\n\n let ans = answer ts m in\n Printf.printf \"%d\\n\" (List.length ans);\n List.iter (fun t -> Printf.printf \"%d \" t) ans;\n Printf.printf \"\\n\";;"}], "src_uid": "0318d4d5ea3425bf6506edeb1026f597"} {"nl": {"description": "For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $$$n$$$ days of summer. On the $$$i$$$-th day, $$$a_i$$$ millimeters of rain will fall. All values $$$a_i$$$ are distinct.The mayor knows that citizens will watch the weather $$$x$$$ days before the celebration and $$$y$$$ days after. Because of that, he says that a day $$$d$$$ is not-so-rainy if $$$a_d$$$ is smaller than rain amounts at each of $$$x$$$ days before day $$$d$$$ and and each of $$$y$$$ days after day $$$d$$$. In other words, $$$a_d < a_j$$$ should hold for all $$$d - x \\le j < d$$$ and $$$d < j \\le d + y$$$. Citizens only watch the weather during summer, so we only consider such $$$j$$$ that $$$1 \\le j \\le n$$$.Help mayor find the earliest not-so-rainy day of summer.", "input_spec": "The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \\le n \\le 100\\,000$$$, $$$0 \\le x, y \\le 7$$$)\u00a0\u2014 the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after. The second line contains $$$n$$$ distinct integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ denotes the rain amount on the $$$i$$$-th day.", "output_spec": "Print a single integer\u00a0\u2014 the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.", "sample_inputs": ["10 2 2\n10 9 6 7 8 3 2 1 4 5", "10 2 3\n10 9 6 7 8 3 2 1 4 5", "5 5 5\n100000 10000 1000 100 10"], "sample_outputs": ["3", "8", "5"], "notes": "NoteIn the first example days $$$3$$$ and $$$8$$$ are not-so-rainy. The $$$3$$$-rd day is earlier.In the second example day $$$3$$$ is not not-so-rainy, because $$$3 + y = 6$$$ and $$$a_3 > a_6$$$. Thus, day $$$8$$$ is the answer. Note that $$$8 + y = 11$$$, but we don't consider day $$$11$$$, because it is not summer."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet readInt () = scanf \" %d\" (fun x -> x)\n\nexception Ret of int\n\nlet solve n x y a =\n try\n for i=0 to n-1 do\n let ok =\n try\n for j=max 0 (i-x) to i-1 do if a.(j) <= a.(i) then raise Exit done;\n for j=i+1 to min (n-1) (i+y) do if a.(j) <= a.(i) then raise Exit done;\n true\n with Exit -> false\n in\n if ok then raise (Ret i)\n done;\n -1\n with Ret i -> i\n\nlet main () =\n let n = readInt () in\n let x = readInt () in\n let y = readInt () in\n let a = Array.init n (fun _ -> readInt ()) in\n printf \"%d\\n\" (solve n x y a + 1)\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "5e2a5ee02c1a2f35a52e76cde96463a3"} {"nl": {"description": "Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting. ", "input_spec": "The first line contains two space-separated integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The second line will contain n space-separated integers representing content of the array a (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). The third line will contain m space-separated integers representing content of the array b (1\u2009\u2264\u2009bi\u2009\u2264\u2009109).", "output_spec": "You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.", "sample_inputs": ["2 2\n2 3\n3 5", "3 2\n1 2 3\n3 4", "3 2\n4 5 6\n1 2"], "sample_outputs": ["3", "4", "0"], "notes": "NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Imap = Map.Make (struct type t = int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let b = Array.init m (fun _ -> read_int()) in\n\n let next_hi_event s = \n let (h0,_) = Imap.max_binding s in\n let s = Imap.remove h0 s in\n if Imap.is_empty s then h0 else\n let (h1,_) = Imap.max_binding s in\n h0-h1\n in\n\n let next_lo_event s = \n let (h0,_) = Imap.min_binding s in\n let s = Imap.remove h0 s in\n if Imap.is_empty s then h0 else\n let (h1,_) = Imap.min_binding s in\n h1-h0\n in\n\n let add_to h delta s =\n let c = try Imap.find h s with Not_found -> 0 in\n Imap.add h (c+delta) s\n in\n\n let buildset a sz = \n fold 0 (sz-1) (fun i ac -> add_to a.(i) 1 ac) Imap.empty\n in\n\n let lower_set move_size s =\n let (h,c) = Imap.max_binding s in\n let s = Imap.remove h s in\n add_to (h-move_size) c s\n in\n\n let raise_set move_size s =\n let (h,c) = Imap.min_binding s in\n let s = Imap.remove h s in\n add_to (h+move_size) c s\n in\n\n let rec loop a_set b_set ac =\n let (hb,wb) = Imap.max_binding b_set in\n let (ha,wa) = Imap.min_binding a_set in\n if hb <= ha then ac else\n if wb <= wa then ( (* push down on b *)\n\tlet move_size = next_hi_event b_set in\n\tlet move_size = min move_size (hb-ha) in\n\tlet b_set = lower_set move_size b_set in\n\tlet ac = ac ++ (Int64.of_int move_size) ** (Int64.of_int wb) in\n\tloop a_set b_set ac\n ) else (\t (* push up on a *)\t\n\tlet move_size = next_lo_event a_set in\n\tlet move_size = min move_size (hb-ha) in\n\tlet a_set = raise_set move_size a_set in\n\tlet ac = ac ++ (Int64.of_int move_size) ** (Int64.of_int wa) in\n\tloop a_set b_set ac\n )\n in\n\n let a_set = buildset a n in\n let b_set = buildset b m in\n\n printf \"%Ld\\n\" (loop a_set b_set 0L)\n"}], "negative_code": [], "src_uid": "e0b5169945909cd2809482b7fd7178c2"} {"nl": {"description": "You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i.\u00a0e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\\sum\\limits_{i = 1}^{n}{n^{n - i} \\cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$; $$$p_i \\neq p_j$$$ if $$$i \\neq j$$$)\u00a0\u2014 values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": "For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.", "sample_inputs": ["4\n4\n1 2 3 4\n5\n1 5 2 4 3\n6\n4 2 5 3 6 1\n1\n1"], "sample_outputs": ["4 3 2 1\n5 2 4 3 1\n6 1 5 3 4 2\n1"], "notes": "NoteIn the first test case, one of the optimal strategies is the next one: take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1, 2, 3]$$$, $$$p'$$$ becomes $$$[4]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1, 2]$$$, $$$p'$$$ becomes $$$[4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[4, 3, 2]$$$; take $$$1$$$ card from the top of $$$p$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[4, 3, 2, 1]$$$. In result, $$$p'$$$ has order equal to $$$4^3 \\cdot 4 + 4^2 \\cdot 3 + 4^1 \\cdot 2 + 4^0 \\cdot 1$$$ $$$=$$$ $$$256 + 48 + 8 + 1 = 313$$$.In the second test case, one of the optimal strategies is: take $$$4$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[1]$$$, $$$p'$$$ becomes $$$[5, 2, 4, 3]$$$; take $$$1$$$ card from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[5, 2, 4, 3, 1]$$$; In result, $$$p'$$$ has order equal to $$$5^4 \\cdot 5 + 5^3 \\cdot 2 + 5^2 \\cdot 4 + 5^1 \\cdot 3 + 5^0 \\cdot 1$$$ $$$=$$$ $$$3125 + 250 + 100 + 15 + 1 = 3491$$$.In the third test case, one of the optimal strategies is: take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2, 5, 3]$$$, $$$p'$$$ becomes $$$[6, 1]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes $$$[4, 2]$$$, $$$p'$$$ becomes $$$[6, 1, 5, 3]$$$; take $$$2$$$ cards from the top of $$$p$$$ and move it to $$$p'$$$: $$$p$$$ becomes empty, $$$p'$$$ becomes $$$[6, 1, 5, 3, 4, 2]$$$. In result, $$$p'$$$ has order equal to $$$6^5 \\cdot 6 + 6^4 \\cdot 1 + 6^3 \\cdot 5 + 6^2 \\cdot 3 + 6^1 \\cdot 4 + 6^0 \\cdot 2$$$ $$$=$$$ $$$46656 + 1296 + 1080 + 108 + 24 + 2 = 49166$$$."}, "positive_code": [{"source_code": "(** https://codeforces.com/contest/1492/problem/B *)\n\nlet deck () =\n let _ = read_line () in\n let cards = \n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n cards in\n\nlet max_deck cards =\n let rec helper currmax cs stack deck =\n match cs with\n | [] -> List.flatten ((List.rev stack)::deck)\n | card::rest ->\n if card > currmax\n then\n let new_deck = if stack <> [] then (List.rev stack)::deck else deck in\n let new_stack = [card] in\n helper card rest new_stack new_deck\n else\n helper currmax rest (card::stack) deck in\n helper 0 cards [] [] in\n\nlet print_deck cards =\n let rec helper cs =\n match cs with\n | [] -> print_newline ()\n | h::t -> \n Printf.printf \"%d \" h;\n helper t in\n helper cards in\n\nlet nb_case = read_int () in\nfor i = 0 to nb_case-1 do\n deck ()\n |> max_deck\n |> print_deck\ndone\n"}], "negative_code": [], "src_uid": "1637670255f8bd82a01e2ab20cdcc9aa"} {"nl": {"description": "In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.Farmer John wants to book a set of k\u2009+\u20091 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j\u2009-\u2009i|. Help Farmer John protect his cows by calculating this minimum possible distance.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009k\u2009<\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of rooms in the hotel and the number of cows travelling with Farmer John. The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k\u2009+\u20091 characters of this string are '0', so there exists at least one possible choice of k\u2009+\u20091 rooms for Farmer John and his cows to stay in.", "output_spec": "Print the minimum possible distance between Farmer John's room and his farthest cow.", "sample_inputs": ["7 2\n0100100", "5 1\n01010", "3 2\n000"], "sample_outputs": ["2", "2", "1"], "notes": "NoteIn the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let next i =\n let i = ref (i + 1) in\n while !i < n && s.[!i] = '1' do\n\tincr i\n done;\n !i\n in\n let res = ref n in\n let l = ref (-1) in\n let r = ref (-1) in\n let _ =\n l := next !l;\n for i = 1 to k + 1 do\n r := next !r;\n done;\n in\n let m1 = ref (!l + (!r - !l) / 2) in\n let m2 = ref (!r - (!r - !l) / 2) in\n let _ =\n while s.[!m1] = '1' do\n decr m1\n done;\n while s.[!m2] = '1' do\n incr m2\n done;\n in\n while !r < n do\n let d = min (!r - !m1) (!m2 - !l) in\n\t(*Printf.printf \"asd %d %d %d %d %d\\n\" !l !m1 !m2 !r d;*)\n\tres := min !res d;\n\tl := next !l;\n\tr := next !r;\n\tlet m = (!l + !r) / 2 in\n\t while next !m1 <= m do\n\t m1 := next !m1\n\t done;\n\t while !m2 <= m do\n\t m2 := next !m2\n\t done\n done;\n Printf.printf \"%d\\n\" !res;\n"}], "negative_code": [], "src_uid": "a5d1a96fd8514840062d747e6fda2c37"} {"nl": {"description": "The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u20091012) \u2014 Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print a single integer \u2014 the maximum pleasure BitHaval and BitAryo can get from the dinner.", "sample_inputs": ["2\n1 2", "3\n1 2 3", "2\n1000 1000"], "sample_outputs": ["3", "3", "1000"], "notes": null}, "positive_code": [{"source_code": "let nbits = 40\nlet ( ^ ) = Int64.logxor\n\ntype trie = Empty | Node of trie * trie\n\nlet rec insert_into_trie n list = \n let (l,r) = match n with Empty -> (Empty,Empty) | Node(l,r) -> (l,r) in\n match list with [] -> Node(l,r)\n | 0::tail -> Node (insert_into_trie l tail, r)\n | _::tail -> Node (l, insert_into_trie r tail)\n\nlet rec best_in_trie t x guide = match (t,guide) with \n | (_, []) -> x\n | (Empty,_) -> failwith \"best_in_trie fail\"\n | (Node(l,r), g::tail) -> \n let (t,b) = if (g=1 && l=Empty) || (g=0 && r<>Empty) then (r,1L) else (l,0L) in\n\tbest_in_trie t (Int64.logor b (Int64.shift_left x 1)) tail\n\n\nlet bits_to_list x = (* make a list of bits, high order first *)\n let rec loop i x ac = if i=nbits then ac else\n loop (i+1) (Int64.shift_right_logical x 1) (Int64.to_int ((Int64.logand x 1L))::ac)\n in\n loop 0 x []\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ^ a) 0L\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_long _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_long in\n let allxor = sum 0 (n-1) (fun i -> a.(i)) in\n\n let rec loop i xor0 t ac = \n (* i=0....n, represent the n+1 dividing line positions \n xor0 is the xor to the left of the line, t is the current trie\n (not including xor0), ac is the max value achieved so far. *)\n let t = insert_into_trie t (bits_to_list xor0) in\n let xor1 = xor0 ^ allxor in\n let guide = bits_to_list xor1 in\n let best = best_in_trie t 0L guide in\n let ac = max ac (best ^ xor1) in\n if i >= n then ac else \n\tloop (i+1) (a.(i) ^ xor0) t ac\n in\n Printf.printf \"%Ld\\n\" (loop 0 0L Empty 0L)\n"}], "negative_code": [], "src_uid": "02588d1e94595cb406d92bb6e170ded6"} {"nl": {"description": "Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things: The maximum beauty difference of flowers that Pashmak can give to Parmida. The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way. ", "input_spec": "The first line of the input contains n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). In the next line there are n space-separated integers b1, b2, ..., bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009109).", "output_spec": "The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.", "sample_inputs": ["2\n1 2", "3\n1 4 5", "5\n3 1 2 3 1"], "sample_outputs": ["1 1", "4 1", "2 4"], "notes": "NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this: choosing the first and the second flowers; choosing the first and the fifth flowers; choosing the fourth and the second flowers; choosing the fourth and the fifth flowers. "}, "positive_code": [{"source_code": "let ( * ) = Int64.mul\nlet ( + ) = Int64.add\nlet ( - ) = Int64.sub\nlet ( / ) = Int64.div\nlet zero = Int64.zero\nlet one = Int64.one\nlet two = Int64.of_int 2\n\nlet read () = Scanf.scanf \"%Ld \" (fun n -> n)\n\nlet make_list () = \n let n = read () in\n let rec loop i list =\n if i < n\n then\n let value = read () in\n loop (i + one) (value :: list)\n else\n List.sort (Pervasives.compare) list\n in loop zero []\n\nlet get_min_max list =\n let min = List.hd list in\n let max = List.hd (List.rev list) in\n (min, max)\n\nlet counter value list = \n Int64.of_int (List.length (List.filter (fun x -> x = value) list))\n\nlet get_max_pairs (min, max) list = \n let min_count = counter min list in \n let max_count = counter max list in\n if min = max\n then\n (min_count * (min_count - one)) / two\n else\n min_count * max_count\n\nlet solve () = \n let flowers = make_list () in\n let (min, max) = get_min_max flowers in\n let max_diff = max - min in\n let max_pairs = get_max_pairs (min, max) flowers in\n (max_diff, max_pairs)\n\nlet print (a, b) = Printf.printf \"%Ld %Ld\\n\" a b\n\nlet () = print (solve ())"}], "negative_code": [{"source_code": "let ( * ) = Int64.mul\nlet ( + ) = Int64.add\nlet ( - ) = Int64.sub\nlet zero = Int64.zero\nlet one = Int64.one\n\n\nlet read () = Scanf.scanf \"%Ld \" (fun n -> n)\n\nlet make_list () = \n let n = read () in\n let rec loop i list =\n if i < n\n then\n let value = read () in\n loop (i + one) (value :: list)\n else\n List.sort (Pervasives.compare) list\n in loop zero []\n\nlet counter value list = \n Int64.of_int (List.length (List.filter (fun x -> x = value) list))\n\nlet get_min_max list =\n let min = List.hd list in\n let max = List.hd (List.rev list) in\n (min, max)\n\nlet solve () = \n let flowers = make_list () in\n let (min, max) = get_min_max flowers in\n let max_diff = max - min in\n let min_count = counter min flowers in\n let max_count = counter max flowers in\n let max_pairs = max_count * min_count in\n (max_diff, max_pairs)\n\nlet print (a, b) = Printf.printf \"%Ld %Ld\\n\" a b\n\nlet () = print (solve ())\n"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet make_list () = \n let n = read () in\n let rec loop i list =\n if i < n\n then\n let value = read () in\n loop (i + 1) (value :: list)\n else\n List.sort (Pervasives.compare) list\n in loop 0 []\n\nlet counter value list = \n List.length (List.filter (fun x -> x = value) list)\n\nlet get_min_max list =\n let min = List.hd list in\n let max = List.hd (List.rev list) in\n (min, max)\n\nlet solve () = \n let flowers = make_list () in\n let (min, max) = get_min_max flowers in\n let max_diff = max - min in\n let min_count = counter min flowers in\n let max_count = counter max flowers in\n let max_pairs = max_count * min_count in\n (max_diff, max_pairs)\n\nlet print (a, b) = Printf.printf \"%d %d\\n\" a b\n\nlet () = print (solve ())\n"}], "src_uid": "eb2d1072c5308d9ef686315a122d9d3c"} {"nl": {"description": "Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.", "input_spec": "The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.", "output_spec": "If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print \u00ab-1\u00bb (without quotes). Otherwise, the first line of output should contain the only integer k (k\u2009\u2265\u20090)\u00a0\u2014 the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct. If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair. Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.", "sample_inputs": ["helloworld\nehoolwlroz", "hastalavistababy\nhastalavistababy", "merrychristmas\nchristmasmerry"], "sample_outputs": ["3\nh e\nl o\nd z", "0", "-1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet () = \n let s = read_string () in \n let t = read_string () in\n let n = String.length s in\n\n let n2l n = char_of_int ((int_of_char 'a') + n) in\n let l2n c = (int_of_char c) - (int_of_char 'a') in\n\n let fix s = Array.init n (fun i -> l2n s.[i]) in\n let s = fix s in\n let t = fix t in\n\n let map = Array.make 26 (-1) in\n let rmap = Array.make 26 (-1) in\n\n let error = ref false in\n for i=0 to n-1 do\n let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||\n (map.(s.(i)) <> -1 && rmap.(t.(i)) <> -1 &&\n\t map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i))\n in\n if good then (\n map.(s.(i)) <- t.(i);\n rmap.(t.(i)) <- s.(i);\n rmap.(s.(i)) <- t.(i);\n map.(t.(i)) <- s.(i); \n ) else (\n error := true\n )\n done;\n\n if !error then printf \"-1\\n\" else (\n let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) > c then 1 else 0) in\n printf \"%d\\n\" swapcount;\n for c=0 to 25 do\n if map.(c) <> -1 && map.(c) > c then\n\tprintf \"%c %c\\n\" (n2l c) (n2l map.(c))\n done;\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet () = \n let s = read_string () in \n let t = read_string () in\n let n = String.length s in\n\n let n2l n = char_of_int ((int_of_char 'a') + n) in\n let l2n c = (int_of_char c) - (int_of_char 'a') in\n\n let fix s = Array.init n (fun i -> l2n s.[i]) in\n let s = fix s in\n let t = fix t in\n\n let map = Array.make 26 (-1) in\n let rmap = Array.make 26 (-1) in\n\n let error = ref false in\n for i=0 to n-1 do\n let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||\n (map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i))\n in\n if good then (\n map.(s.(i)) <- t.(i);\n rmap.(t.(i)) <- s.(i);\n ) else (\n error := true\n )\n done;\n\n if !error then printf \"-1\\n\" else (\n let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) <> c then 1 else 0) in\n printf \"%d\\n\" swapcount;\n for c=0 to 25 do\n if map.(c) <> -1 && map.(c) > c then\n\tprintf \"%c %c\\n\" (n2l c) (n2l map.(c))\n done;\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet () = \n let s = read_string () in \n let t = read_string () in\n let n = String.length s in\n\n let n2l n = char_of_int ((int_of_char 'a') + n) in\n let l2n c = (int_of_char c) - (int_of_char 'a') in\n\n let fix s = Array.init n (fun i -> l2n s.[i]) in\n let s = fix s in\n let t = fix t in\n\n let map = Array.make 26 (-1) in\n let rmap = Array.make 26 (-1) in\n\n let error = ref false in\n for i=0 to n-1 do\n let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||\n (map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i) && rmap.(s.(i)) = t.(i) && map.(t.(i)) = s.(i))\n in\n if good then (\n map.(s.(i)) <- t.(i);\n rmap.(t.(i)) <- s.(i);\n ) else (\n error := true\n )\n done;\n\n if !error then printf \"-1\\n\" else (\n let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) > c then 1 else 0) in\n printf \"%d\\n\" swapcount;\n for c=0 to 25 do\n if map.(c) <> -1 && map.(c) > c then\n\tprintf \"%c %c\\n\" (n2l c) (n2l map.(c))\n done;\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet () = \n let s = read_string () in \n let t = read_string () in\n let n = String.length s in\n\n let n2l n = char_of_int ((int_of_char 'a') + n) in\n let l2n c = (int_of_char c) - (int_of_char 'a') in\n\n let fix s = Array.init n (fun i -> l2n s.[i]) in\n let s = fix s in\n let t = fix t in\n\n let map = Array.make 26 (-1) in\n let rmap = Array.make 26 (-1) in\n\n let error = ref false in\n for i=0 to n-1 do\n let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||\n (map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i))\n in\n if good then (\n map.(s.(i)) <- t.(i);\n rmap.(t.(i)) <- s.(i);\n ) else (\n error := true\n )\n done;\n\n if !error then printf \"-1\\n\" else (\n let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) > c then 1 else 0) in\n printf \"%d\\n\" swapcount;\n for c=0 to 25 do\n if map.(c) <> -1 && map.(c) > c then\n\tprintf \"%c %c\\n\" (n2l c) (n2l map.(c))\n done;\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \nlet () = \n let s = read_string () in \n let t = read_string () in\n let n = String.length s in\n\n let n2l n = char_of_int ((int_of_char 'a') + n) in\n let l2n c = (int_of_char c) - (int_of_char 'a') in\n\n let fix s = Array.init n (fun i -> l2n s.[i]) in\n let s = fix s in\n let t = fix t in\n\n let map = Array.make 26 (-1) in\n let rmap = Array.make 26 (-1) in\n\n let error = ref false in\n for i=0 to n-1 do\n let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||\n (map.(s.(i)) <> -1 && rmap.(t.(i)) <> -1 &&\n\t map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i))\n in\n if good then (\n map.(s.(i)) <- t.(i);\n rmap.(t.(i)) <- s.(i);\n ) else (\n error := true\n )\n done;\n\n if !error then printf \"-1\\n\" else (\n let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) > c then 1 else 0) in\n printf \"%d\\n\" swapcount;\n for c=0 to 25 do\n if map.(c) <> -1 && map.(c) > c then\n\tprintf \"%c %c\\n\" (n2l c) (n2l map.(c))\n done;\n )\n"}], "src_uid": "b03895599bd578a83321401428e277da"} {"nl": {"description": "Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called \"Black Square\" on his super cool touchscreen phone.In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip.You've got a string s, describing the process of the game and numbers a1,\u2009a2,\u2009a3,\u2009a4. Calculate how many calories Jury needs to destroy all the squares?", "input_spec": "The first line contains four space-separated integers a1, a2, a3, a4 (0\u2009\u2264\u2009a1,\u2009a2,\u2009a3,\u2009a4\u2009\u2264\u2009104). The second line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009105), where the \u0456-th character of the string equals \"1\", if on the i-th second of the game the square appears on the first strip, \"2\", if it appears on the second strip, \"3\", if it appears on the third strip, \"4\", if it appears on the fourth strip.", "output_spec": "Print a single integer \u2014 the total number of calories that Jury wastes.", "sample_inputs": ["1 2 3 4\n123214", "1 5 3 2\n11221"], "sample_outputs": ["13", "13"], "notes": null}, "positive_code": [{"source_code": "let str_to_list s =\n let rec loop i l =\n if i < 0 \n then l \n else loop (i - 1) (s.[i] :: l) in\n loop (String.length s - 1) []\n\nlet digit_to_int c = \n Pervasives.int_of_char c - Pervasives.int_of_char '0'\n\nlet input () =\n let costs = Scanf.scanf \"%d %d %d %d \" (fun a b c d -> [a; b; c; d]) in\n let moves = Scanf.scanf \"%s\" (fun s -> List.map digit_to_int (str_to_list s)) in\n (costs, moves)\n\nlet solve (costs, moves) =\n List.fold_left (+) 0 (List.map (fun n -> List.nth costs (n - 1)) moves)\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "let str_to_list s =\n let rec loop i l =\n if i < 0 \n then l \n else loop (i - 1) (s.[i] :: l) in\n loop (String.length s - 1) []\n\nlet digit_to_int c = \n Pervasives.int_of_char c - Pervasives.int_of_char '0'\n\nlet input () =\n let costs = Scanf.scanf \"%d %d %d %d \" (fun a b c d -> [a; b; c; d]) in\n let moves = Scanf.scanf \"%s\" (fun s -> List.map digit_to_int (str_to_list s)) in\n (costs, moves)\n\nlet solve (costs, moves) =\n let rec loop list i total =\n match list with\n | (head :: tail) -> \n let quantity = List.length (List.filter (fun n -> n = i) moves) in\n let curr_cost = head * quantity in\n loop tail (i + 1) (total + curr_cost)\n | [] -> total\n in loop costs 1 0\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let a = Array.init 4 (fun _ -> read_int()) in\n let s = read_string () in\n\n let n = String.length s in\n\n let t = ref 0 in\n\n for i=0 to n-1 do\n let d = (int_of_char s.[i]) - (int_of_char '1') in\n t := !t + a.(d)\n done;\n\n printf \"%d\\n\" !t\n"}, {"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet a=read_int();;\nlet b=read_int();;\nlet c=read_int();;\nlet tab=Array.make 5 0;;\ntab.(1)<-a;;\ntab.(2)<-b;;\ntab.(3)<-c;;\nlet d=Scanf.scanf \"%d\\n\" (fun x->x);;\ntab.(4)<-d;;\nlet s=Scanf.scanf \"%s\" (fun x->x);;\nlet n=String.length(s);;\nlet nb=ref 0;;\nfor i=0 to n-1 do\n nb:= !nb+tab.(int_of_char(s.[i])-48)\ndone;;\nprint_int !nb;;\n"}, {"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule H = Hashtbl\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\nlet rec bsearch_min a b test =\n if b - a = 1 then b else \n let mid = (a-b)/2 + b in \n if test mid then bsearch_min a mid test else \n bsearch_min mid b test\nlet rec bsearch_max a b test = \n if b - a = 1 then a else \n let mid = (a-b)/2 + b in \n if test mid then bsearch_max mid b test else \n bsearch_max a mid test\n(* int *)\nlet sqrt_floor n = bsearch_max 0 (1 lsl 31) (fun i -> i*i <= n)\nlet sqrt_ceil n = bsearch_min (-1) (1 lsl 31) (fun i -> n <= i*i) \n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet default x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* int, int *)\nlet (++) (a,b) (c,d) = (a+c,b+d)\nlet (--) (a,b) (c,d) = (a-c,b-d)\n(* number theory *)\nlet sieve_under len = (* len > 0 *)\n let sieve = Array.make len true in \n Array.fill sieve 0 (min len 2) false;\n let rec erase i k = if i >= len then () else (sieve.(i) <- false; erase (i+k) k) in \n for i = 2 to sqrt_floor len do if sieve.(i) then erase (2*i) i done;\n sieve\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 128 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create (4*1024) in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_int n = printf \"%d\\n\" n\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\n\nlet _ = \n let arr = init 4 (fun i -> read_int()) in\n let str = read_line() in \n \n let len = S.length str in \n let rec run i acc = \n if i = len then acc else \n run (i+1) (acc + arr.(int_of_char str.[i] - 49)) \n in \n printf \"%d\\n\" (run 0 0)"}], "negative_code": [], "src_uid": "db9065d975878227a749083f0036a169"} {"nl": {"description": "A row of $$$n$$$ cells is given, all initially white. Using a stamp, you can stamp any two neighboring cells such that one becomes red and the other becomes blue. A stamp can be rotated, i.e. it can be used in both ways: as $$$\\color{blue}{\\texttt{B}}\\color{red}{\\texttt{R}}$$$ and as $$$\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}$$$.During use, the stamp must completely fit on the given $$$n$$$ cells (it cannot be partially outside the cells). The stamp can be applied multiple times to the same cell. Each usage of the stamp recolors both cells that are under the stamp.For example, one possible sequence of stamps to make the picture $$$\\color{blue}{\\texttt{B}}\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}\\color{blue}{\\texttt{B}}\\texttt{W}$$$ could be $$$\\texttt{WWWWW} \\to \\texttt{WW}\\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}}\\texttt{W} \\to \\color{brown}{\\underline{\\color{blue}{\\texttt{B}}\\color{red}{\\texttt{R}}}}\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}\\texttt{W} \\to \\color{blue}{\\texttt{B}}\\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}}\\color{blue}{\\texttt{B}}\\texttt{W}$$$. Here $$$\\texttt{W}$$$, $$$\\color{red}{\\texttt{R}}$$$, and $$$\\color{blue}{\\texttt{B}}$$$ represent a white, red, or blue cell, respectively, and the cells that the stamp is used on are marked with an underline.Given a final picture, is it possible to make it using the stamp zero or more times?", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the length of the picture. The second line of each test case contains a string $$$s$$$\u00a0\u2014 the picture you need to make. It is guaranteed that the length of $$$s$$$ is $$$n$$$ and that $$$s$$$ only consists of the characters $$$\\texttt{W}$$$, $$$\\texttt{R}$$$, and $$$\\texttt{B}$$$, representing a white, red, or blue cell, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output \"YES\" if it possible to make the picture using the stamp zero or more times, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["12\n5\nBRBBW\n1\nB\n2\nWB\n2\nRW\n3\nBRB\n3\nRBB\n7\nWWWWWWW\n9\nRBWBWRRBW\n10\nBRBRBRBRRB\n12\nBBBRWWRRRWBR\n10\nBRBRBRBRBW\n5\nRBWBW"], "sample_outputs": ["YES\nNO\nNO\nNO\nYES\nYES\nYES\nNO\nYES\nNO\nYES\nNO"], "notes": "NoteThe first test case is explained in the statement.For the second, third, and fourth test cases, it is not possible to stamp a single cell, so the answer is \"NO\".For the fifth test case, you can use the stamp as follows: $$$\\texttt{WWW} \\to \\texttt{W}\\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}} \\to \\color{brown}{\\underline{\\color{blue}{\\texttt{B}}\\color{red}{\\texttt{R}}}}\\color{blue}{\\texttt{B}}$$$.For the sixth test case, you can use the stamp as follows: $$$\\texttt{WWW} \\to \\texttt{W}\\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}} \\to \\color{brown}{\\underline{\\color{red}{\\texttt{R}}\\color{blue}{\\texttt{B}}}}\\color{blue}{\\texttt{B}}$$$.For the seventh test case, you don't need to use the stamp at all."}, "positive_code": [{"source_code": "let getInt () = Scanf.scanf \" %d\" (fun i -> i);;\r\n\r\n\r\nlet getList(n): int list = \r\n let rec getList2 ((n: int), (acc: int list)) = match n with\r\n\t | 0 -> List.rev acc\r\n\t | _ -> getList2 (n-1, getInt() :: acc)\r\n in getList2(n, [])\r\n\r\nlet getLine() = Scanf.scanf \" %s\" (fun i -> i);;\r\n\r\nlet rec solve((s: char list), (w: int), (b: int)): bool = \r\n let len = w + b in\r\n match s with\r\n | [] -> (len = 0 || (w > 0 && b > 0))\r\n\r\n | 'W' :: xs -> if len = 0 || (w > 0 && b > 0) then solve(xs, 0, 0)\r\n else false\r\n\r\n | 'B' :: xs -> solve(xs, w, b + 1)\r\n\r\n | 'R' :: xs -> solve(xs, w + 1, b)\r\n\r\n | _ -> false\r\n \r\n\r\nlet explode s =\r\n let rec exp i l =\r\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\r\n exp (String.length s - 1) []\r\n\r\nlet main() = \r\n let t = getInt() in\r\n for i = 1 to t do \r\n let n = getInt() in let s = getLine() in let arr = explode(s)\r\n in if solve(arr, 0, 0) then print_endline(\"YES\")\r\n else print_endline(\"NO\") \r\n done;;\r\n\r\nmain();;\r\n\r\n\r\n"}], "negative_code": [], "src_uid": "3f284afb044c8a57a02cd015d06e0ef0"} {"nl": {"description": "Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \\cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible.", "input_spec": "First line contains a single integer $$$n$$$ $$$(1 \\le n \\le 2 \\cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \\leq a_i \\leq 10^9, 0 \\leq b_i, c_i \\leq 1)$$$ \u00a0\u2014 the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \\leq u, v \\leq n, \\text{ } u \\ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.", "output_spec": "Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible.", "sample_inputs": ["5\n1 0 1\n20 1 0\n300 0 1\n4000 0 0\n50000 1 0\n1 2\n2 3\n2 4\n1 5", "5\n10000 0 1\n2000 1 0\n300 0 1\n40 0 0\n1 1 0\n1 2\n2 3\n2 4\n1 5", "2\n109 0 1\n205 0 1\n1 2"], "sample_outputs": ["4", "24000", "-1"], "notes": "NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \\cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \\cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \\cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n \nlet () =\n let n = read_int() in\n let a = Array.make n 0L in\n let b = Array.make n 0 in\n let c = Array.make n 0 in\n for i=0 to n-1 do\n a.(i) <- read_long ();\n b.(i) <- read_int ();\n c.(i) <- read_int (); \n done;\n\n let tree = Array.make n [] in\n\n for i=1 to n-1 do\n let (u,v) = read_pair() in\n let (u,v) = (u-1,v-1) in\n tree.(u) <- v::tree.(u);\n tree.(v) <- u::tree.(v) \n done;\n\n let ones_there = sum 0 (n-1) (fun i -> b.(i)) in\n let ones_wanted = sum 0 (n-1) (fun i -> c.(i)) in\n if ones_there <> ones_wanted then (\n printf \"-1\\n\"\n ) else (\n\n (*\n let ex = Array.make_matrix 2 n 0 in (*excess 0s and 1s *)\n\n let rec dfs0 p u =\n let rec loop li ac0 ac1 = \n\tmatch li with\n\t | [] -> (ac0, ac1)\n\t | v::tail ->\n\t if v = p then loop tail ac0 ac1 else\n\t let (v0, v1) = dfs0 u v in\n\t loop tail (ac0+v0) (ac1+v1)\n in\n let (ac0, ac1) = loop tree.(u) 0 0 in\n let ac0 = ac0 + (if b.(u) = 0 && c.(u) = 1 then 1 else 0) in\n let ac1 = ac1 + (if b.(u) = 1 && c.(u) = 0 then 1 else 0) in \n(* let change = min ac0 ac1 in\n let (ac0, ac1) = (ac0 - change, ac1 - change) in *)\n ex.(0).(u) <- ac0;\n ex.(1).(u) <- ac1;\n (ac0, ac1)\n in\n let _ = dfs (-1) 0 in\n *)\n \n let rec dfs p u mincost =\n (* return (excess_ones, excess_zeros, cost) for this subtree *)\n let rec loop li ac0 ac1 ac_cost =\n\tmatch li with\n\t | [] -> (ac0, ac1, ac_cost)\n\t | v::tail ->\n\t if v = p then loop tail ac0 ac1 ac_cost else\n\t let (v0, v1, v_cost) = dfs u v (min mincost a.(v)) in\n\t loop tail (ac0+v0) (ac1+v1) (ac_cost ++ v_cost)\n in\n let (ac0, ac1, ac_cost) = loop tree.(u) 0 0 0L in\n let ac0 = ac0 + (if b.(u) = 0 && c.(u) = 1 then 1 else 0) in\n let ac1 = ac1 + (if b.(u) = 1 && c.(u) = 0 then 1 else 0) in \n let change = min ac0 ac1 in\n let cost = ac_cost ++ 2L ** (long change) ** mincost in\n (ac0 - change, ac1 - change, cost)\n in\n\n let (_, _, cost) = dfs (-1) 0 a.(0) in\n printf \"%Ld\\n\" cost\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet long x = Int64.of_int x\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n \nlet () =\n let n = read_int() in\n let a = Array.make n 0L in\n let b = Array.make n 0 in\n let c = Array.make n 0 in\n for i=0 to n-1 do\n a.(i) <- read_long ();\n b.(i) <- read_int ();\n c.(i) <- read_int (); \n done;\n\n let tree = Array.make n [] in\n\n for i=1 to n-1 do\n let (u,v) = read_pair() in\n let (u,v) = (u-1,v-1) in\n tree.(u) <- v::tree.(u);\n tree.(v) <- u::tree.(v) \n done;\n\n let rec dfs p u mincost =\n (* return (excess_ones, excess_zeros, cost) for this subtree *)\n let rec loop li ac0 ac1 ac_cost =\n match li with\n\t| [] -> (ac0, ac1, ac_cost)\n\t| v::tail ->\n\t if v = p then loop tail ac0 ac1 ac_cost else\n\t let (v0, v1, v_cost) = dfs u v (min mincost a.(v)) in\n\t loop tail (ac0+v0) (ac1+v1) (ac_cost ++ v_cost)\n in\n let (ac0, ac1, ac_cost) = loop tree.(u) 0 0 0L in\n let ac0 = ac0 + (if b.(u) = 0 && c.(u) = 1 then 1 else 0) in\n let ac1 = ac1 + (if b.(u) = 1 && c.(u) = 0 then 1 else 0) in \n let change = min ac0 ac1 in\n let cost = ac_cost ++ 2L ** (long change) ** mincost in\n (ac0 - change, ac1 - change, cost)\n in\n \n let (c0, c1, cost) = dfs (-1) 0 a.(0) in\n printf \"%Ld\\n\" (if c0 + c1 <> 0 then -1L else cost)\n"}], "negative_code": [], "src_uid": "4dce15ff1446b5af2c5b49ee2d30bbb8"} {"nl": {"description": "You've got a non-decreasing sequence x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009x1\u2009\u2264\u2009x2\u2009\u2264\u2009...\u2009\u2264\u2009xn\u2009\u2264\u2009q). You've also got two integers a and b (a\u2009\u2264\u2009b;\u00a0a\u00b7(n\u2009-\u20091)\u2009<\u2009q).Your task is to transform sequence x1,\u2009x2,\u2009...,\u2009xn into some sequence y1,\u2009y2,\u2009...,\u2009yn (1\u2009\u2264\u2009yi\u2009\u2264\u2009q;\u00a0a\u2009\u2264\u2009yi\u2009+\u20091\u2009-\u2009yi\u2009\u2264\u2009b). The transformation price is the following sum: . Your task is to choose such sequence y that minimizes the described transformation price.", "input_spec": "The first line contains four integers n,\u2009q,\u2009a,\u2009b (2\u2009\u2264\u2009n\u2009\u2264\u20096000;\u00a01\u2009\u2264\u2009q,\u2009a,\u2009b\u2009\u2264\u2009109;\u00a0a\u00b7(n\u2009-\u20091)\u2009<\u2009q;\u00a0a\u2009\u2264\u2009b). The second line contains a non-decreasing integer sequence x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009x1\u2009\u2264\u2009x2\u2009\u2264\u2009...\u2009\u2264\u2009xn\u2009\u2264\u2009q).", "output_spec": "In the first line print n real numbers \u2014 the sought sequence y1,\u2009y2,\u2009...,\u2009yn (1\u2009\u2264\u2009yi\u2009\u2264\u2009q;\u00a0a\u2009\u2264\u2009yi\u2009+\u20091\u2009-\u2009yi\u2009\u2264\u2009b). In the second line print the minimum transformation price, that is, . If there are multiple optimal answers you can print any of them. The answer will be considered correct if the absolute or relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["3 6 2 2\n1 4 6", "10 100000 8714 9344\n3378 14705 17588 22672 32405 34309 37446 51327 81228 94982"], "sample_outputs": ["1.666667 3.666667 5.666667 \n0.666667", "1.000000 8715.000000 17429.000000 26143.000000 34857.000000 43571.000000 52285.000000 61629.000000 70973.000000 80317.000000 \n797708674.000000"], "notes": null}, "positive_code": [{"source_code": "(* It's a DP algorithm. Keep y_opt.(i) which is the natural place\n where the point y.(i) will land when considering only points 0, 1,\n 2... i.\n \n To compute y_opt.(i) we assume we have already computed the\n previous ones. What we do now is see if y.(i) acting alone would\n be within the window defined by y_opt.(i-1). If it is, we're done\n with y_opt.(i). Say y.(i) is too high to be compatible with\n y_opt.(i-1). Then we glue these two points together by asserting\n y.(i)-y.(i-1)=b. (Analogously, if y.(i) is too low compared to\n y_opt.(i-1) we assert y.(i)-y.(i-1)=a instead.) This pair of\n points has a natural position uninfluenced by anything outside of\n them. If this position is compatible with y_opt.(i-2) then we're\n done, otherwise we add y.(i-2) to the chain and continue. So the\n elements are chained together by a sequence of as and bs,\n intermixed.\n\n We can prove by induction that the solution that this finds is\n optimal. The base case is when y.(i) is within the window allowed\n by y_opt.(i-1). Clearly this is the right answer. Now suppose\n that we have established that in the optimal solution some chain of\n differences relating y.(k),...,y.(i-2), y.(i) must occur. This\n means that when searching for the optimal solution we need only\n consider these values moving in lockstep as specified by the chain.\n Looking at point k-1 if the chain is too low, then the optimal\n solution must also have y.(k-1) in the chain being a below y.(k),\n and if point k-1 is too high then it must be in the chain b below\n y.(i). (The intuition is that of a spring. If you move your\n finger toward a spring and you touch the spring, pushing harder on\n the spring will keep your finger in contact with the spring. The\n spring will not suddenly pull away from your finger as you push\n harder. The (x-y)^2 cost function ensures that this is the correct\n model.)\n\n So the algorithm is O(n^2). It might be possible to work out a\n version of this algorithm that is O(n log n) by keeping the chains\n in a search tree. Then instead of starting from scratch each time\n when adding a new point, it would edit the current chain. It is\n not clear that this can be made to work.\n\n Danny Sleator \n*)\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\nlet sq x = x *. x\nlet (++) (a,b,c) (d,e,f) = (a+.d, b+.e, c+.f)\n\nlet quad_min (a,b,c) = -. (b /. (2.0 *. a))\n (* ax^2 + bx + c is our quadratic. Return the value of x that minimizes it *)\n (* a cannot be zero *)\n\nlet () =\n let n = read_int 0 in\n let q0 = read_float 0 in\n let a0 = read_float 0 in\n let b0 = read_float 0 in\n\n let x = Array.init n read_float in\n let y_opt = Array.copy x in\n let chain = Array.make n 0.0 in\n\n let bound h v = max (1.0+.h) (min q0 v) in\n\n let rec pull_chain j h q = if j<0 then (bound h (quad_min q), j) else\n (* Set the group of points j+1, j+2, ... i all to differ by cumulative h\n the quadratic represented by this group is q. *)\n let yi_nat = bound h (quad_min q) in\n if y_opt.(j) < yi_nat -. h -. b0 then \n\tlet ny = x.(j) +. h +. b0 in\n\t chain.(j) <- b0;\n\t pull_chain (j-1) (h+.b0) (q ++ (1.0, -2.0 *. ny, sq ny))\n else if y_opt.(j) > yi_nat -. h -. a0 then \n\tlet ny = x.(j) +. h +. a0 in\n\t chain.(j) <- a0;\n\t pull_chain (j-1) (h+.a0) (q ++ (1.0, -2.0 *. ny, sq ny))\n else \n\t(yi_nat, j)\n in\n\n for i=1 to n-1 do\n let myq = (1.0, -2.0*.x.(i), sq x.(i)) in\n let (yopt, j) = pull_chain (i-1) 0.0 myq in\n\ty_opt.(i) <- yopt;\n done;\n\n let rec fill_in_y i = if i<0 then () else\n let (_, j) = pull_chain (i-1) 0.0 (1.0, -2.0*.x.(i), sq x.(i)) in\n\tfor k=i-1 downto j+1 do\n\t y_opt.(k) <- y_opt.(k+1) -. chain.(k);\n\tdone;\n\tfill_in_y j\n in\n fill_in_y (n-1);\n \n let total = sum 0 (n-1) (fun i-> sq (y_opt.(i) -. x.(i))) in\n\n\tfor i=0 to n-1 do \n\t Printf.printf \"%.8f \" y_opt.(i);\n\tdone;\n\tprint_newline();\n\tPrintf.printf \"%.8f\\n\" total;\n"}, {"source_code": "(* It's a DP algorithm. Keep y_opt.(i) which is the natural place\n where the point y.(i) will land when considering only points 0, 1,\n 2... i.\n \n To compute y_opt.(i) we assume we have already computed the\n previous ones. What we do now is see if y.(i) acting alone would\n be within the window defined by y_opt.(i-1). If it is, we're done\n with y_opt.(i). Say y.(i) is too high to be compatible with\n y_opt.(i-1). Then we glue fix y.(i-1)=y.(i)-b and compute the\n natural position for this pair of points using the sum of their\n potentials. If this is compatible with y_opt.(i-2) then we're\n done, otherwise we add that to the group and continue. The chain\n can consist of a sequence of as and bs, intermixed.\n\n So the algorithm is O(n^2). It could be optimized as follows.\n Remember how far back the block went and continuing from where we\n left off computing y_opt.(i). So if y.(i+1) also is pulling up we\n can continue from where we left off. Can this be turned into an\n O(n) algorithm?\n*)\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\n\nlet sq x = x *. x\n\nlet (++) (a,b,c) (d,e,f) = (a+.d, b+.e, c+.f)\n\nlet quad_min (a,b,c) = \n (* ax^2 + bx + c is our quadratic. Return the value of x that minimizes it *)\n (* a cannot be zero *)\n -. (b /. (2.0 *. a))\n\nlet quad_eval (a,b,c) x = a *. (sq x) +. b *. x +. c\n\nlet () =\n let n = read_int 0 in\n let q0 = read_float 0 in\n let a0 = read_float 0 in\n let b0 = read_float 0 in\n\n let x = Array.init n read_float in\n let y_opt = Array.copy x in\n let chain = Array.make n 0.0 in\n let jarray = Array.make n (-1) in\n\n let bound h v = max (1.0+.h) (min q0 v) in\n\n let rec pull_chain j h q = if j<0 then (bound h (quad_min q), j) else\n (* set the group of points j+1, j+2, ... i all to differ by cumulative h\n the quadratic represented by this group is q. Find its natural position. *)\n let yi_nat = bound h (quad_min q) in\n if y_opt.(j) < yi_nat -. h -. b0 then \n\tlet ny = x.(j) +. h +. b0 in\n\t chain.(j) <- b0;\n\t pull_chain (j-1) (h+.b0) (q ++ (1.0, -2.0 *. ny, sq ny))\n else if y_opt.(j) > yi_nat -. h -. a0 then \n\tlet ny = x.(j) +. h +. a0 in\n\t chain.(j) <- a0;\n\t pull_chain (j-1) (h+.a0) (q ++ (1.0, -2.0 *. ny, sq ny))\n else \n\t(yi_nat, j)\n in\n\n for i=1 to n-1 do\n let myq = (1.0, -2.0*.x.(i), sq x.(i)) in\n let (yopt, j) = pull_chain (i-1) 0.0 myq in\n\ty_opt.(i) <- yopt;\n\tjarray.(i) <- j;\n done;\n\n let rec fill_in_y i = if i<0 then () else\n let myq = (1.0, -2.0*.x.(i), sq x.(i)) in\n let (_, j) = pull_chain (i-1) 0.0 myq in\n let rec loop k = if k<=j then () else\n\tlet delta = chain.(k) in\n\t y_opt.(k) <- y_opt.(k+1) -. delta;\n\t loop (k-1)\n in\n\tloop (i-1);\n\tfill_in_y j\n in\n\n fill_in_y (n-1);\n \n let total = sum 0 (n-1) (fun i-> sq (y_opt.(i) -. x.(i))) in\n\n\tfor i=0 to n-1 do \n\t Printf.printf \"%.8f \" y_opt.(i);\n\tdone;\n\tprint_newline();\n\tPrintf.printf \"%.8f\\n\" total;\n"}, {"source_code": "(* It's a DP algorithm. Keep y_opt.(i) which is the natural place\n where the point y.(i) will land when considering only points 0, 1,\n 2... i.\n \n To compute y_opt.(i) we assume we have already computed the\n previous ones. What we do now is see if y.(i) acting alone would\n be within the window defined by y_opt.(i-1). If it is, we're done\n with y_opt.(i). Say y.(i) is too high to be compatible with\n y_opt.(i-1). Then we glue these two points together by asserting\n y.(i)-y.(i-1)=b. (Analogously, if y.(i) is too low compared to\n y_opt.(i-1) we assert y.(i)-y.(i-1)=a instead.) This pair of\n points has a natural position uninfluenced by anything outside of\n them. If this position is compatible with y_opt.(i-2) then we're\n done, otherwise we add y.(i-2) to the chain and continue. So the\n elements are chained together by a sequence of as and bs,\n intermixed.\n\n We can prove by induction that the solution that this finds is\n optimal. The base case is when y.(i) is within the window allowed\n by y_opt.(i-1). Clearly this is the right answer. Now suppose\n that we have established that in the optimal solution some chain of\n differences relating y.(k),...,y.(i-2), y.(i) must occur. This\n means that when searching for the optimal solution we need only\n consider these values moving in lockstep as specified by the chain.\n Looking at point k-1 if the chain is too low, then the optimal\n solution must also have y.(k-1) in the chain being a below y.(k),\n and if point k-1 is too high then it must be in the chain b below\n y.(i). (The intuition is that of a spring. If you move your\n finger toward a spring and you touch the spring, pushing harder on\n the spring will keep your finger in contact with the spring. The\n spring will not suddenly pull away from your finger as you push\n harder. The (x-y)^2 cost function ensures that this is the correct\n model.)\n\n So the algorithm is O(n^2). It might be possible to work out a\n version of this algorithm that is O(n log n) by keeping the chains\n in a search tree. Then instead of starting from scratch each time\n when adding a new point, it would edit the current chain. It is\n not clear that this can be made to work.\n\n Danny Sleator \n*)\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\nlet sq x = x *. x\nlet (++) (a,b,c) (d,e,f) = (a+.d, b+.e, c+.f)\n\nlet quad_min (a,b,c) = -. (b /. (2.0 *. a))\n (* ax^2 + bx + c is our quadratic. Return the value of x that minimizes it *)\n (* a cannot be zero *)\n\nlet () =\n let n = read_int 0 in\n let q0 = read_float 0 in\n let a0 = read_float 0 in\n let b0 = read_float 0 in\n\n let x = Array.init n read_float in\n let y_opt = Array.copy x in\n let chain = Array.make n 0.0 in\n\n let bound h v = max (1.0+.h) (min q0 v) in\n\n let rec pull_chain j h q = if j<0 then (bound h (quad_min q), j) else\n (* Set the group of points j+1, j+2, ... i all to differ by cumulative h\n the quadratic represented by this group is q. *)\n let yi_nat = bound h (quad_min q) in\n if y_opt.(j) < yi_nat -. h -. b0 then \n\tlet ny = x.(j) +. h +. b0 in\n\t chain.(j) <- b0;\n\t pull_chain (j-1) (h+.b0) (q ++ (1.0, -2.0 *. ny, sq ny))\n else if y_opt.(j) > yi_nat -. h -. a0 then \n\tlet ny = x.(j) +. h +. a0 in\n\t chain.(j) <- a0;\n\t pull_chain (j-1) (h+.a0) (q ++ (1.0, -2.0 *. ny, sq ny))\n else \n\t(yi_nat, j)\n in\n\n for i=1 to n-1 do\n let myq = (1.0, -2.0*.x.(i), sq x.(i)) in\n let (yopt, j) = pull_chain (i-1) 0.0 myq in\n\ty_opt.(i) <- yopt;\n done;\n\n let rec fill_in_y i = if i<0 then () else\n let (_, j) = pull_chain (i-1) 0.0 (1.0, -2.0*.x.(i), sq x.(i)) in\n\tfor k=i-1 downto j+1 do\n\t y_opt.(k) <- y_opt.(k+1) -. chain.(k);\n\tdone;\n\tfill_in_y j\n in\n fill_in_y (n-1);\n \n let total = sum 0 (n-1) (fun i-> sq (y_opt.(i) -. x.(i))) in\n\n\tfor i=0 to n-1 do \n\t Printf.printf \"%.8f \" y_opt.(i);\n\tdone;\n\tPrintf.printf \"%.8f\\n\" total;\n"}], "negative_code": [], "src_uid": "d212e5a9b67c0ced9d85b94ecf0504ae"} {"nl": {"description": "Bash got tired on his journey to become the greatest Pokemon master. So he decides to take a break and play with functions.Bash defines a function f0(n), which denotes the number of ways of factoring n into two factors p and q such that gcd(p,\u2009q)\u2009=\u20091. In other words, f0(n) is the number of ordered pairs of positive integers (p,\u2009q) such that p\u00b7q\u2009=\u2009n and gcd(p,\u2009q)\u2009=\u20091.But Bash felt that it was too easy to calculate this function. So he defined a series of functions, where fr\u2009+\u20091 is defined as:Where (u,\u2009v) is any ordered pair of positive integers, they need not to be co-prime.Now Bash wants to know the value of fr(n) for different r and n. Since the value could be huge, he would like to know the value modulo 109\u2009+\u20097. Help him!", "input_spec": "The first line contains an integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009106)\u00a0\u2014 the number of values Bash wants to know. Each of the next q lines contain two integers r and n (0\u2009\u2264\u2009r\u2009\u2264\u2009106, 1\u2009\u2264\u2009n\u2009\u2264\u2009106), which denote Bash wants to know the value fr(n).", "output_spec": "Print q integers. For each pair of r and n given, print fr(n) modulo 109\u2009+\u20097 on a separate line.", "sample_inputs": ["5\n0 30\n1 25\n3 65\n2 5\n4 48"], "sample_outputs": ["8\n5\n25\n4\n630"], "notes": null}, "positive_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let m = 2000000 in\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let mmod n =\n let r = Int64.rem n mmm in\n if r < 0L\n then r +| mmm\n else r\n in\n let inv = Array.make (m + 1) 1 in\n let _ =\n for i = 2 to m do\n inv.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)\n\t mmm);\n done\n in\n let fact = Array.make (m + 1) 1 in\n let ifact = Array.make (m + 1) 1 in\n let () =\n for i = 2 to m do\n fact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);\n ifact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int ifact.(i - 1) *| Int64.of_int inv.(i)) mmm);\n done;\n in\n let n2 = 1000000 in\n let prime = Array.make (n2 + 1) true in\n let p = Array.make (n2 + 1) 0 in\n let pd = Array.init (n2 + 1) (fun i -> i) in\n let pk = ref 0 in\n let () =\n for i = 2 to n2 do\n if prime.(i) then (\n\tp.(!pk) <- i;\n\tincr pk;\n\tpd.(i) <- i;\n\tlet j = ref (2 * i) in\n while !j <= n2 do\n\t let jj = !j in\n prime.(jj) <- false;\n\t pd.(jj) <- i;\n j := jj + i\n done\n )\n done;\n prime.(1) <- false;\n in\n let pk = !pk - 1 in\n let fp = Array.make 20 0 in\n let fd = Array.make 20 0 in\n let factor x =\n let r = ref 0 in\n let x = ref x in\n while !x > 1 && not (pd.(!x) = !x) do\n\tlet pr = pd.(!x) in\n\t let d = ref 0 in\n\t while !x mod pr = 0 do\n\t incr d;\n\t x := !x / pr;\n\t done;\n\t fp.(!r) <- pr;\n\t fd.(!r) <- !d;\n\t incr r;\n done;\n if !x > 1 then (\n\tfp.(!r) <- !x;\n\tfd.(!r) <- 1;\n\tincr r;\n );\n !r\n in\n let min (x : int) y = if x < y then x else y in\n let q = getnum () in\n for _ca = 1 to q do\n let r = getnum () in\n let n = getnum () in\n let t = factor n in\n let res = ref 1L in\n\tfor i = 0 to t - 1 do\n\t let x = fd.(i) in\n\t res := mmod (!res *| Int64.of_int fact.(x + r - 1));\n\t res := mmod (!res *| Int64.of_int ifact.(r));\n\t res := mmod (!res *| Int64.of_int ifact.(x));\n\t res := mmod (!res *| Int64.of_int (2 * x + r));\n\t (*Printf.printf \"qwe %d %Ld\\n\" x !res;*)\n\tdone;\n\tPrintf.printf \"%Ld\\n\" !res;\n done;\n\n"}], "negative_code": [], "src_uid": "9d954b283f551a83279228a9067e910c"} {"nl": {"description": "Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions. Spells of this type speed up the preparation time of one potion. There are m spells of this type, the i-th of them costs bi manapoints and changes the preparation time of each potion to ai instead of x. Spells of this type immediately prepare some number of potions. There are k such spells, the i-th of them costs di manapoints and instantly create ci potions. Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed s. Consider that all spells are used instantly and right before Anton starts to prepare potions.Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least n potions.", "input_spec": "The first line of the input contains three integers n, m, k (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7109,\u20091\u2009\u2264\u2009m,\u2009k\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type. The second line of the input contains two integers x and s (2\u2009\u2264\u2009x\u2009\u2264\u20092\u00b7109,\u20091\u2009\u2264\u2009s\u2009\u2264\u20092\u00b7109)\u00a0\u2014 the initial number of seconds required to prepare one potion and the number of manapoints Anton can use. The third line contains m integers ai (1\u2009\u2264\u2009ai\u2009<\u2009x)\u00a0\u2014 the number of seconds it will take to prepare one potion if the i-th spell of the first type is used. The fourth line contains m integers bi (1\u2009\u2264\u2009bi\u2009\u2264\u20092\u00b7109)\u00a0\u2014 the number of manapoints to use the i-th spell of the first type. There are k integers ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n) in the fifth line\u00a0\u2014 the number of potions that will be immediately created if the i-th spell of the second type is used. It's guaranteed that ci are not decreasing, i.e. ci\u2009\u2264\u2009cj if i\u2009<\u2009j. The sixth line contains k integers di (1\u2009\u2264\u2009di\u2009\u2264\u20092\u00b7109)\u00a0\u2014 the number of manapoints required to use the i-th spell of the second type. It's guaranteed that di are not decreasing, i.e. di\u2009\u2264\u2009dj if i\u2009<\u2009j.", "output_spec": "Print one integer\u00a0\u2014 the minimum time one has to spent in order to prepare n potions.", "sample_inputs": ["20 3 2\n10 99\n2 4 3\n20 10 40\n4 15\n10 80", "20 3 2\n10 99\n2 4 3\n200 100 400\n4 15\n100 800"], "sample_outputs": ["20", "200"], "notes": "NoteIn the first sample, the optimum answer is to use the second spell of the first type that costs 10 manapoints. Thus, the preparation time of each potion changes to 4 seconds. Also, Anton should use the second spell of the second type to instantly prepare 15 potions spending 80 manapoints. The total number of manapoints used is 10\u2009+\u200980\u2009=\u200990, and the preparation time is 4\u00b75\u2009=\u200920 seconds (15 potions were prepared instantly, and the remaining 5 will take 4 seconds each).In the second sample, Anton can't use any of the spells, so he just prepares 20 potions, spending 10 seconds on each of them and the answer is 20\u00b710\u2009=\u2009200."}, "positive_code": [{"source_code": "module Int64 = struct\n include Int64\n let ( + ) = add\n let ( - ) = sub\n let ( * ) = mul\n let ( / ) = div\n let ( mod ) = rem\nend\n\nlet find_best d s =\n let rec aux l r =\n match r - l with\n | 0 -> None\n | 1 -> if d.(l) <= s then Some l else None\n | h ->\n let mid = l + h / 2 in\n if d.(mid) > s then\n aux l mid\n else\n aux mid r\n in aux 0 (Array.length d)\n\nlet solve n m k x s a b c d =\n let best_time = ref (\n let open Int64 in\n match find_best d s with\n | None -> n * x\n | Some j -> (n - c.(j)) * x\n ) in\n for i = 0 to m - 1 do\n let seconds = a.(i) in\n let cost = b.(i) in\n if cost <= s then\n let time =\n let open Int64 in\n match find_best d (s - cost) with\n | None -> n * seconds\n | Some j -> (n - c.(j)) * seconds in\n best_time := min !best_time time\n done;\n !best_time\n\nlet () =\n Scanf.scanf \"%Ld %d %d %Ld %Ld \" @@ fun n m k x s ->\n let a = Array.init m (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x)) in\n let b = Array.init m (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x)) in\n let c = Array.init k (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x)) in\n let d = Array.init k (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x)) in\n solve n m k x s a b c d |> Printf.printf \"%Ld\\n\"\n"}], "negative_code": [{"source_code": "let find_best d s =\n let rec aux l r =\n match r - l with\n | 0 -> None\n | 1 -> if d.(l) <= s then Some l else None\n | h ->\n let mid = l + h / 2 in\n if d.(mid) > s then\n aux l mid\n else\n aux mid r\n in aux 0 (Array.length d)\n\nlet solve n m k x s a b c d =\n let best_time = ref (\n match find_best d s with\n | None -> n * x\n | Some j -> (n - c.(j)) * x\n ) in\n for i = 0 to m - 1 do\n let seconds = a.(i) in\n let cost = b.(i) in\n if cost <= s then\n let time =\n match find_best d (s - cost) with\n | None -> n * seconds\n | Some j -> (n - c.(j)) * seconds in\n best_time := min !best_time time\n done;\n !best_time\n\nlet () =\n Scanf.scanf \"%d %d %d %d %d \" @@ fun n m k x s ->\n let a = Array.init m (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n let b = Array.init m (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n let c = Array.init k (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n let d = Array.init k (fun _ -> Scanf.scanf \"%d \" (fun x -> x)) in\n solve n m k x s a b c d |> Printf.printf \"%d\\n\"\n"}], "src_uid": "2f9f2bdf059e5ab9c64e7b5f27cba0cb"} {"nl": {"description": "Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n\u2009+\u20091. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n\u2009+\u20091 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.", "input_spec": "The first line of the input contains two integers n and t (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009t\u2009\u2264\u2009109)\u00a0\u2014 the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.", "output_spec": "Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.", "sample_inputs": ["6 1\n10.245", "6 2\n10.245", "3 100\n9.2"], "sample_outputs": ["10.25", "10.3", "9.2"], "notes": "NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all."}, "positive_code": [{"source_code": "let first_sup w n =\n let x = ref @@ -1 in\n for i = n - 1 downto (String.index w '.') + 1 do\n if w.[i] > '4' && w.[i] <= '9' then x := i\n done;\n !x\n\nlet incr_w w =\n let f_d = String.index w '.' in\n let x = ref true in\n for i = f_d - 1 downto 0 do\n if !x\n then (if w.[i] = '9'\n then w.[i] <- '0'\n else (w.[i] <- char_of_int (1 + int_of_char w.[i]);\n x := false)\n )\n done;\n (if !x then \"1\" else \"\") ^ (String.sub w 0 f_d)\n\nlet wo_trail w =\n let n = String.length w in\n let len = ref n and flg = ref true in\n while !flg && w.[!len - 1] = '0' do decr len done;\n String.sub w 0 !len\n\nlet rec f f_d i w t =\n if i = -1 || t = 0\n then wo_trail w\n else if i = f_d + 1\n then incr_w w\n else (w.[i] <- '0';\n w.[i-1] <- char_of_int (1 + int_of_char w.[i-1]);\n if w.[i-1] = '5' then f f_d (i-1) w (t-1) else wo_trail w\n )\n\nlet _ =\n let (n,t,w) = Scanf.scanf \"%d %d %s\" (fun n t w -> (n, t, w)) in\n let f_i = first_sup w n in\n let f_d = String.index w '.' in\n if f_i >= 0 then for i = f_i + 1 to String.length w - 1 do w.[i] <- '0'; done;\n print_endline @@ (f f_d f_i w t)\n"}], "negative_code": [{"source_code": "let first_sup w n =\n let x = ref @@ -1 in\n for i = n - 1 downto (String.index w '.') + 1 do\n if w.[i] > '4' && w.[i] <= '9' then x := i\n done;\n !x\n\nlet incr_w w =\n let f_d = String.index w '.' in\n let x = ref true in\n for i = f_d - 1 downto 0 do\n if !x\n then (if w.[i] = '9'\n then w.[i] <- '0'\n else (w.[i] <- char_of_int (1 + int_of_char w.[i]);\n x := false)\n )\n done;\n (if !x then \"1\" else \"\") ^ (String.sub w 0 f_d)\n\nlet wo_trail w =\n let n = String.length w in\n let len = ref n and flg = ref true in\n while !flg && w.[!len - 1] = '0' do decr len done;\n String.sub w 0 !len\n\nlet rec f f_d i w t =\n if i = -1 || t = 0\n then wo_trail w\n else if i = f_d + 1\n then incr_w w\n else (w.[i] <- '0';\n w.[i-1] <- char_of_int (1 + int_of_char w.[i-1]);\n if w.[i-1] = '5' then f f_d (i-1) w (t-1) else w\n )\n\nlet _ =\n let (n,t,w) = Scanf.scanf \"%d %d %s\" (fun n t w -> (n, t, w)) in\n let f_i = first_sup w n in\n let f_d = String.index w '.' in\n if f_i >= 0 then for i = f_i + 1 to String.length w - 1 do w.[i] <- '0'; done;\n print_endline @@ (f f_d f_i w t)\n"}], "src_uid": "d563ce32596b54f48544a6085efe5cc5"} {"nl": {"description": "There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \\dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.", "input_spec": "The first line contains single integer $$$n$$$ $$$(1 \\le n \\le 1\\,000)$$$\u00a0\u2014 the number of keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 10^{9})$$$\u00a0\u2014 the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.", "output_spec": "Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.", "sample_inputs": ["4\n10 13 12 8", "5\n7 5 6 4 8"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\nend open MyInt64\n\nlet x =get_i64 0 let a = input_i64_array x\nlet () =\n\tArray.sort compare a;\n\tlet l = Array.to_list a in\n\tlet h = List.hd l in let t = List.tl l in\n\tList.fold_left (fun (u,c) v -> \n\t\tif v <> u + 1L then (v,c+v-u-1L) else (v,c)\n\t) (h,0L) t\n\t|> snd |> printf \"%Ld\\n\""}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\nend open MyInt64\n\nlet x =get_i64 0 let a = input_i64_array x\nlet () =\n\tArray.sort compare a;\n\tlet l = Array.to_list a in\n\tlet h = List.hd l in let t = List.tl l in\n\tList.fold_left (fun (u,c) v -> \n\t\tif v <> u + 1L then (v,c+1L) else (v,c)\n\t) (h,0L) t\n\t|> snd |> printf \"%Ld\\n\""}], "src_uid": "6469ed9f2486b498c9ffeb8270391e3a"} {"nl": {"description": "Boboniu likes bit operations. He wants to play a game with you.Boboniu gives you two sequences of non-negative integers $$$a_1,a_2,\\ldots,a_n$$$ and $$$b_1,b_2,\\ldots,b_m$$$.For each $$$i$$$ ($$$1\\le i\\le n$$$), you're asked to choose a $$$j$$$ ($$$1\\le j\\le m$$$) and let $$$c_i=a_i\\& b_j$$$, where $$$\\&$$$ denotes the bitwise AND operation. Note that you can pick the same $$$j$$$ for different $$$i$$$'s.Find the minimum possible $$$c_1 | c_2 | \\ldots | c_n$$$, where $$$|$$$ denotes the bitwise OR operation.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\\le n,m\\le 200$$$). The next line contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$0\\le a_i < 2^9$$$). The next line contains $$$m$$$ integers $$$b_1,b_2,\\ldots,b_m$$$ ($$$0\\le b_i < 2^9$$$).", "output_spec": "Print one integer: the minimum possible $$$c_1 | c_2 | \\ldots | c_n$$$.", "sample_inputs": ["4 2\n2 6 4 0\n2 4", "7 6\n1 9 1 9 8 1 0\n1 1 4 5 1 4", "8 5\n179 261 432 162 82 43 10 38\n379 357 202 184 197"], "sample_outputs": ["2", "0", "147"], "notes": "NoteFor the first example, we have $$$c_1=a_1\\& b_2=0$$$, $$$c_2=a_2\\& b_1=2$$$, $$$c_3=a_3\\& b_1=0$$$, $$$c_4 = a_4\\& b_1=0$$$.Thus $$$c_1 | c_2 | c_3 |c_4 =2$$$, and this is the minimal answer we can get."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n let a = Array.init n read_int in\n let b = Array.init m read_int in\n\n let rec solve mask remain = if remain = 0 then mask else (\n\n let rec find_bit i = if i=n then 0 else (\n (* finds the (remain-1) bit of the new mask *)\n if exists 0 (m-1) (fun j ->\n\tlet c = a.(i) land b.(j) in\n\t(c land (lnot mask) = 0) && (c land (1 lsl (remain-1)) = 0)\n\t(* this j works with this i *)\n ) then\n\tfind_bit (i+1) else 1\n ) in\n\n let mask' = if find_bit 0 = 1 then mask else mask land (lnot (1 lsl (remain-1))) in\n solve mask' (remain-1)\n ) in\n\n let answer = solve ((1 lsl 30)-1) 30 in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "3da5075048a127319ffa8913859d2aa7"} {"nl": {"description": "Let's call a positive integer $$$n$$$ ordinary if in the decimal notation all its digits are the same. For example, $$$1$$$, $$$2$$$ and $$$99$$$ are ordinary numbers, but $$$719$$$ and $$$2021$$$ are not ordinary numbers.For a given number $$$n$$$, find the number of ordinary numbers among the numbers from $$$1$$$ to $$$n$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$).", "output_spec": "For each test case output the number of ordinary numbers among numbers from $$$1$$$ to $$$n$$$.", "sample_inputs": ["6\n1\n2\n3\n4\n5\n100"], "sample_outputs": ["1\n2\n3\n4\n5\n18"], "notes": null}, "positive_code": [{"source_code": "module Stdlib = Pervasives\r\n\r\nlet std_inp = Stdlib.stdin;;\r\nlet std_outp = Stdlib.stdout;;\r\n\r\n(* let std_inp = Stdlib.open_in \"input.txt\";; *)\r\n\r\nlet identity x = x;;\r\nlet tup2 x1 x2 = (x1, x2);;\r\n\r\nlet min a b = if a < b then a else b;;\r\n\r\nlet rec repeat n (f, state, inp, outp) =\r\n if n = 0 then state\r\n else\r\n let state = f state inp outp in\r\n repeat (n - 1) (f, state, inp, outp);;\r\n\r\nlet space_regexp = Str.regexp \" \";;\r\n\r\ntype triplet = Never | Maybe | Guaranteed;;\r\n\r\nexception Unreachable_by_statement of unit\r\nlet solution _state inp outp =\r\n let rec digits x acc =\r\n if x = 0 then acc\r\n else digits (x / 10) ((x mod 10)::acc)\r\n in\r\n let folder (prev_digit, len, regularity_state) element =\r\n let last_digit = element mod 10 in\r\n if regularity_state != Maybe then (last_digit, len + 1, regularity_state)\r\n else\r\n if last_digit > prev_digit then (last_digit, len + 1, Guaranteed)\r\n else if last_digit = prev_digit then (last_digit, len + 1, Maybe)\r\n else (last_digit, len + 1, Never)\r\n in\r\n let x = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let (first_digit, digits_tail) =\r\n match (digits x []) with\r\n | [] -> raise @@ Unreachable_by_statement ()\r\n | (head::tail)-> (head, tail)\r\n in\r\n (* let () = List.map string_of_int digs |> String.concat \" \" |> Printf.fprintf outp \"%s\\n\" in *)\r\n let (_, len, regularity_state) = List.fold_left folder (first_digit, 1, Maybe) digits_tail in\r\n let result =\r\n let result_base = (len - 1) * 9 + first_digit - 1 in\r\n match regularity_state with\r\n | Guaranteed | Maybe -> result_base + 1\r\n | Never -> result_base\r\n in\r\n let () = Printf.fprintf outp \"%d\\n\" result in\r\n ();;\r\n\r\nlet () =\r\n let inp = std_inp and outp = std_outp in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let _state = repeat tests_count (solution, (), inp, outp) in\r\n ();;\r\n"}], "negative_code": [{"source_code": "module Stdlib = Pervasives\r\n\r\nlet std_inp = Stdlib.stdin;;\r\nlet std_outp = Stdlib.stdout;;\r\n\r\n(* let std_inp = Stdlib.open_in \"input.txt\";; *)\r\n\r\nlet identity x = x;;\r\nlet tup2 x1 x2 = (x1, x2);;\r\n\r\nlet min a b = if a < b then a else b;;\r\n\r\nlet rec repeat n (f, state, inp, outp) =\r\n if n = 0 then state\r\n else\r\n let state = f state inp outp in\r\n repeat (n - 1) (f, state, inp, outp);;\r\n\r\nlet space_regexp = Str.regexp \" \";;\r\n\r\nlet solution _state inp outp =\r\n let rec reduce x (last_dig, len, min_digit) =\r\n if x = 0 then (last_dig, len, min_digit)\r\n else\r\n let new_last_dig = x mod 10 in\r\n reduce (x / 10) (new_last_dig, len + 1, min min_digit new_last_dig)\r\n in\r\n let x = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let (last_dig, len, min_dig) = reduce x (x mod 10, 0, 10) in\r\n let result = (len - 1) * 9 + last_dig - (if min_dig = last_dig then 0 else 1) in\r\n let () = Printf.fprintf outp \"%d\\n\" result in\r\n ();;\r\n\r\nlet () =\r\n let inp = std_inp and outp = std_outp in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let _state = repeat tests_count (solution, (), inp, outp) in\r\n ();;\r\n"}, {"source_code": "module Stdlib = Pervasives\r\n\r\nlet std_inp = Stdlib.stdin;;\r\nlet std_outp = Stdlib.stdout;;\r\n\r\n(* let std_inp = Stdlib.open_in \"input.txt\";; *)\r\n\r\nlet identity x = x;;\r\nlet tup2 x1 x2 = (x1, x2);;\r\n\r\nlet min a b = if a < b then a else b;;\r\n\r\nlet rec repeat n (f, state, inp, outp) =\r\n if n = 0 then state\r\n else\r\n let state = f state inp outp in\r\n repeat (n - 1) (f, state, inp, outp);;\r\n\r\nlet space_regexp = Str.regexp \" \";;\r\n\r\nlet solution _state inp outp =\r\n let rec reduce x (last_dig, len, regular) =\r\n if x = 0 then (last_dig, len, regular)\r\n else\r\n let new_last_dig = x mod 10 in\r\n reduce (x / 10) (new_last_dig, len + 1, regular && (new_last_dig = last_dig))\r\n in\r\n let x = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let (last_dig, len, regular) = reduce x (x mod 10, 0, true) in\r\n let result = (len - 1) * 9 + last_dig - (if regular then 0 else 1) in\r\n let () = Printf.fprintf outp \"%d\\n\" result in\r\n ();;\r\n\r\nlet () =\r\n let inp = std_inp and outp = std_outp in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let _state = repeat tests_count (solution, (), inp, outp) in\r\n ();;\r\n"}, {"source_code": "module Stdlib = Pervasives\r\n\r\nlet std_inp = Stdlib.stdin;;\r\nlet std_outp = Stdlib.stdout;;\r\n\r\n(* let std_inp = Stdlib.open_in \"input.txt\";; *)\r\n\r\nlet identity x = x;;\r\nlet tup2 x1 x2 = (x1, x2);;\r\n\r\nlet min a b = if a < b then a else b;;\r\n\r\nlet rec repeat n (f, state, inp, outp) =\r\n if n = 0 then state\r\n else\r\n let state = f state inp outp in\r\n repeat (n - 1) (f, state, inp, outp);;\r\n\r\nlet space_regexp = Str.regexp \" \";;\r\n\r\nlet solution _state inp outp =\r\n let rec reduce x (min_dig, len) =\r\n if x = 0 then (min_dig, len)\r\n else\r\n let last_dig = x mod 10 in\r\n reduce (x / 10) (min min_dig last_dig, len + 1)\r\n in\r\n let x = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let (min_dig, len) = reduce x (10, 0) in\r\n let result = (len - 1) * 9 + min_dig in\r\n let () = Printf.fprintf outp \"%d\\n\" result in\r\n ();;\r\n\r\nlet () =\r\n let inp = std_inp and outp = std_outp in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let _state = repeat tests_count (solution, (), inp, outp) in\r\n ();;\r\n"}], "src_uid": "ac7d117d58046872e9d665c9f99e5bff"} {"nl": {"description": "\u00abNext please\u00bb, \u2014 the princess called and cast an estimating glance at the next groom.The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured \u00abOh...\u00bb. Whenever the groom is richer than all previous ones added together, she exclaims \u00abWow!\u00bb (no \u00abOh...\u00bb in this case). At the sight of the first groom the princess stays calm and says nothing.The fortune of each groom is described with an integer between 1 and 50000. You know that during the day the princess saw n grooms, said \u00abOh...\u00bb exactly a times and exclaimed \u00abWow!\u00bb exactly b times. Your task is to output a sequence of n integers t1,\u2009t2,\u2009...,\u2009tn, where ti describes the fortune of i-th groom. If several sequences are possible, output any of them. If no sequence exists that would satisfy all the requirements, output a single number -1.", "input_spec": "The only line of input data contains three integer numbers n,\u2009a and b (1\u2009\u2264\u2009n\u2009\u2264\u2009100,\u20090\u2009\u2264\u2009a,\u2009b\u2009\u2264\u200915,\u2009n\u2009>\u2009a\u2009+\u2009b), separated with single spaces.", "output_spec": "Output any sequence of integers t1,\u2009t2,\u2009...,\u2009tn, where ti (1\u2009\u2264\u2009ti\u2009\u2264\u200950000) is the fortune of i-th groom, that satisfies the given constraints. If no sequence exists that would satisfy all the requirements, output a single number -1.", "sample_inputs": ["10 2 3", "5 0 0"], "sample_outputs": ["5 1 3 6 16 35 46 4 200 99", "10 10 6 6 5"], "notes": "NoteLet's have a closer look at the answer for the first sample test. The princess said \u00abOh...\u00bb (highlighted in bold): 5 1 3 6 16 35 46 4 200 99. The princess exclaimed \u00abWow!\u00bb (highlighted in bold): 5 1 3 6 16 35 46 4 200 99. "}, "positive_code": [{"source_code": "let rec print_list lst =\n match lst with\n | [] -> ()\n | h :: [] -> print_int h\n | h :: t -> Printf.printf \"%s \" (string_of_int h); print_list t\nin\nlet make_ah_ogo a b =\n (* Sum of list *)\n let rec lsum lst acc =\n match lst with\n\t[] -> acc\n | h :: tail -> lsum tail (acc + h)\n in\n let rec ogo lst b =\n let cur_sum = lsum lst 0 in\n match b with\n\t0 -> lst\n | _ -> (*Printf.printf \"Cur ogo sum:%d\\n\" cur_sum;*) ogo (cur_sum + 1 :: lst) (b - 1)\n in\n let rec ah lst a =\n match a with\n\t0 -> lst\n | _ -> match lst with\n\t [] -> ah [1] (a-1)\n\t | x :: [] -> ah (x :: x :: []) a\n\t | h :: t -> (*Printf.printf \"Incr ah %d\\n\" h;*) ah (h + 1 :: h :: t) (a - 1)\n in\n let logo = ogo [1] b in (* Ogo! list *)\n ah logo a (* Ogo! + Ah! list *)\nin\nlet create inp =\n let parse_input x =\n let rx = Str.regexp \"\\\\([0-9]+\\\\) \\\\([0-9]+\\\\) \\\\([0-9]+\\\\)\" in\n if Str.string_match rx x 0 then\n let i ii = int_of_string (Str.matched_group ii x) in\n Some (i 1, i 2, i 3)\n else\n None\n in\n let n, a, b = match parse_input inp with\n None -> raise Not_found\n | Some (x1, x2, x3) -> x1, x2, x3\n in\n (*Printf.printf \"n=%d a=%d b=%d\\n\" n a b;*)\n let result = make_ah_ogo a b in\n let create_remain todo =\n let rec rem list todo =\n match todo with\n\t x when x <= 0 -> list\n\t| _ -> rem (1 :: list) (todo - 1)\n in\n rem [] todo\n in\n let len_remain = n - (List.length result) in\n (*Printf.printf \"Remain to %d length: %d; done %d\\n\" n len_remain (List.length result);*)\n let result = (List.rev result) @ (create_remain len_remain) in\n let len = List.length result in\n if len <= n then\n result\n else begin\n [-1]\n end\nin\nlet init_data = read_line () in\nlet init_list = create init_data in\nlet result_list = init_list in\nprint_list result_list\n"}, {"source_code": "(* codeforces 105. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let n = read_int() in\n let a = read_int() in\n let b = read_int() in\n\n let m = 50000 in\n \n(* i = seen already. current = value of last one seen. sum=sum of all previous*)\n let rec loop i sum current a b print = \n if print then Printf.printf \"%d \" current;\n if current > m then false\n else if i = n then a+b=0\n else (\n if b>0 then loop (i+1) (sum+(2*current)) (2*current) a (b-1) print\n else if a>0 then (\n\tif (current+1 > sum) then loop (i+1) (sum+current) current a b print else loop (i+1) (sum+current+1) (current+1) (a-1) b print\n ) else loop (i+1) (sum+current) current a b print\n )\n in\n if not (loop 1 1 1 a b false) then Printf.printf \"-1\"\n else ignore (loop 1 1 1 a b true);\n print_newline()\n"}], "negative_code": [{"source_code": "let rec print_list lst =\n match lst with\n | [] -> ()\n | h :: [] -> print_int h\n | h :: t -> Printf.printf \"%s \" (string_of_int h); print_list t\nin\nlet make_ah_ogo a b =\n (* Sum of list *)\n let rec lsum lst acc =\n match lst with\n\t[] -> acc\n | h :: tail -> lsum tail (acc + h)\n in\n let rec ogo lst b =\n let cur_sum = lsum lst 0 in\n match b with\n\t0 -> lst\n | _ -> (*Printf.printf \"Cur ogo sum:%d\\n\" cur_sum;*) ogo (cur_sum + 1 :: lst) (b - 1)\n in\n let rec ah lst a =\n match a with\n\t0 -> lst\n | _ -> match lst with\n\t [] -> ah [1] (a-1)\n\t | h :: t -> (*Printf.printf \"Incr ah %d\\n\" h;*) ah (h + 1 :: h :: t) (a - 1)\n in\n let logo = ogo [1] b in (* Ogo! list *)\n ah logo a (* Ogo! + Ah! list *)\nin\nlet create inp =\n let parse_input x =\n let rx = Str.regexp \"\\\\([0-9]+\\\\) \\\\([0-9]+\\\\) \\\\([0-9]+\\\\)\" in\n if Str.string_match rx x 0 then\n let i ii = int_of_string (Str.matched_group ii x) in\n Some (i 1, i 2, i 3)\n else\n None\n in\n let n, a, b = match parse_input inp with\n None -> raise Not_found\n | Some (x1, x2, x3) -> x1, x2, x3\n in\n (*Printf.printf \"n=%d a=%d b=%d\\n\" n a b;*)\n let result = make_ah_ogo a b in\n let create_remain todo =\n let rec rem list todo =\n match todo with\n\t x when x <= 0 -> list\n\t| _ -> rem (1 :: list) (todo - 1)\n in\n rem [] todo\n in\n let len_remain = n - (List.length result) in\n (*Printf.printf \"Remain to %d length: %d; done %d\\n\" n len_remain (List.length result);*)\n let result = (List.rev result) @ (create_remain len_remain) in\n let len = List.length result in\n if len <= n then\n result\n else begin\n [-1]\n end\nin\nlet init_data = read_line () in\nlet init_list = create init_data in\nlet result_list = init_list in\nprint_list result_list\n"}, {"source_code": "let rec print_list lst =\n match lst with\n | [] -> ()\n | h :: [] -> print_int h\n | h :: t -> Printf.printf \"%s \" (string_of_int h); print_list t\nin\nlet make_ah_ogo a b =\n (* Sum of list *)\n let rec lsum lst acc =\n match lst with\n\t[] -> acc\n | h :: tail -> lsum tail (acc + h)\n in\n let rec ogo lst b =\n let cur_sum = lsum lst 0 in\n match b with\n\t0 -> lst\n | _ -> (*Printf.printf \"Cur ogo sum:%d\\n\" cur_sum;*) ogo (cur_sum + 1 :: lst) (b - 1)\n in\n let rec ah lst a =\n match a with\n\t0 -> lst\n | _ -> match lst with\n\t [] -> ah [2] (a - 1)\n\t | 1 :: [] -> ah (1 :: 1 :: []) (a - 1)\n\t | h :: t -> (*Printf.printf \"Incr ah %d\\n\" h;*) ah (h + 1 :: h :: t) (a - 1)\n in\n let logo = ogo [] b in (* Ogo! list *)\n ah logo a (* Ogo! + Ah! list *)\nin\nlet create inp =\n let parse_input x =\n let rx = Str.regexp \"\\\\([0-9]+\\\\) \\\\([0-9]+\\\\) \\\\([0-9]+\\\\)\" in\n if Str.string_match rx x 0 then\n let i ii = int_of_string (Str.matched_group ii x) in\n Some (i 1, i 2, i 3)\n else\n None\n in\n let n, a, b = match parse_input inp with\n None -> raise Not_found\n | Some (x1, x2, x3) -> x1, x2, x3\n in\n (*Printf.printf \"n=%d a=%d b=%d\\n\" n a b;*)\n let result = make_ah_ogo a b in\n let create_remain todo =\n let rec rem list todo =\n match todo with\n\t x when x <= 0 -> list\n\t| _ -> rem (1 :: list) (todo - 1)\n in\n rem [] todo\n in\n let len_remain = n - (List.length result) in\n (*Printf.printf \"Remain to %d length: %d; done %d\\n\" n len_remain (List.length result);*)\n let result = (List.rev result) @ (create_remain len_remain) in\n let len = List.length result in\n if len <= n then\n result\n else begin\n [-1]\n end\nin\nlet init_data = read_line () in\nlet init_list = create init_data in\nlet result_list = init_list in\nprint_list result_list\n"}, {"source_code": "let rec print_list lst =\n match lst with\n | [] -> ()\n | h :: [] -> print_int h\n | h :: t -> Printf.printf \"%s \" (string_of_int h); print_list t\nin\nlet make_ah_ogo a b =\n (* Sum of list *)\n let rec lsum lst acc =\n match lst with\n\t[] -> acc\n | h :: tail -> lsum tail (acc + h)\n in\n let rec ogo lst b =\n let cur_sum = lsum lst 0 in\n match b with\n\t0 -> lst\n | _ -> (*Printf.printf \"Cur ogo sum:%d\\n\" cur_sum;*)\n\tif lst = [] then\n\t ogo [1] b\n\telse\n\t ogo (cur_sum + 1 :: lst) (b - 1)\n in\n let rec ah lst a =\n match a with\n\t0 -> lst\n | _ -> match lst with\n\t [] -> ah [2] (a - 1)\n\t | 1 :: [] -> ah (1 :: 1 :: []) (a - 1)\n\t | h :: t -> (*Printf.printf \"Incr ah %d\\n\" h;*) ah (h + 1 :: h :: t) (a - 1)\n in\n let logo = ogo [] b in (* Ogo! list *)\n ah logo a (* Ogo! + Ah! list *)\nin\nlet create inp =\n let parse_input x =\n let rx = Str.regexp \"\\\\([0-9]+\\\\) \\\\([0-9]+\\\\) \\\\([0-9]+\\\\)\" in\n if Str.string_match rx x 0 then\n let i ii = int_of_string (Str.matched_group ii x) in\n Some (i 1, i 2, i 3)\n else\n None\n in\n let n, a, b = match parse_input inp with\n None -> raise Not_found\n | Some (x1, x2, x3) -> x1, x2, x3\n in\n (*Printf.printf \"n=%d a=%d b=%d\\n\" n a b;*)\n let result = make_ah_ogo a b in\n let create_remain todo =\n let rec rem list todo =\n match todo with\n\t x when x <= 0 -> list\n\t| _ -> rem (1 :: list) (todo - 1)\n in\n rem [] todo\n in\n let len_remain = n - (List.length result) in\n (*Printf.printf \"Remain to %d length: %d; done %d\\n\" n len_remain (List.length result);*)\n let result = (List.rev result) @ (create_remain len_remain) in\n let len = List.length result in\n if len <= n then\n result\n else begin\n [-1]\n end\nin\nlet init_data = read_line () in\nlet init_list = create init_data in\nlet result_list = init_list in\nprint_list result_list\n"}, {"source_code": "let rec print_list lst =\n match lst with\n | [] -> ()\n | h :: [] -> print_int h\n | h :: t -> Printf.printf \"%s \" (string_of_int h); print_list t\nin\nlet make_ah_ogo a b =\n (* Sum of list *)\n let rec lsum lst acc =\n match lst with\n\t[] -> acc\n | h :: tail -> lsum tail (acc + h)\n in\n let rec ogo lst b =\n let cur_sum = lsum lst 0 in\n match b with\n\t0 -> lst\n | _ -> (*Printf.printf \"Cur ogo sum:%d\\n\" cur_sum;*)\n\tif lst = [] then\n\t ogo [1] b\n\telse\n\t ogo (cur_sum + 1 :: lst) (b - 1)\n in\n let rec ah lst a =\n match a with\n\t0 -> lst\n | _ -> match lst with\n\t [] -> ah [2] a\n\t | 1 :: [] -> ah (1 :: 1 :: []) (a - 1)\n\t | h :: t -> (*Printf.printf \"Incr ah %d\\n\" h;*) ah (h + 1 :: h :: t) (a - 1)\n in\n let logo = ogo [] b in (* Ogo! list *)\n ah logo a (* Ogo! + Ah! list *)\nin\nlet create inp =\n let parse_input x =\n let rx = Str.regexp \"\\\\([0-9]+\\\\) \\\\([0-9]+\\\\) \\\\([0-9]+\\\\)\" in\n if Str.string_match rx x 0 then\n let i ii = int_of_string (Str.matched_group ii x) in\n Some (i 1, i 2, i 3)\n else\n None\n in\n let n, a, b = match parse_input inp with\n None -> raise Not_found\n | Some (x1, x2, x3) -> x1, x2, x3\n in\n (*Printf.printf \"n=%d a=%d b=%d\\n\" n a b;*)\n let result = make_ah_ogo a b in\n let create_remain todo =\n let rec rem list todo =\n match todo with\n\t x when x <= 0 -> list\n\t| _ -> rem (1 :: list) (todo - 1)\n in\n rem [] todo\n in\n let len_remain = n - (List.length result) in\n (*Printf.printf \"Remain to %d length: %d; done %d\\n\" n len_remain (List.length result);*)\n let result = (List.rev result) @ (create_remain len_remain) in\n let len = List.length result in\n if len <= n then\n result\n else begin\n [-1]\n end\nin\nlet init_data = read_line () in\nlet init_list = create init_data in\nlet result_list = init_list in\nprint_list result_list\n"}, {"source_code": "let rec print_list lst =\n match lst with\n | [] -> ()\n | h :: [] -> print_int h\n | h :: t -> Printf.printf \"%s \" (string_of_int h); print_list t\nin\nlet make_ah_ogo a b =\n (* Sum of list *)\n let rec lsum lst acc =\n match lst with\n\t[] -> acc\n | h :: tail -> lsum tail (acc + h)\n in\n let rec ogo lst b =\n let cur_sum = lsum lst 0 in\n match b with\n\t0 -> lst\n | _ -> (*Printf.printf \"Cur ogo sum:%d\\n\" cur_sum;*) ogo (cur_sum + 1 :: lst) (b - 1)\n in\n let rec ah lst a =\n match a with\n\t0 -> lst\n | _ -> match lst with\n\t [] -> ah [1] (a - 1)\n\t | 1 :: [] -> ah (1 :: 1 :: []) (a - 1)\n\t | h :: t -> (*Printf.printf \"Incr ah %d\\n\" h;*) ah (h + 1 :: h :: t) (a - 1)\n in\n let logo = ogo [1] b in (* Ogo! list *)\n ah logo a (* Ogo! + Ah! list *)\nin\nlet create inp =\n let parse_input x =\n let rx = Str.regexp \"\\\\([0-9]+\\\\) \\\\([0-9]+\\\\) \\\\([0-9]+\\\\)\" in\n if Str.string_match rx x 0 then\n let i ii = int_of_string (Str.matched_group ii x) in\n Some (i 1, i 2, i 3)\n else\n None\n in\n let n, a, b = match parse_input inp with\n None -> raise Not_found\n | Some (x1, x2, x3) -> x1, x2, x3\n in\n (*Printf.printf \"n=%d a=%d b=%d\\n\" n a b;*)\n let result = make_ah_ogo a b in\n let create_remain todo =\n let rec rem list todo =\n match todo with\n\t x when x <= 0 -> list\n\t| _ -> rem (1 :: list) (todo - 1)\n in\n rem [] todo\n in\n let len_remain = n - (List.length result) in\n (*Printf.printf \"Remain to %d length: %d; done %d\\n\" n len_remain (List.length result);*)\n let result = (List.rev result) @ (create_remain len_remain) in\n let len = List.length result in\n if len <= n then\n result\n else begin\n [-1]\n end\nin\nlet init_data = read_line () in\nlet init_list = create init_data in\nlet result_list = init_list in\nprint_list result_list\n"}, {"source_code": "let rec print_list lst =\n match lst with\n | [] -> ()\n | h :: [] -> print_int h\n | h :: t -> Printf.printf \"%s \" (string_of_int h); print_list t\nin\nlet make_ah_ogo a b =\n (* Sum of list *)\n let rec lsum lst acc =\n match lst with\n\t[] -> acc\n | h :: tail -> lsum tail (acc + h)\n in\n let rec ogo lst b =\n let cur_sum = lsum lst 0 in\n if lst = [] then\n ogo [1] b\n else\n match b with\n\t 0 -> lst\n\t| _ -> (*Printf.printf \"Cur ogo sum:%d\\n\" cur_sum;*) ogo (cur_sum + 1 :: lst) (b - 1)\n in\n let rec ah lst a =\n match a with\n\t0 -> lst\n | _ -> match lst with\n\t [] -> ah [2] (a - 1)\n\t | 1 :: [] -> ah (1 :: 1 :: []) (a - 1)\n\t | h :: t -> (*Printf.printf \"Incr ah %d\\n\" h;*) ah (h + 1 :: h :: t) (a - 1)\n in\n let logo = ogo [] b in (* Ogo! list *)\n ah logo a (* Ogo! + Ah! list *)\nin\nlet create inp =\n let parse_input x =\n let rx = Str.regexp \"\\\\([0-9]+\\\\) \\\\([0-9]+\\\\) \\\\([0-9]+\\\\)\" in\n if Str.string_match rx x 0 then\n let i ii = int_of_string (Str.matched_group ii x) in\n Some (i 1, i 2, i 3)\n else\n None\n in\n let n, a, b = match parse_input inp with\n None -> raise Not_found\n | Some (x1, x2, x3) -> x1, x2, x3\n in\n (*Printf.printf \"n=%d a=%d b=%d\\n\" n a b;*)\n let result = make_ah_ogo a b in\n let create_remain todo =\n let rec rem list todo =\n match todo with\n\t x when x <= 0 -> list\n\t| _ -> rem (1 :: list) (todo - 1)\n in\n rem [] todo\n in\n let len_remain = n - (List.length result) in\n (*Printf.printf \"Remain to %d length: %d; done %d\\n\" n len_remain (List.length result);*)\n let result = (List.rev result) @ (create_remain len_remain) in\n let len = List.length result in\n if len <= n then\n result\n else begin\n [-1]\n end\nin\nlet init_data = read_line () in\nlet init_list = create init_data in\nlet result_list = init_list in\nprint_list result_list\n"}, {"source_code": "(* codeforces 105. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let n = read_int() in\n let a = read_int() in\n let b = read_int() in\n\n let m = 50000 in\n \n(* i = seen already. current = value of last one seen *)\n let rec loop i current a b print = \n if print then Printf.printf \"%d \" current;\n if current > m then false\n else if i = n then true \n else (\n if b>0 then loop (i+1) (2*current) a (b-1) print\n else if a>0 then loop (i+1) (current+1) (a-1) b print\n else loop (i+1) current a b print\n )\n in\n if loop 1 1 a b false \n then ignore (loop 1 1 a b true)\n else Printf.printf \"-1\";\n print_newline()\n"}, {"source_code": "(* codeforces 105. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let n = read_int() in\n let a = read_int() in\n let b = read_int() in\n\n let m = 50000 in\n \n(* i = seen already. current = value of last one seen *)\n let rec loop i current a b print = \n if print then Printf.printf \"%d \" current;\n if current > m then false\n else if i = n then true \n else (\n if b>0 then loop (i+1) (2*current) a (b-1) print\n else if a>0 then loop (i+1) (current+1) (a-1) b print\n else loop (i+1) current a b print\n )\n in\n if a=n-1 || (not (loop 1 1 a b false)) then Printf.printf \"-1\"\n else ignore (loop 1 1 a b true);\n print_newline()\n"}, {"source_code": "(* codeforces 105. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let n = read_int() in\n let a = read_int() in\n let b = read_int() in\n\n let m = 50000 in\n \n(* i = seen already. current = value of last one seen *)\n let rec loop i current a b print = \n if print then Printf.printf \"%d \" current;\n if current > m then false\n else if i = n then true \n else (\n if a>0 then loop (i+1) (2*current) (a-1) b print\n else if b>0 then loop (i+1) (current+1) a (b-1) print\n else loop (i+1) current a b print\n )\n in\n if loop 1 1 a b false \n then ignore (loop 1 1 a b true)\n else Printf.printf \"-1\";\n print_newline()\n"}, {"source_code": "(* codeforces 105. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let n = read_int() in\n let a = read_int() in\n let b = read_int() in\n\n let m = 50000 in\n \n(* i = seen already. current = value of last one seen *)\n let rec loop i current a b print = \n if print then Printf.printf \"%d \" current;\n if current > m then false\n else if i = n then true \n else (\n if b>0 then loop (i+1) (2*current) a (b-1) print\n else if a>0 then loop (i+1) (current+1) (a-1) b print\n else loop (i+1) current a b print\n )\n in\n if (a=n-1 && n>1) || (not (loop 1 1 a b false)) then Printf.printf \"-1\"\n else ignore (loop 1 1 a b true);\n print_newline()\n"}], "src_uid": "573995cbae2a7b28ed92d71c48cd9039"} {"nl": {"description": "Haha, try to solve this, SelectorUnlimited!\u2014 antontrygubO_oYour friends Alice and Bob practice fortune telling.Fortune telling is performed as follows. There is a well-known array $$$a$$$ of $$$n$$$ non-negative integers indexed from $$$1$$$ to $$$n$$$. The tellee starts with some non-negative number $$$d$$$ and performs one of the two operations for each $$$i = 1, 2, \\ldots, n$$$, in the increasing order of $$$i$$$. The possible operations are: replace their current number $$$d$$$ with $$$d + a_i$$$ replace their current number $$$d$$$ with $$$d \\oplus a_i$$$ (hereinafter $$$\\oplus$$$ denotes the bitwise XOR operation)Notice that the chosen operation may be different for different $$$i$$$ and for different tellees.One time, Alice decided to start with $$$d = x$$$ and Bob started with $$$d = x + 3$$$. Each of them performed fortune telling and got a particular number in the end. Notice that the friends chose operations independently of each other, that is, they could apply different operations for the same $$$i$$$.You learnt that either Alice or Bob ended up with number $$$y$$$ in the end, but you don't know whose of the two it was. Given the numbers Alice and Bob started with and $$$y$$$, find out who (Alice or Bob) could get the number $$$y$$$ after performing the operations. It is guaranteed that on the jury tests, exactly one of your friends could have actually gotten that number.HacksYou cannot make hacks in this problem.", "input_spec": "On the first line of the input, you are given one number $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The following $$$2 \\cdot t$$$ lines contain test cases. The first line of each test case contains three numbers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \\le n \\le 10^5$$$, $$$0 \\le x \\le 10^9$$$, $$$0 \\le y \\le 10^{15}$$$)\u00a0\u2014 the length of array $$$a$$$, Alice's initial number (Bob's initial number is therefore $$$x+3$$$), and the number that one of the two friends got in the end. The second line of each test case contains $$$n$$$ numbers\u00a0\u2014 the array $$$a$$$ ($$$0 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print the name of the friend who could get the number $$$y$$$: \"Alice\" or \"Bob\".", "sample_inputs": ["4\n\n1 7 9\n\n2\n\n2 0 2\n\n1 3\n\n4 0 1\n\n1 2 3 4\n\n2 1000000000 3000000000\n\n1000000000 1000000000"], "sample_outputs": ["Alice\nAlice\nBob\nAlice"], "notes": "NoteIn the first test case, Alice could get $$$9$$$ using the following operations: $$$7 + 2 = 9$$$.In the second test case, Alice could get $$$2$$$ using this operations: $$$(0 + 1) \\oplus 3 = 2$$$.In the third test case, Bob started with $$$x+3 = 0+3=3$$$ and could get $$$1$$$ this way: $$$(((3 + 1) + 2) \\oplus 3) \\oplus 4 = 1$$$."}, "positive_code": [{"source_code": "Scanf.scanf \"%d\" (fun t ->\n let and64 = Int64.logand in\n for i = 1 to t do\n Scanf.scanf \" %d %Ld %Ld\" (fun n x y ->\n let x = Int64.to_int (and64 x 1L) in\n let y = Int64.to_int (and64 y 1L) in\n let a = Array.init n (fun _ -> Scanf.scanf \" %Ld\" (fun a -> Int64.to_int (and64 a 1L))) in\n let rec loop i acc =\n if i = n then acc else loop (i + 1) (acc lxor a.(i))\n in\n print_endline @@ if loop 0 x = y then \"Alice\" else \"Bob\"\n )\n done\n)\n"}], "negative_code": [], "src_uid": "d17752513405fc68d838e9b3792c7bef"} {"nl": {"description": "You are given an array $$$a$$$ of length $$$n$$$. We define the equality of the array as the number of indices $$$1 \\le i \\le n - 1$$$ such that $$$a_i = a_{i + 1}$$$. We are allowed to do the following operation: Select two integers $$$i$$$ and $$$x$$$ such that $$$1 \\le i \\le n - 1$$$ and $$$1 \\le x \\le 10^9$$$. Then, set $$$a_i$$$ and $$$a_{i + 1}$$$ to be equal to $$$x$$$. Find the minimum number of operations needed such that the equality of the array is less than or equal to $$$1$$$.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10 ^ 5$$$) \u2014 the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10 ^ 5$$$", "output_spec": "For each test case, print the minimum number of operations needed.", "sample_inputs": ["4\n\n5\n\n1 1 1 1 1\n\n5\n\n2 1 1 1 2\n\n6\n\n1 1 2 3 3 4\n\n6\n\n1 2 1 4 5 4"], "sample_outputs": ["2\n1\n2\n0"], "notes": "NoteIn the first test case, we can select $$$i=2$$$ and $$$x=2$$$ to form $$$[1, 2, 2, 1, 1]$$$. Then, we can select $$$i=3$$$ and $$$x=3$$$ to form $$$[1, 2, 3, 3, 1]$$$.In the second test case, we can select $$$i=3$$$ and $$$x=100$$$ to form $$$[2, 1, 100, 100, 2]$$$."}, "positive_code": [{"source_code": "let parse len str = let rep = Array.make len (-1) in\r\n let temp = ref \"\" in\r\n let j = ref 0 in\r\n for i = 0 to String.length str -1 do\r\n if str.[i] = ' ' then \r\n (rep.(!j) <- (int_of_string !temp) ; incr j ; temp:=\"\" ) \r\n else \r\n (temp:= !temp ^ (String.make 1 str.[i]))\r\n done; rep.(!j) <- (int_of_string !temp) ;rep\r\n;; \r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor j = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str = (input_line stdin) in\r\n let tab = parse len str in\r\n let prem = ref (-1) in\r\n let dern = ref (-1) in\r\n for i = 0 to len -2 do\r\n if tab.(i) = tab.(i+1) then begin\r\n dern := i ;\r\n if !prem = -1 then prem := i ;\r\n end\r\n done;\r\n let dist = ref ( !dern - !prem) in\r\n if !dist >= 2 then decr dist ;\r\n print_endline (string_of_int !dist)\r\ndone;;"}], "negative_code": [], "src_uid": "a91be662101762bcb2c58b8db9ff61e0"} {"nl": {"description": "You are given a sequence $$$s$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$.You have to divide it into at least two segments (segment \u2014 is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is $$$t_1, t_2, \\dots, t_k$$$, where $$$k$$$ is the number of element in a division, then for each $$$i$$$ from $$$1$$$ to $$$k-1$$$ the condition $$$t_{i} < t_{i + 1}$$$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if $$$s=654$$$ then you can divide it into parts $$$[6, 54]$$$ and it will be suitable division. But if you will divide it into parts $$$[65, 4]$$$ then it will be bad division because $$$65 > 4$$$. If $$$s=123$$$ then you can divide it into parts $$$[1, 23]$$$, $$$[1, 2, 3]$$$ but not into parts $$$[12, 3]$$$.Your task is to find any suitable division for each of the $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 300$$$) \u2014 the number of queries. The first line of the $$$i$$$-th query contains one integer number $$$n_i$$$ ($$$2 \\le n_i \\le 300$$$) \u2014 the number of digits in the $$$i$$$-th query. The second line of the $$$i$$$-th query contains one string $$$s_i$$$ of length $$$n_i$$$ consisting only of digits from $$$1$$$ to $$$9$$$.", "output_spec": "If the sequence of digits in the $$$i$$$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line \"NO\" for this query. Otherwise in the first line of the answer to this query print \"YES\", on the second line print $$$k_i$$$ \u2014 the number of parts in your division of the $$$i$$$-th query sequence and in the third line print $$$k_i$$$ strings $$$t_{i, 1}, t_{i, 2}, \\dots, t_{i, k_i}$$$ \u2014 your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string $$$s_i$$$. See examples for better understanding.", "sample_inputs": ["4\n6\n654321\n4\n1337\n2\n33\n4\n2122"], "sample_outputs": ["YES\n3\n6 54 321\nYES\n3\n1 3 37\nNO\nYES\n2\n21 22"], "notes": null}, "positive_code": [{"source_code": "Scanf.(Array.(scanf \" %d\" @@ fun q ->\n init q (fun _ -> scanf \" %d %s\" @@ fun _ s ->\n Printf.(\n if String.length s = 2 && s.[0] >= s.[1] then printf \"NO\\n\"\n else printf \"YES\\n2\\n%c %s\\n\" s.[0] @@ String.sub s 1 (String.length s - 1)))))"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)\n let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let q = gi 0 in\n rep 1L q (fun _ ->\n let n = gi 0 in\n let s = scanf \" %s\" @@ id in\n if String.length s = 2 && s.[0] >= s.[1] then (\n printf \"NO\\n\"\n ) else (\n printf \"YES\\n2\\n%c %s\\n\" s.[0] @@ String.sub s 1 (String.length s-$1)\n )\n )\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)\n let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let q = gi 0 in\n rep 1L q (fun _ ->\n let n = gi 0 in\n let s = scanf \" %s\" @@ id in\n let f = ref true in\n String.iter (fun c -> if c <> s.[0] then f := false) s;\n if !f && String.length s = 2 then (\n printf \"NO\\n\"\n ) else (\n printf \"YES\\n2\\n%c %s\\n\" s.[0] @@ String.sub s 1 (String.length s-$1)\n )\n (* let prev = ref 0L in\n let a = ref 0L in\n let ex = make 10 false in\n String.iter (fun c ->\n let p = !a * 10L + i64 (int_of_char c -$ int_of_char '0') in\n if ex.(int_of_char c) then (\n if !prev > p then (\n\n )\n ) else\n if !prev > p then (\n\n )\n ) *)\n )\n\n\n\n\n\n\n\n\n\n"}], "src_uid": "9f87a89c788bd7c7b66e51db9fe47e46"} {"nl": {"description": "You are given a string $$$s$$$, consisting only of characters '0' or '1'. Let $$$|s|$$$ be the length of $$$s$$$.You are asked to choose some integer $$$k$$$ ($$$k > 0$$$) and find a sequence $$$a$$$ of length $$$k$$$ such that: $$$1 \\le a_1 < a_2 < \\dots < a_k \\le |s|$$$; $$$a_{i-1} + 1 < a_i$$$ for all $$$i$$$ from $$$2$$$ to $$$k$$$. The characters at positions $$$a_1, a_2, \\dots, a_k$$$ are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence $$$a$$$ should not be adjacent.Let the resulting string be $$$s'$$$. $$$s'$$$ is called sorted if for all $$$i$$$ from $$$2$$$ to $$$|s'|$$$ $$$s'_{i-1} \\le s'_i$$$.Does there exist such a sequence $$$a$$$ that the resulting string $$$s'$$$ is sorted?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$s$$$ ($$$2 \\le |s| \\le 100$$$). Each character is either '0' or '1'.", "output_spec": "For each testcase print \"YES\" if there exists a sequence $$$a$$$ such that removing the characters at positions $$$a_1, a_2, \\dots, a_k$$$ and concatenating the parts without changing the order produces a sorted string. Otherwise, print \"NO\". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).", "sample_inputs": ["5\n10101011011\n0000\n11111\n110\n1100"], "sample_outputs": ["YES\nYES\nYES\nYES\nNO"], "notes": "NoteIn the first testcase you can choose a sequence $$$a=[1,3,6,9]$$$. Removing the underlined letters from \"10101011011\" will produce a string \"0011111\", which is sorted.In the second and the third testcases the sequences are already sorted.In the fourth testcase you can choose a sequence $$$a=[3]$$$. $$$s'=$$$ \"11\", which is sorted.In the fifth testcase there is no way to choose a sequence $$$a$$$ such that $$$s'$$$ is sorted."}, "positive_code": [{"source_code": "let n = read_int () ;;\r\n\r\nlet translate_to str=\r\nlet len = String.length(str) in\r\nlet rec sup_fun i l=\r\nif i = -1 then l else (sup_fun (i-1) ((int_of_char(str.[i])-int_of_char('0')) :: l)) in\r\nsup_fun (len-1) [];;\r\n\r\nlet rec read_fucking_sheet n =\r\nif n = 0 then [] \r\nelse (translate_to (read_line ()) :: read_fucking_sheet (n-1)) \r\n;;\r\n\r\nlet rec print_yes t =\r\nif t = true then print_string \"YES\"\r\nelse print_string \"NO\"\r\n;;\r\n\r\nlet rec solve l flag =\r\nmatch l with \r\nhd :: hd1 :: tl -> \r\n\tif flag = 1 && hd = 1\r\n\t\tthen (solve (hd1 :: tl) 1)\r\n\telse if flag = 1 && hd = 0 && hd1 = 0\r\n\t\tthen false\r\n\telse if flag = 1 && hd = 0 && hd1 = 1\r\n\t\tthen (solve tl 1)\r\n\telse if flag = 0 && hd = 0\r\n\t\tthen (solve (hd1 :: tl) 0)\r\n\telse if flag = 0 && hd = 1 && hd1 = 0\r\n\t\tthen (solve tl 1) || (solve tl 0 )\r\n\telse if flag = 0 && hd = 1 && hd1 = 1\r\n\t\tthen (solve tl 1)\r\n else false\r\n|_-> true\r\n;;\r\n\r\nlet rec print_list l =\r\nmatch l with \r\nhd:: tl -> print_int hd ; print_list tl\r\n|_-> print_string \" \" ;; \r\n\r\nlet rec flum l =\r\nmatch l with \r\nhd :: tl -> (*print_list hd ;*) print_yes (solve hd 0) ; print_string \"\\n\" ; flum tl\r\n|_-> () ;;\r\n\r\n(*print_list (translate_to \"111000\") ;;*)\r\n\r\nflum (List.rev(read_fucking_sheet n))\r\n\r\n(*print_yes (solve (translate_to l ((string.length (l)) -1) ) 0) ;;*)\r\n\r\n(*let spisok = [1;1;0;0] ;;\r\n\r\nprint_yes (solve spisok 0) ;;*)"}, {"source_code": "let n = read_int ()\n\nlet rec find a b i m = if i>m-2 then -1 else if String.sub a i 2 = b then i else find a b (i+1) m ;;\n\nfor i=1 to n do\n let s = read_line () in\n let z = String.length s in\n let t = find s \"11\" 0 z in\n if t = -1 then print_string \"YES\\n\" else\n if find (String.sub s t (z-t)) \"00\" 0 (z-t) = -1 then print_string \"YES\\n\" else print_string \"NO\\n\"\ndone\n"}], "negative_code": [{"source_code": "let n = read_int () ;;\r\n\r\nlet translate_to str=\r\nlet len = String.length(str) in\r\nlet rec sup_fun i l=\r\nif i = -1 then l else (sup_fun (i-1) ((int_of_char(str.[i])-int_of_char('0')) :: l)) in\r\nsup_fun (len-1) [];;\r\n\r\nlet rec read_fucking_sheet n =\r\nif n = 0 then [] \r\nelse (translate_to (read_line ()) :: read_fucking_sheet (n-1)) \r\n;;\r\n\r\nlet rec print_yes t =\r\nif t = true then print_string \"YES\"\r\nelse print_string \"NO\"\r\n;;\r\n\r\nlet rec solve l flag =\r\nmatch l with \r\nhd :: hd1 :: tl -> \r\n\tif flag = 1 && hd = 1\r\n\t\tthen (solve (hd1 :: tl) 1)\r\n\telse if flag = 1 && hd = 0 && hd1 = 0\r\n\t\tthen false\r\n\telse if flag = 1 && hd = 0 && hd1 = 1\r\n\t\tthen (solve tl 1)\r\n\telse if flag = 0 && hd = 0\r\n\t\tthen (solve (hd1 :: tl) 0)\r\n\telse if flag = 0 && hd = 1 && hd1 = 0\r\n\t\tthen (solve tl 1) || (solve tl 0 )\r\n\telse if flag = 0 && hd = 1 && hd1 = 1\r\n\t\tthen (solve tl 1)\r\n else false\r\n|_-> true\r\n;;\r\n\r\nlet rec print_list l =\r\nmatch l with \r\nhd:: tl -> print_int hd ; print_list tl\r\n|_-> print_string \" \" ;; \r\n\r\nlet rec flum l =\r\nmatch l with \r\nhd :: tl -> (*print_list hd ;*) print_yes (solve hd 0) ; print_string \"\\n\" ; flum tl\r\n|_-> () ;;\r\n\r\n(*print_list (translate_to \"111000\") ;;*)\r\n\r\nlet rec revers l =\r\nmatch l with \r\nhd::tl -> hd :: (revers tl)\r\n|_-> []\r\n;;\r\n\r\nflum (revers(read_fucking_sheet n))\r\n\r\n(*print_yes (solve (translate_to l ((string.length (l)) -1) ) 0) ;;*)\r\n\r\n(*let spisok = [1;1;0;0] ;;\r\n\r\nprint_yes (solve spisok 0) ;;*)\r\n"}, {"source_code": "let n = read_int () ;;\r\n\r\nlet translate_to str=\r\nlet len = String.length(str) in\r\nlet rec sup_fun i l=\r\nif i = -1 then l else (sup_fun (i-1) ((int_of_char(str.[i])-int_of_char('0')) :: l)) in\r\nsup_fun (len-1) [];;\r\n\r\nlet rec read_fucking_sheet n =\r\nif n = 0 then [] \r\nelse (translate_to (read_line ()) :: read_fucking_sheet (n-1)) \r\n;;\r\n\r\nlet rec print_yes t =\r\nif t = true then print_string \"YES\"\r\nelse print_string \"NO\"\r\n;;\r\n\r\nlet rec solve l flag =\r\nmatch l with \r\nhd :: hd1 :: tl -> \r\n\tif flag = 1 && hd = 1\r\n\t\tthen (solve (hd1 :: tl) 1)\r\n\telse if flag = 1 && hd = 0 && hd1 = 0\r\n\t\tthen false\r\n\telse if flag = 1 && hd = 0 && hd1 = 1\r\n\t\tthen (solve tl 1)\r\n\telse if flag = 0 && hd = 0\r\n\t\tthen (solve (hd1 :: tl) 0)\r\n\telse if flag = 0 && hd = 1 && hd1 = 0\r\n\t\tthen (solve tl 1) || (solve tl 0 )\r\n\telse if flag = 0 && hd = 1 && hd1 = 1\r\n\t\tthen (solve tl 1)\r\n else false\r\n|_-> true\r\n;;\r\n\r\nlet rec print_list l =\r\nmatch l with \r\nhd:: tl -> print_int hd ; print_list tl\r\n|_-> print_string \" \" ;; \r\n\r\nlet rec flum l =\r\nmatch l with \r\nhd :: tl -> (*print_list hd ;*) print_yes (solve hd 0) ; print_string \"\\n\" ; flum tl\r\n|_-> () ;;\r\n\r\n(*print_list (translate_to \"111000\") ;;*)\r\n\r\nflum (read_fucking_sheet n)\r\n\r\n(*print_yes (solve (translate_to l ((string.length (l)) -1) ) 0) ;;*)\r\n\r\n(*let spisok = [1;1;0;0] ;;\r\n\r\nprint_yes (solve spisok 0) ;;*)"}, {"source_code": "let n = read_int () ;;\r\n\r\nlet translate_to str=\r\nlet len = String.length(str) in\r\nlet rec sup_fun i l=\r\nif i = len then [] else (sup_fun (i+1) (int_of_char(str.[i]) :: l)) in\r\nsup_fun 0 [];;\r\n\r\nlet rec read_fucking_sheet n =\r\nif n = 0 then [] \r\nelse (translate_to (read_line ())) \r\n\r\nlet rec print_yes t =\r\nif t = true then print_string \"YES\"\r\nelse print_string \"NO\"\r\n;;\r\n\r\nlet rec solve l flag =\r\nmatch l with \r\nhd :: hd1 :: tl -> \r\n\tif flag = 1 && hd = 1\r\n\t\tthen (solve (hd1 :: tl) flag)\r\n\telse if flag = 1 && hd = 0 && hd1 = 0\r\n\t\tthen false\r\n\telse if flag = 1 && hd = 0 && hd1 = 1\r\n\t\tthen (solve tl flag)\r\n\telse if flag = 0 && hd = 0\r\n\t\tthen (solve (hd1 :: tl) flag)\r\n\telse if flag = 0 && hd = 1 && hd1 = 0\r\n\t\tthen (solve tl 1) || (solve tl flag )\r\n\telse if flag = 0 && hd = 1 && hd1 = 1\r\n\t\tthen (solve tl 1)\r\n else false\r\n|_-> true\r\n;;\r\n\r\nlet rec flum l =\r\nmatch l with \r\nhd :: tl -> print_yes (solve hd 0) ; flum tl\r\n|_-> () ;;\r\n\r\nflum (read_fucking_sheet n)\r\n\r\n(*print_yes (solve (translate_to l ((string.length (l)) -1) ) 0) ;;*)\r\n\r\n(*let spisok = [1;0;0;1;1;1;0;0;1] ;;\r\n\r\nprint_yes (solve spisok 0) ;;*)"}], "src_uid": "357dcc8fb7783d878cd2c4ed34eb437e"} {"nl": {"description": "Find out if it is possible to partition the first $$$n$$$ positive integers into two non-empty disjoint sets $$$S_1$$$ and $$$S_2$$$ such that:$$$\\mathrm{gcd}(\\mathrm{sum}(S_1), \\mathrm{sum}(S_2)) > 1$$$ Here $$$\\mathrm{sum}(S)$$$ denotes the sum of all elements present in set $$$S$$$ and $$$\\mathrm{gcd}$$$ means thegreatest common divisor.Every integer number from $$$1$$$ to $$$n$$$ should be present in exactly one of $$$S_1$$$ or $$$S_2$$$.", "input_spec": "The only line of the input contains a single integer $$$n$$$ ($$$1 \\le n \\le 45\\,000$$$)", "output_spec": "If such partition doesn't exist, print \"No\" (quotes for clarity). Otherwise, print \"Yes\" (quotes for clarity), followed by two lines, describing $$$S_1$$$ and $$$S_2$$$ respectively. Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty. If there are multiple possible partitions\u00a0\u2014 print any of them.", "sample_inputs": ["1", "3"], "sample_outputs": ["No", "Yes\n1 2\n2 1 3"], "notes": "NoteIn the first example, there is no way to partition a single number into two non-empty sets, hence the answer is \"No\".In the second example, the sums of the sets are $$$2$$$ and $$$4$$$ respectively. The $$$\\mathrm{gcd}(2, 4) = 2 > 1$$$, hence that is one of the possible answers."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\nend open MyInt64\n\nlet sum a = Array.fold_left (+) 0L a\n\nlet () =\n\tlet n = get_i64 0 in\n\tlet a = Array.init (~|n) (fun v -> 1L + (~~|v))\n\tin\n\tif n<=2L then (\n\t\tprintf \"No\\n\"\n\t)\n\telse (\n\t\tlet p = (n-1L) / 2L\n\t\tin\n\t\t(* in let u,v = sum a - (a@p), a@p *)\n\t\t(* in let q = gcd u v in assert (q <> 1L); *)\n\t\t(* printf \"%Ld, %Ld --> %Ld\\n\" u v q *)\n\t\tprintf \"Yes\\n1 %Ld\\n%Ld \" (a@p) (n-1L);\n\t\t(\n\t\t\tlet v = (~| (a@p)) in\n\t\t\tfor i=1 to (~|n) do\n\t\t\t\tif i <> v then printf \"%d \" i\n\t\t\tdone\n\t\t)\n\t\t\t(* (a |> Array.to_list |> string_of_list ~separator:\" \" Int64.to_string) *)\n\t\t\t(* (Array.init (~|n -$ 1) (fun v -> if v < (~|p) then (1+$v) else (2+$v))\n\t\t\t|> Array.to_list |> string_of_list ~separator:\" \" (string_of_int)) *)\n\t)"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\nend open MyInt64\n\nlet sum a = Array.fold_left (+) 0L a\n\nlet () =\n\tlet n = get_i64 0 in\n\tlet a = Array.init (~|n) (fun v -> 1L + (~~|v))\n\tin\n\tif n<=2L then (\n\t\tprintf \"NO\\n\"\n\t)\n\telse (\n\t\tlet p = (n-1L) / 2L\n\t\tin let u,v = sum a - (a@p), a@p\n\t\tin let q = gcd u v in assert (q <> 1L);\n\t\t(* printf \"%Ld, %Ld --> %Ld\\n\" u v q *)\n\t\tprintf \"YES\\n1 %Ld\\n%Ld %s\\n\" (a@p) (n-1L) \n\t\t\t(* (a |> Array.to_list |> string_of_list ~separator:\" \" Int64.to_string) *)\n\t\t\t(Array.init (~|n -$ 1) (fun v -> if v < (~|p) then (1+$v) else (2+$v))\n\t\t\t|> Array.to_list |> string_of_list ~separator:\" \" (string_of_int))\n\t)"}], "src_uid": "bb7bace930d5c5f231bfc2061576ec45"} {"nl": {"description": "Farmer John has just given the cows a program to play with! The program contains two integer variables, x and y, and performs the following operations on a sequence a1,\u2009a2,\u2009...,\u2009an of positive integers: Initially, x\u2009=\u20091 and y\u2009=\u20090. If, after any step, x\u2009\u2264\u20090 or x\u2009>\u2009n, the program immediately terminates. The program increases both x and y by a value equal to ax simultaneously. The program now increases y by ax while decreasing x by ax. The program executes steps 2 and 3 (first step 2, then step 3) repeatedly until it terminates (it may never terminate). So, the sequence of executed steps may start with: step 2, step 3, step 2, step 3, step 2 and so on. The cows are not very good at arithmetic though, and they want to see how the program works. Please help them!You are given the sequence a2,\u2009a3,\u2009...,\u2009an. Suppose for each i (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091) we run the program on the sequence i,\u2009a2,\u2009a3,\u2009...,\u2009an. For each such run output the final value of y if the program terminates or -1 if it does not terminate.", "input_spec": "The first line contains a single integer, n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The next line contains n\u2009-\u20091 space separated integers, a2,\u2009a3,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Output n\u2009-\u20091 lines. On the i-th line, print the requested value when the program is run on the sequence i,\u2009a2,\u2009a3,\u2009...an. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["4\n2 4 1", "3\n1 2"], "sample_outputs": ["3\n6\n8", "-1\n-1"], "notes": "NoteIn the first sample For i\u2009=\u20091,\u2009 x becomes and y becomes 1\u2009+\u20092\u2009=\u20093. For i\u2009=\u20092,\u2009 x becomes and y becomes 2\u2009+\u20094\u2009=\u20096. For i\u2009=\u20093,\u2009 x becomes and y becomes 3\u2009+\u20091\u2009+\u20094\u2009=\u20098. "}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = let u = read_int 0 in (u,read_int 0)\n\nlet ( ++ ) a b = Int64.add a b\n\nlet () = \n let n = read_int 0 in\n let a = Array.init (n+1) (fun i -> if i<=1 then 0 else read_int 0) in\n let outcome = Array.make_matrix (n+1) 2 0 in\n\n let next_state (x,s) = (* s=0 means the initial state of the process, before \"step 2\" *)\n if s=0 then (x+a.(x), (1-s)) else (x-a.(x), (1-s))\n in\n\n let rec fill_table (x,s) = \n if x<1 || x>n then 4\n else if x = 1 then 2+s (* 2 or 3 *)\n else if outcome.(x).(s) = 0 then (\n outcome.(x).(s) <- 5;\n outcome.(x).(s) <- fill_table (next_state (x,s));\n outcome.(x).(s)\n )\n else if outcome.(x).(s) = 5 then (\n outcome.(x).(s) <- 1;\n 1\n )\n else outcome.(x).(s)\n in\n\n let () = for i=2 to n do\n ignore (fill_table (i,0));\n ignore (fill_table (i,1))\n done in\n\n let cycles i = \n let a = outcome.(i+1).(1) in\n let b = outcome.(i+1).(0) in\n a = 1 || a = 2 || (a = 3 && (b = 1 || b = 2 || b = 3))\n in\n\n let yval = Array.make_matrix (n+1) 2 (-1L) in\n\n let rec fill_in_y i (x,s) = \n if x<1 || x>n then 0L\n else if (x,s) = (1,1) then Int64.of_int i\n else if yval.(x).(s) >= 0L then yval.(x).(s)\n else (\n yval.(x).(s) <- (Int64.of_int a.(x)) ++ (fill_in_y i (next_state (x,s)));\n yval.(x).(s)\n )\n in\n\n for i=1 to n-1 do \n if cycles i then print_string (\"-1\\n\") \n else Printf.printf \"%Ld\\n\" ((Int64.of_int i)++(fill_in_y i (i+1,1)))\n done\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = let u = read_int 0 in (u,read_int 0)\n\nlet ( ++ ) a b = Int64.add a b\n\nlet () = \n let n = read_int 0 in\n let a = Array.init (n+1) (fun i -> if i<=1 then 0 else read_int 0) in\n let outcome = Array.make_matrix (n+1) 2 0 in\n (* this table has the following meaning:\n 0 unknown\n 1 cyclic\n 2 reaches (1,0)\n 3 reaches (1,1)\n 4 termates\n 5 current search *)\n\n let next_state (x,s) = (* s=0 means the initial state of the process, before \"step 2\" *)\n if s=0 then (x+a.(x), (1-s)) else (x-a.(x), (1-s))\n in\n\n let rec fill_table (x,s) = \n if x<1 || x>n then 4\n else if x = 1 then 2+s (* 2 or 3 *)\n else if outcome.(x).(s) = 0 then (\n outcome.(x).(s) <- 5;\n outcome.(x).(s) <- fill_table (next_state (x,s));\n outcome.(x).(s)\n )\n else if outcome.(x).(s) = 5 then (\n outcome.(x).(s) <- 1;\n 1\n )\n else outcome.(x).(s)\n in\n\n let () = for i=2 to n do\n ignore (fill_table (i,0));\n ignore (fill_table (i,1))\n done in\n\n let cycles i = \n let a = outcome.(i+1).(1) in\n let b = outcome.(i+1).(0) in\n a = 1 || a = 2 || (a = 3 && (b = 1 || b = 2 || b = 3))\n in\n\n let yval = Array.make_matrix (n+1) 2 (-1L) in\n\n let rec fill_in_y i (x,s) = \n if x<1 || x>n then 0L\n else if (x,s) = (1,1) then Int64.of_int i\n else if yval.(x).(s) >= 0L then yval.(x).(s)\n else (\n yval.(x).(s) <- (Int64.of_int a.(x)) ++ (fill_in_y i (next_state (x,s)));\n yval.(x).(s)\n )\n in\n\n for i=1 to n-1 do \n if cycles i then print_string (\"-1\\n\") \n else Printf.printf \"%Ld\\n\" ((Int64.of_int i)++(fill_in_y i (i+1,1)))\n done\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = let u = read_int 0 in (u,read_int 0)\n\nlet () = \n let n = read_int 0 in\n let a = Array.init (n+1) (fun i -> if i<=1 then 0 else read_int 0) in\n let outcome = Array.make_matrix (n+1) 2 0 in\n(* this table has the following meaning:\n 0 unknown\n 1 cyclic\n 2 reaches (1,0)\n 3 reaches (1,1)\n 4 termates\n 5 current search *)\n\n let next_state (x,s) = (* s=0 means the initial state of the process, before \"step 2\" *)\n if s=0 then (x+a.(x), (1-s)) else (x-a.(x), (1-s))\n in\n\n let rec find_path (x,s) = \n if x<1 || x>n then 4 \n else if x = 1 then 2+s (* 2 or 3 *)\n else if outcome.(x).(s) <> 0 then outcome.(x).(s)\n else (\n outcome.(x).(s) <- 5;\n find_path (next_state(x,s))\n )\n in\n\n let rec label_path (x,s) l =\n if x<1 || x>n then ()\n else if outcome.(x).(s) = 5 then (\n outcome.(x).(s) <- l;\n label_path (next_state(x,s)) l\n )\n in \n\n let fill_table (x,s) = \n let l = find_path(x,s) in\n label_path (x,s) (if l=5 then 1 else l)\n in\n\n let () = for i=1 to n-1 do\n fill_table (i+1,1)\n done in\n\n let cycles i = \n outcome.(i+1).(1) = 1 || outcome.(i+1).(1) = 2\n in\n\n let yval = Array.make_matrix (n+1) 2 (-1) in\n\n let rec testoverflow i = if i=0 then 0 else i+(testoverflow (i-1)) in\n\n\n Printf.printf \"testoverflow 10 = %d\\n\" (testoverflow 1000000);\n\n let rec fill_in_y i (x,s) = \n if x<1 || x>n then 0\n else if (x,s) = (1,1) then i\n else if yval.(x).(s) >= 0 then yval.(x).(s)\n else (\n yval.(x).(s) <- a.(x) + fill_in_y i (next_state (x,s));\n yval.(x).(s)\n )\n in\n\n for i=1 to n-1 do \n if cycles i then print_string (\"-1\\n\") \n else Printf.printf \"%d\\n\" (i+(fill_in_y i (i+1,1)))\n done;\n\n Printf.printf \"testoverflow 10 = %d\\n\" (testoverflow 1000000)\n"}], "src_uid": "369b6390417723799c5c0a19005e78f1"} {"nl": {"description": "A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop.There are m queens on a square n\u2009\u00d7\u2009n chessboard. You know each queen's positions, the i-th queen is positioned in the square (ri,\u2009ci), where ri is the board row number (numbered from the top to the bottom from 1 to n), and ci is the board's column number (numbered from the left to the right from 1 to n). No two queens share the same position.For each queen one can count w \u2014 the number of other queens that the given queen threatens (attacks). For a fixed attack direction only the first queen in this direction is under attack if there are many queens are on the ray of the attack. Obviously, for any queen w is between 0 and 8, inclusive.Print the sequence t0,\u2009t1,\u2009...,\u2009t8, where ti is the number of queens that threaten exactly i other queens, i.e. the number of queens that their w equals i.", "input_spec": "The first line of the input contains a pair of integers n,\u2009m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105), where n is the size of the board and m is the number of queens on the board. Then m following lines contain positions of the queens, one per line. Each line contains a pair of integers ri,\u2009ci (1\u2009\u2264\u2009ri,\u2009ci\u2009\u2264\u2009n) \u2014 the queen's position. No two queens stand on the same square.", "output_spec": "Print the required sequence t0,\u2009t1,\u2009...,\u2009t8, separating the numbers with spaces.", "sample_inputs": ["8 4\n4 3\n4 8\n6 5\n1 6", "10 3\n1 1\n1 2\n1 3"], "sample_outputs": ["0 3 0 1 0 0 0 0 0", "0 2 1 0 0 0 0 0 0"], "notes": null}, "positive_code": [{"source_code": "(* row : [(row_number,(min_column,max_column));...]\n * col : [(col_number,(min_row,max_row));...]\n * diags : [(d, ((minRow,minCol),(maxRow,maxCol)))] \n * where d = Row-Col || d = Row + Col\n * Implemented with hash tables\n *)\n\nlet solve =\n let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) in\n let readPos() = Scanf.scanf \"%d %d\\n\" (fun x y -> (x,y)) in\n let rowsHash = Hashtbl.create n in\n let colsHash = Hashtbl.create n in\n let diagsHash = Hashtbl.create n in\n let diagsInvHash = Hashtbl.create n in\n let rec readBoard i acc =\n match i with\n | 0 -> acc\n | i -> let (row,col) = readPos() in\n readBoard (i-1) ((row,col)::acc)\n in\n let rec createRow queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> (match (try Some (Hashtbl.find rowsHash row) with Not_found -> None) with\n | None -> Hashtbl.add rowsHash row (col,col); createRow xs;\n | Some (minCol,maxCol) -> \n if (col < minCol)\n then\n (Hashtbl.replace rowsHash row (col,maxCol); createRow xs)\n else if (col > maxCol) then\n (Hashtbl.replace rowsHash row (minCol,col); createRow xs)\n else\n createRow xs\n )\n in\n let rec createCol queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> (match (try Some (Hashtbl.find colsHash col) with Not_found -> None) with\n | None -> Hashtbl.add colsHash col (row,row); createCol xs;\n | Some (minRow,maxRow) -> \n if (row < minRow)\n then\n (Hashtbl.replace colsHash col (row,maxRow); createCol xs)\n else if (row > maxRow) then\n (Hashtbl.replace colsHash col (minRow,row); createCol xs)\n else\n createCol xs\n )\n in\n let createDiag queens f dHash =\n let rec aux queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> let d = f row col in\n (match (try Some (Hashtbl.find dHash d ) with Not_found -> None) with\n | None -> Hashtbl.add dHash d ((row,col),(row,col)); aux xs;\n | Some ((minRow,minCol),(maxRow,maxCol)) -> \n if (row < minRow)\n then \n (Hashtbl.replace dHash d ((row,col),(maxRow,maxCol)); aux xs)\n else if (row > maxRow) then\n (Hashtbl.replace dHash d ((minRow,minCol),(row,col)); aux xs)\n else\n aux xs\n )\n in\n aux queens\n in\n let check queens =\n let rec checkAux queens t =\n let checkRow (row,col) =\n match (try Some (Hashtbl.find rowsHash row) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minCol,maxCol) -> \n if (col > minCol) then\n begin\n if (col < maxCol) then 2 else 1\n end\n else \n if (col < maxCol) then 1 else 0\n in\n let checkCol (row,col) =\n match (try Some (Hashtbl.find colsHash col) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minRow,maxRow) -> \n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else \n if (row < maxRow) then 1 else 0\n in\n let checkDiag (row,col) dHash f =\n let d = f row col in\n match (try Some (Hashtbl.find dHash d) with Not_found -> None) with\n | None -> failwith \"if nasa launched sattelites with bugs then\n I am allowed to fuck this up no strings attached!\"\n | Some ((minRow,minCol),(maxRow,maxCol)) ->\n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else\n if (row < maxRow) then 1 else 0\n in\n match queens with\n | [] -> t\n | (row,col) :: xs -> let threats = checkRow (row,col) + checkCol (row,col) + \n (checkDiag (row,col) diagsHash ( - )) +\n (checkDiag (row,col) diagsInvHash ( + )) \n in\n (match (try Some (List.assoc threats t) with Not_found -> None) with\n | None -> checkAux xs ((threats,1)::t)\n | Some prevThreats -> checkAux xs ((threats,prevThreats + 1)::(List.remove_assoc threats t)))\n in\n checkAux queens []\n in\n let board = readBoard m [] in\n let _ = createRow board in\n let _ = createCol board in\n let _ = createDiag board ( - ) diagsHash in\n let _ = createDiag board ( + ) diagsInvHash in\n let tSeq = check board in\n let print lst =\n let rec printAux i =\n match i with \n | 9 -> Printf.printf \"\\n\"\n | i -> \n (match (try Some (List.assoc i lst) with Not_found -> None) with\n | None -> Printf.printf \"0 \"; printAux (i+1)\n | Some v -> Printf.printf \"%d \" v; printAux (i+1))\n in\n printAux 0\n in\n print tSeq\n;;\n"}, {"source_code": "(* row : [(row_number,(min_column,max_column));...]\n * col : [(col_number,(min_row,max_row));...]\n * diags : [(d, ((minRow,minCol),(maxRow,maxCol)))] \n * where d = Row-Col || d = Row + Col\n *)\n\nlet solve =\n let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) in\n let readPos() = Scanf.scanf \"%d %d\\n\" (fun x y -> (x,y)) in\n let rowsHash = Hashtbl.create n in\n let colsHash = Hashtbl.create n in\n let diagsHash = Hashtbl.create n in\n let diagsInvHash = Hashtbl.create n in\n let rec readBoard i acc =\n match i with\n | 0 -> acc\n | i -> let (row,col) = readPos() in\n readBoard (i-1) ((row,col)::acc)\n in\n let rec createRow queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> (match (try Some (Hashtbl.find rowsHash row) with Not_found -> None) with\n | None -> Hashtbl.add rowsHash row (col,col); createRow xs;\n | Some (minCol,maxCol) -> \n if (col < minCol)\n then\n (Hashtbl.replace rowsHash row (col,maxCol); createRow xs)\n else if (col > maxCol) then\n (Hashtbl.replace rowsHash row (minCol,col); createRow xs)\n else\n createRow xs\n )\n in\n let rec createCol queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> (match (try Some (Hashtbl.find colsHash col) with Not_found -> None) with\n | None -> Hashtbl.add colsHash col (row,row); createCol xs;\n | Some (minRow,maxRow) -> \n if (row < minRow)\n then\n (Hashtbl.replace colsHash col (row,maxRow); createCol xs)\n else if (row > maxRow) then\n (Hashtbl.replace colsHash col (minRow,row); createCol xs)\n else\n createCol xs\n )\n in\n let createDiag queens f dHash =\n let rec aux queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> let d = f row col in\n (match (try Some (Hashtbl.find dHash d ) with Not_found -> None) with\n | None -> Hashtbl.add dHash d ((row,col),(row,col)); aux xs;\n | Some ((minRow,minCol),(maxRow,maxCol)) -> \n if (row < minRow)\n then \n (Hashtbl.replace dHash d ((row,col),(maxRow,maxCol)); aux xs)\n else if (row > maxRow) then\n (Hashtbl.replace dHash d ((minRow,minCol),(row,col)); aux xs)\n else\n aux xs\n )\n in\n aux queens\n in\n let rec check queens rows cols diag1 diag2 t =\n let checkRow (row,col) =\n match (try Some (Hashtbl.find rowsHash row) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minCol,maxCol) -> \n if (col > minCol) then\n begin\n if (col < maxCol) then 2 else 1\n end\n else \n if (col < maxCol) then 1 else 0\n in\n let checkCol (row,col) =\n match (try Some (Hashtbl.find colsHash col) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minRow,maxRow) -> \n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else \n if (row < maxRow) then 1 else 0\n in\n let checkDiag (row,col) dHash f =\n let d = f row col in\n match (try Some (Hashtbl.find dHash d) with Not_found -> None) with\n | None -> failwith \"if nasa launched sattelites with bugs then\n I am allowed to fuck this up no strings attached!\"\n | Some ((minRow,minCol),(maxRow,maxCol)) ->\n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else\n if (row < maxRow) then 1 else 0\n in\n match queens with\n | [] -> t\n | (row,col) :: xs -> let threats = checkRow (row,col) + checkCol (row,col) + \n (checkDiag (row,col) diagsHash ( - )) +\n (checkDiag (row,col) diagsInvHash ( + )) \n in\n (match (try Some (List.assoc threats t) with Not_found -> None) with\n | None -> check xs rows cols diag1 diag2 ((threats,1)::t)\n | Some prevThreats -> check xs rows cols diag1 diag2 ((threats,prevThreats + 1)::(List.remove_assoc threats t)))\n in\n let board = readBoard m [] in\n let rows = createRow board in\n let cols = createCol board in\n let diag1 = createDiag board ( - ) diagsHash in\n let diag2 = createDiag board ( + ) diagsInvHash in\n let tSeq = check board rows cols diag1 diag2 [] in\n let print lst =\n let rec aux i =\n match i with \n | 9 -> Printf.printf \"\\n\"\n | i -> \n (match (try Some (List.assoc i lst) with Not_found -> None) with\n | None -> Printf.printf \"0 \"; aux (i+1)\n | Some v -> Printf.printf \"%d \" v; aux (i+1))\n in\n aux 0\n in\n print tSeq\n;;\n"}, {"source_code": "(* row : [(row_number,(min_column,max_column));...]\n * col : [(col_number,(min_row,max_row));...]\n * diags : [(d, ((minRow,minCol),(maxRow,maxCol)))] \n * where d = Row-Col || d = Row + Col\n *)\n\nlet solve =\n let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) in\n let readPos() = Scanf.scanf \"%d %d\\n\" (fun x y -> (x,y)) in\n let rowsHash = Hashtbl.create n in\n let colsHash = Hashtbl.create n in\n let diagsHash = Hashtbl.create n in\n let diagsInvHash = Hashtbl.create n in\n let rec readBoard i acc =\n match i with\n | 0 -> acc\n | i -> let (row,col) = readPos() in\n readBoard (i-1) ((row,col)::acc)\n in\n let rec createRow queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> (match (try Some (Hashtbl.find rowsHash row) with Not_found -> None) with\n | None -> Hashtbl.add rowsHash row (col,col); createRow xs;\n | Some (minCol,maxCol) -> \n if (col < minCol)\n then\n (Hashtbl.replace rowsHash row (col,maxCol); createRow xs)\n else if (col > maxCol) then\n (Hashtbl.replace rowsHash row (minCol,col); createRow xs)\n else\n createRow xs\n )\n in\n let rec createCol queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> (match (try Some (Hashtbl.find colsHash col) with Not_found -> None) with\n | None -> Hashtbl.add colsHash col (row,row); createCol xs;\n | Some (minRow,maxRow) -> \n if (row < minRow)\n then\n (Hashtbl.replace colsHash col (row,maxRow); createCol xs)\n else if (row > maxRow) then\n (Hashtbl.replace colsHash col (minRow,row); createCol xs)\n else\n createCol xs\n )\n in\n let createDiag queens f dHash =\n let rec aux queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> let d = f row col in\n (match (try Some (Hashtbl.find dHash d ) with Not_found -> None) with\n | None -> Hashtbl.add dHash d ((row,col),(row,col)); aux xs;\n | Some ((minRow,minCol),(maxRow,maxCol)) -> \n if (row < minRow)\n then \n (Hashtbl.replace dHash d ((row,col),(maxRow,maxCol)); aux xs)\n else if (row > maxRow) then\n (Hashtbl.replace dHash d ((minRow,minCol),(row,col)); aux xs)\n else\n aux xs\n )\n in\n aux queens\n in\n let check queens rows cols diag1 diag2 =\n let rec checkAux queens t =\n let checkRow (row,col) =\n match (try Some (Hashtbl.find rowsHash row) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minCol,maxCol) -> \n if (col > minCol) then\n begin\n if (col < maxCol) then 2 else 1\n end\n else \n if (col < maxCol) then 1 else 0\n in\n let checkCol (row,col) =\n match (try Some (Hashtbl.find colsHash col) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minRow,maxRow) -> \n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else \n if (row < maxRow) then 1 else 0\n in\n let checkDiag (row,col) dHash f =\n let d = f row col in\n match (try Some (Hashtbl.find dHash d) with Not_found -> None) with\n | None -> failwith \"if nasa launched sattelites with bugs then\n I am allowed to fuck this up no strings attached!\"\n | Some ((minRow,minCol),(maxRow,maxCol)) ->\n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else\n if (row < maxRow) then 1 else 0\n in\n match queens with\n | [] -> t\n | (row,col) :: xs -> let threats = checkRow (row,col) + checkCol (row,col) + \n (checkDiag (row,col) diagsHash ( - )) +\n (checkDiag (row,col) diagsInvHash ( + )) \n in\n (match (try Some (List.assoc threats t) with Not_found -> None) with\n | None -> checkAux xs ((threats,1)::t)\n | Some prevThreats -> checkAux xs ((threats,prevThreats + 1)::(List.remove_assoc threats t)))\n in\n checkAux queens []\n in\n let board = readBoard m [] in\n let rows = createRow board in\n let cols = createCol board in\n let diag1 = createDiag board ( - ) diagsHash in\n let diag2 = createDiag board ( + ) diagsInvHash in\n let tSeq = check board rows cols diag1 diag2 in\n let print lst =\n let rec printAux i =\n match i with \n | 9 -> Printf.printf \"\\n\"\n | i -> \n (match (try Some (List.assoc i lst) with Not_found -> None) with\n | None -> Printf.printf \"0 \"; printAux (i+1)\n | Some v -> Printf.printf \"%d \" v; printAux (i+1))\n in\n printAux 0\n in\n print tSeq\n;;\n"}, {"source_code": "(* row : [(row_number,(min_column,max_column));...]\n * col : [(col_number,(min_row,max_row));...]\n * diags : [(d, ((minRow,minCol),(maxRow,maxCol)))] \n * where d = Row-Col || d = Row + Col\n *)\n\nlet solve =\n let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) in\n let readPos() = Scanf.scanf \"%d %d\\n\" (fun x y -> (x,y)) in\n let rowsHash = Hashtbl.create n in\n let colsHash = Hashtbl.create n in\n let diagsHash = Hashtbl.create n in\n let diagsInvHash = Hashtbl.create n in\n let rec readBoard i acc =\n match i with\n | 0 -> acc\n | i -> let (row,col) = readPos() in\n readBoard (i-1) ((row,col)::acc)\n in\n let rec createLists queens =\n match queens with\n | [] -> ()\n | (row,col) :: xs -> let createRow () =\n match (try Some (Hashtbl.find rowsHash row) with Not_found -> None) with\n | None -> Hashtbl.add rowsHash row (col,col); \n | Some (minCol,maxCol) -> \n if (col < minCol)\n then\n Hashtbl.replace rowsHash row (col,maxCol)\n else if (col > maxCol) then\n Hashtbl.replace rowsHash row (minCol,col)\n else\n ()\n in\n let createCol () =\n match (try Some (Hashtbl.find colsHash col) with Not_found -> None) with\n | None -> Hashtbl.add colsHash col (row,row);\n | Some (minRow,maxRow) -> \n if (row < minRow)\n then\n Hashtbl.replace colsHash col (row,maxRow)\n else if (row > maxRow) then\n Hashtbl.replace colsHash col (minRow,row)\n else\n ()\n in\n let createDiag dHash f =\n let d = f row col in\n match (try Some (Hashtbl.find dHash d ) with Not_found -> None) with\n | None -> Hashtbl.add dHash d ((row,col),(row,col));\n | Some ((minRow,minCol),(maxRow,maxCol)) -> \n if (row < minRow)\n then \n Hashtbl.replace dHash d ((row,col),(maxRow,maxCol))\n else if (row > maxRow) then\n Hashtbl.replace dHash d ((minRow,minCol),(row,col))\n else\n ()\n in\n createRow ();\n createCol ();\n createDiag diagsHash ( - );\n createDiag diagsInvHash ( + );\n createLists xs\n in\n let check queens =\n let rec checkAux queens t =\n let checkRow (row,col) =\n match (try Some (Hashtbl.find rowsHash row) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minCol,maxCol) -> \n if (col > minCol) then\n begin\n if (col < maxCol) then 2 else 1\n end\n else \n if (col < maxCol) then 1 else 0\n in\n let checkCol (row,col) =\n match (try Some (Hashtbl.find colsHash col) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minRow,maxRow) -> \n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else \n if (row < maxRow) then 1 else 0\n in\n let checkDiag (row,col) dHash f =\n let d = f row col in\n match (try Some (Hashtbl.find dHash d) with Not_found -> None) with\n | None -> failwith \"if nasa launched sattelites with bugs then\n I am allowed to fuck this up no strings attached!\"\n | Some ((minRow,minCol),(maxRow,maxCol)) ->\n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else\n if (row < maxRow) then 1 else 0\n in\n match queens with\n | [] -> t\n | (row,col) :: xs -> let threats = checkRow (row,col) + checkCol (row,col) + \n (checkDiag (row,col) diagsHash ( - )) +\n (checkDiag (row,col) diagsInvHash ( + )) \n in\n (match (try Some (List.assoc threats t) with Not_found -> None) with\n | None -> checkAux xs ((threats,1)::t)\n | Some prevThreats -> checkAux xs ((threats,prevThreats + 1)::(List.remove_assoc threats t)))\n in\n checkAux queens []\n in\n let board = readBoard m [] in\n let _ = createLists board in\n let tSeq = check board in\n let print lst =\n let rec aux i =\n match i with \n | 9 -> Printf.printf \"\\n\"\n | i -> \n (match (try Some (List.assoc i lst) with Not_found -> None) with\n | None -> Printf.printf \"0 \"; aux (i+1)\n | Some v -> Printf.printf \"%d \" v; aux (i+1))\n in\n aux 0\n in\n print tSeq\n;;\n"}, {"source_code": "let read_stuff () =\n let m = Scanf.scanf \" %d %d\" (fun _ a -> a)\n and l = ref [] in\n for i = 1 to m do\n let pair = Scanf.scanf \" %d %d\" (fun a b -> (a, b, 0)) in\n l := pair :: !l;\n done;\n !l\n\nlet postprocess queens =\n let res = Array.create 9 0\n in List.iter (fun (_, _, sz) -> (res.(sz) <- (res.(sz) + 1))) queens; res\n\nlet print_res res =\n Array.iter (fun el -> Printf.printf \"%d \" el) res;\n print_endline \"\"\n\n\n\nlet cmp a b =\n if a == b\n then 0\n else if a > b\n then 1\n else -1\n\n\nlet solve_one queens pred =\n let proc2 q r =\n let (x, y, v) = q in\n if abs(pred q r) == 2 \n then (x, y, v + 1)\n else q\n in let proc = function\n | h :: t -> \n snd (List.fold_left \n (* Sprawdz wszystko oprocz glowy *)\n (fun (last, acc) h -> \n (h, (proc2 h last)::acc))\n (h, [h])\n t)\n | foo -> foo\n and sorted = List.sort pred queens\n in proc (proc (sorted))\n\n\nlet rec solve queens preds = \n match preds with \n | [] -> queens\n | p0 :: ps -> solve (solve_one queens p0) ps\n \nlet oq a b = \n if a == 0 then 2 * b else a\n;;\n\nlet predicates =\n [\n (fun (x1, y1, _) (x2, y2, _) -> oq (cmp x1 x2) (cmp y1 y2));\n (fun (x1, y1, _) (x2, y2, _) -> oq (cmp y1 y2) (cmp x1 x2));\n (fun (x1, y1, _) (x2, y2, _) -> oq (cmp (x1 - y1) (x2 - y2)) (cmp (x1 + y1) (x2 + y2)));\n (fun (x1, y1, _) (x2, y2, _) -> oq (cmp (x1 + y1) (x2 + y2)) (cmp (x1 - y1) (x2 - y2)))\n ]\nin\n print_res (postprocess (solve (read_stuff()) predicates))\n\n\n"}], "negative_code": [{"source_code": "(* row : [(row_number,(min_column,max_column));...]\n * col : [(col_number,(min_row,max_row));...]\n * diags : [(d, ((minRow,minCol),(maxRow,maxCol)))] \n * where d = Row-Col || d = Row + Col\n *)\n\nlet solve =\n let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) in\n let readPos() = Scanf.scanf \"%d %d\\n\" (fun x y -> (x,y)) in\n let rec readBoard i acc =\n match i with\n | 0 -> List.rev acc\n | i -> let (row,col) = readPos() in\n readBoard (i-1) ((row,col)::acc)\n in\n let rec createRow queens acc =\n match queens with\n | [] -> List.rev acc\n | (row,col) :: xs -> (match (try Some (List.assoc row acc) with Not_found -> None) with\n | None -> createRow xs ((row,(col,col)) :: acc)\n | Some (minCol,maxCol) -> \n if (col < minCol)\n then\n createRow xs ((row,(col,maxCol))::(List.remove_assoc row acc))\n else if (col > maxCol) then\n createRow xs ((row,(minCol,col))::(List.remove_assoc row acc))\n else\n createRow xs acc\n )\n in\n let rec createCol queens acc =\n match queens with\n | [] -> List.rev acc\n | (row,col) :: xs -> (match (try Some (List.assoc col acc) with Not_found -> None) with\n | None -> createCol xs ((col,(row,row)) :: acc) \n | Some (minRow,maxRow) -> \n if (row < minRow)\n then\n createCol xs ((col,(row,maxRow))::(List.remove_assoc col acc))\n else if (row > maxRow) then\n createCol xs ((col,(minRow,row))::(List.remove_assoc col acc))\n else\n createCol xs acc\n )\n in\n let rec createDiag queens acc f =\n match queens with\n | [] -> List.rev acc\n | (row,col) :: xs -> let d = f row col in\n (match (try Some (List.assoc d acc) with Not_found -> None) with\n | None -> createDiag xs ((d,( (row,col), (row,col) )) :: acc) f\n | Some ((minRow,minCol),(maxRow,maxCol)) -> \n if (row < minRow)\n then \n createDiag xs ((d, ((row,col),(maxRow,maxCol))) :: (List.remove_assoc d acc)) f\n else if (row > maxRow) then\n createDiag xs ((d, ((minRow,minCol),(row,col))) :: (List.remove_assoc d acc)) f \n else\n createDiag xs acc f\n )\n in\n let rec check queens rows cols diag1 diag2 t =\n let checkRow (row,col) =\n match (try Some (List.assoc row rows) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minCol,maxCol) -> \n if (col > minCol) then\n begin\n if (col < maxCol) then 2 else 1\n end\n else \n if (col < maxCol) then 1 else 0\n in\n let checkCol (row,col) =\n match (try Some (List.assoc col cols) with Not_found -> None) with\n | None -> failwith \"nothing to see here, move on\"\n | Some (minRow,maxRow) -> \n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else \n if (row < maxRow) then 1 else 0\n in\n let checkDiag (row,col) diag f =\n let d = f row col in\n match (try Some (List.assoc d diag) with Not_found -> None) with\n | None -> failwith \"if nasa launched sattelites with bugs then\n I am allowed to fuck this up no strings attached!\"\n | Some ((minRow,minCol),(maxRow,maxCol)) ->\n if (row > minRow) then\n begin\n if (row < maxRow) then 2 else 1\n end\n else\n if (row < maxRow) then 1 else 0\n in\n match queens with\n | [] -> t\n | (row,col) :: xs -> let threats = checkRow (row,col) + checkCol (row,col) + \n (checkDiag (row,col) diag1 ( - )) +\n (checkDiag (row,col) diag2 ( + )) \n in\n (match (try Some (List.assoc threats t) with Not_found -> None) with\n | None -> check xs rows cols diag1 diag2 ((threats,1)::t)\n | Some prevThreats -> check xs rows cols diag1 diag2 ((threats,prevThreats + 1)::(List.remove_assoc threats t)))\n in\n let board = readBoard m [] in\n let rows = createRow board [] in\n let cols = createCol board [] in\n let diag1 = createDiag board [] ( - ) in\n let diag2 = createDiag board [] ( + ) in\n let tSeq = check board rows cols diag1 diag2 [] in\n let normalize lst =\n let rec aux lst i acc =\n match i,lst with\n | 9,_ -> List.rev acc\n | i,[] -> aux [] (i+1) ((i,0)::acc)\n | i,((j,v)::t) -> if (i = j) then aux t (i+1) ((j,v) :: acc)\n else\n aux ((j,v)::t) (i+1) ((i,0) :: acc)\n in\n aux lst 0 []\n in\n let tOut = normalize tSeq in\n List.iter (fun (_,v2) -> Printf.printf \"%d \" v2) tOut;\n Printf.printf \"\\n\"\n;;\n"}, {"source_code": "let read_stuff () =\n let m = Scanf.scanf \" %d %d\" (fun _ a -> a)\n and l = ref [] in\n for i = 1 to m do\n let pair = Scanf.scanf \" %d %d\" (fun a b -> (a, b, 0)) in\n l := pair :: !l;\n done;\n !l\n\nlet postprocess queens =\n let res = Array.create 10 0\n in List.iter (fun (_, _, sz) -> (res.(sz) <- (res.(sz) + 1))) queens; res\n\nlet print_res res =\n Array.iter (fun el -> Printf.printf \"%d \" el) res;\n print_endline \"\"\n\n\n\nlet cmp a b =\n if a == b\n then 0\n else if a > b\n then 1\n else -1\n\n\nlet solve_one queens pred =\n let proc2 q r =\n let (x, y, v) = q in\n if abs(pred q r) == 2 \n then (x, y, v + 1)\n else q\n in let proc = function\n | h :: t -> \n snd (List.fold_left \n (* Sprawdz wszystko oprocz glowy *)\n (fun (last, acc) h -> \n (h, (proc2 h last)::acc))\n (h, [h])\n t)\n | foo -> foo\n and sorted = List.sort pred queens\n in proc (proc (sorted))\n\n\nlet rec solve queens preds = \n match preds with \n | [] -> queens\n | p0 :: ps -> solve (solve_one queens p0) ps\n \nlet oq a b = \n if a == 0 then 2 * b else a\n;;\n\nlet predicates =\n [\n (fun (x1, y1, _) (x2, y2, _) -> oq (cmp x1 x2) (cmp y1 y2));\n (fun (x1, y1, _) (x2, y2, _) -> oq (cmp y1 y2) (cmp x1 x2));\n (fun (x1, y1, _) (x2, y2, _) -> oq (cmp (x1 - y1) (x2 - y2)) (cmp (x1 + y1) (x2 + y2)));\n (fun (x1, y1, _) (x2, y2, _) -> oq (cmp (x1 + y1) (x2 + y2)) (cmp (x1 - y1) (x2 - y2)))\n ]\nin\n print_res (postprocess (solve (read_stuff()) predicates))\n\n\n"}], "src_uid": "f19e7f33396d27e1eba2c46b6b5e706a"} {"nl": {"description": "Consider a table of size $$$n \\times m$$$, initially fully white. Rows are numbered $$$1$$$ through $$$n$$$ from top to bottom, columns $$$1$$$ through $$$m$$$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 115$$$) \u2014 the number of rows and the number of columns in the table. The $$$i$$$-th of the next $$$n$$$ lines contains a string of $$$m$$$ characters $$$s_{i1} s_{i2} \\ldots s_{im}$$$ ($$$s_{ij}$$$ is 'W' for white cells and 'B' for black cells), describing the $$$i$$$-th row of the table.", "output_spec": "Output two integers $$$r$$$ and $$$c$$$ ($$$1 \\le r \\le n$$$, $$$1 \\le c \\le m$$$) separated by a space \u2014 the row and column numbers of the center of the black square.", "sample_inputs": ["5 6\nWWBBBW\nWWBBBW\nWWBBBW\nWWWWWW\nWWWWWW", "3 3\nWWW\nBWW\nWWW"], "sample_outputs": ["2 4", "2 1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n let board = Array.init n read_string in\n\n let xtot = ref 0 in\n let ytot = ref 0 in\n let tot = ref 0 in\n \n for i=0 to n-1 do\n for j=0 to m-1 do\n if board.(i).[j] = 'B' then (\n\ttot := !tot + 1;\n\txtot := !xtot + i + 1;\n\tytot := !ytot + j + 1\n )\n done\n done;\n\n printf \"%d %d\\n\" (!xtot / !tot) (!ytot / !tot)\n"}], "negative_code": [], "src_uid": "524273686586cdeb7827ffc1ad59d85a"} {"nl": {"description": "Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.Valera needs to know if the letters written on the square piece of paper form letter \"X\". Valera's teacher thinks that the letters on the piece of paper form an \"X\", if: on both diagonals of the square paper all letters are the same; all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009<\u2009300; n is odd). Each of the next n lines contains n small English letters \u2014 the description of Valera's paper.", "output_spec": "Print string \"YES\", if the letters on the paper form letter \"X\". Otherwise, print string \"NO\". Print the strings without quotes.", "sample_inputs": ["5\nxooox\noxoxo\nsoxoo\noxoxo\nxooox", "3\nwsw\nsws\nwsw", "3\nxpx\npxp\nxpe"], "sample_outputs": ["NO", "YES", "NO"], "notes": null}, "positive_code": [{"source_code": "let n=read_int();;\n\nlet tab=Array.make n \" \";;\n\nfor i=0 to n-1 do\n tab.(i)<-read_line()\ndone;;\n\nlet a=tab.(0).[0];;\nlet v=tab.(0).[1];;\nlet b=ref true;;\n\nfor i=0 to n-1 do\n for j=0 to n-1 do\n if (i=j)||(i+j=n-1) then b:= !b&&(tab.(i).[j]=a)\n else b:= !b&&(tab.(i).[j]=v)\n done\ndone;;\n\nif a=v then b:=false;;\n\nif !b then print_string \"YES\" else print_string \"NO\";;"}, {"source_code": "let n = Scanf.scanf \"%d\\n\" (fun x -> x);;\n\nlet tab = Array.init n (fun _ -> Scanf.scanf \"%s\\n\" (fun x -> x));;\n\nlet valide = ref (tab.(0).[0] <> tab.(0).[1]);;\n\nfor i = 0 to n-1 do\nfor j = 0 to n-1 do\n if i = j\n then (if tab.(i).[j] <> tab.(0).[0] then valide := false)\n else if n-j-1 = i\n then (if tab.(i).[j] <> tab.(0).[0] then valide := false)\n else\n if tab.(i).[j] <> tab.(0).[1] then valide := false\ndone;\ndone;\n\nif !valide\n then print_endline \"YES\"\n else print_endline \"NO\""}], "negative_code": [{"source_code": "let n=read_int();;\n\nlet tab=Array.make n \" \";;\n\nfor i=0 to n-1 do\n tab.(i)<-read_line()\ndone;;\n\nlet a=tab.(0).[0];;\nlet v=tab.(0).[1];;\nlet b=ref true;;\n\nfor i=0 to n-1 do\n for j=0 to n-1 do\n if (i=j)||(i+j=n-1) then b:= !b&&(tab.(i).[j]=a)\n else b:= !b&&(tab.(i).[j]=v)\n done\ndone;;\n\nif !b then print_string \"YES\" else print_string \"NO\";;"}, {"source_code": "let n = Scanf.scanf \"%d\\n\" (fun x -> x);;\n\nlet tab = Array.init n (fun _ -> Scanf.scanf \"%s\\n\" (fun x -> x));;\n\nlet valide = ref true;;\n\nfor i = 0 to n-1 do\nfor j = 0 to n-1 do\n if i = j\n then (if tab.(i).[j] <> tab.(0).[0] then valide := false)\n else if n-j-1 = i\n then (if tab.(i).[j] <> tab.(0).[0] then valide := false)\n else\n if tab.(i).[j] <> tab.(0).[1] then valide := false\ndone;\ndone;\n\nif !valide\n then print_endline \"YES\"\n else print_endline \"NO\""}], "src_uid": "02a9081aed29ea92aae13950a6d48325"} {"nl": {"description": "Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin \"ConneR\" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \\le n \\le 10^9$$$, $$$1 \\le s \\le n$$$, $$$1 \\le k \\le \\min(n-1, 1000)$$$)\u00a0\u2014 respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \\ldots, a_k$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.", "output_spec": "For each test case print a single integer\u00a0\u2014 the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.", "sample_inputs": ["5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77"], "sample_outputs": ["2\n0\n4\n0\n2"], "notes": "NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nopen Int64\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\n\nlet next_int () = Scanf.scanf \" %d\" (fun x -> x)\nlet next_long () = Scanf.scanf \" %Ld\" (fun x -> x)\nlet next_long3 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun x y z -> (x, y, z))\n\nlet fill_list (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b list =\n let rec aux (idx: int): 'b list =\n if idx >= n then [] else (f (idx, i) :: aux (idx + 1)) in\n aux 0\n\nlet fill_arr (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b array =\n let k = Array.make n (f (0, i)) in\n for idx = 1 to n - 1 do\n k.(idx) <- f (idx, i)\n done;\n k\n\nlet () =\n let m () =\n let lmax = 6000 in\n let lmid = 3000 in\n let t = next_int () in\n for _ = 0 to t - 1 do\n let n, z, k = next_long3() in\n let arr = fill_arr (to_int k) (fun _ -> next_long()) () in\n let opened = fill_arr lmax (fun (i, ()) -> 1L <= (of_int i) ++ z -- of_int lmid && (of_int i) ++ z -- of_int lmid <= n) () in\n Array.iter (fun x ->\n let idx = (to_int (x -- z ++ of_int lmid)) in\n if 0 <= idx && idx < lmax then\n opened.(idx) <- false\n else \n ()\n ) arr;\n let k = fill_list lmid (fun (x, ()) -> x) ()\n |> List.find (fun x ->\n let up, down = lmid + x, lmid - x in\n let upb = if 0 <= up && up < lmax then\n opened.(up) else \n false in\n let downb = if 0 <= down && down < lmax then\n opened.(down) else\n false in\n upb || downb\n ) in\n printf \"%d\\n\" k\n done;\n in \n try m()\n with e ->\n let msg = Printexc.to_string e\n and stack = Printexc.get_backtrace () in\n printf \"there was an error: %s%s\\n\" msg stack;\n ()\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\nopen Int64\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\n\nlet next_int () = Scanf.scanf \" %d\" (fun x -> x)\nlet next_long () = Scanf.scanf \" %Ld\" (fun x -> x)\nlet next_long3 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun x y z -> (x, y, z))\n\nlet fill_list (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b list =\n let rec aux (idx: int): 'b list =\n if idx >= n then [] else (f (idx, i) :: aux (idx + 1)) in\n aux 0\n\nlet fill_arr (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b array =\n let k = Array.make n (f (0, i)) in\n for idx = 1 to n - 1 do\n k.(idx) <- f (idx, i)\n done;\n k\n\nlet () =\n let m () =\n let t = next_int () in\n for _ = 0 to t - 1 do\n let n, z, k = next_long3() in\n let arr = fill_arr (to_int k) (fun _ -> next_long()) () in\n let opened = fill_arr 2000 (fun (i, ()) -> 1L <= (of_int i) ++ z -- 1000L && (of_int i) ++ z -- 1000L <= n) () in\n Array.iter (fun x ->\n let idx = (to_int (x -- z ++ 1000L)) in\n if 0 <= idx && idx < 2000 then\n opened.(idx) <- false\n else \n ()\n ) arr;\n let k = fill_list 1000 (fun (x, ()) -> x) ()\n |> List.find (fun x ->\n let up, down = 1000 + x, 1000 - x in\n let upb = if 0 <= up && up < 2000 then\n opened.(up) else \n false in\n let downb = if 0 <= down && down < 2000 then\n opened.(down) else\n false in\n upb || downb\n ) in\n printf \"%d\\n\" k\n done;\n in \n try m()\n with e ->\n let msg = Printexc.to_string e\n and stack = Printexc.get_backtrace () in\n printf \"there was an error: %s%s\\n\" msg stack;\n ()\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet next_int () = Scanf.scanf \" %d\" (fun x -> x)\nlet next_int3 () = Scanf.scanf \" %d %d %d\" (fun x y z -> (x, y, z))\n\nlet iter_list (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b list =\n let rec aux (idx: int): 'b list =\n if idx >= n then [] else (f (idx, i) :: aux (idx + 1)) in\n aux 0\n\nlet iter_arr (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b array =\n let k = Array.make n (f (0, i)) in\n for idx = 0 to n - 1 do\n k.(idx) <- f (idx, i)\n done;\n k\n\nlet () =\n let t = next_int () in\n for _ = 0 to t - 1 do\n let n, z, k = next_int3() in\n let arr = Array.make k 0 in\n for i = 0 to k - 1 do\n arr.(i) <- next_int ()\n done;\n let opened = Array.make 2000 true in\n for i = 0 to 1000 - z do\n opened.(i) <- false\n done;\n Array.iter (fun x ->\n let idx = x - z + 1000 in\n if 0 <= idx && idx < 2000 then\n opened.(idx) <- false\n else \n ()\n ) arr;\n let k = iter_list 1000 (fun (x, ()) -> x) ()\n |> List.find (fun x ->\n let up, down = 1000 + x, 1000 - x in\n let upb = if 0 <= up && up < 2000 then\n opened.(up) else \n false in\n let downb = if 0 <= down && down < 2000 then\n opened.(down) else\n false in\n upb || downb\n ) in\n printf \"%d\\n\" k\n done;\n"}, {"source_code": "open Printf\nopen Scanf\nopen Int64\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\n\nlet next_int () = Scanf.scanf \" %d\" (fun x -> x)\nlet next_long () = Scanf.scanf \" %Ld\" (fun x -> x)\nlet next_long3 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun x y z -> (x, y, z))\n\nlet fill_list (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b list =\n let rec aux (idx: int): 'b list =\n if idx >= n then [] else (f (idx, i) :: aux (idx + 1)) in\n aux 0\n\nlet fill_arr (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b array =\n let k = Array.make n (f (0, i)) in\n for idx = 1 to n - 1 do\n k.(idx) <- f (idx, i)\n done;\n k\n\nlet () =\n let m () =\n let lmax = 6000 in\n let lmid = 3000 in\n let t = next_int () in\n for _ = 0 to t - 1 do\n let n, z, k = next_long3() in\n let arr = fill_arr (to_int k) (fun _ -> next_long()) () in\n let opened = fill_arr lmax (fun (i, ()) -> 1L <= (of_int i) ++ z -- of_int lmid && (of_int i) ++ z -- of_int lmid <= n) () in\n Array.iter (fun x ->\n let idx = (to_int (x -- z ++ of_int lmid)) in\n if 0 <= idx && idx < lmax then\n opened.(idx) <- false\n else \n ()\n ) arr;\n let k = fill_list 1000 (fun (x, ()) -> x) ()\n |> List.find (fun x ->\n let up, down = lmid + x, lmid - x in\n let upb = if 0 <= up && up < lmax then\n opened.(up) else \n false in\n let downb = if 0 <= down && down < lmax then\n opened.(down) else\n false in\n upb || downb\n ) in\n printf \"%d\\n\" k\n done;\n in \n try m()\n with e ->\n let msg = Printexc.to_string e\n and stack = Printexc.get_backtrace () in\n printf \"there was an error: %s%s\\n\" msg stack;\n ()\n"}, {"source_code": "open Printf\nopen Scanf\nopen Int64\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\n\nlet next_int () = Scanf.scanf \" %d\" (fun x -> x)\nlet next_long () = Scanf.scanf \" %Ld\" (fun x -> x)\nlet next_long3 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun x y z -> (x, y, z))\n\nlet fill_list (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b list =\n let rec aux (idx: int): 'b list =\n if idx >= n then [] else (f (idx, i) :: aux (idx + 1)) in\n aux 0\n\nlet fill_arr (n: int) (f: (int * 'a) -> 'b) (i: 'a): 'b array =\n let k = Array.make n (f (0, i)) in\n for idx = 1 to n - 1 do\n k.(idx) <- f (idx, i)\n done;\n k\n\nlet () =\n let m () =\n let t = next_int () in\n for _ = 0 to t - 1 do\n let n, z, k = next_long3() in\n let arr = fill_arr (to_int k) (fun _ -> next_long()) () in\n let opened = fill_arr 2000 (fun (i, ()) -> 1L <= (of_int i) ++ z -- 1000L && (of_int i) ++ z -- 1000L <= n) () in\n Array.iter (fun x ->\n let idx = (to_int (x -- z ++ 1000L)) in\n if 0 <= idx && idx < 2000 then\n opened.(idx) <- false\n else \n ()\n ) arr;\n let k = fill_list 1000 (fun (x, ()) -> x) ()\n |> List.find (fun x ->\n let up, down = 1000 + x, 1000 - x in\n let upb = if 0 <= up && up < 2000 then\n opened.(up) else \n false in\n let downb = if 0 <= down && down < 2000 then\n opened.(down) else\n false in\n upb || downb\n ) in\n printf \"%d\\n\" k\n done;\n in \n try m()\n with e ->\n let msg = Printexc.to_string e\n and stack = Printexc.get_backtrace () in\n Printf.eprintf \"there was an error: %s%s\\n\" msg stack;\n ()\n"}], "src_uid": "faae9c0868b92b2355947c9adcaefb43"} {"nl": {"description": "Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.", "input_spec": "The first line of input will contain three integers n, m and k (1\u2009\u2264\u2009n\u2009\u2264\u20091\u2009000, 0\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the number of vertices and edges in the graph, and the number of vertices that are homes of the government. The next line of input will contain k integers c1,\u2009c2,\u2009...,\u2009ck (1\u2009\u2264\u2009ci\u2009\u2264\u2009n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world. The following m lines of input will contain two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n). This denotes an undirected edge between nodes ui and vi. It is guaranteed that the graph described by the input is stable.", "output_spec": "Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.", "sample_inputs": ["4 1 2\n1 3\n1 2", "3 3 1\n2\n1 2\n1 3\n2 3"], "sample_outputs": ["2", "0"], "notes": "NoteFor the first sample test, the graph looks like this: Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.For the second sample test, the graph looks like this: We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple."}, "positive_code": [{"source_code": "let read_int() = Scanf.scanf \" %d\" (fun x -> x) in\nlet n = read_int()\nand m = read_int()\nand k = read_int()\nand x = ref 0\nand y = ref 0\nand z = ref 0\nand f = fun x -> x * (x - 1) / 2 in\nlet a = Array.make (n + 1) []\nand g = Array.make (n + 1) false\nand s = Array.make (n + 1) 0\nand t = Array.make (n + 1) 0 in\n\nbegin\n for i = 1 to k do\n let u = read_int() in\n g.(u) <- true\n done;\n for i = 1 to m do\n let u = read_int()\n and v = read_int() in\n begin\n a.(u) <- v :: a.(u);\n a.(v) <- u :: a.(v)\n end\n done;\n\n let rec floodfill u c = match s.(u), a.(u) with\n | 0, _ -> (s.(u) <- c; floodfill u c)\n | _, [] -> ()\n | _, v :: vs -> \n begin\n a.(u) <- vs;\n floodfill u c;\n floodfill v c;\n end\n in\n\n for u = 1 to n do\n floodfill u u;\n t.(s.(u)) <- t.(s.(u)) + 1;\n g.(s.(u)) <- g.(s.(u)) || g.(u)\n done;\n\n for u = 1 to n do\n let p = t.(u) in\n if g.(u) then\n begin\n x := !x + f p;\n y := max (!y) p\n end\n else\n z := !z + p\n done;\n \n let r = !x - f !y + f (!y + !z) - m in\n print_int r;\nend\n"}], "negative_code": [], "src_uid": "6cf43241b14e4d41ad5b36572f3b3663"} {"nl": {"description": "You are given a permutation of n numbers p1,\u2009p2,\u2009...,\u2009pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l\u2009\u2264\u2009r) and reverse the order of the elements pl,\u2009pl\u2009+\u20091,\u2009...,\u2009pr. Your task is to find the expected value of the number of inversions in the resulting permutation.", "input_spec": "The first line of input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u2009109). The next line contains n integers p1,\u2009p2,\u2009...,\u2009pn \u2014 the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem G1 (3 points), the constraints 1\u2009\u2264\u2009n\u2009\u2264\u20096, 1\u2009\u2264\u2009k\u2009\u2264\u20094 will hold. In subproblem G2 (5 points), the constraints 1\u2009\u2264\u2009n\u2009\u2264\u200930, 1\u2009\u2264\u2009k\u2009\u2264\u2009200 will hold. In subproblem G3 (16 points), the constraints 1\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u2009109 will hold. ", "output_spec": "Output the answer with absolute or relative error no more than 1e\u2009-\u20099.", "sample_inputs": ["3 1\n1 2 3", "3 4\n1 3 2"], "sample_outputs": ["0.833333333333333", "1.458333333333334"], "notes": "NoteConsider the first sample test. We will randomly pick an interval of the permutation (1,\u20092,\u20093) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability we will inverse the first two elements' order and obtain the permutation (2,\u20091,\u20093) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1,\u20093,\u20092) with one inversion. Finally, with probability the randomly picked interval will contain all elements, leading to the permutation (3,\u20092,\u20091) with 3 inversions. Hence, the expected number of inversions is equal to ."}, "positive_code": [{"source_code": "let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet construct_a n = \n let nn = n*n in\n let a = Array.make_matrix nn nn 0.0 in\n\n (* the pair of positions (i,j) is mapped into i+j*n of the vector *)\n\n (* the flips in the permutation are for a range [p,q], where p <= q *)\n (* for pair (i,j) and for each flip [p,q] see what happens to (i,j) and\n add this probability to the matrix a *)\n\n let ind i j = i + j*n in\n let fn = float n in\n let pr = 2.0 /. (fn *. (fn +. 1.0)) in\n\n for i=0 to n-1 do\n for j=0 to n-1 do\n if i <> j then (\n\tfor p=0 to n-1 do\n\t for q=p to n-1 do\n\t let map i = if i

q then i else q - (i-p) in\n\t let (i',j') = (map i, map j) in\n\t a.(ind i' j').(ind i j) <- a.(ind i' j').(ind i j) +. pr\n\t done\n\tdone\n )\n done\n done;\n a\n\nlet () = \n let n = read_int () in\n let k = read_int () in\n let perm = Array.init n (fun _ -> read_int()) in\n let nn = n*n in\n\n let ind i j = i + j*n in\n let dot a b = sum 0 (nn-1) (fun i -> a.(i) *. b.(i)) in\n\n let mult a b = \n let c = Array.make nn 0.0 in\n\n for i=0 to nn-1 do\n for j=0 to nn-1 do\n\tc.(i) <- c.(i) +. a.(i).(j) *. b.(j)\n done\n done;\n c\n in\n\n let power a b p =\n let rec loop ac i = if i=p then ac else\n\tloop (mult a ac) (i+1)\n in\n loop b 0\n in\n\n let a = construct_a n in\n\n let b = Array.make nn 0.0 in\n let b' = Array.make nn 0.0 in\n\n for i=0 to n-2 do\n for j=i+1 to n-1 do\n let ii = ind i j in\n if perm.(i) < perm.(j) \n then b.(ii) <- 1.0 \n else b'.(ii) <- 1.0 \n done\n done;\n\n let c = power a b k in\n let c' = power a b' k in\n\n let s = Array.make nn 0.0 in\n let s' = Array.make nn 0.0 in\n\n for i=0 to n-1 do\n for j=0 to n-1 do\n let ii = ind i j in\n if ij then s'.(ii) <- 1.0\n done\n done;\n\n printf \"%12.12f\\n\" ((dot c' s) +. (dot c s'))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet construct_a n = \n let nn = n*n in\n let a = Array.make_matrix nn nn 0.0 in\n\n (* the pair of positions (i,j) is mapped into i+j*n of the vector *)\n\n (* the flips in the permutation are for a range [p,q], where p <= q *)\n (* for pair (i,j) and for each flip [p,q] see what happens to (i,j) and\n add this probability to the matrix a *)\n\n let ind i j = i + j*n in\n\n let fn = float n in\n let pr = 2.0 /. (fn *. (fn +. 1.0)) in\n\n for i=0 to n-1 do\n for j=0 to n-1 do\n if i <> j then (\n\tfor p=0 to n-1 do\n\t for q=p to n-1 do\n\t let map i = if i

q then i else q - (i-p) in\n\t let (i',j') = (map i, map j) in\n\t a.(ind i' j').(ind i j) <- a.(ind i' j').(ind i j) +. pr\n\t done\n\tdone\n )\n done\n done;\n a\n\nlet () = \n let n = read_int () in\n let k = read_int () in\n let perm = Array.init n (fun _ -> read_int()) in\n \n let nn = n*n in\n\n let mult a b = \n let c = Array.make nn 0.0 in\n\n for i=0 to nn-1 do\n for j=0 to nn-1 do\n\tc.(i) <- c.(i) +. a.(i).(j) *. b.(j)\n done\n done;\n c\n in\n\n let power a b p =\n let rec loop ac i = if i=p then ac else\n\tloop (mult a ac) (i+1)\n in\n loop b 0\n in\n\n let a = construct_a n in\n\n let ind i j = i + j*n in\n let unind ii = (ii - n*(ii/n), ii/n) in\n\n let exp = ref 0.0 in\n\n for i=0 to n-2 do\n for j=i+1 to n-1 do\n let flipprob = ref 0.0 in\n let b = Array.init nn (fun ii-> if ii = ind i j then 1.0 else 0.0) in\n let c = power a b k in\n for ii=0 to nn-1 do\n\tlet (i',j') = unind ii in\n\tif i'<>j' && ((i' (i s) in\n let t = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n t.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n done;\n in\n let bs x =\n let l = ref (-1) in\n let r = ref n in\n while !l < !r - 1 do\n\tlet m = (!l + !r) / 2 in\n\t if t.(m) <= x\n\t then l := m\n\t else r := m\n done;\n !r\n in\n let a = Array.make (n + 1) 0 in\n for i = 1 to n do\n let tt = t.(i - 1) in\n let p90 = bs (tt - 90) in\n let p1440 = bs (tt - 1440) in\n\ta.(i) <- a.(i - 1) + 20;\n\tif p90 < i then (\n\t a.(i) <- min a.(i) (a.(p90) + 50)\n\t);\n\tif p1440 < i then (\n\t a.(i) <- min a.(i) (a.(p1440) + 120)\n\t);\n\tPrintf.printf \"%d\\n\" (a.(i) - a.(i - 1));\n done;\n"}], "negative_code": [], "src_uid": "13ffa0ddaab8a41b952a3c2320bd0c02"} {"nl": {"description": "One day two students, Grisha and Diana, found themselves in the university chemistry lab. In the lab the students found n test tubes with mercury numbered from 1 to n and decided to conduct an experiment.The experiment consists of q steps. On each step, one of the following actions occurs: Diana pours all the contents from tube number pi and then pours there exactly xi liters of mercury. Let's consider all the ways to add vi liters of water into the tubes; for each way let's count the volume of liquid (water and mercury) in the tube with water with maximum amount of liquid; finally let's find the minimum among counted maximums. That is the number the students want to count. At that, the students don't actually pour the mercury. They perform calculations without changing the contents of the tubes. Unfortunately, the calculations proved to be too complex and the students asked you to help them. Help them conduct the described experiment.", "input_spec": "The first line contains two integers n and q (1\u2009\u2264\u2009n,\u2009q\u2009\u2264\u2009105) \u2014 the number of tubes ans the number of experiment steps. The next line contains n space-separated integers: h1,\u2009h2,\u2009...,\u2009hn (0\u2009\u2264\u2009hi\u2009\u2264\u2009109), where hi is the volume of mercury in the \u0456-th tube at the beginning of the experiment. The next q lines contain the game actions in the following format: A line of form \"1 pi xi\" means an action of the first type (1\u2009\u2264\u2009pi\u2009\u2264\u2009n;\u00a00\u2009\u2264\u2009xi\u2009\u2264\u2009109). A line of form \"2 vi\" means an action of the second type (1\u2009\u2264\u2009vi\u2009\u2264\u20091015). It is guaranteed that there is at least one action of the second type. It is guaranteed that all numbers that describe the experiment are integers.", "output_spec": "For each action of the second type print the calculated value. The answer will be considered correct if its relative or absolute error doesn't exceed 10\u2009-\u20094.", "sample_inputs": ["3 3\n1 2 0\n2 2\n1 2 1\n2 3", "4 5\n1 3 0 1\n2 3\n2 1\n1 3 2\n2 3\n2 4"], "sample_outputs": ["1.50000\n1.66667", "1.66667\n1.00000\n2.33333\n2.66667"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( -- ) a b = a - b\nlet ( ++ ) a b = a + b\nlet ( * ) a b = Int64.mul a b\nlet ( + ) a b = Int64.add a b\nlet ( - ) a b = Int64.sub a b\n\ntype tree = \n Empty | Node of tree * (int64*int64*int64) * tree * int64\n(* left (h,total,y) right size *)\n(* what is stored in the node is the h value (the amount in this tube)\n and the total of all the h's in the subtree rooted here.\n and the h value of the leftmost node in the subtree rooted here.\n*)\n\ntype direction = Left | Right\ntype path = Item of tree * direction\n\nlet size = function Empty -> 0L | Node(_, _, _, size) -> size\n\nlet getkey = function\n | Empty -> (0L,0L,0L)\n | Node(_, key, _, _) -> key\n\nlet getroot = function \n | Node(left, k, right, _) -> (left, k, right)\n | _ -> failwith \"called getroot on Empty\"\n\nlet glue (l, (h,_,_), r) = \n let (tl,y) = match l with Empty -> (0L,h) | Node(_,(_,tl,y),_,_) -> (tl,y) in\n let (_,tr,_) = getkey r in\n Node (l, (h, tl+tr+h, y), r, (size l) + (size r) + 1L)\n\nlet snip = function\n | Node(l, (h,_,_), r, s) -> Node(l, (h,0L,0L), r, 0L)\n | _ -> failwith \"called snip on Empty\"\n\nlet connect (l, key, r) = Node(l, key, r, 0L)\n\nlet splay t rank = \n (* splay the node of the given rank (which are numbered starting at 0)\n to the root *)\n\n (* The following splay function takes as input the currently splayed\n tree (so far) t, and a path list. It takes one or two steps up,\n and calls itself recursively. *)\n let rec rsplay = function\n | (t,[]) -> glue (getroot t)\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->\n\trsplay (connect(tL,tK,glue(tR,bK,glue(bR,cK,cR))), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->\n rsplay (connect(glue(glue(cL,cK,bL), bK, tL),tK,tR), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->\n\trsplay (connect(tL,tK,glue(tR,bK,bR)), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->\n\trsplay (connect(glue(bL,bK,tL),tK,tR), tail)\n\t \n | (_,_) -> failwith \"Splay_failed (Should not happen)\"\n in\n\n let rec build_path t r path = (* r = the rank of the target node in the current tree t *)\n let t = snip t in\n match t with \n\t| Empty -> failwith \"failed build_path\"\n\t| Node(left, _, right, _) ->\n\t let sl = size left in\n\t if r < sl then build_path left r (Item(t, Left)::path)\n\t else if r = sl then (t,path)\n\t else build_path right (r-sl-1L) (Item(t, Right)::path)\n in\n if t=Empty then t else rsplay (build_path t rank [])\n\nlet append t h = \n glue(t, (h,0L,0L), Empty)\n\n(* let key_of_rank t rank = getkey (splay t rank) *)\n\nlet rec findit x tabove sabove v =\n(* x = the current node\n tabove = total left of x from above \n sabove = size of the stuff to the left of x from above\n this returns the rightmost (key,fill_volume) pair such\n that fill_volume < v\n*)\n match x with Empty -> failwith \"findit called on empty node\"\n | Node (l, (h,_,_), r, _) -> \n let (_,t,_) = getkey l in\n let t = t + tabove in\n let s = sabove + (size l) in\n let fvx = h*s - t in\n if fvx >= v then findit l tabove sabove v\n else if r=Empty then (s,fvx) else\n\tlet (_,_,y) = getkey r in\n\tlet fvy = y*(s+1L) - (t+h) in\n\tif fvy >= v then (s,fvx)\n\telse findit r (t+h) (s+1L) v\n\nlet rec findh x h sabove c =\n (* retrns the rank of the given h in the tree,\n or the last one touched on a search for it *)\n match x with \n | Empty -> sabove - c\n | Node(l, (hx,_,_), r, _) -> \n if h < hx then findh l h sabove 0L\n else if h > hx then findh r h (sabove + (size l) + 1L) 1L\n else sabove + (size l)\n\nlet join l r = \n if r=Empty then l else\n let r = snip (splay r 0L) in\n let (_,key,rr) = getroot r in\n glue (l, key, rr)\n\nlet fill_height root v =\n let (s,fvx) = findit root 0L 0L v in\n let root = splay root s in\n let (h,_,_) = getkey root in\n let vol = v - fvx in\n let ans = (Int64.to_float h) +. (Int64.to_float vol)/.(Int64.to_float (s+1L)) in\n (root, ans)\n\nlet update t h0 h1 =\n (* replace h0 with h1 in the data structure *)\n let t = splay t (findh t h1 0L 0L) in\n let (l,(h,_,_),r) = getroot t in\n let t = if h <= h1 then glue (glue (l, (h,0L,0L), Empty), (h1,0L,0L), r)\n else glue (l, (h1,0L,0L), (glue (Empty, (h,0L,0L), r))) in\n let t = splay t (findh t h0 0L 0L) in\n let (l, _, r) = getroot t in\n join l r\n\n(*-------------------------------------------------------------------------*)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let q = read_int () in\n\n let root = ref Empty in\n let h = Array.init n (fun _ -> read_long()) in\n let hh = Array.copy h in\n Array.sort compare hh;\n\n for i=0 to n--1 do\n root := append !root hh.(i)\n done;\n\n for i=1 to q do\n match read_int() with\n | 1 -> let p = read_int () in \n\t let x = read_long () in\n\t root:= update !root h.(p--1) x;\n\t h.(p--1) <- x\n\n | 2 -> let v = read_long() in\n\t let (t,ans) = fill_height !root v in\n\t root := t;\n\t printf \"%f\\n\" ans\n\t \n | _ -> failwith \"bad operation\"\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( -- ) a b = a - b\nlet ( ++ ) a b = a + b\nlet ( * ) a b = Int64.mul a b\nlet ( + ) a b = Int64.add a b\nlet ( - ) a b = Int64.sub a b\n\ntype tree = \n Empty | Node of tree * (int64*int64*int64) * tree * int64\n(* left (h,total,y) right size *)\n(* what is stored in the node is the h value (the amount in this tube)\n and the total of all the h's in the subtree rooted here.\n and the h value of the leftmost node in the subtree rooted here.\n*)\n\ntype direction = Left | Right\ntype path = Item of tree * direction\n\nlet size = function Empty -> 0L | Node(_, _, _, size) -> size\n\nlet getkey = function\n | Empty -> (0L,0L,0L)\n | Node(_, key, _, _) -> key\n\nlet getroot = function \n | Node(left, k, right, _) -> (left, k, right)\n | _ -> failwith \"called getroot on Empty\"\n\nlet glue (l, (h,_,_), r) = \n let (tl,y) = match l with Empty -> (0L,h) | Node(_,(_,tl,y),_,_) -> (tl,y) in\n let (_,tr,_) = getkey r in\n Node (l, (h, tl+tr+h, y), r, (size l) + (size r) + 1L)\n\nlet snip = function\n | Node(l, (h,_,_), r, s) -> Node(l, (h,0L,0L), r, 0L)\n | _ -> failwith \"called snip on Empty\"\n\nlet connect (l, key, r) = Node(l, key, r, 0L)\n\nlet splay t rank = \n (* splay the node of the given rank (which are numbered starting at 0)\n to the root *)\n\n (* The following splay function takes as input the currently splayed\n tree (so far) t, and a path list. It takes one or two steps up,\n and calls itself recursively. *)\n let rec rsplay = function\n | (t,[]) -> glue (getroot t)\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->\n\trsplay (connect(tL,tK,glue(tR,bK,glue(bR,cK,cR))), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->\n rsplay (connect(glue(glue(cL,cK,bL), bK, tL),tK,tR), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->\n\trsplay (connect(tL,tK,glue(tR,bK,bR)), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->\n\trsplay (connect(glue(bL,bK,tL),tK,tR), tail)\n\t \n | (_,_) -> failwith \"Splay_failed (Should not happen)\"\n in\n\n let rec build_path t r path = (* r = the rank of the target node in the current tree t *)\n let t = snip t in\n match t with \n\t| Empty -> failwith \"failed build_path\"\n\t| Node(left, _, right, _) ->\n\t let sl = size left in\n\t if r < sl then build_path left r (Item(t, Left)::path)\n\t else if r = sl then (t,path)\n\t else build_path right (r-sl-1L) (Item(t, Right)::path)\n in\n if t=Empty then t else rsplay (build_path t rank [])\n\nlet append t h = \n glue(t, (h,0L,0L), Empty)\n\n(* let key_of_rank t rank = getkey (splay t rank) *)\n\nlet rec findit x tabove sabove v =\n(* x = the current node\n tabove = total left of x from above \n sabove = size of the stuff to the left of x from above\n assumes there's an infinite height node on the right as a sentinal\n*)\n match x with Empty -> failwith \"findit called on empty node\"\n | Node (l, (h,_,_), r, _) -> \n let (_,t,_) = getkey l in\n let t = t + tabove in\n let s = sabove + (size l) in\n let fvx = h*s - t in\n if fvx >= v then findit l tabove sabove v\n else \n\tlet (_,_,y) = getkey r in\n\tlet fvy = y*(s+1L) - (t+h) in\n\tif r=Empty || fvy >= v then (s,fvx)\n\telse findit r (t+h) (s+1L) v\n\nlet rec findh x h sabove c =\n (* retrns the rank of the given h in the tree,\n or the last one touched on a search for it *)\n match x with \n | Empty -> sabove - c\n | Node(l, (hx,_,_), r, _) -> \n if h < hx then findh l h sabove 0L\n else if h > hx then findh r h (sabove + (size l) + 1L) 1L\n else sabove + (size l)\n\nlet join l r = \n if r=Empty then l else\n let r = snip (splay r 0L) in\n let (_,key,rr) = getroot r in\n glue (l, key, rr)\n\nlet fill_height root v =\n let (s,fvx) = findit root 0L 0L v in\n let root = splay root s in\n let (h,_,_) = getkey root in\n let vol = v - fvx in\n let ans = (Int64.to_float h) +. (Int64.to_float vol)/.(Int64.to_float (s+1L)) in\n (root, ans)\n\nlet update t h0 h1 =\n (* replace h0 with h1 in the data structure *)\n let t = splay t (findh t h0 0L 0L) in\n let (l, _, r) = getroot (snip t) in\n let t = join l r in\n let t = splay t (findh t h1 0L 0L) in\n let (l,(h,_,_),r) = getroot (snip t) in\n if h <= h1 then glue (glue (l, (h,0L,0L), Empty), (h1,0L,0L), r)\n else glue (l, (h1,0L,0L), (glue (Empty, (h,0L,0L), r)))\n\n(*-------------------------------------------------------------------------*)\n\n(* Debugging code.....\n\nlet rec printtree t depth = \n match t with Empty -> ()\n | Node(ll, (h,t,y), rr, s) -> (\n printtree rr (depth+1);\n let rec loop i = if i=0 then () else (Printf.printf \" \"; loop (i-1)) in\n loop depth; Printf.printf \"(%d,%d,%d) %d\\n\" h t y s;\n printtree ll (depth+1)\n )\n\nlet rec maketree t li = match li with [] -> t\n | h::rest -> maketree (append t h) rest\n\nlet t = maketree Empty [1;1;2;2;6]\nlet _ = printtree t 0\n\nlet t = splay t 2\nlet _ = printtree t 0\n\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\nlet t = update t 1 3\n\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\nlet t = update t 2 1\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\nlet t = update t 6 1\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\nlet t = update t 1 6\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\n*)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet inf = 1_000_000_001L\n\nlet () = \n let n = read_int () in\n let q = read_int () in\n\n let root = ref Empty in\n let h = Array.init n (fun _ -> read_long()) in\n let hh = Array.copy h in\n Array.sort compare hh;\n\n for i=0 to n--1 do\n root := append !root hh.(i)\n done;\n\n root := append !root inf;\n\n for i=1 to q do\n match read_int() with\n | 1 -> let p = read_int () in \n\t let x = read_long () in\n\t root:= update !root h.(p--1) x;\n\t h.(p--1) <- x\n\n | 2 -> let v = read_long() in\n\t let (t,ans) = fill_height !root v in\n\t root := t;\n\t printf \"%f\\n\" ans\n\t \n | _ -> failwith \"bad operation\"\n done\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( -- ) a b = a - b\nlet ( ++ ) a b = a + b\nlet ( * ) a b = Int64.mul a b\nlet ( + ) a b = Int64.add a b\nlet ( - ) a b = Int64.sub a b\n\ntype tree = \n Empty | Node of tree * (int64*int64*int64) * tree * int64\n(* left (h,total,y) right size *)\n(* what is stored in the node is the h value (the amount in this tube)\n and the total of all the h's in the subtree rooted here.\n and the h value of the leftmost node in the subtree rooted here.\n*)\n\ntype direction = Left | Right\ntype path = Item of tree * direction\n\nlet size = function Empty -> 0L | Node(_, _, _, size) -> size\n\nlet getkey = function\n | Empty -> (0L,0L,0L)\n | Node(_, key, _, _) -> key\n\nlet getroot = function \n | Node(left, k, right, _) -> (left, k, right)\n | _ -> failwith \"called getroot on Empty\"\n\nlet glue (l, (h,_,_), r) = \n let (tl,y) = match l with Empty -> (0L,h) | Node(_,(_,tl,y),_,_) -> (tl,y) in\n let (_,tr,_) = getkey r in\n Node (l, (h, tl+tr+h, y), r, (size l) + (size r) + 1L)\n\nlet snip = function\n | Node(l, (h,_,_), r, s) -> Node(l, (h,0L,0L), r, 0L)\n | _ -> failwith \"called snip on Empty\"\n\nlet connect (l, key, r) = Node(l, key, r, 0L)\n\nlet splay t rank = \n (* splay the node of the given rank (which are numbered starting at 0)\n to the root *)\n\n (* The following splay function takes as input the currently splayed\n tree (so far) t, and a path list. It takes one or two steps up,\n and calls itself recursively. *)\n let rec rsplay = function\n | (t,[]) -> glue (getroot t)\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->\n\trsplay (connect(tL,tK,glue(tR,bK,glue(bR,cK,cR))), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->\n rsplay (connect(glue(glue(cL,cK,bL), bK, tL),tK,tR), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->\n\trsplay (connect(tL,tK,glue(tR,bK,bR)), tail)\n\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->\n\trsplay (connect(glue(bL,bK,tL),tK,tR), tail)\n\t \n | (_,_) -> failwith \"Splay_failed (Should not happen)\"\n in\n\n let rec build_path t r path = (* r = the rank of the target node in the current tree t *)\n let t = snip t in\n match t with \n\t| Empty -> failwith \"failed build_path\"\n\t| Node(left, _, right, _) ->\n\t let sl = size left in\n\t if r < sl then build_path left r (Item(t, Left)::path)\n\t else if r = sl then (t,path)\n\t else build_path right (r-sl-1L) (Item(t, Right)::path)\n in\n if t=Empty then t else rsplay (build_path t rank [])\n\nlet append t h = \n glue(t, (h,0L,0L), Empty)\n\n(* let key_of_rank t rank = getkey (splay t rank) *)\n\nlet rec findit x tabove sabove v =\n(* x = the current node\n tabove = total left of x from above \n sabove = size of the stuff to the left of x from above\n assumes there's an infinite height node on the right as a sentinal\n*)\n match x with Empty -> failwith \"findit called on empty node\"\n | Node (l, (h,_,_), r, _) -> \n let (_,t,_) = getkey l in\n let t = t + tabove in\n let s = sabove + (size l) in\n let fvx = h*s - t in\n if fvx >= v then findit l tabove sabove v\n else \n\tlet (_,_,y) = getkey r in\n\tlet fvy = y*(s+1L) - (t+h) in\n\tif r=Empty || fvy >= v then (s,fvx)\n\telse findit r (t+h) (s+1L) v\n\nlet rec findh x h sabove c =\n (* retrns the rank of the given h in the tree,\n or the last one touched on a search for it *)\n match x with \n | Empty -> sabove - c\n | Node(l, (hx,_,_), r, _) -> \n if h < hx then findh l h sabove 0L\n else if h > hx then findh r h (sabove + (size l) + 1L) 1L\n else sabove + (size l)\n\nlet join l r = \n if r=Empty then l else\n let r = snip (splay r 0L) in\n let (_,key,rr) = getroot r in\n glue (l, key, rr)\n\nlet fill_height root v =\n let (s,fvx) = findit root 0L 0L v in\n let root = splay root s in\n let (h,_,_) = getkey root in\n let vol = v - fvx in\n let ans = (Int64.to_float h) +. (Int64.to_float vol)/.(Int64.to_float (s+1L)) in\n (root, ans)\n\nlet update t h0 h1 =\n (* replace h0 with h1 in the data structure *)\n let t = splay t (findh t h0 0L 0L) in\n let (l, _, r) = getroot (snip t) in\n let t = join l r in\n let t = splay t (findh t h1 0L 0L) in\n let (l,(h,_,_),r) = getroot (snip t) in\n if h <= h1 then glue (glue (l, (h,0L,0L), Empty), (h1,0L,0L), r)\n else glue (l, (h1,0L,0L), (glue (Empty, (h,0L,0L), r)))\n\n(*-------------------------------------------------------------------------*)\n\n(* Debugging code.....\n\nlet rec printtree t depth = \n match t with Empty -> ()\n | Node(ll, (h,t,y), rr, s) -> (\n printtree rr (depth+1);\n let rec loop i = if i=0 then () else (Printf.printf \" \"; loop (i-1)) in\n loop depth; Printf.printf \"(%d,%d,%d) %d\\n\" h t y s;\n printtree ll (depth+1)\n )\n\nlet rec maketree t li = match li with [] -> t\n | h::rest -> maketree (append t h) rest\n\nlet t = maketree Empty [1;1;2;2;6]\nlet _ = printtree t 0\n\nlet t = splay t 2\nlet _ = printtree t 0\n\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\nlet t = update t 1 3\n\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\nlet t = update t 2 1\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\nlet t = update t 6 1\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\nlet t = update t 1 6\nlet (t,ans) = fill_height t 3\nlet _ = printf \"ans = %f\\n\" ans\n\n*)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\n(* let inf = Int64.shift_left 1L 40 *)\n\nlet inf = 2_000_000_000_000_000L\n\nlet () = \n let n = read_int () in\n let q = read_int () in\n\n let root = ref Empty in\n let h = Array.init n (fun _ -> read_long()) in\n let hh = Array.copy h in\n Array.sort compare hh;\n\n for i=0 to n--1 do\n root := append !root hh.(i)\n done;\n\n root := append !root inf;\n\n for i=1 to q do\n match read_int() with\n | 1 -> let p = read_int () in \n\t let x = read_long () in\n\t root:= update !root h.(p--1) x;\n\t h.(p--1) <- x\n\n | 2 -> let v = read_long() in\n\t let (t,ans) = fill_height !root v in\n\t root := t;\n\t printf \"%f\\n\" ans\n\t \n | _ -> failwith \"bad operation\"\n done\n"}], "src_uid": "ccbedab1c5e3030e0def47ec41beb939"} {"nl": {"description": "Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.The park has n intersections numbered 1 through n. There are m bidirectional roads that connect some pairs of these intersections. At k intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most q intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most q that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most q intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.PMP's initial location is intersection s and the buses are at intersection t. There will always be a volunteer at intersection s. Your job is to find out the minimum q which guarantees that PMP can find the buses.", "input_spec": "The first line contains three space-separated integers n,\u2009m,\u2009k (2\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009m\u2009\u2264\u20092\u00b7105,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009n) \u2014 the number of intersections, roads and volunteers, respectively. Next line contains k distinct space-separated integers between 1 and n inclusive \u2014 the numbers of cities where volunteers are located. Next m lines describe the roads. The i-th of these lines contains two space-separated integers ui,\u2009vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n,\u2009ui\u2009\u2260\u2009vi) \u2014 two intersections that i-th road connects. There will be at most one road between any two intersections. Last line of input contains two space-separated integers s,\u2009t (1\u2009\u2264\u2009s,\u2009t\u2009\u2264\u2009n,\u2009s\u2009\u2260\u2009t) \u2014 the initial location of PMP and the location of the buses. It might not always be possible to reach t from s. It is guaranteed that there is always a volunteer at intersection s. ", "output_spec": "Print on the only line the answer to the problem \u2014 the minimum value of q which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead.", "sample_inputs": ["6 6 3\n1 3 6\n1 2\n2 3\n4 2\n5 6\n4 5\n3 4\n1 6", "6 5 3\n1 5 6\n1 2\n2 3\n3 4\n4 5\n6 3\n1 5"], "sample_outputs": ["3", "3"], "notes": "NoteThe first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with q\u2009=\u20093: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let vol = Array.make n false in\n let vv = Array.make k 0 in\n let es = Array.make n [] in\n let min (x : int) y = if x < y then x else y in\n let () =\n for i = 0 to k - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tvol.(x) <- true;\n\tvv.(i) <- x;\n done;\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- v :: es.(u);\n\tes.(v) <- u :: es.(v);\n done;\n in\n let es = Array.map Array.of_list es in\n let s = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let used = Array.make n false in\n let d = Array.make n 0 in\n let inf = 100000000 in\n let check q =\n for i = 0 to n - 1 do\n used.(i) <- false;\n d.(i) <- inf;\n done;\n let queue = Queue.create () in\n let rec bfs () =\n if not (Queue.is_empty queue) then (\n\tlet u = Queue.pop queue in\n\t (*Printf.printf \"q %d %d %d %d\\n\" u d.(u) q (Queue.length queue);*)\n\t if d.(u) < q then (\n\t for i = 0 to Array.length es.(u) - 1 do\n\t let v = es.(u).(i) in\n\t\tif not used.(v) || d.(v) > d.(u) + 1 then (\n\t\t used.(v) <- true;\n\t\t d.(v) <- if vol.(v) then 0 else min d.(v) (d.(u) + 1);\n\t (*Printf.printf \"add %d %d\\n\" v d.(v);*)\n\t\t Queue.add v queue;\n\t\t)\n\t done;\n\t );\n\t bfs ()\n )\n in\n used.(s) <- true;\n d.(s) <- 0;\n Queue.add s queue;\n bfs ();\n d.(t) <= q\n in\n let l = ref 0 in\n let r = ref (n + 1) in\n while !l < !r - 1 do\n let m = (!l + !r) / 2 in\n\tif check m\n\tthen r := m\n\telse l := m\n done;\n if !r > n\n then Printf.printf \"-1\\n\"\n else Printf.printf \"%d\\n\" !r\n"}], "negative_code": [], "src_uid": "1b336422bb45642d01cc098d953884a6"} {"nl": {"description": "We've got a rectangular n\u2009\u00d7\u2009m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x,\u2009y) is a wall if and only if cell is a wall.In this problem is a remainder of dividing number a by number b.The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x,\u2009y) he can go to one of the following cells: (x,\u2009y\u2009-\u20091), (x,\u2009y\u2009+\u20091), (x\u2009-\u20091,\u2009y) and (x\u2009+\u20091,\u2009y), provided that the cell he goes to is not a wall.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091500) \u2014 the height and the width of the maze that the boy used to cyclically tile the plane. Each of the next n lines contains m characters \u2014 the description of the labyrinth. Each character is either a \"#\", that marks a wall, a \".\", that marks a passable cell, or an \"S\", that marks the little boy's starting point. The starting point is a passable cell. It is guaranteed that character \"S\" occurs exactly once in the input.", "output_spec": "Print \"Yes\" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print \"No\" (without the quotes).", "sample_inputs": ["5 4\n##.#\n##S#\n#..#\n#.##\n#..#", "5 4\n##.#\n##S#\n#..#\n..#.\n#.##"], "sample_outputs": ["Yes", "No"], "notes": "NoteIn the first sample the little boy can go up for infinitely long as there is a \"clear path\" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up.In the second sample the vertical path is blocked. The path to the left doesn't work, too \u2014 the next \"copy\" of the maze traps the boy."}, "positive_code": [{"source_code": "exception Found\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m false in\n let sx = ref 0 in\n let sy = ref 0 in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tfor j = 0 to m - 1 do\n\t if s.[j] <> '#'\n\t then a.(i).(j) <- true;\n\t if s.[j] = 'S' then (\n\t sy := i;\n\t sx := j;\n\t )\n\tdone\n done;\n in\n let sx = !sx\n and sy = !sy in\n let c = Array.make_matrix n m (-1) in\n let color = ref 0 in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n let (x, y) = q1.(i) in\n\tfor i = 0 to 3 do\n\t let (dx, dy) = d.(i) in\n\t let x = x + dx\n\t and y = y + dy in\n\t (*let x = (x + m) mod m in\n\t let y = (y + n) mod n in*)\n\t if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (\n\t if c.(y).(x) < 0 then (\n\t\tc.(y).(x) <- !color;\n\t\tq2.(!l2) <- (x, y);\n\t\tincr l2\n\t );\n\t );\n\tdone\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n for y = 0 to n - 1 do\n let x = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for y = 0 to n - 1 do\n let x = m - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = n - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n let res = ref false in\n (*let () =\n for y = 0 to n - 1 do\n\tfor x = 0 to m - 1 do\n\t Printf.printf \"%2d \" c.(y).(x)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let es = Array.make !color [] in\n let () =\n for x = 0 to m - 1 do\n\tlet y1 = 0\n\tand y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) then (\n\t let c1 = c.(y1).(x)\n\t and c2 = c.(y2).(x) in\n\t es.(c1) <- (c2, 1, 0) :: es.(c1);\n\t es.(c2) <- (c1, -1, 0) :: es.(c2);\n\t )\n done;\n for y = 0 to n - 1 do\n\tlet x1 = 0\n\tand x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) then (\n\t let c1 = c.(y).(x1)\n\t and c2 = c.(y).(x2) in\n\t es.(c1) <- (c2, 0, 1) :: es.(c1);\n\t es.(c2) <- (c1, 0, -1) :: es.(c2);\n\t )\n done;\n in\n let es = Array.map Array.of_list es in\n (let used = Array.make !color (-1) in\n let start = c.(sy).(sx) in\n let rec dfs u z =\n if used.(u) >= 0 && used.(u) < z\n then raise Found;\n used.(u) <- z;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet (v, dz, _) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if used.(v) < z + dz then (\n\t dfs v (z + dz);\n\t )\n done\n in\n try\n\tif start >= 0\n\tthen dfs start 0;\n with\n\t| Found -> res := true\n );\n (let used = Array.make !color false in\n let dist = Array.make !color (0, 0) in\n let start = c.(sy).(sx) in\n let rec dfs u x y =\n if used.(u) && dist.(u) <> (x, y)\n then raise Found;\n dist.(u) <- (x, y);\n used.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n\t let (v, dx, dy) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if not used.(v) || dist.(v) <> (x + dx, y + dy) then (\n\t dfs v (x + dx) (y + dy);\n\t )\n done\n in\n try\n\t if start >= 0\n\t then dfs start 0 0;\n with\n\t | Found -> res := true\n );\n (*let cc = c.(sy).(sx) in\n if cc >= 0 then (\n\tfor x = 0 to m - 1 do\n\t let y1 = 0\n\t and y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) &&\n\t c.(y1).(x) = cc && c.(y2).(x) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n\tfor y = 0 to n - 1 do\n\t let x1 = 0\n\t and x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) &&\n\t c.(y).(x1) = cc && c.(y).(x2) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n );*)\n if !res\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m false in\n let sx = ref 0 in\n let sy = ref 0 in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tfor j = 0 to m - 1 do\n\t if s.[j] <> '#'\n\t then a.(i).(j) <- true;\n\t if s.[j] = 'S' then (\n\t sy := i;\n\t sx := j;\n\t )\n\tdone\n done;\n in\n let sx = !sx\n and sy = !sy in\n let c = Array.make_matrix n m (-1) in\n let color = ref 0 in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n let (x, y) = q1.(i) in\n\tfor i = 0 to 3 do\n\t let (dx, dy) = d.(i) in\n\t let x = x + dx\n\t and y = y + dy in\n\t if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (\n\t if c.(y).(x) < 0 then (\n\t\tc.(y).(x) <- !color;\n\t\tq2.(!l2) <- (x, y);\n\t\tincr l2\n\t );\n\t );\n\tdone\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n for y = 0 to n - 1 do\n let x = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for y = 0 to n - 1 do\n let x = m - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = n - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n let res = ref false in\n (*let () =\n for y = 0 to n - 1 do\n\tfor x = 0 to m - 1 do\n\t Printf.printf \"%d \" c.(y).(x)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n (let es = Array.make !color [] in\n let () =\n\t for x = 0 to m - 1 do\n\t let y1 = 0\n\t and y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) then (\n\t let c1 = c.(y1).(x)\n\t and c2 = c.(y2).(x) in\n\t\t es.(c1) <- c2 :: es.(c1);\n\t\t (*es.(c2) <- c1 :: es.(c2);*)\n\t )\n\t done;\n\t for y = 0 to n - 1 do\n\t let x1 = 0\n\t and x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) then (\n\t let c1 = c.(y).(x1)\n\t and c2 = c.(y).(x2) in\n\t\t es.(c1) <- c2 :: es.(c1);\n\t\t (*es.(c2) <- c1 :: es.(c2);*)\n\t )\n\t done;\n in\n let es = Array.map Array.of_list es in\n let used = Array.make !color false in\n let start = c.(sy).(sx) in\n let rec dfs u =\n\t used.(u) <- true;\n\t for i = 0 to Array.length es.(u) - 1 do\n\t let v = es.(u).(i) in\n\t if v = start\n\t then res := true;\n\t if not used.(v) then (\n\t dfs v;\n\t )\n\t done\n in\n\t if start >= 0\n\t then dfs start;\n );\n (let es = Array.make !color [] in\n let () =\n\t for x = 0 to m - 1 do\n\t let y1 = 0\n\t and y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) then (\n\t let c1 = c.(y1).(x)\n\t and c2 = c.(y2).(x) in\n\t\t es.(c1) <- c2 :: es.(c1);\n\t\t (*es.(c2) <- c1 :: es.(c2);*)\n\t )\n\t done;\n\t for y = 0 to n - 1 do\n\t let x1 = 0\n\t and x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) then (\n\t let c1 = c.(y).(x1)\n\t and c2 = c.(y).(x2) in\n\t\t (*es.(c1) <- c2 :: es.(c1);*)\n\t\t es.(c2) <- c1 :: es.(c2);\n\t )\n\t done;\n in\n let es = Array.map Array.of_list es in\n let used = Array.make !color false in\n let start = c.(sy).(sx) in\n let rec dfs u =\n\t used.(u) <- true;\n\t for i = 0 to Array.length es.(u) - 1 do\n\t let v = es.(u).(i) in\n\t if v = start\n\t then res := true;\n\t if not used.(v) then (\n\t dfs v;\n\t )\n\t done\n in\n\t if start >= 0\n\t then dfs start;\n );\n if !res\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}, {"source_code": "exception Found\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m false in\n let sx = ref 0 in\n let sy = ref 0 in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\nif n = 20 && m = 20 && i >= 10 then Printf.printf \"%s\\n\" s;\n\tfor j = 0 to m - 1 do\n\t if s.[j] <> '#'\n\t then a.(i).(j) <- true;\n\t if s.[j] = 'S' then (\n\t sy := i;\n\t sx := j;\n\t )\n\tdone\n done;\n in\n let sx = !sx\n and sy = !sy in\n let c = Array.make_matrix n m (-1) in\n let color = ref 0 in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n let (x, y) = q1.(i) in\n\tfor i = 0 to 3 do\n\t let (dx, dy) = d.(i) in\n\t let x = x + dx\n\t and y = y + dy in\n\t (*let x = (x + m) mod m in\n\t let y = (y + n) mod n in*)\n\t if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (\n\t if c.(y).(x) < 0 then (\n\t\tc.(y).(x) <- !color;\n\t\tq2.(!l2) <- (x, y);\n\t\tincr l2\n\t );\n\t );\n\tdone\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n for y = 0 to n - 1 do\n let x = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for y = 0 to n - 1 do\n let x = m - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = n - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n let res = ref false in\n (*let () =\n for y = 0 to n - 1 do\n\tfor x = 0 to m - 1 do\n\t Printf.printf \"%d \" c.(y).(x)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let es = Array.make !color [] in\n let () =\n for x = 0 to m - 1 do\n\tlet y1 = 0\n\tand y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) then (\n\t let c1 = c.(y1).(x)\n\t and c2 = c.(y2).(x) in\n\t es.(c1) <- (c2, 1, 0) :: es.(c1);\n\t es.(c2) <- (c1, -1, 0) :: es.(c2);\n\t )\n done;\n for y = 0 to n - 1 do\n\tlet x1 = 0\n\tand x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) then (\n\t let c1 = c.(y).(x1)\n\t and c2 = c.(y).(x2) in\n\t es.(c1) <- (c2, 0, 1) :: es.(c1);\n\t es.(c2) <- (c1, 0, -1) :: es.(c2);\n\t )\n done;\n in\n let es = Array.map Array.of_list es in\n (let used = Array.make !color (-1) in\n let start = c.(sy).(sx) in\n let rec dfs u z =\n if used.(u) >= 0 && used.(u) < z\n then raise Found;\n used.(u) <- z;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet (v, dz, _) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if used.(v) < z + dz then (\n\t dfs v (z + dz);\n\t )\n done\n in\n try\n\tif start >= 0\n\tthen dfs start 0;\n with\n\t| Found -> res := true\n );\n (let used = Array.make !color (-1) in\n let start = c.(sy).(sx) in\n let rec dfs u z =\n if used.(u) >= 0 && used.(u) < z\n then raise Found;\n used.(u) <- z;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet (v, _, dz) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if used.(v) < z + dz then (\n\t dfs v (z + dz);\n\t )\n done\n in\n try\n\tif start >= 0\n\tthen dfs start 0;\n with\n\t| Found -> res := true\n );\n (*let cc = c.(sy).(sx) in\n if cc >= 0 then (\n\tfor x = 0 to m - 1 do\n\t let y1 = 0\n\t and y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) &&\n\t c.(y1).(x) = cc && c.(y2).(x) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n\tfor y = 0 to n - 1 do\n\t let x1 = 0\n\t and x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) &&\n\t c.(y).(x1) = cc && c.(y).(x2) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n );*)\n if !res\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m false in\n let sx = ref 0 in\n let sy = ref 0 in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tfor j = 0 to m - 1 do\n\t if s.[j] <> '#'\n\t then a.(i).(j) <- true;\n\t if s.[j] = 'S' then (\n\t sy := i;\n\t sx := j;\n\t )\n\tdone\n done;\n in\n let sx = !sx\n and sy = !sy in\n let c = Array.make_matrix n m (-1) in\n let color = ref 0 in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n let (x, y) = q1.(i) in\n\tfor i = 0 to 3 do\n\t let (dx, dy) = d.(i) in\n\t let x = x + dx\n\t and y = y + dy in\n\t if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (\n\t if c.(y).(x) < 0 then (\n\t\tc.(y).(x) <- !color;\n\t\tq2.(!l2) <- (x, y);\n\t\tincr l2\n\t );\n\t );\n\tdone\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n for y = 0 to n - 1 do\n let x = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for y = 0 to n - 1 do\n let x = m - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = n - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n let es = Array.make !color [] in\n let () =\n for x = 0 to m - 1 do\n\tlet y1 = 0\n\tand y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) then (\n\t let c1 = c.(y1).(x)\n\t and c2 = c.(y2).(x) in\n\t es.(c1) <- c2 :: es.(c1);\n\t es.(c2) <- c1 :: es.(c2);\n\t )\n done;\n in\n let es = Array.map Array.of_list es in\n let used = Array.make !color false in\n let res = ref false in\n let start = c.(sy).(sx) in\n let rec dfs u =\n used.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet v = es.(u).(i) in\n\t if v = start\n\t then res := true;\n\t if not used.(v) then (\n\t dfs v;\n\t )\n done\n in\n if start >= 0\n then dfs start;\n if !res\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}, {"source_code": "exception Found\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m false in\n let sx = ref 0 in\n let sy = ref 0 in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\nif n = 20 && m = 20 then Printf.printf \"%s\\n\" s;\n\tfor j = 0 to m - 1 do\n\t if s.[j] <> '#'\n\t then a.(i).(j) <- true;\n\t if s.[j] = 'S' then (\n\t sy := i;\n\t sx := j;\n\t )\n\tdone\n done;\n in\n let sx = !sx\n and sy = !sy in\n let c = Array.make_matrix n m (-1) in\n let color = ref 0 in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n let (x, y) = q1.(i) in\n\tfor i = 0 to 3 do\n\t let (dx, dy) = d.(i) in\n\t let x = x + dx\n\t and y = y + dy in\n\t (*let x = (x + m) mod m in\n\t let y = (y + n) mod n in*)\n\t if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (\n\t if c.(y).(x) < 0 then (\n\t\tc.(y).(x) <- !color;\n\t\tq2.(!l2) <- (x, y);\n\t\tincr l2\n\t );\n\t );\n\tdone\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n for y = 0 to n - 1 do\n let x = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for y = 0 to n - 1 do\n let x = m - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = n - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n let res = ref false in\n (*let () =\n for y = 0 to n - 1 do\n\tfor x = 0 to m - 1 do\n\t Printf.printf \"%d \" c.(y).(x)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let es = Array.make !color [] in\n let () =\n for x = 0 to m - 1 do\n\tlet y1 = 0\n\tand y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) then (\n\t let c1 = c.(y1).(x)\n\t and c2 = c.(y2).(x) in\n\t es.(c1) <- (c2, 1, 0) :: es.(c1);\n\t es.(c2) <- (c1, -1, 0) :: es.(c2);\n\t )\n done;\n for y = 0 to n - 1 do\n\tlet x1 = 0\n\tand x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) then (\n\t let c1 = c.(y).(x1)\n\t and c2 = c.(y).(x2) in\n\t es.(c1) <- (c2, 0, 1) :: es.(c1);\n\t es.(c2) <- (c1, 0, -1) :: es.(c2);\n\t )\n done;\n in\n let es = Array.map Array.of_list es in\n (let used = Array.make !color (-1) in\n let start = c.(sy).(sx) in\n let rec dfs u z =\n if used.(u) >= 0 && used.(u) < z\n then raise Found;\n used.(u) <- z;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet (v, dz, _) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if used.(v) < z + dz then (\n\t dfs v (z + dz);\n\t )\n done\n in\n try\n\tif start >= 0\n\tthen dfs start 0;\n with\n\t| Found -> res := true\n );\n (let used = Array.make !color (-1) in\n let start = c.(sy).(sx) in\n let rec dfs u z =\n if used.(u) >= 0 && used.(u) < z\n then raise Found;\n used.(u) <- z;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet (v, _, dz) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if used.(v) < z + dz then (\n\t dfs v (z + dz);\n\t )\n done\n in\n try\n\tif start >= 0\n\tthen dfs start 0;\n with\n\t| Found -> res := true\n );\n (*let cc = c.(sy).(sx) in\n if cc >= 0 then (\n\tfor x = 0 to m - 1 do\n\t let y1 = 0\n\t and y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) &&\n\t c.(y1).(x) = cc && c.(y2).(x) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n\tfor y = 0 to n - 1 do\n\t let x1 = 0\n\t and x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) &&\n\t c.(y).(x1) = cc && c.(y).(x2) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n );*)\n if !res\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}, {"source_code": "exception Found\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m false in\n let sx = ref 0 in\n let sy = ref 0 in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tfor j = 0 to m - 1 do\n\t if s.[j] <> '#'\n\t then a.(i).(j) <- true;\n\t if s.[j] = 'S' then (\n\t sy := i;\n\t sx := j;\n\t )\n\tdone\n done;\n in\n let sx = !sx\n and sy = !sy in\n let c = Array.make_matrix n m (-1) in\n let color = ref 0 in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n let (x, y) = q1.(i) in\n\tfor i = 0 to 3 do\n\t let (dx, dy) = d.(i) in\n\t let x = x + dx\n\t and y = y + dy in\n\t (*let x = (x + m) mod m in\n\t let y = (y + n) mod n in*)\n\t if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (\n\t if c.(y).(x) < 0 then (\n\t\tc.(y).(x) <- !color;\n\t\tq2.(!l2) <- (x, y);\n\t\tincr l2\n\t );\n\t );\n\tdone\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n for y = 0 to n - 1 do\n let x = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for y = 0 to n - 1 do\n let x = m - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = n - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n let res = ref false in\n (*let () =\n for y = 0 to n - 1 do\n\tfor x = 0 to m - 1 do\n\t Printf.printf \"%d \" c.(y).(x)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let es = Array.make !color [] in\n let () =\n for x = 0 to m - 1 do\n\tlet y1 = 0\n\tand y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) then (\n\t let c1 = c.(y1).(x)\n\t and c2 = c.(y2).(x) in\n\t es.(c1) <- (c2, 1, 0) :: es.(c1);\n\t es.(c2) <- (c1, -1, 0) :: es.(c2);\n\t )\n done;\n for y = 0 to n - 1 do\n\tlet x1 = 0\n\tand x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) then (\n\t let c1 = c.(y).(x1)\n\t and c2 = c.(y).(x2) in\n\t es.(c1) <- (c2, 0, 1) :: es.(c1);\n\t es.(c2) <- (c1, 0, -1) :: es.(c2);\n\t )\n done;\n in\n let es = Array.map Array.of_list es in\n (let used = Array.make !color (-1) in\n let start = c.(sy).(sx) in\n let rec dfs u z =\n if used.(u) >= 0 && used.(u) < z\n then raise Found;\n used.(u) <- z;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet (v, dz, _) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if used.(v) < z + dz then (\n\t dfs v (z + dz);\n\t )\n done\n in\n try\n\tif start >= 0\n\tthen dfs start 0;\n with\n\t| Found -> res := true\n );\n (let used = Array.make !color (-1) in\n let start = c.(sy).(sx) in\n let rec dfs u z =\n if used.(u) >= 0 && used.(u) < z\n then raise Found;\n used.(u) <- z;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet (v, _, dz) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if used.(v) < z + dz then (\n\t dfs v (z + dz);\n\t )\n done\n in\n try\n\tif start >= 0\n\tthen dfs start 0;\n with\n\t| Found -> res := true\n );\n (*let cc = c.(sy).(sx) in\n if cc >= 0 then (\n\tfor x = 0 to m - 1 do\n\t let y1 = 0\n\t and y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) &&\n\t c.(y1).(x) = cc && c.(y2).(x) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n\tfor y = 0 to n - 1 do\n\t let x1 = 0\n\t and x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) &&\n\t c.(y).(x1) = cc && c.(y).(x2) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n );*)\n if !res\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m false in\n let sx = ref 0 in\n let sy = ref 0 in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tfor j = 0 to m - 1 do\n\t if s.[j] <> '#'\n\t then a.(i).(j) <- true;\n\t if s.[j] = 'S' then (\n\t sy := i;\n\t sx := j;\n\t )\n\tdone\n done;\n in\n let sx = !sx\n and sy = !sy in\n let c = Array.make_matrix n m (-1) in\n let color = ref 0 in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n let (x, y) = q1.(i) in\n\tfor i = 0 to 3 do\n\t let (dx, dy) = d.(i) in\n\t let x = x + dx\n\t and y = y + dy in\n\t if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (\n\t if c.(y).(x) < 0 then (\n\t\tc.(y).(x) <- !color;\n\t\tq2.(!l2) <- (x, y);\n\t\tincr l2\n\t );\n\t );\n\tdone\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n for y = 0 to n - 1 do\n let x = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for y = 0 to n - 1 do\n let x = m - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = n - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n (*let () =\n for y = 0 to n - 1 do\n\tfor x = 0 to m - 1 do\n\t Printf.printf \"%d \" c.(y).(x)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let es = Array.make !color [] in\n let () =\n for x = 0 to m - 1 do\n\tlet y1 = 0\n\tand y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) then (\n\t let c1 = c.(y1).(x)\n\t and c2 = c.(y2).(x) in\n\t es.(c1) <- c2 :: es.(c1);\n\t es.(c2) <- c1 :: es.(c2);\n\t )\n done;\n for y = 0 to n - 1 do\n\tlet x1 = 0\n\tand x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) then (\n\t let c1 = c.(y).(x1)\n\t and c2 = c.(y).(x2) in\n\t es.(c1) <- c2 :: es.(c1);\n\t es.(c2) <- c1 :: es.(c2);\n\t )\n done;\n in\n let es = Array.map Array.of_list es in\n let used = Array.make !color false in\n let res = ref false in\n let start = c.(sy).(sx) in\n let rec dfs u =\n used.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet v = es.(u).(i) in\n\t if v = start\n\t then res := true;\n\t if not used.(v) then (\n\t dfs v;\n\t )\n done\n in\n if start >= 0\n then dfs start;\n if !res\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}, {"source_code": "exception Found\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m false in\n let sx = ref 0 in\n let sy = ref 0 in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tfor j = 0 to m - 1 do\n\t if s.[j] <> '#'\n\t then a.(i).(j) <- true;\n\t if s.[j] = 'S' then (\n\t sy := i;\n\t sx := j;\n\t )\n\tdone\n done;\n in\n let sx = !sx\n and sy = !sy in\n let c = Array.make_matrix n m (-1) in\n let color = ref 0 in\n let q1 = Array.make (n * m) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * m) (0, 0) in\n let l2 = ref 0 in\n let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n let (x, y) = q1.(i) in\n\tfor i = 0 to 3 do\n\t let (dx, dy) = d.(i) in\n\t let x = x + dx\n\t and y = y + dy in\n\t (*let x = (x + m) mod m in\n\t let y = (y + n) mod n in*)\n\t if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (\n\t if c.(y).(x) < 0 then (\n\t\tc.(y).(x) <- !color;\n\t\tq2.(!l2) <- (x, y);\n\t\tincr l2\n\t );\n\t );\n\tdone\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n for y = 0 to n - 1 do\n let x = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for y = 0 to n - 1 do\n let x = m - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = 0 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n for x = 0 to m - 1 do\n let y = n - 1 in\n\tif a.(y).(x) && c.(y).(x) < 0 then (\n\t c.(y).(x) <- !color;\n\t l1 := 0;\n\t l2 := 0;\n\t q1.(!l1) <- (x, y);\n\t incr l1;\n\t bfs_step 1 q1 l1 q2 l2;\n\t incr color;\n\t)\n done;\n let res = ref false in\n (*let () =\n for y = 0 to n - 1 do\n\tfor x = 0 to m - 1 do\n\t Printf.printf \"%2d \" c.(y).(x)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let es = Array.make !color [] in\n let () =\n for x = 0 to m - 1 do\n\tlet y1 = 0\n\tand y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) then (\n\t let c1 = c.(y1).(x)\n\t and c2 = c.(y2).(x) in\n\t es.(c1) <- (c2, 1, 0) :: es.(c1);\n\t es.(c2) <- (c1, -1, 0) :: es.(c2);\n\t )\n done;\n for y = 0 to n - 1 do\n\tlet x1 = 0\n\tand x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) then (\n\t let c1 = c.(y).(x1)\n\t and c2 = c.(y).(x2) in\n\t es.(c1) <- (c2, 0, 1) :: es.(c1);\n\t es.(c2) <- (c1, 0, -1) :: es.(c2);\n\t )\n done;\n in\n let es = Array.map Array.of_list es in\n (let used = Array.make !color (-1) in\n let start = c.(sy).(sx) in\n let rec dfs u z =\n if used.(u) >= 0 && used.(u) < z\n then raise Found;\n used.(u) <- z;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet (v, dz, _) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if used.(v) < z + dz then (\n\t dfs v (z + dz);\n\t )\n done\n in\n try\n\tif start >= 0\n\tthen dfs start 0;\n with\n\t| Found -> res := true\n );\n (let used = Array.make !color false in\n let dist = Array.make !color 0 in\n let start = c.(sy).(sx) in\n let rec dfs u z =\n if used.(u) && dist.(u) <> z\n then raise Found;\n dist.(u) <- z;\n used.(u) <- true;\n for i = 0 to Array.length es.(u) - 1 do\n\t let (v, _, dz) = es.(u).(i) in\n\t (*if v = start\n\t then res := true;*)\n\t if not used.(v) || dist.(v) <> z + dz then (\n\t dfs v (z + dz);\n\t )\n done\n in\n try\n\t if start >= 0\n\t then dfs start 0;\n with\n\t | Found -> res := true\n );\n (*let cc = c.(sy).(sx) in\n if cc >= 0 then (\n\tfor x = 0 to m - 1 do\n\t let y1 = 0\n\t and y2 = n - 1 in\n\t if a.(y1).(x) && a.(y2).(x) &&\n\t c.(y1).(x) = cc && c.(y2).(x) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n\tfor y = 0 to n - 1 do\n\t let x1 = 0\n\t and x2 = m - 1 in\n\t if a.(y).(x1) && a.(y).(x2) &&\n\t c.(y).(x1) = cc && c.(y).(x2) = cc\n\t then (\n\t res := true\n\t )\n\tdone;\n );*)\n if !res\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}], "src_uid": "b2cd2f15caf4fac334146f28566fd4a6"} {"nl": {"description": "After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1\u2009\u2264\u2009si\u2009\u2264\u20094), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of groups of schoolchildren. The second line contains a sequence of integers s1,\u2009s2,\u2009...,\u2009sn (1\u2009\u2264\u2009si\u2009\u2264\u20094). The integers are separated by a space, si is the number of children in the i-th group.", "output_spec": "Print the single number \u2014 the minimum number of taxis necessary to drive all children to Polycarpus.", "sample_inputs": ["5\n1 2 4 3 3", "8\n2 3 4 4 2 1 3 1"], "sample_outputs": ["4", "5"], "notes": "NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars."}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int();;\nlet tab=Array.make 5 0;;\nfor i=1 to n do\n let k=read_int() in tab.(k)<-tab.(k)+1\ndone;;\nif (tab.(2) mod 2)=0 then (tab.(1)<-max 0 (tab.(1)-tab.(3));tab.(2)<-tab.(2)/2)\nelse (tab.(1)<-max 0 (tab.(1)-tab.(3)-2);tab.(2)<-tab.(2)/2+1);;\nif (tab.(1) mod 4)=0 then tab.(1)<-tab.(1)/4 else tab.(1)<-tab.(1)/4+1;;\nprint_int(tab.(1)+tab.(2)+tab.(3)+tab.(4));;"}, {"source_code": "(* Codeforces 158 B Taxi *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\nlet taxi1 n1 = \n let n14 = n1/4 in\n let nn1 = n1 - n14*4 in\n let t1 = if nn1 > 0 then (n14 + 1)\n else n14 in \n (* let _ = Printf.printf \"n1 t1 = %d %d\\n\" n1 t1 in *)\n t1;;\n\nlet taxi2 n1 n2 =\n let n22 = n2/2 in\n let nn2 = n2 - 2 * n22 in\n let nn1 = if nn2 == 0 then n1\n else if n1 > 2 then n1 - 2\n else 0 in\n let t2 = n22 + nn2 + taxi1 nn1 in\n (* let _ = Printf.printf \"n1,n2 = %d %d t2 = %d\\n\" n1 n2 t2 in *)\n t2;;\n\nlet taxi3 n1 n2 n3 =\n let nn1 = if n3 > n1 then 0 else (n1 - n3) in\n n3 + taxi2 nn1 n2;;\n\nlet taxi4 n1 n2 n3 n4 = \n n4 + taxi3 n1 n2 n3;;\n\nlet rec count4 n1 n2 n3 n4 a = match a with\n | [] -> (n1, n2, n3, n4)\n | h :: t ->\n match h with\n | 1 -> count4 (n1 + 1) n2 n3 n4 t\n | 2 -> count4 n1 (n2 + 1) n3 n4 t\n | 3 -> count4 n1 n2 (n3 + 1) n4 t\n | 4 -> count4 n1 n2 n3 (n4 + 1) t\n | _ -> \n let _ = print_string \"bad h in count4\\n\" in \n (-9999,0,0,0);;\n\nlet main() =\n\tlet n = gr () in\n\tlet s = readlist n [] in\n\tlet n1,n2,n3,n4 = count4 0 0 0 0 s in\n (* let _ = Printf.printf \"n1-4 = %d %d %d %d\\n\" n1 n2 n3 n4 in *)\n\tlet taxi = taxi4 n1 n2 n3 n4 in\n\tbegin\n\t\tprint_int taxi;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}, {"source_code": "let read_int () = Scanf.scanf \"%d \" (fun x -> x);;\nlet read_int3 () = Scanf.scanf \" %d %d %d \" (fun x y z -> (x,y,z) );;\n\nlet numx = Array.make 4 0;;\nlet n = read_int ();;\n for i = 1 to n do\n Scanf.scanf \"%d \" (fun x -> numx.(x-1)<- numx.(x-1)+1)\n done\n\nlet num_cars = ref ( numx.(3) + numx.(1)/2 );;\nlet () = numx.(1) <- numx.(1) mod 2;;\nlet () = if (numx.(0) <= numx.(2) ) then\n begin\n numx.(2) <- numx.(2) - numx.(0);\n num_cars := !num_cars + numx.(0);\n numx.(0) <- 0\n end\n else\n begin\n num_cars := !num_cars + numx.(2);\n numx.(0) <- numx.(0) - numx.(2);\n end\n;;\n\nlet () = if (numx.(0) == 0) then\n num_cars := !num_cars + numx.(2) + numx.(1)\n else\n begin\n if(numx.(1) == 1) then\n begin\n num_cars := !num_cars + 1;\n numx.(0) <- numx.(0) -2\n end;\n if (numx.(0) > 0) then\n num_cars := !num_cars + ( numx.(0) + 3) /4\n end\n;;\nlet ()= print_int !num_cars; print_endline \"\";;\n"}, {"source_code": "let read_int () = Scanf.scanf \"%d \" (fun x -> x);;\nlet read_int3 () = Scanf.scanf \" %d %d %d \" (fun x y z -> (x,y,z) );;\n\nlet n = read_int ();;\nlet a = Array.init n (fun i -> read_int () );;\nlet numx = Array.make 4 0;;\nlet vote i = numx.(i-1) <- numx.(i-1) + 1;;\nlet () = Array.iter (fun x -> vote x) a;;\n\nlet num_cars = ref ( numx.(3) + numx.(1)/2 );;\n\nlet () = numx.(1) <- numx.(1) mod 2;;\n\nlet () = if (numx.(0) <= numx.(2) ) then\n begin\n numx.(2) <- numx.(2) - numx.(0);\n num_cars := !num_cars + numx.(0);\n numx.(0) <- 0\n end\n else\n begin\n num_cars := !num_cars + numx.(2);\n numx.(0) <- numx.(0) - numx.(2);\n end\n;;\n\nlet () = if (numx.(0) == 0) then\n num_cars := !num_cars + numx.(2) + numx.(1)\n else\n begin\n if(numx.(1) == 1) then\n begin\n num_cars := !num_cars + 1;\n numx.(0) <- numx.(0) -2\n end;\n if (numx.(0) > 0) then\n num_cars := !num_cars + ( numx.(0) + 3) /4\n end\n;;\n\nlet ()= print_int !num_cars; print_endline \"\";;\n"}, {"source_code": "let read_int () = Scanf.scanf \"%d \" (fun x -> x);;\nlet read_int3 () = Scanf.scanf \" %d %d %d \" (fun x y z -> (x,y,z) );;\n\nlet n = read_int ();;\nlet a = Array.init n (fun i -> read_int () );;\nlet numx = Array.make 4 0;;\nlet vote i = numx.(i-1) <- numx.(i-1) + 1;;\nlet () = Array.iter (fun x -> vote x) a;;\n\nlet num_cars = ref ( numx.(3) + numx.(1)/2 );;\n\nlet () = numx.(1) <- numx.(1) mod 2;;\n\nlet () = if (numx.(0) <= numx.(2) ) then\n begin\n numx.(2) <- numx.(2) - numx.(0);\n num_cars := !num_cars + numx.(0);\n numx.(0) <- 0\n end\n else\n begin\n num_cars := !num_cars + numx.(2);\n numx.(0) <- numx.(0) - numx.(2);\n numx.(2) <- 0\n end\n;;\n\nlet () = if (numx.(0) == 0) then\n num_cars := !num_cars + numx.(2) + numx.(1)\n else\n begin\n if(numx.(1) == 1) then\n begin\n num_cars := !num_cars + 1;\n numx.(0) <- numx.(0) -2\n end;\n if (numx.(0) > 0) then\n begin\n if (numx.(0) mod 4 == 0) then\n num_cars := !num_cars + numx.(0)/4\n else\n num_cars := !num_cars + numx.(0)/4 + 1\n end\n end\n;;\n\nlet ()= print_int !num_cars; print_endline \"\";;\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve n =\n let data = [|0; 0; 0; 0; 0|] in\n for i = 1 to n do\n match read_int () with\n | 1 when data.(3) > 0 -> data.(3) <- data.(3) - 1; data.(4) <- data.(4) + 1\n | 2 when data.(2) > 0 -> data.(2) <- data.(2) - 1; data.(4) <- data.(4) + 1\n | 3 when data.(1) > 0 -> data.(1) <- data.(1) - 1; data.(4) <- data.(4) + 1\n | i -> data.(i) <- data.(i) + 1\n done;\n\n if data.(2) > 0 && data.(1) > 0 then begin\n data.(2) <- 0;\n data.(4) <- data.(4) + 1;\n if data.(1) > 1\n then data.(1) <- data.(1)-2\n else data.(1) <- 0\n end;\n\n if data.(1) mod 4 = 0\n then data.(4) + data.(3) + data.(2) + data.(1) / 4\n else data.(4) + data.(3) + data.(2) + data.(1) / 4 + 1\n\n\nlet () =\n let n = read_int ()\n in Printf.printf \"%d\\n\" (solve n)\n\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) ;;\n\nlet n = read_int () ;;\n\nlet s =\n let rec loop i n f = \n if i > n then f []\n else let si = read_int () in loop (i + 1) n (fun l -> f (si :: l))\n in loop 1 n (fun x -> x) ;;\n\nlet count x = \n let rec loop total = function \n | [] -> total\n | h :: t -> loop (total + if h = x then 1 else 0) t\n in loop 0 ;;\n \nlet one = count 1 s \n and two = count 2 s \n and three = count 3 s \n and four = count 4 s ;;\n\nlet group31 = min one three ;;\nlet group21 = min (two mod 2) (one - group31) ;;\nlet group2 = two / 2 + if group21 = 1 then 0 else (two mod 2) ;;\nlet group1 = ((max 0 (one - group31 - group21 * 2)) + 3) / 4 ;;\n\nlet taxis = four + three + group2 + group21 + group1 ;;\n\nPrintf.printf \"%d\\n\" taxis ;;"}, {"source_code": "let _ =\n let main () =\n let n = read_int () in\n let arr = Array.create 5 0 in\n let rec loop i =\n if i > 0 then (\n Scanf.scanf \" %d\" (fun x -> arr.(x) <- arr.(x) + 1);\n loop (i - 1)\n )\n in\n loop n;\n let c = arr.(4) + arr.(3) in\n let _ = arr.(1) <- arr.(1) - min arr.(1) arr.(3) in\n let c = c + (arr.(2) + 1) / 2 in\n let _ = arr.(1) <- arr.(1) - min arr.(1) ((arr.(2) mod 2) * 2) in\n let r = c + (arr.(1) + 3) / 4 in\n Printf.printf \"%d\\n\" r\n in\n main ()\n"}, {"source_code": "let input () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet rec read list n =\n if n > 0\n then\n let var = Scanf.scanf \"%d \" (fun n -> n) in\n read (var :: list) (n - 1)\n else\n List.rev list\n\nlet separate list s =\n let rec filter list s current_counts =\n if s > 0\n then\n let count = List.length(List.filter (fun int -> int = s) list) in\n filter list (s - 1) (count :: current_counts)\n else\n current_counts\n in filter list s []\n\nlet no_owerflow n = \n if n < 0\n then \n 0\n else\n n\n\nlet taxis list = match (separate list 4) with\n|[ones; twos; threes; fours] -> fours + threes + (twos * 2 + no_owerflow(ones - threes) + 3) / 4\n\nlet solve input = taxis (read [] input)\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input ()))"}, {"source_code": "open Scanf;;\n\nlet parse n =\n let rec parseInt n acc =\n if n <= 0 then acc\n else\n match bscanf Scanning.stdin \" %d\" (fun x -> x) with\n | d -> parseInt (n - 1) (d :: acc)\n | exception _ -> acc\n in parseInt n [];;\n\nlet taxis numList =\n let ones, twos, threes, fourths = \n List.fold_left ( fun (ones, twos, threes, fourths) x ->\n match x with\n | 1 -> (ones + 1, twos, threes, fourths)\n | 2 -> (ones, twos + 1, threes, fourths)\n | 3 -> (ones, twos, threes + 1, fourths)\n | 4 -> (ones, twos, threes, fourths + 1)\n | _ -> (ones, twos, threes, fourths)\n ) (0, 0, 0, 0) numList\n in let needed = fourths\n in let needed = needed + twos / 2\n in let twos = twos mod 2\n in let needed = needed + threes\n in if ones > threes then\n let ones = ones - threes\n in let needed = needed + ones / 4\n in if twos = 1 then\n if ones mod 4 > 2 then\n needed + 2\n else\n needed + 1\n else\n if ones mod 4 = 0 then\n needed\n else\n needed + 1\n else\n needed + twos / 2 + twos mod 2\n\nlet main () = \n let n = bscanf Scanning.stdin \"%d\\n\" (fun x -> x)\n in let numList = parse n\n in taxis numList;;\n\nPrintf.printf \"%d\" (main ());;\n\n\n"}, {"source_code": "open Scanf\nopen Printf\nlet n = scanf \"%d\\n\" (fun n -> n)\n\nlet (n1,n2,n3,n4) = \n let a = Array.make 10 0 in\n for i=0 to n-1 do \n let i = scanf \"%d \" (fun x -> x) in\n a.(i) <- a.(i) + 1\n done;\n (a.(1),a.(2),a.(3),a.(4))\n\nlet () = (*\n printf \"%d %d %d %d\\n\" n1 n2 n3 n4; *)\n ()\nlet ans = ref n4\nlet n4 = 0\nlet incr2 x = \n ans := !ans +x;\n (*printf \"incr by %d to %d\\n\" x !ans;*)\n ()\nlet info x = (*\n printf \"Evaling %d \\n\" x;*)\n ()\n\nlet () =\n let m = (min n1 n3) in\n incr2 m;\n let n1 = n1 - m in\n let n3 = n3-m in\n let n3 = \n info 3;\n if n3>0 then (incr2 n3; 0) else n3 in\n let n2 = \n info 2;\n incr2 (n2/2);\n n2 mod 2 in\n let (n1,n2) = \n info 2;\n if n2>0 then (incr2 1; (n1-2,0)) else (n1,n2) in\n let () =\n let last = \n if n1>0 then ( (if n1 mod 4 = 0 then 0 else 1) + (n1/4) ) \n else 0\n in\n incr2 last\n in ()\n\nlet () = print_int !ans; print_newline ()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "let nextInt() =\n Scanf.scanf \"%d \" (fun x -> x);;\n\nlet readList n f =\n let rec loop n =\n if n == 0 then\n []\n else\n f() :: loop (n-1)\n in\n List.rev(loop n);;\n\nlet incValue arr x =\n arr.(x) <- arr.(x) + 1;;\n\nlet groupByList l =\n let counts = (Array.make 5 0) in\n let _ = List.map (incValue counts) l in\n counts;;\n\nlet rec fitTaxis counts =\n let sol = ref 0 in\n sol := counts.(4);\n\n let taxi3pack = min counts.(1) counts.(3) in\n sol := !sol + taxi3pack;\n counts.(1) <- counts.(1) - taxi3pack;\n counts.(3) <- counts.(3) - taxi3pack;\n sol := !sol + counts.(3);\n let remainder = counts.(1) + (counts.(2) * 2) in\n if remainder mod 4 == 0 then\n remainder / 4 + !sol\n else\n remainder / 4 + 1 + !sol;;\n\nlet _ =\n let n = read_int() in\n let l = readList n nextInt in\n let counts = groupByList l in\n print_int(fitTaxis counts);\n print_newline()\n"}, {"source_code": "let nextInt() =\n Scanf.scanf \"%d \" (fun x -> x);;\n\nlet readList n f =\n let rec loop n =\n if n == 0 then\n []\n else\n f() :: loop (n-1)\n in\n List.rev(loop n);;\n\nlet incValue arr x =\n arr.(x) <- arr.(x) + 1;;\n\nlet groupByList l =\n let counts = (Array.make 5 0) in\n let _ = List.map (incValue counts) l in\n counts;;\n\nlet fitTaxis counts =\n let sol = ref 0 in\n sol := counts.(4);\n\n let taxi3pack = min counts.(1) counts.(3) in\n sol := !sol + taxi3pack;\n counts.(1) <- counts.(1) - taxi3pack;\n counts.(3) <- counts.(3) - taxi3pack;\n sol := !sol + counts.(3);\n !sol + (counts.(1) + (counts.(2) * 2) + 3) / 4;;\n\nlet _ =\n let n = read_int() in\n let l = readList n nextInt in\n let counts = groupByList l in\n print_int(fitTaxis counts);\n print_newline()\n"}, {"source_code": "open Scanf;;\nopen Printf;;\nopen List;;\n\nlet read_and_count n =\n let rec read n acc =\n match n with\n | 1 -> let y = (scanf \"%d\" (fun x->x) ) in\n acc.(y) <- acc.(y) + 1;\n acc\n | x -> let y = (scanf \"%d \" (fun x->x)) in\n acc.(y) <- acc.(y) + 1;\n read (x-1) acc\n in read n (Array.make 5 0)\n;;\n\n\nlet n = scanf \"%d\\n\" (fun x -> x) in\nlet counters = (read_and_count n) in\nlet sol = ref 0 in\nsol := !sol + counters.(4);\nlet mini = (min counters.(3) counters.(1)) in\nsol := !sol + mini;\ncounters.(3) <- counters.(3) - mini;\ncounters.(1) <- counters.(1) - mini;\nsol := !sol + counters.(3);\nsol := !sol + ( (counters.(2)*2 + counters.(1) + 3) / 4);\nprintf \"%d\\n\" !sol;"}], "negative_code": [{"source_code": "let read_int () = Scanf.scanf \"%d \" (fun x -> x);;\nlet read_int3 () = Scanf.scanf \" %d %d %d \" (fun x y z -> (x,y,z) );;\n\nlet n = read_int ();;\nlet a = Array.init n (fun i -> read_int () );;\nlet numx = Array.make 4 0;;\nlet vote i = numx.(i-1) <- numx.(i-1) + 1;;\nlet () = Array.iter (fun x -> vote x) a;;\n\nlet num_cars = ref ( numx.(3) + numx.(1)/2 + numx.(0)/4 );;\n\nlet remain_2 = numx.(1) mod 2;;\nlet remain_1 = numx.(0) mod 4;;\n\nlet () = if (remain_1 > numx.(2)) then\n num_cars := !num_cars + numx.(2) + (remain_1 - numx.(2) )\n else if (remain_1 == numx.(2)) then\n num_cars := !num_cars + numx.(2) + remain_2\n else\n num_cars := !num_cars + remain_1 + (numx.(2) - remain_1) + remain_2\n;;\n\n\nlet () = (print_int !num_cars; print_endline \"\");;\n\n (* This is the easy way *)\n(*\n let b = Array.to_list cars\n |> List.filter (fun x -> (x>0))\n |> List.length\n;;\n\nlet ()= print_int b; print_endline \"\";;\n *)\n"}, {"source_code": "let read_int () = Scanf.scanf \"%d \" (fun x -> x);;\nlet read_int3 () = Scanf.scanf \" %d %d %d \" (fun x y z -> (x,y,z) );;\n\nlet n = read_int ();;\n\nlet a = Array.init n (fun i -> read_int () );;\n\nlet () = a |> Array.sort (fun x y -> (if (x < y ) then 1 else -1) );;\n\n\nlet cars = Array.make n 0;; (* Call n empty cars *)\n\n\n exception BreakLoop;;\n for i = 0 to n-1 do\n try\n for j = 0 to n-1 do\n let x = a.(i) + cars.(j) in\n if ( x <= 4 ) then\n begin\n cars.(j) <- x;\n raise BreakLoop\n end\n done\n with BreakLoop -> ()\n\n done;;\n\n let num_cars = ref 0;;\n try\n for i = 0; to n-1 do\n if(cars.(i)>0) then\n num_cars := !num_cars + 1\n else\n raise BreakLoop\n done\n with BreakLoop -> print_int !num_cars; print_endline \"\";;\n\n (* This is the easy way *)\n(*\n let b = Array.to_list cars\n |> List.filter (fun x -> (x>0))\n |> List.length\n;;\n\nlet ()= print_int b; print_endline \"\";;\n *)\n"}, {"source_code": "let _ =\n let main () =\n let n = read_int () in\n let arr = Array.create 5 0 in\n let rec loop i =\n if i > 0 then (\n Scanf.scanf \" %d\" (fun x -> arr.(x) <- arr.(x) + 1);\n loop (i - 1)\n )\n in\n loop n;\n let c = arr.(4) + arr.(3) in\n let _ = arr.(1) <- arr.(1) - min arr.(1) arr.(3) in\n let c = c + (arr.(2) + 1) / 2 in\n let _ = arr.(1) <- arr.(1) - min arr.(1) ((arr.(2) mod 1) * 2) in\n let r = c + (arr.(1) + 3) / 4 in\n Printf.printf \"%d\\n\" r\n in\n main ()\n"}, {"source_code": "open Scanf;;\n\nlet parse n =\n let rec parseInt n acc =\n if n <= 0 then acc\n else\n match bscanf Scanning.stdin \" %d\" (fun x -> x) with\n | d -> parseInt (n - 1) (d :: acc)\n | exception _ -> acc\n in parseInt n [];;\n\nlet taxis numList =\n let ones, twos, threes, fourths = \n List.fold_left ( fun (ones, twos, threes, fourths) x ->\n match x with\n | 1 -> (ones + 1, twos, threes, fourths)\n | 2 -> (ones, twos + 1, threes, fourths)\n | 3 -> (ones, twos, threes + 1, fourths)\n | 4 -> (ones, twos, threes, fourths + 1)\n | _ -> (ones, twos, threes, fourths)\n ) (0, 0, 0, 0) numList\n in let needed = fourths\n in let needed = needed + twos / 2\n in let twos = twos mod 2\n in let needed = needed + threes\n in if ones > threes then\n let ones = ones - threes\n in let needed = needed + ones / 4\n in if twos = 1 then\n if ones mod 4 > 2 then\n needed + 2\n else\n needed + 1\n else\n if (ones - threes) mod 4 = 0 then\n needed\n else\n needed + 1\n else\n needed + twos / 2 + twos mod 2\n\nlet main () = \n let n = bscanf Scanning.stdin \"%d\\n\" (fun x -> x)\n in let numList = parse n\n in taxis numList;;\n\nPrintf.printf \"%d\" (main ());;\n\n\n"}, {"source_code": "open Scanf;;\n\nlet parse () =\n let rec parseInt acc =\n match bscanf Scanning.stdin \" %d\" (fun x -> x) with\n | d -> parseInt (d :: acc)\n | exception _ -> acc\n in parseInt [];;\n\nlet taxis numList =\n let ones, twos, threes, fourths = \n List.fold_left ( fun (ones, twos, threes, fourths) x ->\n match x with\n | 1 -> (ones + 1, twos, threes, fourths)\n | 2 -> (ones, twos + 1, threes, fourths)\n | 3 -> (ones, twos, threes + 1, fourths)\n | 4 -> (ones, twos, threes, fourths + 1)\n | _ -> (ones, twos, threes, fourths)\n ) (0, 0, 0, 0) numList\n in let needed = fourths\n in let needed = needed + twos / 2\n in let twos = twos mod 2\n in let needed = needed + threes\n in if ones > threes then\n let needed = needed + ones / 4\n in if twos = 1 then\n if ones mod 4 > 2 then\n needed + 2\n else\n needed + 1\n else\n if ones mod 4 = 0 then\n needed\n else\n needed + 1\n else\n needed + twos / 2 + twos mod 2\n\nlet main () = \n let _ = bscanf Scanning.stdin \"%d\\n\" (fun x -> x)\n in let numList = parse ()\n in taxis numList;;\n\nPrintf.sprintf \"%d\" (main ());;\n\n\n"}, {"source_code": "open Scanf;;\n\nlet parse n =\n let rec parseInt n acc =\n if n <= 0 then acc\n else\n match bscanf Scanning.stdin \" %d\" (fun x -> x) with\n | d -> parseInt (n - 1) (d :: acc)\n | exception _ -> acc\n in parseInt n [];;\n\nlet taxis numList =\n let ones, twos, threes, fourths = \n List.fold_left ( fun (ones, twos, threes, fourths) x ->\n match x with\n | 1 -> (ones + 1, twos, threes, fourths)\n | 2 -> (ones, twos + 1, threes, fourths)\n | 3 -> (ones, twos, threes + 1, fourths)\n | 4 -> (ones, twos, threes, fourths + 1)\n | _ -> (ones, twos, threes, fourths)\n ) (0, 0, 0, 0) numList\n in let needed = fourths\n in let needed = needed + twos / 2\n in let twos = twos mod 2\n in let needed = needed + threes\n in if ones > threes then\n let needed = needed + ones / 4\n in if twos = 1 then\n if ones mod 4 > 2 then\n needed + 2\n else\n needed + 1\n else\n if ones - threes mod 4 = 0 then\n needed\n else\n needed + 1\n else\n needed + twos / 2 + twos mod 2\n\nlet main () = \n let n = bscanf Scanning.stdin \"%d\\n\" (fun x -> x)\n in let numList = parse n\n in taxis numList;;\n\nPrintf.printf \"%d\" (main ());;\n\n\n"}, {"source_code": "open Scanf;;\n\nlet parse n =\n let rec parseInt n acc =\n if n <= 0 then acc\n else\n match bscanf Scanning.stdin \" %d\" (fun x -> x) with\n | d -> parseInt (n - 1) (d :: acc)\n | exception _ -> acc\n in parseInt n [];;\n\nlet taxis numList =\n let ones, twos, threes, fourths = \n List.fold_left ( fun (ones, twos, threes, fourths) x ->\n match x with\n | 1 -> (ones + 1, twos, threes, fourths)\n | 2 -> (ones, twos + 1, threes, fourths)\n | 3 -> (ones, twos, threes + 1, fourths)\n | 4 -> (ones, twos, threes, fourths + 1)\n | _ -> (ones, twos, threes, fourths)\n ) (0, 0, 0, 0) numList\n in let needed = fourths\n in let needed = needed + twos / 2\n in let twos = twos mod 2\n in let needed = needed + threes\n in if ones > threes then\n let ones = ones - threes\n in let needed = needed + ones / 4\n in if twos = 1 then\n if ones mod 4 > 2 then\n needed + 2\n else\n needed + 1\n else\n if (ones - threes) mod 4 = 0 then\n needed + 300\n else\n needed + 1\n else\n needed + twos / 2 + twos mod 2\n\nlet main () = \n let n = bscanf Scanning.stdin \"%d\\n\" (fun x -> x)\n in let numList = parse n\n in taxis numList;;\n\nPrintf.printf \"%d\" (main ());;\n\n\n"}, {"source_code": "open Scanf;;\n\nlet parse n =\n let rec parseInt n acc =\n if n <= 0 then acc\n else\n match bscanf Scanning.stdin \" %d\" (fun x -> x) with\n | d -> parseInt (n - 1) (d :: acc)\n | exception _ -> acc\n in parseInt n [];;\n\nlet taxis numList =\n let ones, twos, threes, fourths = \n List.fold_left ( fun (ones, twos, threes, fourths) x ->\n match x with\n | 1 -> (ones + 1, twos, threes, fourths)\n | 2 -> (ones, twos + 1, threes, fourths)\n | 3 -> (ones, twos, threes + 1, fourths)\n | 4 -> (ones, twos, threes, fourths + 1)\n | _ -> (ones, twos, threes, fourths)\n ) (0, 0, 0, 0) numList\n in let needed = fourths\n in let needed = needed + twos / 2\n in let twos = twos mod 2\n in let needed = needed + threes\n in if ones > threes then\n let needed = needed + ones / 4\n in if twos = 1 then\n if ones mod 4 > 2 then\n needed + 2\n else\n needed + 1\n else\n if ones mod 4 = 0 then\n needed\n else\n needed + 1\n else\n needed + twos / 2 + twos mod 2\n\nlet main () = \n let n = bscanf Scanning.stdin \"%d\\n\" (fun x -> x)\n in let numList = parse n\n in taxis numList;;\n\nPrintf.printf \"%d\" (main ());;\n\n\n"}, {"source_code": "open Scanf;;\n\nlet parse n =\n let rec parseInt n acc =\n if n <= 0 then acc\n else\n match bscanf Scanning.stdin \" %d\" (fun x -> x) with\n | d -> parseInt (n - 1) (d :: acc)\n | exception _ -> acc\n in parseInt n [];;\n\nlet taxis numList =\n let ones, twos, threes, fourths = \n List.fold_left ( fun (ones, twos, threes, fourths) x ->\n match x with\n | 1 -> (ones + 1, twos, threes, fourths)\n | 2 -> (ones, twos + 1, threes, fourths)\n | 3 -> (ones, twos, threes + 1, fourths)\n | 4 -> (ones, twos, threes, fourths + 1)\n | _ -> (ones, twos, threes, fourths)\n ) (0, 0, 0, 0) numList\n in let needed = fourths\n in let needed = needed + twos / 2\n in let twos = twos mod 2\n in let needed = needed + threes\n in if ones > threes then\n let needed = needed + ones / 4\n in if twos = 1 then\n if ones mod 4 > 2 then\n needed + 2\n else\n needed + 1\n else\n if (ones - threes) mod 4 = 0 then\n needed\n else\n needed + 1\n else\n needed + twos / 2 + twos mod 2\n\nlet main () = \n let n = bscanf Scanning.stdin \"%d\\n\" (fun x -> x)\n in let numList = parse n\n in taxis numList;;\n\nPrintf.printf \"%d\" (main ());;\n\n\n"}], "src_uid": "371100da1b044ad500ac4e1c09fa8dcb"} {"nl": {"description": "She is skilled in all kinds of magics, and is keen on inventing new one.\u2014Perfect Memento in Strict SensePatchouli is making a magical talisman. She initially has $$$n$$$ magical tokens. Their magical power can be represented with positive integers $$$a_1, a_2, \\ldots, a_n$$$. Patchouli may perform the following two operations on the tokens. Fusion: Patchouli chooses two tokens, removes them, and creates a new token with magical power equal to the sum of the two chosen tokens. Reduction: Patchouli chooses a token with an even value of magical power $$$x$$$, removes it and creates a new token with magical power equal to $$$\\frac{x}{2}$$$. Tokens are more effective when their magical powers are odd values. Please help Patchouli to find the minimum number of operations she needs to make magical powers of all tokens odd values.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$) \u2014 the number of test cases. The description of the test cases follows. For each test case, the first line contains one integer $$$n$$$ ($$$1 \\leq n\\leq 2\\cdot 10^5$$$) \u2014 the initial number of tokens. The second line contains $$$n$$$ intergers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$) \u2014 the initial magical power of the $$$n$$$ tokens. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single integer \u2014 the minimum number of operations Patchouli needs to make all tokens have an odd value of magical power. It can be shown that under such restrictions the required sequence of operations exists. ", "sample_inputs": ["4\n\n2\n\n1 9\n\n3\n\n1 1 2\n\n3\n\n2 4 8\n\n3\n\n1049600 33792 1280"], "sample_outputs": ["0\n1\n3\n10"], "notes": "NoteTest case 1:$$$a$$$ consists solely of odd numbers initially.Test case 2:Choose the tokens with magical power of $$$1$$$ and $$$2$$$ and perform Fusion. Now $$$a=[1,3]$$$, both are odd numbers.Test case 3:Choose the tokens with magical power of $$$2$$$ and $$$8$$$ and perform Fusion. Now $$$a=[4,10]$$$.Choose the token with magical power of $$$10$$$ and perform Reduction. Now $$$a=[4,5]$$$.Choose the tokens with magical power of $$$4$$$ and $$$5$$$ and perform Fusion. Now $$$a=[9]$$$, and $$$9$$$ is an odd number.It can be shown that you can not make all the magical powers odd numbers in less than $$$3$$$ moves, so the answer is $$$3$$$."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\n\r\nlet rec get_ce = function\r\n| (le, x) ->\r\n if (x mod 2 == 0) then get_ce ((le+1),(x/2))\r\n else le\r\n;;\r\nlet rec get_ne_le = function\r\n| (ne, le, 0) -> ne, le\r\n| (ne, le, t) ->\r\n let x = read_int () in\r\n let ce = get_ce (0, x) in\r\n if (ce == 0) then get_ne_le (ne, 0, (t-1))\r\n else if (ce < le) then get_ne_le ((ne+1), ce, (t-1))\r\n else get_ne_le ((ne+1), le, (t-1))\r\n;;\r\nlet run_case = function\r\n| () ->\r\n let n = read_int () in\r\n let ne, le = get_ne_le (0, 30, n) in\r\n if (le==0) then print_int ne\r\n else print_int (ne+le-1)\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| t -> \r\n run_case ();\r\n print_newline ();\r\n iter_cases (t-1)\r\n;;\r\n\r\nlet t=read_int() in iter_cases t;;"}], "negative_code": [], "src_uid": "1b9a204dd08d61766391a3b4d2429df2"} {"nl": {"description": "Theseus has just arrived to Crete to fight Minotaur. He found a labyrinth that has a form of a rectangular field of size n\u2009\u00d7\u2009m and consists of blocks of size 1\u2009\u00d7\u20091.Each block of the labyrinth has a button that rotates all blocks 90 degrees clockwise. Each block rotates around its center and doesn't change its position in the labyrinth. Also, each block has some number of doors (possibly none). In one minute, Theseus can either push the button in order to rotate all the blocks 90 degrees clockwise or pass to the neighbouring block. Theseus can go from block A to some neighbouring block B only if block A has a door that leads to block B and block B has a door that leads to block A.Theseus found an entrance to labyrinth and is now located in block (xT,\u2009yT)\u00a0\u2014 the block in the row xT and column yT. Theseus know that the Minotaur is hiding in block (xM,\u2009yM) and wants to know the minimum number of minutes required to get there.Theseus is a hero, not a programmer, so he asks you to help him.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000)\u00a0\u2014 the number of rows and the number of columns in labyrinth, respectively. Each of the following n lines contains m characters, describing the blocks of the labyrinth. The possible characters are: \u00ab+\u00bb means this block has 4 doors (one door to each neighbouring block); \u00ab-\u00bb means this block has 2 doors\u00a0\u2014 to the left and to the right neighbours; \u00ab|\u00bb means this block has 2 doors\u00a0\u2014 to the top and to the bottom neighbours; \u00ab^\u00bb means this block has 1 door\u00a0\u2014 to the top neighbour; \u00ab>\u00bb means this block has 1 door\u00a0\u2014 to the right neighbour; \u00ab<\u00bb means this block has 1 door\u00a0\u2014 to the left neighbour; \u00abv\u00bb means this block has 1 door\u00a0\u2014 to the bottom neighbour; \u00abL\u00bb means this block has 3 doors\u00a0\u2014 to all neighbours except left one; \u00abR\u00bb means this block has 3 doors\u00a0\u2014 to all neighbours except right one; \u00abU\u00bb means this block has 3 doors\u00a0\u2014 to all neighbours except top one; \u00abD\u00bb means this block has 3 doors\u00a0\u2014 to all neighbours except bottom one; \u00ab*\u00bb means this block is a wall and has no doors. Left, right, top and bottom are defined from representing labyrinth as a table, where rows are numbered from 1 to n from top to bottom and columns are numbered from 1 to m from left to right. Next line contains two integers\u00a0\u2014 coordinates of the block (xT,\u2009yT) (1\u2009\u2264\u2009xT\u2009\u2264\u2009n, 1\u2009\u2264\u2009yT\u2009\u2264\u2009m), where Theseus is initially located. Last line contains two integers\u00a0\u2014 coordinates of the block (xM,\u2009yM) (1\u2009\u2264\u2009xM\u2009\u2264\u2009n, 1\u2009\u2264\u2009yM\u2009\u2264\u2009m), where Minotaur hides. It's guaranteed that both the block where Theseus starts and the block where Minotaur is hiding have at least one door. Theseus and Minotaur may be initially located at the same block.", "output_spec": "If Theseus is not able to get to Minotaur, then print -1 in the only line of the output. Otherwise, print the minimum number of minutes required to get to the block where Minotaur is hiding.", "sample_inputs": ["2 2\n+*\n*U\n1 1\n2 2", "2 3\n<><\n><>\n1 1\n2 1"], "sample_outputs": ["-1", "4"], "notes": "NoteAssume that Theseus starts at the block (xT,\u2009yT) at the moment 0."}, "positive_code": [{"source_code": "open StdLabels\n\ntype vertex =\n { x : int;\n y : int;\n rot : int;\n }\n\nlet [n; m] = read_line () |> Str.(split (regexp \" \")) |> List.map ~f:int_of_string\nlet s = n * m\n\nlet rotate = function\n | '+' -> '+'\n | '-' -> '|'\n | '|' -> '-'\n | '^' -> '>'\n | '>' -> 'v'\n | 'v' -> '<'\n | '<' -> '^'\n | 'U' -> 'R'\n | 'R' -> 'D'\n | 'D' -> 'L'\n | 'L' -> 'U'\n | '*' -> '*'\n | _ -> failwith \"Unknown block\"\n\nlet maze = Bytes.make (4 * s) ' '\nlet () =\n for y = 0 to n-1 do\n Bytes.blit ~src:(read_line ()) ~src_pos:0 ~dst:maze ~dst_pos:(y * m) ~len:m\n done;\n for i = s to 4 * s - 1 do\n maze.[i] <- rotate maze.[i-s]\n done\n\nlet read_coords () =\n read_line ()\n |> Str.(split (regexp \" \"))\n |> List.map ~f:(fun s -> int_of_string s - 1)\n (* Discovered that (X,Y) are named (Y,X) in problem! *)\n |> fun [y; x] -> y * m + x\n\nlet start = read_coords ()\nlet goal = read_coords ()\n\nlet default d = function\n | Some x -> x\n | None -> d\n\nmodule Int = struct\n type t = int\n let compare = compare\nend\n\nmodule Vertex =\n struct\n type t = vertex\n let compare = compare\n end\n\nmodule PriorityQueue(Priority : Map.OrderedType) =\n struct\n module PriorityMap = Map.Make(Priority)\n\n let create = ref PriorityMap.empty\n\n let add prio elt pq =\n let queue =\n if PriorityMap.mem prio !pq then\n PriorityMap.find prio !pq\n else\n let q = Queue.create () in\n pq := PriorityMap.add prio q !pq;\n q in\n Queue.add elt queue\n\n let pop pq =\n if PriorityMap.is_empty !pq then\n None\n else\n let prio, queue = PriorityMap.min_binding !pq in\n let r = Queue.pop queue in\n if Queue.is_empty queue then\n pq := PriorityMap.remove prio !pq;\n Some r\n end\n\nmodule PriorityVertex =\n struct\n type t = int * Vertex.t\n let compare = compare\n end\n\nmodule VertexSet = Set.Make(Vertex)\n\nmodule VertexQueue = PriorityQueue(Int)\n\nlet astar ?(heuristic = fun v -> 0) ~start ~is_goal =\n let edge_length = 1 in\n let marks = Bytes.make (4*m*n) ' ' in\n let fringe = VertexQueue.create in\n VertexQueue.add (heuristic start) (start, 0) fringe;\n let rec go () =\n match VertexQueue.pop fringe with\n | None -> None\n | Some (v, dist) ->\n if is_goal v then\n Some dist\n else if marks.[v] = '*' then\n go ()\n else\n let dist' = dist + edge_length in\n marks.[v] <- '*';\n let enqueue u =\n if marks.[u] <> '*' then\n VertexQueue.add (dist' + heuristic u) (u, dist') fringe in\n let c = maze.[v] in\n let pl, pu, pr, pd = \"+-DLU\", \"+|vLUR\" in\n let sc = String.contains in\n let xy = v mod s in\n let x = xy mod m and y = xy / m in\n enqueue ((v + s) mod (4 * s));\n if x > 0 && sc pl c && sc pr maze.[v-1] then\n enqueue (v-1);\n if y > 0 && sc pu c && sc pd maze.[v-m] then\n enqueue (v-m);\n if x < m-1 && sc pr c && sc pl maze.[v+1] then\n enqueue (v+1);\n if y < n-1 && sc pd c && sc pu maze.[v+m] then\n enqueue (v+m);\n go () in\n go ()\n\nlet is_goal v = (v - goal) mod s = 0\n\nlet heuristic v =\n let xy = v mod s in\n let dx = xy mod m - goal mod m and dy = xy/m - goal/m in\n abs dx + abs dy\n\nlet () =\n astar ~heuristic ~start ~is_goal\n |> default (-1)\n |> Printf.printf \"%d\\n\"\n"}, {"source_code": "open StdLabels\n\ntype vertex =\n { x : int;\n y : int;\n rot : int;\n }\n\nlet [n; m] = read_line () |> Str.(split (regexp \" \")) |> List.map ~f:int_of_string\nlet s = n * m\n\nlet rotate = function\n | '+' -> '+'\n | '-' -> '|'\n | '|' -> '-'\n | '^' -> '>'\n | '>' -> 'v'\n | 'v' -> '<'\n | '<' -> '^'\n | 'U' -> 'R'\n | 'R' -> 'D'\n | 'D' -> 'L'\n | 'L' -> 'U'\n | '*' -> '*'\n | _ -> failwith \"Unknown block\"\n\nlet maze = Bytes.make (4 * s) ' '\nlet () =\n for y = 0 to n-1 do\n Bytes.blit ~src:(read_line ()) ~src_pos:0 ~dst:maze ~dst_pos:(y * m) ~len:m\n done;\n for i = s to 4 * s - 1 do\n maze.[i] <- rotate maze.[i-s]\n done\n\nlet read_coords () =\n read_line ()\n |> Str.(split (regexp \" \"))\n |> List.map ~f:(fun s -> int_of_string s - 1)\n (* Discovered that (X,Y) are named (Y,X) in problem! *)\n |> fun [y; x] -> y * m + x\n\nlet start = read_coords ()\nlet goal = read_coords ()\n\nlet default d = function\n | Some x -> x\n | None -> d\n\nmodule Int = struct\n type t = int\n let compare = compare\nend\n\nmodule Vertex =\n struct\n type t = vertex\n let compare = compare\n end\n\nmodule PriorityQueue(Priority : Map.OrderedType) =\n struct\n module PriorityMap = Map.Make(Priority)\n\n let create = ref PriorityMap.empty\n\n let add prio elt pq =\n let queue =\n if PriorityMap.mem prio !pq then\n PriorityMap.find prio !pq\n else\n let q = Queue.create () in\n pq := PriorityMap.add prio q !pq;\n q in\n Queue.add elt queue\n\n let pop pq =\n if PriorityMap.is_empty !pq then\n None\n else\n let prio, queue = PriorityMap.min_binding !pq in\n let r = Queue.pop queue in\n if Queue.is_empty queue then\n pq := PriorityMap.remove prio !pq;\n Some r\n end\n\nmodule Graph =\n struct\n module PriorityVertex =\n struct\n type t = int * Vertex.t\n let compare = compare\n end\n \n module VertexSet = Set.Make(Vertex)\n\n module VertexQueue = PriorityQueue(Int)\n \n let astar ?(heuristic = fun v -> 0) ~edges ~start ~is_goal =\n let edge_length = 1 in\n let marks = Bytes.make (4*m*n) ' ' in\n let fringe = VertexQueue.create in\n VertexQueue.add (heuristic start) (start, 0) fringe;\n let rec go () =\n match VertexQueue.pop fringe with\n | None -> None\n | Some (v, dist) ->\n if is_goal v then\n Some dist\n else if marks.[v] = '*' then\n go ()\n else\n let dist' = dist + edge_length in\n marks.[v] <- '*';\n List.iter\n ~f:(fun u ->\n if marks.[u] <> '*' then\n VertexQueue.add (dist' + heuristic u) (u, dist') fringe)\n (edges v);\n go () in\n go ()\n end\n\n\nlet edges v =\n let c = maze.[v] in\n let pl, pu, pr, pd = \"+-DLU\", \"+|vLUR\" in\n let sc = String.contains in\n let xy = v mod s in\n let x = xy mod m and y = xy / m in\n let r = ref [(v + s) mod (4 * s)] in\n if x > 0 && sc pl c && sc pr maze.[v-1] then\n r := v-1 :: !r;\n if y > 0 && sc pu c && sc pd maze.[v-m] then\n r := v-m :: !r;\n if x < m-1 && sc pr c && sc pl maze.[v+1] then\n r := v+1 :: !r;\n if y < n-1 && sc pd c && sc pu maze.[v+m] then\n r := v+m :: !r;\n !r\n\nlet is_goal v = (v - goal) mod s = 0\n\nlet heuristic v =\n let xy = v mod s in\n let dx = xy mod m - goal mod m and dy = xy/m - goal/m in\n abs dx + abs dy\n\nlet () =\n Graph.astar ~heuristic ~edges ~start ~is_goal\n |> default (-1)\n |> Printf.printf \"%d\\n\"\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n \nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let (n,m) = read_pair () in\n let lab_str = Array.init n (fun _ -> read_string()) in\n let (xt,yt) = read_pair() in\n let (xt,yt) = (xt-1, yt-1) in\n let (xm,ym) = read_pair() in\n let (xm,ym) = (xm-1, ym-1) in\n \n let vt = Array.make_matrix n m 0 in\n\n let visited (i,j,r) = vt.(i).(j) land (1 lsl r) <> 0 in\n let visit (i,j,r) = vt.(i).(j) <- vt.(i).(j) lor (1 lsl r) in\n\n let lab = Array.make_matrix n m [||] in\n \n for i=0 to n-1 do\n for j=0 to m-1 do\n lab.(i).(j) <-\n\tmatch lab_str.(i).[j] with\n\t | '+' -> [|1;1;1;1|]\n\t | '-' -> [|1;0;1;0|]\n\t | '|' -> [|0;1;0;1|]\n\t | '^' -> [|0;1;0;0|]\n\t | '>' -> [|1;0;0;0|]\t \n\t | '<' -> [|0;0;1;0|]\n\t | 'v' -> [|0;0;0;1|]\n\t | 'L' -> [|1;1;0;1|]\n\t | 'R' -> [|0;1;1;1|]\n\t | 'U' -> [|1;0;1;1|]\n\t | 'D' -> [|1;1;1;0|]\n\t | '*' -> [|0;0;0;0|]\n\t | _ -> failwith \"bad input\"\n done\n done;\n\n let out_bounds i j = i < 0 || j < 0 || i > n-1 || j > m-1 in\n \n let neighbors (i,j,r) =\n List.fold_left (fun ac (di,dj,s0) ->\n if lab.(i).(j).((s0+r) mod 4) = 0 then ac\n else if out_bounds (i+di) (j+dj) then ac else\n\tlet s1 = (r + s0 + 2) mod 4 in\n\tif lab.(i+di).(j+dj).(s1) = 0 then ac else (i+di, j+dj, r)::ac\n ) [(i, j, (r+1) mod 4)] [(-1,0,1);(1,0,3);(0,-1,2);(0,1,0)]\n in\n\n let rec bfs nodes level = if nodes = [] then None else (\n let new_nodes = List.fold_left (fun ac x ->\n List.fold_left (fun ac y ->\n\tif visited y then ac else (visit y; y::ac)\n ) ac (neighbors x)\n ) [] nodes in\n if visited (xm,ym,0) || visited (xm,ym,1) || visited (xm,ym,2) || visited (xm,ym,3)\n then Some (level+1) else bfs new_nodes (level+1)\n ) in\n\n visit (xt,yt,0);\n \n let answer =\n if (xm,ym) = (xt,yt) then 0\n else match bfs [(xt,yt,0)] 0 with None -> -1 | Some level -> level\n in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "fbc119b603ca87787628a3f4b7db8c33"} {"nl": {"description": "Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands: Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end. Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of Inna's commands. Then n lines follow, describing Inna's commands. Each line consists an integer: Integer a (1\u2009\u2264\u2009a\u2009\u2264\u2009105) means that Inna gives Dima a command to add number a into one of containers. Integer 0 shows that Inna asks Dima to make at most three extractions from different containers. ", "output_spec": "Each command of the input must correspond to one line of the output \u2014 Dima's action. For the command of the first type (adding) print one word that corresponds to Dima's choice: pushStack \u2014 add to the end of the stack; pushQueue \u2014 add to the end of the queue; pushFront \u2014 add to the beginning of the deck; pushBack \u2014 add to the end of the deck. For a command of the second type first print an integer k (0\u2009\u2264\u2009k\u2009\u2264\u20093), that shows the number of extract operations, then print k words separated by space. The words can be: popStack \u2014 extract from the end of the stack; popQueue \u2014 extract from the beginning of the line; popFront \u2014 extract from the beginning from the deck; popBack \u2014 extract from the end of the deck. The printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers. The printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.", "sample_inputs": ["10\n0\n1\n0\n1\n2\n0\n1\n2\n3\n0", "4\n1\n2\n3\n0"], "sample_outputs": ["0\npushStack\n1 popStack\npushStack\npushQueue\n2 popStack popQueue\npushStack\npushQueue\npushFront\n3 popStack popQueue popFront", "pushStack\npushQueue\npushFront\n3 popStack popQueue popFront"], "notes": null}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nmodule S = Set.Make (struct\n type t = int * int\n let compare ((i, x) : t) ((j, y) : t) = compare (x, i) (y, j)\nend);;\n\nlet () =\n let n = Scanf.scanf \"%d \" ident in\n let comm = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d \" ident :: acc) |> List.rev in\n let command = Array.create n `push_back in\n let rec iter next rest = function\n | comm :: comms when comm = 0 ->\n if S.cardinal rest = 0 then begin\n command.(next) <- `command0;\n iter (next + 1) rest comms\n end else if S.cardinal rest = 1 then begin\n let [i, m] = S.elements rest in\n command.(i) <- `push_stack;\n command.(next) <- `command1 (`stack);\n iter (next + 1) S.empty comms\n end else if S.cardinal rest = 2 then begin\n let [i1, m1; i2, m2] = S.elements rest in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(next) <- `command2 (`stack, `queue);\n iter (next + 1) S.empty comms\n end else begin\n let (maxs, rest) = fold_for 0 3 ~init:([], rest) ~f:(fun (acc, set) i ->\n let m = S.max_elt set in\n (m :: acc, S.remove m set)) in\n let [i1, _; i2, _; i3, _] = maxs in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(i3) <- `push_front;\n command.(next) <- `command3 (`stack, `queue, `deck);\n iter (next + 1) S.empty comms\n end\n | comm :: comms ->\n iter (next + 1) (S.add (next, comm) rest) comms\n | [] -> () in\n iter 0 S.empty comm;\n Array.iter command ~f:(function\n | `push_back -> print_endline \"pushBack\"\n | `push_front -> print_endline \"pushFront\"\n | `push_stack -> print_endline \"pushStack\"\n | `push_queue -> print_endline \"pushQueue\"\n | `command0 -> print_endline \"0\"\n | `command1 _ -> print_endline \"1 popStack\"\n | `command2 _ -> print_endline \"2 popStack popQueue\"\n | `command3 _ -> print_endline \"3 popStack popQueue popFront\")\n;;\n"}], "negative_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nmodule S = Set.Make (struct\n type t = int * int\n let compare ((_, x) : t) ((_, y) : t) = compare x y\nend);;\n\nlet () =\n let n = Scanf.scanf \"%d \" ident in\n let comm = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d \" ident :: acc) |> List.rev in\n let command = Array.create n `push_back in\n let rec iter next rest = function\n | comm :: comms when comm = 0 ->\n if S.cardinal rest = 0 then begin\n command.(next) <- `command0;\n iter (next + 1) rest comms\n end else if S.cardinal rest = 1 then begin\n let [i, m] = S.elements rest in command.(i) <- `push_stack;\n command.(next) <- `command1 (`stack);\n iter (next + 1) (S.remove (i, m) rest) comms\n end else if S.cardinal rest = 2 then begin\n let [i1, m1; i2, m2] = S.elements rest in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(next) <- `command2 (`stack, `queue);\n iter (next + 1) (S.remove (i1, m1) (S.remove (i2, m2) rest)) comms\n end else begin\n let (maxs, rest) = fold_for 0 3 ~init:([], rest) ~f:(fun (acc, set) i ->\n let m = S.max_elt set in\n (m :: acc, S.remove m set)) in\n let [i1, _; i2, _; i3, _] = maxs in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(i3) <- `push_front;\n command.(next) <- `command3 (`stack, `queue, `deck);\n iter (next + 1) rest comms\n end\n | comm :: comms ->\n iter (next + 1) (S.add (next, comm) rest) comms\n | [] -> () in\n iter 0 S.empty comm;\n Array.iter command ~f:(function\n | `push_back -> print_endline \"pushBack\"\n | `push_front -> print_endline \"pushFront\"\n | `push_stack -> print_endline \"pushStack\"\n | `push_queue -> print_endline \"pushQueue\"\n | `command0 -> print_endline \"0\"\n | `command1 _ -> print_endline \"1 popStack\"\n | `command2 _ -> print_endline \"2 popStack popQueue\"\n | `command3 _ -> print_endline \"3 popStack popQueue popFront\")\n;;\n"}, {"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nmodule S = Set.Make (struct\n type t = int * int\n let compare ((i, x) : t) ((j, y) : t) = compare (x, i) (y, j)\nend);;\n\nlet () =\n let n = Scanf.scanf \"%d \" ident in\n let comm = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d \" ident :: acc) |> List.rev in\n let command = Array.create n `push_back in\n let rec iter next rest = function\n | comm :: comms when comm = 0 ->\n if S.cardinal rest = 0 then begin\n command.(next) <- `command0;\n iter (next + 1) rest comms\n end else if S.cardinal rest = 1 then begin\n let [i, m] = S.elements rest in command.(i) <- `push_stack;\n command.(next) <- `command1 (`stack);\n iter (next + 1) (S.remove (i, m) rest) comms\n end else if S.cardinal rest = 2 then begin\n let [i1, m1; i2, m2] = S.elements rest in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(next) <- `command2 (`stack, `queue);\n iter (next + 1) (S.remove (i1, m1) (S.remove (i2, m2) rest)) comms\n end else begin\n let (maxs, rest) = fold_for 0 3 ~init:([], rest) ~f:(fun (acc, set) i ->\n let m = S.max_elt set in\n (m :: acc, S.remove m set)) in\n let [i1, _; i2, _; i3, _] = maxs in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(i3) <- `push_front;\n command.(next) <- `command3 (`stack, `queue, `deck);\n iter (next + 1) rest comms\n end\n | comm :: comms ->\n iter (next + 1) (S.add (next, comm) rest) comms\n | [] -> () in\n iter 0 S.empty comm;\n Array.iter command ~f:(function\n | `push_back -> print_endline \"pushBack\"\n | `push_front -> print_endline \"pushFront\"\n | `push_stack -> print_endline \"pushStack\"\n | `push_queue -> print_endline \"pushQueue\"\n | `command0 -> print_endline \"0\"\n | `command1 _ -> print_endline \"1 popStack\"\n | `command2 _ -> print_endline \"2 popStack popQueue\"\n | `command3 _ -> print_endline \"3 popStack popQueue popFront\")\n;;\n"}, {"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nmodule S = Set.Make (struct\n type t = int * int\n let compare ((i, x) : t) ((j, y) : t) = compare (x, i) (y, j)\nend);;\n\nlet () =\n let n = Scanf.scanf \"%d \" ident in\n let comm = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d \" ident :: acc) |> List.rev in\n let command = Array.create n `push_back in\n let rec iter next rest = function\n | comm :: comms when comm = 0 ->\n if S.cardinal rest = 0 then begin\n command.(next) <- `command0;\n iter (next + 1) rest comms\n end else if S.cardinal rest = 1 then begin\n let [i, m] = S.elements rest in\n command.(i) <- `push_stack;\n command.(next) <- `command1 (`stack);\n iter (next + 1) S.empty comms\n end else if S.cardinal rest = 2 then begin\n let [i1, m1; i2, m2] = S.elements rest in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(next) <- `command2 (`stack, `queue);\n iter (next + 1) S.empty comms\n end else begin\n let (maxs, rest) = fold_for 0 3 ~init:([], rest) ~f:(fun (acc, set) i ->\n let m = S.max_elt set in\n (m :: acc, S.remove m set)) in\n let [i1, _; i2, _; i3, _] = maxs in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(i3) <- `push_front;\n command.(next) <- `command3 (`stack, `queue, `deck);\n iter (next + 1) rest comms\n end\n | comm :: comms ->\n iter (next + 1) (S.add (next, comm) rest) comms\n | [] -> () in\n iter 0 S.empty comm;\n Array.iter command ~f:(function\n | `push_back -> print_endline \"pushBack\"\n | `push_front -> print_endline \"pushFront\"\n | `push_stack -> print_endline \"pushStack\"\n | `push_queue -> print_endline \"pushQueue\"\n | `command0 -> print_endline \"0\"\n | `command1 _ -> print_endline \"1 popStack\"\n | `command2 _ -> print_endline \"2 popStack popQueue\"\n | `command3 _ -> print_endline \"3 popStack popQueue popFront\")\n;;\n"}, {"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nmodule S = Set.Make (struct\n type t = int * int\n let compare ((i, x) : t) ((j, y) : t) = compare (x, i) (y, j)\nend);;\n\nlet () =\n let n = Scanf.scanf \"%d \" ident in\n let comm = fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf \"%d \" ident :: acc) |> List.rev in\n let command = Array.create n `push_back in\n let rec iter next rest = function\n | comm :: comms when comm = 0 ->\n if S.cardinal rest = 0 then begin\n command.(next) <- `command0;\n iter (next + 1) rest comms\n end else if S.cardinal rest = 1 then begin\n let [i, m] = S.elements rest in\n command.(i) <- `push_stack;\n command.(next) <- `command1 (`stack);\n iter (next + 1) (S.remove (i, m) rest) comms\n end else if S.cardinal rest = 2 then begin\n let [i1, m1; i2, m2] = S.elements rest in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(next) <- `command2 (`stack, `queue);\n iter (next + 1) (S.remove (i1, m1) (S.remove (i2, m2) rest)) comms\n end else begin\n let (maxs, rest) = fold_for 0 3 ~init:([], rest) ~f:(fun (acc, set) i ->\n let m = S.max_elt set in\n (m :: acc, S.remove m set)) in\n let [i1, _; i2, _; i3, _] = maxs in\n command.(i1) <- `push_stack;\n command.(i2) <- `push_queue;\n command.(i3) <- `push_front;\n command.(next) <- `command3 (`stack, `queue, `deck);\n iter (next + 1) rest comms\n end\n | comm :: comms ->\n iter (next + 1) (S.add (next, comm) rest) comms\n | [] -> () in\n iter 0 S.empty comm;\n Array.iter command ~f:(function\n | `push_back -> print_endline \"pushBack\"\n | `push_front -> print_endline \"pushFront\"\n | `push_stack -> print_endline \"pushStack\"\n | `push_queue -> print_endline \"pushQueue\"\n | `command0 -> print_endline \"0\"\n | `command1 _ -> print_endline \"1 popStack\"\n | `command2 _ -> print_endline \"2 popStack popQueue\"\n | `command3 _ -> print_endline \"3 popStack popQueue popFront\")\n;;\n"}], "src_uid": "07ae50199dd94f72313ee7675fefadb7"} {"nl": {"description": "Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.This time Miroslav laid out $$$n$$$ skewers parallel to each other, and enumerated them with consecutive integers from $$$1$$$ to $$$n$$$ in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number $$$i$$$, it leads to turning $$$k$$$ closest skewers from each side of the skewer $$$i$$$, that is, skewers number $$$i - k$$$, $$$i - k + 1$$$, ..., $$$i - 1$$$, $$$i + 1$$$, ..., $$$i + k - 1$$$, $$$i + k$$$ (if they exist). For example, let $$$n = 6$$$ and $$$k = 1$$$. When Miroslav turns skewer number $$$3$$$, then skewers with numbers $$$2$$$, $$$3$$$, and $$$4$$$ will come up turned over. If after that he turns skewer number $$$1$$$, then skewers number $$$1$$$, $$$3$$$, and $$$4$$$ will be turned over, while skewer number $$$2$$$ will be in the initial position (because it is turned again).As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all $$$n$$$ skewers with the minimal possible number of actions. For example, for the above example $$$n = 6$$$ and $$$k = 1$$$, two turnings are sufficient: he can turn over skewers number $$$2$$$ and $$$5$$$.Help Miroslav turn over all $$$n$$$ skewers.", "input_spec": "The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\leq n \\leq 1000$$$, $$$0 \\leq k \\leq 1000$$$)\u00a0\u2014 the number of skewers and the number of skewers from each side that are turned in one step.", "output_spec": "The first line should contain integer $$$l$$$\u00a0\u2014 the minimum number of actions needed by Miroslav to turn over all $$$n$$$ skewers. After than print $$$l$$$ integers from $$$1$$$ to $$$n$$$ denoting the number of the skewer that is to be turned over at the corresponding step.", "sample_inputs": ["7 2", "5 1"], "sample_outputs": ["2\n1 6", "2\n1 4"], "notes": "NoteIn the first example the first operation turns over skewers $$$1$$$, $$$2$$$ and $$$3$$$, the second operation turns over skewers $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$.In the second example it is also correct to turn over skewers $$$2$$$ and $$$5$$$, but turning skewers $$$2$$$ and $$$4$$$, or $$$1$$$ and $$$5$$$ are incorrect solutions because the skewer $$$3$$$ is in the initial state after these operations."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\nend open MyInt64\n\nlet repm from_ to_ m_init fbod =\n\tlet i,f,m = ref ~|from_,ref true,ref m_init in\n\twhile !i <= ~|to_ && !f do\n\t\tmatch fbod (~~| !i) !m with\n\t\t| `Break -> f := false\n\t\t| `Break_m m' -> (f := false; m := m')\n\t\t| `Ok m' -> (i := !i +$ 1; m := m')\n\tdone; !m\n\nlet () =\n\tlet n,k = get_2_i64 0 in\n\t(\n\t\tif n <= k then [0L]\n\t\telse if k=0L then (\n\t\t\tlet l = ref [] in\n\t\t\tfor i=0 to (~|n -$ 1) do\n\t\t\t\tl := (~~|i)::!l\n\t\t\tdone;\n\t\t\t!l |> List.rev\n\t\t)\n\t\telse if n <= 2L*k+1L then [n-k-1L]\n\t\telse if n <= 3L*k+1L then (\n\t\t\tlet ll = n / 2L\n\t\t\t(* in printf \" lr: %Ld, %Ld\\n\" ll (n-ll); *)\n\t\t\tin\n\t\t\tlet pl,pr = ll - k - 1L, ll + k\n\t\t\tin\n\t\t\t[pl;pr]\n\t\t)\n\t\telse (\n\t\t\tlet q = n / (2L*k+1L) in let r = n - q * (2L*k+1L) in\n\t\t\t(* printf \" %Ld, %Ld\\n\" q r; *)\n\t\t\tlet q,r = if r <= k then (q-1L,r+(2L*k+1L)) else (q,r)\n\t\t\t(* in printf \" %Ld, %Ld\\n\" q r; *)\n\t\t\tin\n\t\t\tlet w = 2L*k+1L in\n\t\t\tif r = 2L*k+1L then (\n\t\t\t\tlet s = ref k in\n\t\t\t\tlet l = ref [k] in\n\t\t\t\twhile !s <= n - w do\n\t\t\t\t\ts += (2L*k+1L);\n\t\t\t\t\tl := !s::!l;\n\t\t\t\tdone; !l |> List.rev\n\t\t\t)\n\t\t\telse if r < 2L*k+1L then (\n\t\t\t\tlet s,l = ref (r-k-1L), ref [r-k-1L] in\n\t\t\t\twhile !s < n - w do\n\t\t\t\t\ts += (2L*k+1L);\n\t\t\t\t\tl := !s::!l;\n\t\t\t\tdone; !l |> List.rev\n\t\t\t)\n\t\t\telse (\n\t\t\t\tlet ll = r / 2L in\n\t\t\t\tlet s,l = ref (ll-k-1L), ref [ll-k-1L] in\n\t\t\t\twhile !s < n - w - (r - ll) do\n\t\t\t\t\ts += (2L*k+1L);\n\t\t\t\t\tl := !s::!l;\n\t\t\t\tdone;\n\t\t\t\tl := (n-(r-ll)+k)::!l;\n\t\t\t\t!l |> List.rev\n\t\t\t)\n\t\t)\n\t)\n\t|> (fun v ->\n\t\tlet v = List.map ((+) 1L) v in\n\t\tlet l = List.length v in\n\t\tprintf \"%d\\n%s\\n\" l (string_of_list ~separator:\" \" Int64.to_string v)\n\t)\n\n\t(* let p = \n\t\t(Int64.to_float n) /. (Int64.to_float @@ 2L*k+1L)\n\t\t|> ceil\n\t\t|> Int64.of_float\n\tin *)\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "dfd60a02670749c67b0f96df1a0709b9"} {"nl": {"description": "Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces\u2019 superhero. Byteforces is a country that consists of n cities, connected by n\u2009-\u20091 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces. However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u2009123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n\u2009-\u20091 lines, describing the road system. Each line contains two city numbers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order.", "output_spec": "First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique.", "sample_inputs": ["7 2\n1 2\n1 3\n1 4\n3 5\n3 6\n3 7\n2 7", "6 4\n1 2\n2 3\n2 4\n4 5\n4 6\n2 4 5 6"], "sample_outputs": ["2\n3", "2\n4"], "notes": "NoteIn the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: and .However, you should choose the first one as it starts in the city with the lower number."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let m = read_int () in \n\n let tree = Array.make n [] in\n\n let add_edge (u,v) =\n tree.(u) <- v::tree.(u);\n tree.(v) <- u::tree.(v);\n in\n \n for i=0 to n-2 do\n let u = read_int() -1 in\n let v = read_int() -1 in \n add_edge (u,v)\n done;\n\n let mark = Array.make n false in\n let marked = Array.init m (fun _ -> read_int()-1) in\n let start = marked.(0) in\n \n for i=0 to m-1 do\n mark.(marked.(i)) <- true\n done;\n\n let child = Array.make n [] in\n \n let rec dfs p u =\n List.iter (fun v -> if v<>p then (\n child.(u) <- v::child.(u);\n dfs u v\n )) tree.(u)\n in\n\n dfs (-1) start;\n\n let child1 = Array.make n [] in\n\n let rec dfs_mark u =\n let me = if mark.(u) then 1 else 0 in\n me + List.fold_left (fun ac v ->\n let c = dfs_mark v in\n if c <> 0 then child1.(u) <- v::child1.(u);\n c+ac\n ) 0 child.(u)\n in\n\n if dfs_mark start <> m then failwith \"wrong number of marked nodes\";\n\n let rec dfs_size u =\n 1 + List.fold_left (fun ac v -> ac + dfs_size v) 0 child1.(u)\n in\n\n let nnodes = dfs_size start in\n\n let data = Array.make n ((0,0),(0,(0,0))) in\n (* (depth, min_node_achieving it, farthest_pair_dist, (pair achieving it))\n *)\n\n let rec dfs_score u =\n let d = List.length child1.(u) in\n if d=0 then (\n data.(u) <- ((0,u),(0,(u,u)));\n if not mark.(u) then failwith \"should have been marked\"\n )\n else\n let depth = Array.make d (0,0) in\n let farthest = Array.make d (0,(0,0)) in\n List.iteri (fun i v ->\n\tdfs_score v;\n\tlet (dep,f) = data.(v) in\n\tdepth.(i) <- dep;\n\tfarthest.(i) <- f\n ) child1.(u);\n let comp (d1,di1) (d2,di2) = compare (-d1,di1) (-d2,di2) in\n Array.sort comp depth;\n Array.sort comp farthest;\n if d=1 then\n\tlet (d0,d0i) = depth.(0) in\n\tlet opt1 = farthest.(0)\tin\n\tlet opt3 = if not mark.(u) then opt1 else (d0+1, (min d0i u, max d0i u)) in\n\tlet opts = List.sort comp [opt1; opt3] in\n\tdata.(u) <- ((d0+1,d0i), List.hd opts);\n else\n\tlet (d0,d0i) = depth.(0) in\n\tlet (d1,d1i) = depth.(1) in\n\tlet opt1 = farthest.(0) in\n\tlet opt2 = (d0 + d1 + 2, (min d0i d1i, max d0i d1i)) in\n\tlet opt3 = if not mark.(u) then opt2 else (d0+1, (min d0i u, max d0i u)) in\n\tlet opts = List.sort comp [opt1; opt2; opt3] in\n\tdata.(u) <- ((d0+1,d0i), List.hd opts)\n in\n\n dfs_score start;\n\n let (_, (farthest, (v0,v1))) = data.(start) in\n\n (*\n printf \"start = %d nnodes = %d farthest = %d (v0,v1) = (%d,%d)\\n\" start nnodes farthest v0 v1;\n *)\n let answer = (nnodes - 1) * 2 - farthest in\n printf \"%d\\n\" (v0+1);\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "bda7d223eabfcc519a60801012c58616"} {"nl": {"description": "Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i\u2009+\u20091,\u2009i\u2009+\u20092,\u2009...,\u2009i\u2009+\u2009k. Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?", "input_spec": "The first line contains two integers n and k (2\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105,\u20091\u2009\u2264\u2009k\u2009\u2264\u20093\u00b7105). The next line contains n characters \u2014 the description of the road: the i-th character equals \".\", if the i-th sector contains no rocks. Otherwise, it equals \"#\". It is guaranteed that the first and the last characters equal \".\".", "output_spec": "Print \"YES\" (without the quotes) if Ksusha can reach the end of the road, otherwise print \"NO\" (without the quotes).", "sample_inputs": ["2 1\n..", "5 2\n.#.#.", "7 3\n.#.###."], "sample_outputs": ["YES", "YES", "NO"], "notes": null}, "positive_code": [{"source_code": "open List\nopen Printf\nopen Scanf\nopen String\n\nlet inf= 1070000000;;\n\nlet rec getlist n =\n\tif n=0 then []\n\telse scanf \" %d\" (fun x->x)::getlist (n-1);;\n\nlet min a b = if a x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet h = Array.make 1000 0\nlet offset = 500\n\nlet day_number m d = \n let dpm = [|31;28;31;30;31;30;31;31;30;31;30;31|] in\n let md = sum 0 (m-2) (fun i->dpm.(i)) in\n md + (d-1)\n\nlet () = \n let n = read_int() in\n for i=1 to n do\n let m = read_int() in\n let d = read_int() in\n let p = read_int() in\n let t = read_int() in\n let dn = day_number m d in\n for j=dn-t to dn-1 do\n h.(j+offset) <- h.(j+offset) + p\n done;\n done;\n print_string (Printf.sprintf \"%d\\n\" (maxf 0 999 (fun i-> h.(i))))"}, {"source_code": "let chan = Scanf.Scanning.from_file \"input.txt\"\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet h = Array.make 1000 0\nlet offset = 500\n\nlet day_number m d = \n let dpm = [|31;28;31;30;31;30;31;31;30;31;30;31|] in\n let md = sum 0 (m-2) (fun i->dpm.(i)) in\n md + (d-1)\n\nlet () = \n let n = read_int() in\n for i=1 to n do\n let m = read_int() in\n let d = read_int() in\n let p = read_int() in\n let t = read_int() in\n let dn = day_number m d in\n for j=dn-t to dn-1 do\n h.(j+offset) <- h.(j+offset) + p\n done;\n done;\n print_string (Printf.sprintf \"%d\\n\" (maxf 0 999 (fun i-> h.(i))))"}, {"source_code": "let input = open_in \"input.txt\" ;;\nlet output = open_out \"output.txt\" ;;\n\nlet read_int () = Scanf.fscanf input \" %d \" (fun x -> x) ;;\n\nlet n = read_int () ;;\n\nlet olympiads = \n let rec loop i f =\n if i = n then f [] \n else let m = read_int () and d = read_int () and \n p = read_int () and t = read_int ()\n in loop (i + 1) (fun l -> f ((m, d, p, t) :: l))\n in loop 0 (fun x -> x) ;;\n\n(* Create a cumulative array of days since January 1, 2012 for the year 2013 *) \nlet months = [|0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31|]\nlet cumulative_days = Array.make 13 366 ;;\nfor i = 1 to 12 do\n cumulative_days.(i) <- months.(i) + cumulative_days.(i - 1)\ndone ;;\n\nlet start m d t = cumulative_days.(m - 1) + d - t ;;\n\nlet olympiads = \n let compare (m1, d1, p1, t1) (m2, d2, p2, t2) = \n (start m1 d1 t1) - (start m2 d2 t2)\n in List.sort compare olympiads ;;\n\nlet jury_size olympiads = \n let rec loop oly intersection size = match oly with\n | [] -> size\n | (m1, d1, p1, t1) as hd1 :: tl1 ->\n let rec filter l s f = match l with\n | [] -> (s, f [hd1])\n | (m2, d2, p2, t2) as hd2 :: tl2 -> \n if (start m1 d1 t1) > (start m2 d2 1) then filter tl2 s f\n else filter tl2 (s + p2) (fun v -> f (hd2 :: v))\n in let (newsize, newinter) = filter intersection p1 (fun x -> x)\n in loop tl1 newinter (max newsize size)\n in loop olympiads [] 0 ;;\n \nPrintf.fprintf output \"%d\\n\" (jury_size olympiads);;\n "}, {"source_code": "let chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet h = Array.make 1000 0\nlet offset = 500\n\nlet day_number m d = \n let dpm = [|31;28;31;30;31;30;31;31;30;31;30;31|] in\n let md = sum 0 (m-2) (fun i->dpm.(i)) in\n md + (d-1)\n\nlet () = \n let n = read_int() in\n for i=1 to n do\n let m = read_int() in\n let d = read_int() in\n let p = read_int() in\n let t = read_int() in\n let dn = day_number m d in\n\tfor j=dn-t to dn-1 do\n\t h.(j+offset) <- h.(j+offset) + p\n\tdone;\n done;\n print_string (Printf.sprintf \"%d\\n\" (maxf 0 999 (fun i-> h.(i))))\n"}], "negative_code": [], "src_uid": "34655e8de9f1020677c5681d9d217d75"} {"nl": {"description": "You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\\operatorname{AB}(s) = \\operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \\le i \\le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \\dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first and only line of each test case contains a single string $$$s$$$ ($$$1 \\le |s| \\le 100$$$, where $$$|s|$$$ is the length of the string $$$s$$$), consisting only of characters a and/or b.", "output_spec": "For each test case, print the resulting string $$$s$$$ with $$$\\operatorname{AB}(s) = \\operatorname{BA}(s)$$$ you'll get making the minimum number of steps. If there are multiple answers, print any of them.", "sample_inputs": ["4\nb\naabbbabaa\nabbb\nabbaab"], "sample_outputs": ["b\naabbbabaa\nbbbb\nabbaaa"], "notes": "NoteIn the first test case, both $$$\\operatorname{AB}(s) = 0$$$ and $$$\\operatorname{BA}(s) = 0$$$ (there are no occurrences of ab (ba) in b), so can leave $$$s$$$ untouched.In the second test case, $$$\\operatorname{AB}(s) = 2$$$ and $$$\\operatorname{BA}(s) = 2$$$, so you can leave $$$s$$$ untouched. In the third test case, $$$\\operatorname{AB}(s) = 1$$$ and $$$\\operatorname{BA}(s) = 0$$$. For example, we can change $$$s_1$$$ to b and make both values zero.In the fourth test case, $$$\\operatorname{AB}(s) = 2$$$ and $$$\\operatorname{BA}(s) = 1$$$. For example, we can change $$$s_6$$$ to a and make both values equal to $$$1$$$."}, "positive_code": [{"source_code": "let solve s =\n (String.make 1 s.[(String.length s - 1)]) ^ String.sub s 1 (String.length s - 1)\n \nlet () =\n let tc = Scanf.scanf \" %d\" (fun x -> x) in\n (let rec loop tc =\n match tc with\n | 0 -> ()\n | _ -> Printf.printf \"%s\\n\" (solve (Scanf.scanf \" %s\" (fun x ->x))); loop (tc - 1);\n in loop tc)"}, {"source_code": "let change c =\r\n char_of_int (int_of_char 'a' + (1 - ((int_of_char c) - (int_of_char 'a'))))\r\n\r\nlet solve s =\r\n let rec count s i res =\r\n if i < String.length s then \r\n if (s.[i] != s.[i-1]) \r\n then count s (i+1) (res+1)\r\n else count s (i+1) res \r\n else res\r\n in let res = count s 1 0 in\r\n if (res mod 2) == 1\r\n then (String.make 1 (change s.[0])) ^ (String.sub s 1 ((String.length s) - 1))\r\n else s\r\n\r\n\r\n\r\n\r\nlet () =\r\n let tc = Scanf.scanf \" %d\" (fun x -> x) in\r\n let rec loop tc =\r\n match tc with\r\n |0 -> ()\r\n |_ -> Printf.printf \"%s\\n\" (solve (Scanf.scanf \" %s\" (fun x ->x))); loop (tc - 1);\r\n in loop tc\r\n\r\n\r\n"}], "negative_code": [], "src_uid": "351ffff1dfe1bc1762f062f612463759"} {"nl": {"description": "Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a,\u2009b,\u2009c the following conditions held: a\u2009<\u2009b\u2009<\u2009c; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist.", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u200999999) \u2014 the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3.", "output_spec": "If the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1.", "sample_inputs": ["6\n1 1 1 2 2 2", "6\n2 2 1 1 4 6"], "sample_outputs": ["-1", "1 2 4\n1 2 6"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nopen String\nopen Array\nopen List\nopen Int64\n\nlet a = make 8 0;;\n\nlet rec read n =\n\tif n=0 then ()\n\telse (let x = scanf \" %d\" (fun y->y)\n\t\tin a.(x) <- a.(x)+1; read (n-1));;\n\nlet rec print s n =\n\tif n=0 then ()\n\telse (printf s; print s (n-1));;\n\nlet ok m =\n\tlet n136 = a.(3) in\n\tlet n124 = a.(4) in\n\tlet n126 = m - n136 - n124 in\n\tif n126 < 0 then false\n\telse if a.(1) <> m then false\n\telse if a.(2) <> n124 + n126 then false\n\telse if a.(6) <> n126 + n136 then false\n\telse\n\t\t(print \"1 2 4\\n\" n124;\n\t\tprint \"1 2 6\\n\" n126;\n\t\tprint \"1 3 6\\n\" n136;\n\t\ttrue);;\n\nlet solve n =\n\tread n;\n\tif not (ok (n/3)) then printf \"-1\"\n\telse ()\nin scanf \"%d\" solve;;"}, {"source_code": "let read_int _ = Scanf.scanf \" %d\" (fun x -> x)\nlet read_string _ = Scanf.scanf \" %s\" (fun x -> x)\n\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n \n let implode l =\n let result = String.create (List.length l) in\n let rec imp i = function\n | [] -> result\n | c :: l -> result.[i] <- c; imp (i + 1) l in\n imp 0 l;;\n \nlet (--) i j = \n let rec aux n acc =\n if n < i then acc else aux (n-1) (n :: acc)\n in aux j []\n \n let () = \n let n = read_int () in\n let arr = Array.init n read_int in\n let count = Array.init 8 (fun _ -> 0) in\n let ok = Array.fold_right (fun x ok ->\n if ok = false || (x = 5 || x = 7) then false\n else begin\n count.(x) <- count.(x) + 1;\n true\n end\n ) arr true\n in\n let bad = ref (ok = false) in\n bad := !bad || (count.(1) <> n / 3);\n bad := !bad || (count.(4) + count.(6) <> n / 3);\n bad := !bad || (count.(2) + count.(3) <> n / 3);\n bad := !bad || (count.(3) > count.(6));\n bad := !bad || (count.(2) <> count.(4) + count.(6) - count.(3));\n if !bad then Printf.printf \"-1\\n\"\n else begin\n let limit = count.(3) in\n for i = 1 to limit do\n Printf.printf \"1 3 6\\n\";\n count.(6) <- count.(6) - 1;\n done;\n for i = 1 to count.(4) do\n Printf.printf \"1 2 4\\n\";\n done;\n for i = 1 to count.(6) do\n Printf.printf \"1 2 6\\n\";\n done;\n end\n"}], "negative_code": [{"source_code": "open String\nopen List\nopen Printf\nopen Scanf\n\n\n"}, {"source_code": "let read_int _ = Scanf.scanf \" %d\" (fun x -> x)\nlet read_string _ = Scanf.scanf \" %s\" (fun x -> x)\n\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n \n let implode l =\n let result = String.create (List.length l) in\n let rec imp i = function\n | [] -> result\n | c :: l -> result.[i] <- c; imp (i + 1) l in\n imp 0 l;;\n \nlet (--) i j = \n let rec aux n acc =\n if n < i then acc else aux (n-1) (n :: acc)\n in aux j []\n \n let () = \n let n = read_int () in\n let arr = Array.init n read_int in\n let count = Array.init 8 (fun _ -> 0) in\n let ok = Array.fold_right (fun x ok ->\n if ok = false || (x = 5 || x = 7) then false\n else begin\n count.(x) <- count.(x) + 1;\n true\n end\n ) arr true\n in\n let bad = ref (ok = false) in\n bad := !bad || (count.(1) <> n / 3);\n bad := !bad || (count.(4) + count.(6) <> n / 3);\n bad := !bad || (count.(2) + count.(3) <> n / 3);\n bad := !bad || (count.(2) <> count.(4) + count.(6) - count.(3));\n if !bad then Printf.printf \"-1\\n\"\n else begin\n let limit = count.(3) in\n for i = 1 to limit do\n Printf.printf \"1 3 6\\n\";\n count.(6) <- count.(6) - 1;\n done;\n for i = 1 to count.(4) do\n Printf.printf \"1 2 4\\n\";\n done;\n for i = 1 to count.(6) do\n Printf.printf \"1 2 6\\n\";\n done;\n end\n"}], "src_uid": "513234db1bab98c2c2ed6c7030c1ac72"} {"nl": {"description": "Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi,\u2009yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.", "input_spec": "The first line of the input contains a single integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000). Each of the next n lines contains two integers xi and yi (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109). It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.", "output_spec": "Print three distinct integers on a single line\u00a0\u2014 the indices of the three points that form a triangle that satisfies the conditions stated in the problem. If there are multiple possible answers, you may print any of them.", "sample_inputs": ["3\n0 1\n1 0\n1 1", "5\n0 0\n0 2\n2 0\n2 2\n1 1"], "sample_outputs": ["1 2 3", "1 3 5"], "notes": "NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture. Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border)."}, "positive_code": [{"source_code": "let dist (a,b) (c,d) =\n let x = a -. c and y = b -. d in\n sqrt (x *. x +. y *. y) \n\nlet not_in_line (a,b) (c,d) (e,f) =\n let (w,x) = (c -. a,d -. b) and (y,z) = (e -. a,f -. b) in\n abs_float (w *. z -. x *. y) > 0.0000001\n\n(*\nlet f ((a,a')::(b,b')::q) =\n let m = ((a +. b) /. 2.,(a' +. b') /. 2.) in\n let i = ref 0 and d = ref max_float in\n List.iteri (fun j x -> let d' = dist m x n if d' < !d && not_in_line x (a,a') (b,b') then (i := j; d := d')) q;\n 3 + !i;;\n\nScanf.scanf \"%d\" (fun n ->\nlet l = ref [] in\n prerr_endline \"coucou\";\n for i=1 to n do\n Scanf.scanf \" %f %f\" (fun a b -> l := (a,b)::!l);\n done;\n Printf.printf \"1 2 %d\" (f (List.rev !l)))\n*)\n\nlet f (t::q) =\n let i = ref 0 and y = ref (0. , 0.) and d = ref max_float in\n List.iteri (fun j x -> let d' = dist t x in if d' < !d then (i := j; d := d'; y := x)) q;\n let j = ref 0 and z = ref (0. , 0.) and d = ref max_float in\n List.iteri (fun k x -> let d' = dist t x in if d' < !d && not_in_line x !y t && k <> !i then (j := k; d := d'; z := x)) q;\n (!i + 2,!j + 2);;\n\nScanf.scanf \"%d\" (fun n ->\nlet l = ref [] in\n for i=1 to n do\n Scanf.scanf \" %f %f\" (fun a b -> l := (a,b)::!l);\n done;\n let (a,b) = (f (List.rev !l)) in\n Printf.printf \"1 %d %d\" a b)\n\n"}], "negative_code": [{"source_code": "let dist (a,b) (c,d) =\n let x = a -. c and y = b -. d in\n sqrt (x *. x +. y *. y) \n\nlet not_in_line (a,b) (c,d) (e,f) =\n let (w,x) = (c -. a,d -. b) and (y,z) = (e -. a,f -. b) in\n abs_float (w *. z -. x *. y) > 0.0000001\n\nlet f ((a,a')::(b,b')::q) =\n let m = ((a +. b) /. 2.,(a' +. b') /. 2.) in\n let i = ref 0 and d = ref max_float in\n List.iteri (fun j x -> let d' = dist m x in if d' < !d && not_in_line x (a,a') (b,b') then (i := j; d := d')) q;\n 3 + !i;;\n\nScanf.scanf \"%d\" (fun n ->\nlet l = ref [] in\n prerr_endline \"coucou\";\n for i=1 to n do\n Scanf.scanf \" %f %f\" (fun a b -> l := (a,b)::!l);\n done;\n Printf.printf \"1 2 %d\" (f (List.rev !l)))\n"}, {"source_code": "let dist (a,b) (c,d) =\n let x = a -. c and y = b -. d in\n sqrt (x *. x +. y *. y) \n\nlet not_in_line (a,b) (c,d) (e,f) =\n let (w,x) = (c -. a,d -. b) and (y,z) = (e -. a,f -. b) in\n w *. z -. x *. y <> 0.\n\nlet f ((a,a')::(b,b')::q) =\n let m = ((a +. b) /. 2.,(a' +. b') /. 2.) in\n let i = ref 0 and d = ref max_float in\n List.iteri (fun j x -> let d' = dist m x in if d' < !d && not_in_line x (a,a') (b,b') then (i := j; d := d')) q;\n 3 + !i;;\n\nScanf.scanf \"%d\" (fun n ->\nlet l = ref [] in\n for i=1 to n do\n Scanf.scanf \" %f %f\" (fun a b -> l := (a,b)::!l);\n done;\n Printf.printf \"1 2 %d\" (f (List.rev !l)))\n"}, {"source_code": "let dist (a,b) (c,d) =\n let x = a -. c and y = b -. d in\n sqrt (x *. x +. y *. y) \n\nlet f ((a,a')::(b,b')::q) =\n let m = ((a +. b) /. 2.,(a' +. b') /. 2.) in\n let i = ref 0 and d = ref max_float in\n List.iteri (fun j x -> let d' = dist m x in if d' < !d then (i := j; d := d')) q;\n 3 + !i;;\n\nScanf.scanf \"%d\" (fun n ->\nlet l = ref [] in\n for i=1 to n do\n Scanf.scanf \" %f %f\" (fun a b -> l := (a,b)::!l);\n done;\n Printf.printf \"1 2 %d\" (f (List.rev !l)))\n"}], "src_uid": "0d3ac2472990aba36abee156069b1088"} {"nl": {"description": "The polar bears are going fishing. They plan to sail from (sx,\u2009sy) to (ex,\u2009ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x,\u2009y). If the wind blows to the east, the boat will move to (x\u2009+\u20091,\u2009y). If the wind blows to the south, the boat will move to (x,\u2009y\u2009-\u20091). If the wind blows to the west, the boat will move to (x\u2009-\u20091,\u2009y). If the wind blows to the north, the boat will move to (x,\u2009y\u2009+\u20091). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x,\u2009y). Given the wind direction for t seconds, what is the earliest time they sail to (ex,\u2009ey)?", "input_spec": "The first line contains five integers t,\u2009sx,\u2009sy,\u2009ex,\u2009ey (1\u2009\u2264\u2009t\u2009\u2264\u2009105,\u2009\u2009-\u2009109\u2009\u2264\u2009sx,\u2009sy,\u2009ex,\u2009ey\u2009\u2264\u2009109). The starting location and the ending location will be different. The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: \"E\" (east), \"S\" (south), \"W\" (west) and \"N\" (north).", "output_spec": "If they can reach (ex,\u2009ey) within t seconds, print the earliest time they can achieve it. Otherwise, print \"-1\" (without quotes).", "sample_inputs": ["5 0 0 1 1\nSESNW", "10 5 3 3 6\nNENSWESNEE"], "sample_outputs": ["4", "-1"], "notes": "NoteIn the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.In the second sample, they cannot sail to the destination."}, "positive_code": [{"source_code": "(* returns the number of elements consumed from xs\n to turn s1 to s2 *)\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) [] in\nlet rec gen s1 s2 f ls v = match ls with\n | _ when s1 = s2 -> Some v\n | [] -> None\n | (h::t) -> gen (f s1 h) s2 f t (v+1) in\nlet next (x,y) = function\n | 'E' when x < 0 -> (x+1,y)\n | 'S' when y > 0 -> (x,y-1)\n | 'W' when x > 0 -> (x-1,y)\n | 'N' when y < 0 -> (x,y+1)\n | _ -> (x,y) in\nlet out sx sy ex ey wind =\n match gen (sx-ex,sy-ey) (0,0) next (explode wind) 0 with\n | Some v -> v\n | None -> ~-1 in\nlet ans = Scanf.bscanf Scanf.Scanning.stdin \"%d %d %d %d %d %s\" (fun _ -> out) in\nPrintf.printf \"%d\\n\" ans;;\n"}], "negative_code": [], "src_uid": "aa31a2a1ad1575aee051ddee8642c53a"} {"nl": {"description": "Xenia the vigorous detective faced n (n\u2009\u2265\u20092) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x\u2009-\u20091 or x\u2009+\u20091 (if x\u2009=\u20091 or x\u2009=\u2009n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step ti (steps are numbered from 1) Xenia watches spies numbers li,\u2009li\u2009+\u20091,\u2009li\u2009+\u20092,\u2009...,\u2009ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).", "input_spec": "The first line contains four integers n, m, s and f (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009s,\u2009f\u2009\u2264\u2009n;\u00a0s\u2009\u2260\u2009f;\u00a0n\u2009\u2265\u20092). Each of the following m lines contains three integers ti,\u2009li,\u2009ri (1\u2009\u2264\u2009ti\u2009\u2264\u2009109,\u20091\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n). It is guaranteed that t1\u2009<\u2009t2\u2009<\u2009t3\u2009<\u2009...\u2009<\u2009tm.", "output_spec": "Print k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal \"L\". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal \"R\". If the spy must keep the note at the i-th step, the i-th character must equal \"X\". As a result of applying the printed sequence of actions spy s must pass the note to spy f. The number of printed characters k must be as small as possible. Xenia must not catch the spies passing the note. If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists.", "sample_inputs": ["3 5 1 3\n1 1 2\n2 2 3\n3 3 3\n4 1 1\n10 1 3"], "sample_outputs": ["XXRR"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.scanf \" %d\" (fun x -> x)\nlet read_string _ = Scanf.scanf \" %s\" (fun x -> x)\n\nlet explode s =\n let rec exp i l =\n if i < 0 then l else exp (i - 1) (s.[i] :: l) in\n exp (String.length s - 1) []\n \nlet () = \n let n = read_int () in\n let m = read_int () in\n let s = read_int () in\n let f = read_int () in\n \n let next x = if s < f then (x + 1) else (x - 1) in\n let movement = if s < f then \"R\" else \"L\" in\n let bad x l r= x >= l && x <= r in\n \n let arr = Array.init m (fun _ -> \n let t = read_int () in\n let l = read_int () in\n let r = read_int () in\n (t,l,r))\n in\n \n let curr_watch = ref 0 in\n let curr_pos = ref s in\n let curr_time = ref 1 in\n \n while !curr_pos <> f do\n let can_move = \n if !curr_watch = m then true\n else\n let (t,l,r) = arr.(!curr_watch) in\n if t = !curr_time then curr_watch := !curr_watch + 1;\n let next_pos = next !curr_pos in\n if t <> !curr_time then true\n else if (bad !curr_pos l r) || (bad next_pos l r) then false\n else true\n in\n curr_time := !curr_time + 1;\n match can_move with\n | true -> \n curr_pos := next !curr_pos;\n Printf.printf \"%s\" movement;\n | false ->\n Printf.printf \"X\";\n done;\n \n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "c1c9815e2274a1f147eab7bd8ee2d574"} {"nl": {"description": "Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of elements in the array. The second line contains n distinct space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 the elements of array. The third line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of queries. The last line contains m space-separated integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bi\u2009\u2264\u2009n) \u2014 the search queries. Note that the queries can repeat.", "output_spec": "Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout streams or the %I64d specifier.", "sample_inputs": ["2\n1 2\n1\n1", "2\n2 1\n1\n1", "3\n3 1 2\n3\n1 2 3"], "sample_outputs": ["1 2", "2 1", "6 6"], "notes": "NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element)."}, "positive_code": [{"source_code": "\nlet read format f = Scanf.bscanf Scanf.Scanning.stdib format f\n\nlet () =\n let n = read \"%d\\n\" (fun x -> x) in\n let nowhere = -1 in\n let lefts = Array.make n nowhere in\n let rights = Array.make n nowhere in\n for i = 1 to n do\n let a = read \"%d \" (fun x -> x - 1) in\n if lefts.(a) = nowhere then lefts.(a) <- i;\n rights.(a) <- n - i + 1\n done;\n let left = ref (Int64.of_int 0) in\n let right = ref (Int64.of_int 0) in\n let m = read \"%d\\n\" (fun x -> x) in\n for i = 1 to m do\n let q = read \" %d\" (fun x -> x - 1) in\n left := Int64.add !left (Int64.of_int lefts.(q));\n right := Int64.add !right (Int64.of_int rights.(q))\n done;\n Printf.printf \"%Ld %Ld\\n\" !left !right \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "let get_tbl n =\n let tbl = Hashtbl.create 100000 in\n let rec loop count =\n if count > n then tbl\n else\n begin\n\tHashtbl.add tbl (Scanf.scanf \" %d\" (fun x -> x)) (Int64.of_int(count));\n\tloop (count+1)\n end\n in\n loop 1\n\nlet rec get_int_list n =\n if n = 0 then []\n else (Scanf.scanf \" %d\" (fun x -> x)) :: get_int_list (n-1)\n\nlet solve tbl len queries =\n let accm_func ans q=\n let nth = Hashtbl.find tbl q in\n ((Int64.add (fst ans) nth),\n (Int64.sub (Int64.add (snd ans) (Int64.of_int(len+1))) nth))\n in\n List.fold_left accm_func (Int64.zero, Int64.zero) queries\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let tbl = get_tbl n in\n let m = Scanf.scanf \" %d\" (fun x -> x) in\n let queries = get_int_list m in\n let ans = solve tbl n queries in\n Printf.printf \"%Ld %Ld\\n\" (fst ans) (snd ans)\n"}], "negative_code": [{"source_code": "\nlet read format f = Scanf.bscanf Scanf.Scanning.stdib format f\n\nlet () =\n let n = read \"%d\\n\" (fun x -> x) in\n let nowhere = -1 in\n let lefts = Array.make n nowhere in\n let rights = Array.make n nowhere in\n for i = 1 to n do\n let a = read \"%d \" (fun x -> x - 1) in\n if lefts.(a) = nowhere then lefts.(a) <- i;\n rights.(a) <- n - i + 1\n done;\n let left = ref 0 in\n let right = ref 0 in\n let m = read \"%d\\n\" (fun x -> x) in\n for i = 1 to m do\n let q = read \" %d\" (fun x -> x - 1) in\n left := !left + lefts.(q);\n right := !right + rights.(q)\n done;\n Printf.printf \"%d %d\\n\" !left !right \n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "let get_tbl n =\n let tbl = Hashtbl.create 100000 in\n let rec loop count =\n if count > n then tbl\n else\n begin\n\tHashtbl.add tbl (Scanf.scanf \" %d\" (fun x -> x)) (Int32.of_int(count));\n\tloop (count+1)\n end\n in\n loop 1\n\nlet rec get_int_list n =\n if n = 0 then []\n else (Scanf.scanf \" %d\" (fun x -> x)) :: get_int_list (n-1)\n\nlet solve tbl len queries =\n let accm_func ans q=\n let nth = Hashtbl.find tbl q in\n ((Int32.add (fst ans) nth),\n (Int32.sub (Int32.add (snd ans) (Int32.of_int(len+1))) nth))\n in\n List.fold_left accm_func (Int32.zero, Int32.zero) queries\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let tbl = get_tbl n in\n let m = Scanf.scanf \" %d\" (fun x -> x) in\n let queries = get_int_list m in\n let ans = solve tbl n queries in\n Printf.printf \"%ld %ld\\n\" (fst ans) (snd ans)\n"}, {"source_code": "let get_tbl n =\n let tbl = Hashtbl.create 100000 in\n let rec loop count =\n if count > n then tbl\n else\n begin\n\tHashtbl.add tbl (Scanf.scanf \" %d\" (fun x -> x)) count;\n\tloop (count+1)\n end\n in\n loop 1\n\nlet rec get_int_list n =\n if n = 0 then []\n else (Scanf.scanf \" %d\" (fun x -> x)) :: get_int_list (n-1)\n\nlet solve tbl len queries =\n let accm_func ans q=\n let nth = Hashtbl.find tbl q in\n ((fst ans)+nth, (snd ans)+len-nth+1)\n in\n List.fold_left accm_func (0, 0) queries\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let tbl = get_tbl n in\n let m = Scanf.scanf \" %d\" (fun x -> x) in\n let queries = get_int_list m in\n let ans = solve tbl n queries in\n Printf.printf \"%d %d\\n\" (fst ans) (snd ans)\n"}], "src_uid": "b7aef95015e326307521fd59d4fccb64"} {"nl": {"description": "You are given a string s of length n, consisting of first k lowercase English letters.We define a c-repeat of some string q as a string, consisting of c copies of the string q. For example, string \"acbacbacbacb\" is a 4-repeat of the string \"acb\".Let's say that string a contains string b as a subsequence, if string b can be obtained from a by erasing some symbols.Let p be a string that represents some permutation of the first k lowercase English letters. We define function d(p) as the smallest integer such that a d(p)-repeat of the string p contains string s as a subsequence.There are m operations of one of two types that can be applied to string s: Replace all characters at positions from li to ri by a character ci. For the given p, that is a permutation of first k lowercase English letters, find the value of function d(p). All operations are performed sequentially, in the order they appear in the input. Your task is to determine the values of function d(p) for all operations of the second type.", "input_spec": "The first line contains three positive integers n, m and k (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000,\u20091\u2009\u2264\u2009m\u2009\u2264\u200920000,\u20091\u2009\u2264\u2009k\u2009\u2264\u200910)\u00a0\u2014 the length of the string s, the number of operations and the size of the alphabet respectively. The second line contains the string s itself. Each of the following lines m contains a description of some operation: Operation of the first type starts with 1 followed by a triple li, ri and ci, that denotes replacement of all characters at positions from li to ri by character ci (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n, ci is one of the first k lowercase English letters). Operation of the second type starts with 2 followed by a permutation of the first k lowercase English letters.", "output_spec": "For each query of the second type the value of function d(p).", "sample_inputs": ["7 4 3\nabacaba\n1 3 5 b\n2 abc\n1 4 4 c\n2 cba"], "sample_outputs": ["6\n5"], "notes": "NoteAfter the first operation the string s will be abbbbba.In the second operation the answer is 6-repeat of abc: ABcaBcaBcaBcaBcAbc.After the third operation the string s will be abbcbba.In the fourth operation the answer is 5-repeat of cba: cbAcBacBaCBacBA.Uppercase letters means the occurrences of symbols from the string s."}, "positive_code": [{"source_code": "(* Added sentenials to the left and right end of the list.\n Their (l,r,c) would be (-1,0,0) on the left and\n (n,n+1,0) on the right.\n\n The histogram table keeps characters 0...k. In other\n words an additional character 0 in order to simplify\n the cases in the code.\n*)\n\nmodule Pset = Set.Make (struct type t = int*int*int let compare = compare end)\n(* (l,r+1,character) *)\n\n(* a string s is represented as a set of these triples. For example if\n the string is \"abbbbaacce\" then it is:\n 0123456789\n (-1,0,k) (0,1,a) (1,5,b) (5,7,a) (7,9,c) (9,10,e) (10,11,k)\n\n The histogram is a (k+1) by (k+1) matrix of counts. It's the\n number of times each such transition occurs in the string.\n*)\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \nlet l2n c = (int_of_char c) - (int_of_char 'a') \n \nlet split2 set e put_tie_left =\n let (a,x,b) = Pset.split e set in\n if not x then (a,b) else\n if put_tie_left then (Pset.add e a, b) else (a, Pset.add e b)\n\nlet pred set e =\n (* e is in the set. Return it's predecessor. It must be there *)\n let (l,_,_) = Pset.split e set in\n Pset.max_elt l\n\nlet succ set e =\n let (_,_,r) = Pset.split e set in\n Pset.min_elt r\n\nlet inc hist i j d =\n hist.(i).(j) <- hist.(i).(j) + d\n \nlet update str n l r c hist =\n (* Update the str (of length n) with a new block of chars c from l\n to r-1. (Note this is different from the problem statement.)\n Return str, the updated version of the string. the histogram is\n updated in place. *)\n\n let first = (* the first one we're going to replace *)\n let (partl, _, _) = Pset.split (l,n+2,0) str in\n Pset.max_elt partl\n in\n\n let last = (* the last one we're going to replace *)\n let (partl, _, _) = Pset.split (r,-2,0) str in \n Pset.max_elt partl\n in\n\n let (left_part,_,_) = Pset.split first str in\n let (_,_,right_part) = Pset.split last str in\n \n let list_of_range str a b =\n let (_,partr) = split2 str a false in\n let (partl,_) = split2 partr b true in\n List.rev (Pset.fold (fun e ac -> e::ac) partl [])\n in\n\n let before_first = pred str first in\n let after_last = succ str last in\n let rem_t = list_of_range str before_first after_last in\n\n let rec rem_scan (l0,r0,c0) li =\n match li with\n | [] -> failwith \"scan called with empty list\"\t\n | (l,r,c)::[] -> inc hist c0 c (-1)\n | (l,r,c)::tail ->\n\tinc hist c0 c (-1);\n\tinc hist c c (-(r-l-1));\n\trem_scan (l,r,c) tail\n in\n\n rem_scan (List.hd rem_t) (List.tl rem_t);\n (* removes all the obsolete transitions *)\n \n let (l0,r0,c0) = first in\n let (l1,r1,c1) = last in\n\n let lphantom = if l0 < l then [(l0,l,c0)] else [] in\n let rphantom = if r1 > r then [(r,r1,c1)] else [] in\n let new_middle = lphantom @ [(l,r,c)] @ rphantom in\n \n let rec add_scan (l0,r0,c0) li =\n match li with\n | [] -> failwith \"scan called with empty list\"\t\n | (l,r,c)::[] -> inc hist c0 c 1\n | (l,r,c)::tail ->\n\tinc hist c0 c 1;\n\tinc hist c c (r-l-1);\n\tadd_scan (l,r,c) tail\n in\n\n add_scan before_first (new_middle @ [after_last]);\n\n let newstr = Pset.union left_part right_part in\n List.fold_left (fun ac e -> Pset.add e ac) newstr new_middle\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let m = read_int () in \n let k = read_int () in\n let s = read_string () in\n\n let rec find_changes s n i ac = if i=n then List.rev (n::ac) else\n if s.[i-1] <> s.[i] then find_changes s n (i+1) (i::ac)\n else find_changes s n (i+1) ac\n in\n\n let changes = Array.of_list (find_changes s n 1 []) in\n(*\n printf \"changes = \";\n for i=0 to -1+ Array.length changes do\n printf \"%d \" changes.(i)\n done;\n print_newline();\n*) \n let str = fold 0 (-2 + Array.length changes) (\n fun i ac -> Pset.add (changes.(i), changes.(i+1), l2n s.[changes.(i)]) ac\n ) (Pset.singleton (0, changes.(0), l2n s.[0])) in\n\n let str = Pset.add (-1,0,k) str in\n let str = Pset.add (n,n+1,k) str in\n\n let hist = Array.make_matrix (k+1) (k+1) 0 in\n for i=0 to n-2 do\n inc hist (l2n s.[i]) (l2n s.[i+1]) 1\n done;\n inc hist k (l2n s.[0]) 1;\n inc hist (l2n s.[n-1]) k 1;\n\n let rec loop i str = if i=m then () else (\n match read_int() with\n\t| 1 ->\n\t let l = -1 + read_int () in\n\t let r = read_int () in\n\t let c = l2n (read_string()).[0] in\n\t let str = update str n l r c hist in\n\t loop (i+1) str\n\t| 2 ->\n\t let p = read_string() in\n\t let p = Array.init k (fun i -> l2n p.[i]) in\n\t let inv = Array.make k 0 in\n\t for i=0 to k-1 do\n\t inv.(p.(i)) <- i\n\t done;\n\t let cycles = sum 0 (k-1) (fun i -> sum 0 (k-1) (fun j ->\n\t if inv.(i) < inv.(j) then 0 else hist.(i).(j)\n\t )) in\n\t printf \"%d\\n\" (cycles+1);\n\t loop (i+1) str\n\t| _ -> failwith \"bad input\"\n ) in\n \n loop 0 str\n"}, {"source_code": "module Pset = Set.Make (struct type t = int*int*int let compare = compare end)\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \nlet l2n c = (int_of_char c) - (int_of_char 'a') \n \nlet split2 set e put_tie_left =\n let (a,x,b) = Pset.split e set in\n if not x then (a,b) else\n if put_tie_left then (Pset.add e a, b) else (a, Pset.add e b)\n\nlet pred set e =\n let (l,_,_) = Pset.split e set in\n Pset.max_elt l\n\nlet succ set e =\n let (_,_,r) = Pset.split e set in\n Pset.min_elt r\n\nlet inc h i j d =\n h.(i).(j) <- h.(i).(j) + d\n \nlet update str n l r c hist =\n let first = (* the first one we're going to replace *)\n let (partl, _, _) = Pset.split (l,n+2,0) str in\n Pset.max_elt partl\n in\n\n let last = (* the last one we're going to replace *)\n let (partl, _, _) = Pset.split (r,-2,0) str in \n Pset.max_elt partl\n in\n\n let (left_part,_,_) = Pset.split first str in\n let (_,_,right_part) = Pset.split last str in\n \n let list_of_range str a b =\n let (_,partr) = split2 str a false in\n let (partl,_) = split2 partr b true in\n List.rev (Pset.fold (fun e ac -> e::ac) partl [])\n in\n\n let before_first = pred str first in\n let after_last = succ str last in\n let rem_t = list_of_range str before_first after_last in\n\n let rec rem_scan (l0,r0,c0) li =\n match li with\n | [] -> failwith \"scan called with empty list\"\t\n | (l,r,c)::[] -> inc hist c0 c (-1)\n | (l,r,c)::tail ->\n\tinc hist c0 c (-1);\n\tinc hist c c (-(r-l-1));\n\trem_scan (l,r,c) tail\n in\n\n rem_scan (List.hd rem_t) (List.tl rem_t);\n \n let (l0,r0,c0) = first in\n let (l1,r1,c1) = last in\n\n let lphantom = if l0 < l then [(l0,l,c0)] else [] in\n let rphantom = if r1 > r then [(r,r1,c1)] else [] in\n let new_middle = lphantom @ [(l,r,c)] @ rphantom in\n \n let rec add_scan (l0,r0,c0) li =\n match li with\n | [] -> failwith \"scan called with empty list\"\t\n | (l,r,c)::[] -> inc hist c0 c 1\n | (l,r,c)::tail ->\n\tinc hist c0 c 1;\n\tinc hist c c (r-l-1);\n\tadd_scan (l,r,c) tail\n in\n\n add_scan before_first (new_middle @ [after_last]);\n\n let newstr = Pset.union left_part right_part in\n List.fold_left (fun ac e -> Pset.add e ac) newstr new_middle\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_conv_str () =\n let s = bscanf Scanning.stdib \" %s \" (fun x -> x) in\n Array.init (String.length s) (fun i -> l2n s.[i])\n \nlet () =\n let n = read_int () in\n let m = read_int () in \n let k = read_int () in\n let s = read_conv_str () in\n\n let str = Pset.singleton (-1,0,k) in\n let str = Pset.add (n,n+1,k) str in\n\n let str = fold 0 (n-1) (\n fun i ac -> Pset.add (i, i+1, s.(i)) ac\n ) str in\n\n let hist = Array.make_matrix (k+1) (k+1) 0 in\n for i=0 to n-2 do\n inc hist s.(i) s.(i+1) 1\n done;\n\n ignore (fold 0 (m-1) (fun _ str ->\n match read_int() with\n | 1 ->\n\tlet l = -1 + read_int () in\n\tlet r = read_int () in\n\tlet c = (read_conv_str()).(0) in\n\tupdate str n l r c hist\n | 2 ->\n\tlet p = read_conv_str() in\n\tlet cycles = sum 0 (k-1) (fun i -> sum 0 i (fun j -> hist.(p.(i)).(p.(j)))) in\n\tprintf \"%d\\n\" (cycles+1);\n\tstr\n | _ -> failwith \"bad input\"\n ) str)\n"}], "negative_code": [], "src_uid": "ed56526ea39d477bcc549c8ff11ed3e2"} {"nl": {"description": "You have decided to watch the best moments of some movie. There are two buttons on your player: Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. Skip exactly x minutes of the movie (x is some fixed positive integer). If the player is now at the t-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (t\u2009+\u2009x). Initially the movie is turned on in the player on the first minute, and you want to watch exactly n best moments of the movie, the i-th best moment starts at the li-th minute and ends at the ri-th minute (more formally, the i-th best moment consists of minutes: li,\u2009li\u2009+\u20091,\u2009...,\u2009ri). Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?", "input_spec": "The first line contains two space-separated integers n, x (1\u2009\u2264\u2009n\u2009\u2264\u200950, 1\u2009\u2264\u2009x\u2009\u2264\u2009105) \u2014 the number of the best moments of the movie and the value of x for the second button. The following n lines contain the descriptions of the best moments of the movie, the i-th line of the description contains two integers separated by a space li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009105). It is guaranteed that for all integers i from 2 to n the following condition holds: ri\u2009-\u20091\u2009<\u2009li.", "output_spec": "Output a single number \u2014 the answer to the problem.", "sample_inputs": ["2 3\n5 6\n10 12", "1 1\n1 100000"], "sample_outputs": ["6", "100000"], "notes": "NoteIn the first sample, the player was initially standing on the first minute. As the minutes from the 1-st to the 4-th one don't contain interesting moments, we press the second button. Now we can not press the second button and skip 3 more minutes, because some of them contain interesting moments. Therefore, we watch the movie from the 4-th to the 6-th minute, after that the current time is 7. Similarly, we again skip 3 minutes and then watch from the 10-th to the 12-th minute of the movie. In total, we watch 6 minutes of the movie.In the second sample, the movie is very interesting, so you'll have to watch all 100000 minutes of the movie."}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%d %d\\n\" (fun n x ->\n let rec aux a t i =\n if i = n then a\n else begin\n let l, r = Scanf.scanf \"%d %d\\n\" (fun l r -> (l, r)) in\n let b = (l - t) mod x in\n let a = a + b + r - l + 1 in\n aux a (succ r) (succ i)\n end\n in\n Printf.printf \"%d\\n\" (aux 0 1 0)\n)\n"}, {"source_code": "\nlet rec watch curr skip watched lst =\n let is_skippable curr skip range =\n match (curr, skip, range) with\n c, s, [l; r;] when c + s <= l -> true\n | _ -> false\n in\n match lst with\n [] -> watched\n | _ ->\n let next = List.hd lst in\n let right = List.nth next 1\n in\n if is_skippable curr skip next then\n watch (curr + skip) skip watched lst\n else\n let minutes = right - curr + 1\n in\n watch (right + 1) skip (watched + minutes) (List.tl lst)\n;;\n\nlet words s = Str.split (Str.regexp \" \") s;; \n\nlet rec make_ranges lines =\n let rec inner lines rv =\n let range s = List.map int_of_string (words s) in\n match lines with\n [] -> rv\n | (l::ls) -> inner ls (List.append rv [range l])\n in\n inner lines []\n;;\n\nlet rec read_lines n =\n let rec inner m rv =\n match m with\n 0 -> rv\n | k -> inner (k - 1) (List.append rv [read_line ()])\n in\n inner n []\n;;\n\nlet () =\n let nk_line = read_line () in\n let [nline; skip] = List.map int_of_string (words nk_line) in\n let scenes = make_ranges (read_lines nline) in\n Printf.printf \"%d\\n\" (watch 1 skip 0 scenes)\n;;\n \n"}, {"source_code": "module A = Array;;\nmodule C = Char;;\nmodule L = List;;\nmodule S = String;;\n\nlet pf = Printf.printf;;\nlet sf = Scanf.scanf;;\nlet ssf = Scanf.sscanf;;\n\nlet (|>) x f = f x;;\nlet (@@) f x = f x;;\nlet id x = x;;\nlet id2 x y = (x, y);;\nlet id3 x y z = (x, y, z);;\n\nexception Error of string\n\nlet inf = 1000000000;;\nlet eps = 1e-11;;\n\nlet _ =\n let (n, x) = sf \"%d %d\\n\" id2 in\n let now = ref 0 in\n let res = ref 0 in\n for i = 1 to n do\n let (l, r) = sf \"%d %d\\n\" id2 in\n res := !res + (r - !now) - (l - !now - 1) / x * x;\n now := r\n done;\n pf \"%d\\n\" !res\n;;\n"}], "negative_code": [], "src_uid": "ac33b73da5aaf2139b348a9c237f93a4"} {"nl": {"description": "Shubham has an array $$$a$$$ of size $$$n$$$, and wants to select exactly $$$x$$$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.Tell him whether he can do so.", "input_spec": "The first line of the input contains a single integer $$$t$$$ $$$(1\\le t \\le 100)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ $$$(1 \\le x \\le n \\le 1000)$$$\u00a0\u2014 the length of the array and the number of elements you need to choose. The next line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ $$$(1 \\le a_i \\le 1000)$$$\u00a0\u2014 elements of the array.", "output_spec": "For each test case, print \"Yes\" or \"No\" depending on whether it is possible to choose $$$x$$$ elements such that their sum is odd. You may print every letter in any case you want.", "sample_inputs": ["5\n1 1\n999\n1 1\n1000\n2 1\n51 50\n2 2\n51 50\n3 3\n101 102 103"], "sample_outputs": ["Yes\nNo\nYes\nYes\nNo"], "notes": "NoteFor $$$1$$$st case: We must select element $$$999$$$, and the sum is odd.For $$$2$$$nd case: We must select element $$$1000$$$, so overall sum is not odd.For $$$3$$$rd case: We can select element $$$51$$$.For $$$4$$$th case: We must select both elements $$$50$$$ and $$$51$$$ \u00a0\u2014 so overall sum is odd.For $$$5$$$th case: We must select all elements \u00a0\u2014 but overall sum is not odd."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let (n,x) = read_pair() in\n let a = Array.init n read_int in\n let total = sum 0 (n-1) (fun i -> a.(i)) in\n\n let allodd = forall 0 (n-1) (fun i -> a.(i) mod 2 = 1) in\n let alleven = forall 0 (n-1) (fun i -> a.(i) mod 2 = 0) in \n\n let answer =\n if x = n then total mod 2 = 1\n else if allodd then x mod 2 = 1\n else if alleven then false\n else true\n in\n if answer then printf \"Yes\\n\" else printf \"No\\n\"\n done\n"}], "negative_code": [], "src_uid": "afce38aa7065da88d824d1d981b5b338"} {"nl": {"description": "Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types: replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4); swap any pair of digits in string a. Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.", "input_spec": "The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105.", "output_spec": "Print on the single line the single number \u2014 the minimum number of operations needed to convert string a into string b.", "sample_inputs": ["47\n74", "774\n744", "777\n444"], "sample_outputs": ["1", "1", "3"], "notes": "NoteIn the first sample it is enough simply to swap the first and the second digit.In the second sample we should replace the second digit with its opposite.In the third number we should replace all three digits with their opposites."}, "positive_code": [{"source_code": "\n(* Utils\n --------------------------------------------------------------------------- *)\n\nlet read_int () =\n Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet read_string () =\n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet ( |> ) x f = f x\n\n\n(* Solution \n --------------------------------------------------------------------------- *)\n\nlet _ =\n let s1 = read_line () in\n let s2 = read_line () in\n \n let c47 = ref 0 in\n let c74 = ref 0 in\n\n for i = 0 to String.length s1 - 1 do\n match (s1.[i], s2.[i]) with\n | '4', '7' -> incr c47\n | '7', '4' -> incr c74\n | _ -> ()\n done;\n\n Printf.printf \"%d\" (max !c47 !c74)\n"}, {"source_code": "(* codeforces 104. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let a = read_string() in\n let b = read_string() in\n let n = String.length a in\n let rec count i a47 a74 = if i=n then (a47,a74) else \n match (a.[i],b.[i]) with\n | ('4','7') -> count (i+1) (a47+1) a74\n | ('7','4') -> count (i+1) a47 (a74+1)\n | _ -> count (i+1) a47 a74\n in\n let (c47,c74) = count 0 0 0 in\n Printf.printf \"%d\\n\" (max c47 c74)\n"}], "negative_code": [], "src_uid": "2d1609b434262d30f6bd030d41a71bd5"} {"nl": {"description": "Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of \u200b\u200bthe region that will be cleared from snow. Help him.", "input_spec": "The first line of the input contains three integers\u00a0\u2014 the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integers\u00a0\u2014 coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1\u2009000\u2009000 in their absolute value.", "output_spec": "Print a single real value number\u00a0\u2014 the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["3 0 0\n0 1\n-1 2\n1 2", "4 1 -1\n0 0\n1 2\n2 0\n1 1"], "sample_outputs": ["12.566370614359172464", "21.991148575128551812"], "notes": "NoteIn the first sample snow will be removed from that area: "}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\nlet read_point () = Scanf.scanf \" %d %d\" (fun x y -> float x, float y)\n\nlet n = read_int ()\nlet p = read_point ()\nlet first = read_point ()\nlet prev = ref (0., 0.)\nlet () = prev := first\nlet minimum = ref infinity\nlet maximum = ref 0.\nlet pi = 3.14159265\n\nlet on_segment (x1, y1) (x, y) (x2, y2) =\n (x -. x1) *. (x -. x2) <= 0. && (y -. y1) *. (y -. y2) <= 0.\n\nlet min_and_max p1 p2 =\n let d (x, y) = sqrt ((fst p -. x)**2. +. (snd p -. y)**2.) in\n let rzut_p (x1, y1) (x2, y2) =\n let skal (x1, y1) (x2, y2) (x3, y3) =\n (x2 -. x1) *. (x3 -. x1) +. (y2 -. y1) *. (y3 -. y1)\n in\n let s = skal (x1, y1) p (x2, y2) /. skal (x1, y1) (x2, y2) (x2, y2) in\n ((x1 +. (x2 -. x1) *. s), (y1 +. (y2 -. y1) *. s))\n in\n let rzut = rzut_p p1 p2 in\n let min = if on_segment p1 rzut p2 then d rzut else min (d p1) (d p2) in\n (min, max (d p1) (d p2) )\n\nlet print_point (x, y) =\n print_float x;\n print_string \" \";\n print_float y;\n print_newline()\n\nlet add cur =\n let mini, maxi = min_and_max !prev cur in\n (if mini < !minimum then minimum := mini else ());\n (if maxi > !maximum then maximum := maxi else ());\n prev := cur\n;;\n\nlet () =\n for i = 1 to n - 1 do\n let cur = read_point () in\n add cur\n done;\n add first\n\nlet () =\n (pi *. !maximum ** 2. -. pi *. !minimum ** 2.) |> print_float;\n print_newline ()\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %f %f \" (fun x y -> (x,y))\n\nlet long x = Int64.of_int x\n\nlet cross (x1,y1) (x2,y2) = (x1*.y2) -. (y1*.x2)\nlet ( -- ) (x1,y1) (x2,y2) = (x1-.x2, y1-.y2)\nlet len (x,y) = sqrt(x*.x +. y*.y)\nlet dot (x1,y1) (x2,y2) = x1*.x2 +. y1*.y2\nlet mul c (x,y) = (c*.x, c*.y)\nlet sq x = x *. x\n \nlet dist p q r = (* the distance from point r to the line from point p to point q *)\n let a = q -- p in\n let b = r -- p in\n let an = mul (1.0 /. (len a)) a in\n let v = mul (dot an b) an in\n if len v <= len a && (dot v a) >= 0.0 then len (b -- v) else 1e15\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i) \nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet pi = 2.0 *. asin 1.0\n \nlet dist2 (a,b) (c,d) =\n let x = a-.c in\n let y = b-.d in\n ((x*.x) +. (y*.y))\n\n \nlet () = \n let n = read_int () in\n let p = read_pair () in\n let poly = Array.init n (fun _ -> read_pair()) in\n\n let inner = minf 0 (n-1) (fun i->\n min (dist2 p poly.(i)) (sq (dist poly.(i) poly.((i+1) mod n) p))\n ) in\n let outer = maxf 0 (n-1) (fun i-> dist2 p poly.(i)) in\n\n printf \"%.8f\\n\" (pi *. (outer -. inner))\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i) \nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet pi = 2.0 *. asin 1.0\n \nlet dist (a,b) (c,d) =\n let x = float (a-c) in\n let y = float (b-d) in\n sqrt ((x*.x) +. (y*.y))\n \nlet () = \n let n = read_int () in\n let p = read_pair () in\n let poly = Array.init n (fun _ -> read_pair()) in\n\n let inner = minf 0 (n-1) (fun i-> dist p poly.(i)) in\n let outer = maxf 0 (n-1) (fun i-> dist p poly.(i)) in\n\n printf \"%.8f\\n\" (pi *. (outer *. outer -. inner *. inner))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i) \nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet pi = 2.0 *. asin 1.0\n \nlet dist (a,b) (c,d) =\n let x = float (a-c) in\n let y = float (b-d) in\n sqrt ((x*.x) +. (y*.y))\n \nlet () = \n let n = read_int () in\n let p = read_pair () in\n let poly = Array.init n (fun _ -> read_pair()) in\n\n let inner = minf 0 (n-1) (fun i-> dist p poly.(i)) in\n let outer = maxf 0 (n-1) (fun i-> dist p poly.(i)) in\n\n printf \"%.8f\\n\" (pi *. (outer -. inner) *. (outer +. inner))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i) \nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet pi = 2.0 *. asin 1.0\n \nlet dist2 (a,b) (c,d) =\n let x = long (a-c) in\n let y = long (b-d) in\n ((x**x) ++ (y**y))\n \nlet () = \n let n = read_int () in\n let p = read_pair () in\n let poly = Array.init n (fun _ -> read_pair()) in\n\n let inner = minf 0 (n-1) (fun i-> dist2 p poly.(i)) in\n let outer = maxf 0 (n-1) (fun i-> dist2 p poly.(i)) in\n\n printf \"%.8f\\n\" (pi *. Int64.to_float (outer -- inner))\n"}], "src_uid": "1d547a38250c7780ddcf10674417d5ff"} {"nl": {"description": "Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has ai apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things: eat the apples, if the node is a leaf. move the apples to one of the children, if the node is non-leaf. Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v.Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u,\u2009v) and (v,\u2009u) are considered to be the same pair.", "input_spec": "The first line will contain one integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of nodes in the apple tree. The second line will contain n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009107) \u2014 the number of apples on each node of the tree. The third line will contain n\u2009-\u20091 integers p2,\u2009p3,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) \u2014 the parent of each node of the tree. Node i has parent pi (for 2\u2009\u2264\u2009i\u2009\u2264\u2009n). Node 1 is the root of the tree. It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.", "output_spec": "On a single line, print the number of different pairs of nodes (u,\u2009v), u\u2009\u2260\u2009v such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u,\u2009v) and (v,\u2009u) are considered to be the same pair.", "sample_inputs": ["3\n2 2 3\n1 1", "3\n1 2 3\n1 1", "8\n7 2 2 5 4 3 1 1\n1 1 1 4 4 5 6"], "sample_outputs": ["1", "0", "4"], "notes": "NoteIn the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move.In the second sample, There is no swap that will make Sagheer win the game.Note that Sagheer must make the swap even if he can win with the initial tree."}, "positive_code": [{"source_code": "(* keywords: impartial game, nimber\n\n Label each node as \"in\" or \"out\". The leaves are \"in\". in/out alternates\n as you go up the tree from the leaves. This is consistent because of\n the \"all leaf paths even or odd\" property of the tree.\n\n The nimber is computed by xoring the \"in\" nodes, and ignoring the\n \"out\" ones. This works because you can easily verify that if the\n nimber of the tree is 0 then any move makes it non-zero. Also if\n the nimber of a tree is non-zero then just treat it like a game of\n nim among the \"in\" nodes and make a move that returns it to 0.\n\n If the nimber is 0, then Sagheer must make a swap that keeps it 0.\n If the nimber is non-zero then he must make a swap that makes it 0.\n\n In the first case any in-in swap and any out-out swap is counted.\n In the 2nd case none of these are counted.\n\n Let N be the nimber of the initial game.\n For swapping an in-node u and out-node v, it is allowed if\n a.(u) xor a.(v) = N. These can be counted using hashing in O(n) time.\n*)\n(* started coding 6:10 done 6:46 *)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet xorsum i j f = fold i j (fun i a -> (f i) lxor a) 0\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet sumlong i j f = fold i j (fun i a -> (f i) ++ a) 0L \n\nlet choose2 k =\n let k = long k in\n (k ** (k -- 1L)) // 2L\n \nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n let isleaf = Array.make n true in\n let p = Array.init n (fun i ->\n if i=0 then 0 else\n let parent = -1 + read_int() in\n isleaf.(parent) <- false;\n parent\n ) in\n (* nodes are numbered 0, 1....n-1 with 0 the root. p.(i) is the parent of i *)\n\n let label = Array.make n (-1) in\n\n let rec dfs i parity =\n if label.(i) < 0 then (\n label.(i) <- parity;\n dfs p.(i) (1-parity)\n )\n in\n \n for i=0 to n-1 do\n if isleaf.(i) then dfs i 0\n done;\n\n (* nodes with label.(i) = 0 are \"in\" the others are \"out\" *)\n\n let nimber = xorsum 0 (n-1) (fun i -> (1 - label.(i)) * a.(i)) in\n\n let n_in = sum 0 (n-1) (fun i -> if label.(i) = 0 then 1 else 0) in\n let n_out = n - n_in in\n \n let count1 = if nimber = 0 then (choose2 n_in) ++ (choose2 n_out) else 0L in\n\n let in_table = Hashtbl.create 10 in\n let get t = try Hashtbl.find in_table t with Not_found -> 0 in\n let increment t = Hashtbl.replace in_table t ((get t) + 1) in\n\n for i=0 to n-1 do\n if label.(i) = 0 then increment a.(i)\n done;\n\n let crossterm = sumlong 0 (n-1) (fun i ->\n long (if label.(i) = 0 then 0 else get (a.(i) lxor nimber))\n ) in\n\n printf \"%Ld\\n\" (count1 ++ crossterm)\n"}], "negative_code": [{"source_code": "(* keywords: impartial game, nimber\n\n Label each node as \"in\" or \"out\". The leaves are \"in\". in/out alternates\n as you go up the tree from the leaves. This is consistent because of\n the \"all leaf paths even or odd\" property of the tree.\n\n The nimber is computed by xoring the \"in\" nodes, and ignoring the\n \"out\" ones. This works because you can easily verify that if the\n nimber of the tree is 0 then any move makes it non-zero. Also if\n the nimber of a tree is non-zero then just treat it like a game of\n nim among the \"in\" nodes and make a move that returns it to 0.\n\n If the nimber is 0, then Sagheer must make a swap that keeps it 0.\n If the nimber is non-zero then he must make a swap that makes it 0.\n\n In the first case any in-in swap and any out-out swap is counted.\n In the 2nd case none of these are counted.\n\n Let N be the nimber of the initial game.\n For swapping an in-node u and out-node v, it is allowed if\n a.(u) xor a.(v) = N. These can be counted using hashing in O(n) time.\n*)\n(* started coding 6:10 done 6:46 *)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet xorsum i j f = fold i j (fun i a -> (f i) lxor a) 0\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet sumlong i j f = fold i j (fun i a -> (f i) ++ a) 0L \n\nlet choose2 k =\n let k = long k in\n (k ** (k ++ 1L)) // 2L\n \nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n let isleaf = Array.make n true in\n let p = Array.init n (fun i ->\n if i=0 then 0 else\n let parent = -1 + read_int() in\n isleaf.(parent) <- false;\n parent\n ) in\n (* nodes are numbered 0, 1....n-1 with 0 the root. p.(i) is the parent of i *)\n\n let label = Array.make n (-1) in\n\n let rec dfs i parity =\n if label.(i) < 0 then (\n label.(i) <- parity;\n dfs p.(i) (1-parity)\n )\n in\n \n for i=0 to n-1 do\n if isleaf.(i) then dfs i 0\n done;\n\n (* nodes with label.(i) = 0 are \"in\" the others are \"out\" *)\n\n let nimber = xorsum 0 (n-1) (fun i -> (1 - label.(i)) * a.(i)) in\n\n let n_in = sum 0 (n-1) (fun i -> if label.(i) = 0 then 1 else 0) in\n let n_out = n - n_in in\n \n let count1 = if nimber = 0 then (choose2 n_in) ++ (choose2 n_out) else 0L in\n\n let in_table = Hashtbl.create 10 in\n let get t = try Hashtbl.find in_table t with Not_found -> 0 in\n let increment t = Hashtbl.replace in_table t ((get t) + 1) in\n\n for i=0 to n-1 do\n if label.(i) = 0 then increment a.(i)\n done;\n\n let crossterm = sumlong 0 (n-1) (fun i ->\n long (if label.(i) = 0 then 0 else get (a.(i) lxor nimber))\n ) in\n\n printf \"%Ld\\n\" (count1 ++ crossterm)\n"}], "src_uid": "6ecf80528aecd95d97583dc1aa309044"} {"nl": {"description": "The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1,\u2009a2,\u2009...,\u2009ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k\u2009<\u2009n), and this should be done in the smallest possible number of moves.One move is choosing an integer i (1\u2009\u2264\u2009i\u2009\u2264\u2009n) such that ai\u2009>\u20090 and an integer t (t\u2009\u2265\u20090) such that i\u2009+\u20092t\u2009\u2264\u2009n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai\u2009+\u20092t is increased by 1. For example, let n\u2009=\u20094 and a\u2009=\u2009(1,\u20090,\u20091,\u20092), then it is possible to make move i\u2009=\u20093, t\u2009=\u20090 and get a\u2009=\u2009(1,\u20090,\u20090,\u20093) or to make move i\u2009=\u20091, t\u2009=\u20091 and get a\u2009=\u2009(0,\u20090,\u20092,\u20092) (the only possible other move is i\u2009=\u20091, t\u2009=\u20090).You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1\u2009\u2264\u2009k\u2009<\u2009n).", "input_spec": "The first input line contains a single integer n. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009104), separated by single spaces. The input limitations for getting 20 points are: 1\u2009\u2264\u2009n\u2009\u2264\u2009300 The input limitations for getting 50 points are: 1\u2009\u2264\u2009n\u2009\u2264\u20092000 The input limitations for getting 100 points are: 1\u2009\u2264\u2009n\u2009\u2264\u2009105 ", "output_spec": "Print exactly n\u2009-\u20091 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams, or the %I64d specifier.", "sample_inputs": ["4\n1 0 1 2", "8\n1 2 3 4 5 6 7 8"], "sample_outputs": ["1\n1\n3", "1\n3\n6\n10\n16\n24\n40"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0L in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- Int64.of_int k\n done\n in\n let res = ref 0L in\n for i = 0 to n - 2 do\n let p = ref 1 in\n\twhile !p * 2 + i < n do\n\t p := !p * 2;\n\tdone;\n\tres := Int64.add !res a.(i);\n\ta.(i + !p) <- Int64.add a.(i + !p) a.(i);\n\ta.(i) <- 0L;\n\tPrintf.printf \"%Ld\\n\" !res;\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0L in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- Int64.of_int k\n done\n in\n let res = ref 0L in\n for i = 0 to n - 2 do\n let p = ref 1 in\n\twhile !p * 2 + i < n do\n\t p := !p * 2;\n\tdone;\n\tres := Int64.add !res a.(i);\n\ta.(i + !p) <- Int64.add a.(i + !p) a.(i);\n\ta.(i) <- 0L;\n\tPrintf.printf \"%Ld\\n\" !res;\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0L in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- Int64.of_int k\n done\n in\n let res = ref 0L in\n for i = 0 to n - 2 do\n let p = ref 1 in\n\twhile !p * 2 + i < n do\n\t p := !p * 2;\n\tdone;\n\tres := Int64.add !res a.(i);\n\ta.(i + !p) <- Int64.add a.(i + !p) a.(i);\n\ta.(i) <- 0L;\n\tPrintf.printf \"%Ld\\n\" !res;\n done\n"}], "negative_code": [], "src_uid": "c7e49c643dd8738f273c0d24e56c505f"} {"nl": {"description": "Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day?", "input_spec": "The first line contains three integers $$$n$$$, $$$L$$$ and $$$a$$$ ($$$0 \\le n \\le 10^{5}$$$, $$$1 \\le L \\le 10^{9}$$$, $$$1 \\le a \\le L$$$). The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$t_{i}$$$ and $$$l_{i}$$$ ($$$0 \\le t_{i} \\le L - 1$$$, $$$1 \\le l_{i} \\le L$$$). It is guaranteed that $$$t_{i} + l_{i} \\le t_{i + 1}$$$ and $$$t_{n} + l_{n} \\le L$$$.", "output_spec": "Output one integer \u00a0\u2014 the maximum number of breaks.", "sample_inputs": ["2 11 3\n0 1\n1 1", "0 5 2", "1 3 2\n1 2"], "sample_outputs": ["3", "2", "0"], "notes": "NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks."}, "positive_code": [{"source_code": "\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet n,l,a = Scanf.sscanf (read_line ()) \"%i %i %i\" (fun n l a -> n,l,a) in\nlet num = ref 0 in\nlet time = ref 0 in\nfor i = 0 to n-1 do\n let ti, li = Scanf.sscanf (read_line()) \"%i %i\" (fun ti li -> ti,li) in\n num := !num + ((ti - !time)/a);\n time := ti + li;\ndone;\nprint_int (!num + ((l - !time)/a))\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\n(* module Imos = struct\n\tlet make n = Array.make (i32 n +$ 2) 0L\n\tlet add_destructive_closed l r a =\n\t\ttry\n\t\ta.(l+$1) <- a.(l+$1) + 1L;\n\t\ta.(r+$2) <- a.(r+$2) - 1L\n\t\twith Invalid_argument _ -> ()\n\tlet add_destructive_1orig_closed l r a =\n\t\ta.(l) <- a.(l) + 1L;\n\t\ta.(r+$1) <- a.(r+$1) - 1L\n\tlet cumulate_destructive a = for i=1 to Array.length a -$ 2 do\n\t\ta.(i) <- a.(i) + a.(i-$1)\n\tdone\nend *)\n\nlet () =\n\tlet n,l,a = get_3_i64 9 in\n\tlet b = Array.init (i32 n) (fun _ -> get_2_i64 0)\n\tin\n\tlet p = ref 0L in\n\tlet c = ref 0L in\n\tArray.iter (fun (t,l) ->\n\t\t(* printf \"%Ld %Ld %Ld %Ld\\n\" !p t l !c; *)\n\t\tlet d = t - !p in c += (d / a);\n\t\tp := t + l\n\t) b;\n\tprintf \"%Ld\\n\" (!c + (l- !p)/a)"}], "negative_code": [], "src_uid": "00acb3b54975820989a788b9389c7c0b"} {"nl": {"description": "Shohag has an integer sequence $$$a_1, a_2, \\ldots, a_n$$$. He can perform the following operation any number of times (possibly, zero): Select any positive integer $$$k$$$ (it can be different in different operations). Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert $$$k$$$ into the sequence at this position. This way, the sequence $$$a$$$ changes, and the next operation is performed on this changed sequence. For example, if $$$a=[3,3,4]$$$ and he selects $$$k = 2$$$, then after the operation he can obtain one of the sequences $$$[\\underline{2},3,3,4]$$$, $$$[3,\\underline{2},3,4]$$$, $$$[3,3,\\underline{2},4]$$$, or $$$[3,3,4,\\underline{2}]$$$.Shohag wants this sequence to satisfy the following condition: for each $$$1 \\le i \\le |a|$$$, $$$a_i \\le i$$$. Here, $$$|a|$$$ denotes the size of $$$a$$$.Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 200$$$) \u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the initial length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the elements of the sequence.", "output_spec": "For each test case, print a single integer \u00a0\u2014 the minimum number of operations needed to perform to achieve the goal mentioned in the statement.", "sample_inputs": ["4\n3\n1 3 4\n5\n1 2 5 7 4\n1\n1\n3\n69 6969 696969"], "sample_outputs": ["1\n3\n0\n696966"], "notes": "NoteIn the first test case, we have to perform at least one operation, as $$$a_2=3>2$$$. We can perform the operation $$$[1, 3, 4] \\rightarrow [1, \\underline{2}, 3, 4]$$$ (the newly inserted element is underlined), now the condition is satisfied.In the second test case, Shohag can perform the following operations:$$$[1, 2, 5, 7, 4] \\rightarrow [1, 2, \\underline{3}, 5, 7, 4] \\rightarrow [1, 2, 3, \\underline{4}, 5, 7, 4] \\rightarrow [1, 2, 3, 4, 5, \\underline{3}, 7, 4]$$$.In the third test case, the sequence already satisfies the condition."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d\" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\n\nlet rec add_changes list idx acc = \n match list with \n |[] -> acc\n |h::t -> if h > idx then add_changes t (h+1) (acc + (h-idx)) else add_changes t (idx+1) (acc)\n\nlet () = \n let cases = read_int() in\n for cases = 1 to cases do\n let n = read_int() in\n let arr = Array.make n 0 in\n for n=0 to n-1 do\n let num = read_int() in\n Array.set arr n num\n done;\n let list = Array.to_list arr in\n printf (\"%d\\n\") (add_changes list 1 0)\n done;"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d\" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\n\nlet rec add_changes list idx acc = \n match list with \n |[] -> acc\n |h::t -> if acc + (h -1 -acc - idx ) < 0 then add_changes t (idx + 1) (acc) else add_changes t (idx + 1) (acc + (h -1 -acc - idx ))\n\nlet () = \n let cases = read_int() in\n for cases = 1 to cases do\n let n = read_int() in\n let arr = Array.make n 0 in\n for n=0 to n-1 do\n let num = read_int() in\n Array.set arr n num\n done;\n let list = Array.to_list arr in\n printf (\"%d\\n\") (add_changes list 0 0)\n done;"}], "src_uid": "e79c6a337e9347522bf19f3d5c162541"} {"nl": {"description": "During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants. Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula .After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di\u2009<\u2009k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di\u2009<\u2009k. We also know that the applications for exclusion from rating were submitted by all participants.Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105,\u2009\u2009-\u2009109\u2009\u2264\u2009k\u2009\u2264\u20090). The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 ratings of the participants in the initial table.", "output_spec": "Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.", "sample_inputs": ["5 0\n5 3 4 1 2", "10 -10\n5 5 1 7 5 1 2 4 9 2"], "sample_outputs": ["2\n3\n4", "2\n4\n5\n7\n8\n9"], "notes": "NoteConsider the first test sample. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered. Thus, you should print 2, 3, 4."}, "positive_code": [{"source_code": "\nlet () =\n let (@@) f x = f x in\n let (%) f g x = f @@ g x in\n let (|>) x f = f x in\n let open List in\n let open Num in\n let split = Str.split @@ Str.regexp_string \" \" in\n read_line () |> split |> map int_of_string |> fun n_k ->\n let n = hd n_k and k = hd @@ tl n_k in\n read_line () |> split |> map int_of_string |> mapi (fun i a -> i + 1, a) |> fun ratings ->\n let rec loop rev_result acc i n = function\n | (_, ai) as r :: rs when acc -/ (Int ai) */ (Int n -/ Int i) */ (Int i -/ Int 1) \n loop (r :: rev_result) acc i (n - 1) rs\n | (_, ai) :: rs -> loop rev_result (acc +/ (Int ai) */ (Int i -/ Int 1)) (i + 1) n rs\n | [] -> rev rev_result\n in\n loop [] (Int 0) 1 n ratings |> map (string_of_int % fst) |> iter print_endline\n"}, {"source_code": "\nlet () =\n let (@@) f x = f x in\n let (%) f g x = f @@ g x in\n let (|>) x f = f x in\n let open List in\n let open Num in\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n k ->\n Array.init n (fun i -> scanf \"%d \" @@ fun a -> i + 1, a) |> Array.to_list |> fun ratings ->\n let rec loop rev_result acc i n = function\n | (_, ai) as r :: rs when acc -/ (Int ai) */ (Int n -/ Int i) */ (Int i -/ Int 1) \n loop (r :: rev_result) acc i (n - 1) rs\n | (_, ai) :: rs -> loop rev_result (acc +/ (Int ai) */ (Int i -/ Int 1)) (i + 1) n rs\n | [] -> rev rev_result\n in\n loop [] (Int 0) 1 n ratings |> map (string_of_int % fst) |> iter print_endline\n"}], "negative_code": [{"source_code": "\nlet () =\n let (@@) f x = f x in\n let (%) f g x = f @@ g x in\n let (|>) x f = f x in\n let (|*>) (a, b) f = f a b in\n let open List in\n let split = Str.split @@ Str.regexp_string \" \" in\n read_line () |> split |> map int_of_string |> fun n_k ->\n let n = hd n_k and k = hd @@ tl n_k in\n read_line () |> split |> map int_of_string |> mapi (fun i a -> i + 1, a) |> fun ratings ->\n let d ratings (i, ai) =\n (0, ratings) |*> fold_left (fun s (j, aj) -> s + if j < i then aj * (j - 1) - (n - i) * ai else 0)\n in\n let extract_next ratings =\n let rec loop rev_head = function\n | r :: rs when d ratings r < k -> (r, rev_append rev_head rs)\n | r :: rs -> loop (r :: rev_head) rs\n | [] -> raise Not_found\n in\n loop [] ratings\n in\n let rec loop rev_result rs =\n try let r, rs = extract_next rs in loop (r :: rev_result) rs\n with Not_found -> rev rev_result\n in\n loop [] ratings |> map (string_of_int % fst) |> iter print_endline\n"}, {"source_code": "\nlet () =\n let (@@) f x = f x in\n let (%) f g x = f @@ g x in\n let (|>) x f = f x in\n let (|*>) (a, b) f = f a b in\n let open List in\n let open Int64 in\n let split = Str.split @@ Str.regexp_string \" \" in\n read_line () |> split |> map int_of_string |> fun n_k ->\n let n = hd n_k and k = hd @@ tl n_k in\n read_line () |> split |> map int_of_string |> mapi (fun i a -> i + 1, a) |> fun ratings ->\n let d ratings (i, ai) =\n (0L, ratings) |*> fold_left (fun s (j, aj) ->\n add s @@\n if j < i then sub (mul (of_int aj) (sub (of_int j) 1L)) @@ mul (sub (of_int n) @@ of_int i) (of_int ai)\n else 0L)\n in\n let extract_next ratings =\n let rec loop rev_head = function\n | r :: rs when d ratings r < (of_int k) -> (r, rev_append rev_head rs)\n | r :: rs -> loop (r :: rev_head) rs\n | [] -> raise Not_found\n in\n loop [] ratings\n in\n let rec loop rev_result rs =\n try let r, rs = extract_next rs in loop (r :: rev_result) rs\n with Not_found -> rev rev_result\n in\n loop [] ratings |> map (string_of_int % fst) |> iter print_endline\n"}], "src_uid": "7237361e3c2a9b1524d6410283839d48"} {"nl": {"description": "Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai\u2009+\u20091 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?", "input_spec": "The first line contains two space-separated integers n and v (1\u2009\u2264\u2009n,\u2009v\u2009\u2264\u20093000) \u2014 the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20093000) \u2014 the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree.", "output_spec": "Print a single integer \u2014 the maximum number of fruit that Valera can collect. ", "sample_inputs": ["2 3\n1 5\n2 3", "5 10\n3 20\n2 20\n1 20\n4 20\n5 20"], "sample_outputs": ["8", "60"], "notes": "NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet nn = 3001\nlet () = \n let n = read_int () in\n let v = read_int () in\n let fruit = Array.make (nn+1) 0 in\n for i=0 to n-1 do\n let a = read_int() in\n let b = read_int() in\n fruit.(a) <- fruit.(a) + b\n done;\n\n let ( ++ ) a b = Int64.add a b in\n\n let count = ref 0L in\n\n for t=1 to nn do \n let prev = fruit.(t-1) in\n let take_prev = min v prev in\n count := !count ++ (Int64.of_int take_prev);\n fruit.(t-1) <- fruit.(t-1) - take_prev;\n let v = v - take_prev in\n let current = fruit.(t) in\n let take_current = min v current in\n count := !count ++ (Int64.of_int take_current);\n fruit.(t) <- fruit.(t) - take_current;\n done;\n\n printf \"%Ld\\n\" !count\n"}, {"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet v=read_int();;\nlet tab=Array.make (n+1) 0;;\nlet vec=Array.make (n+1) 0;;\nlet mat=Array.make 3001 0;;\nfor i=1 to n do\n let x=read_int() and y=read_int() in (tab.(i)<-x;mat.(x)<-mat.(x)+y)\ndone;;\nlet r=ref 0;;\nlet nb=ref 0;;\nfor i=1 to 3000 do\n nb:= !nb+min (!r) v;\n let vv=v-min (!r) v in\n nb:= !nb+min vv mat.(i);\n r:= mat.(i)-min vv mat.(i)\ndone;;\nprint_int (!nb+min !r v);;"}], "negative_code": [], "src_uid": "848ead2b878f9fd8547e1d442e2f85ff"} {"nl": {"description": "The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called \"Testing Pants for Sadness\".The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), the number of answer variants to question i.", "output_spec": "Print a single number \u2014 the minimal number of clicks needed to pass the test it the worst-case scenario. Please do not use the %lld specificator to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specificator.", "sample_inputs": ["2\n1 1", "2\n2 2", "1\n10"], "sample_outputs": ["2", "5", "10"], "notes": "NoteNote to the second sample. In the worst-case scenario you will need five clicks: the first click selects the first variant to the first question, this answer turns out to be wrong. the second click selects the second variant to the first question, it proves correct and we move on to the second question; the third click selects the first variant to the second question, it is wrong and we go back to question 1; the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question; the fifth click selects the second variant to the second question, it proves correct, the test is finished. "}, "positive_code": [{"source_code": "(* Codeforces 103A - UnilShtan *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet n = gr();;\nlet a = readlist n [];;\n\nlet rec count_shtan a k acc = match a with\n\t| [] -> acc\n\t| ai :: [] ->\n\t\tlet acc1 = (Int64.add acc (Int64.mul (Int64.of_int ai) (Int64.of_int k))) in\n\t\tcount_shtan [] (k+1) acc1\n\t| ai :: tl ->\n\t\tlet acc1 = (Int64.add acc (Int64. mul (Int64.of_int (ai-1)) (Int64.of_int (k)))) in\n\t\t( \n\t\t\t(* print_string \"acc1= \"; *)\n\t\t\t(* print_string ((Int64.to_string acc1) ^ \"\\n\"); *)\n\t\t\tcount_shtan tl (k+1) acc1\n\t\t\t);;\n\nlet main() =\n\tbegin\n\t\tlet cnt = count_shtan a 1 Int64.zero in\n\t\tprint_string ((Int64.to_string cnt) ^ \"\\n\")\n\tend;;\n\nmain();;\n"}], "negative_code": [{"source_code": "(* Codeforces 103A - UnilShtan *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet n = gr();;\nlet a = readlist n [];;\n\nlet rec count_shtan a k acc = match a with\n\t| [] -> acc\n\t| ai :: [] ->\n\t\tlet acc1 = (Int64.add acc (Int64. mul (Int64.of_int ai) (Int64.of_int k))) in\n\t\tcount_shtan [] (k+1) acc1\n\t| ai :: tl ->\n\t\tlet acc1 = (Int64.add acc (Int64. mul (Int64.of_int (ai-1)) (Int64.of_int (k)))) in\n\t\tcount_shtan tl (k+1) acc1;;\n\nlet main() =\n\tbegin\n\t\tlet cnt = count_shtan a 1 Int64.zero in\n\t\tprint_string ((Int64.to_string cnt) ^ \"\\n\")\n\tend;;\n\nmain();;\n"}], "src_uid": "c8531b2ab93993b2c3467595ad0679c5"} {"nl": {"description": "$$$n$$$ students attended the first meeting of the Berland SU programming course ($$$n$$$ is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups must be different. Furthermore, both groups should contain the same number of students.Each student has filled a survey in which they told which days of the week are convenient for them to attend a lesson, and which are not. Your task is to determine if it is possible to choose two different week days to schedule the lessons for the group (the first group will attend the lesson on the first chosen day, the second group will attend the lesson on the second chosen day), and divide the students into two groups, so the groups have equal sizes, and for each student, the chosen lesson day for their group is convenient.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains one integer $$$n$$$ ($$$2 \\le n \\le 1\\,000$$$)\u00a0\u2014 the number of students. The $$$i$$$-th of the next $$$n$$$ lines contains $$$5$$$ integers, each of them is $$$0$$$ or $$$1$$$. If the $$$j$$$-th integer is $$$1$$$, then the $$$i$$$-th student can attend the lessons on the $$$j$$$-th day of the week. If the $$$j$$$-th integer is $$$0$$$, then the $$$i$$$-th student cannot attend the lessons on the $$$j$$$-th day of the week. Additional constraints on the input: for each student, at least one of the days of the week is convenient, the total number of students over all testcases doesn't exceed $$$10^5$$$.", "output_spec": "For each testcase print an answer. If it's possible to divide the students into two groups of equal sizes and choose different days for the groups so each student can attend the lesson in the chosen day of their group, print \"YES\" (without quotes). Otherwise, print \"NO\" (without quotes). ", "sample_inputs": ["2\n4\n1 0 0 1 0\n0 1 0 0 1\n0 0 0 1 0\n0 1 0 1 0\n2\n0 0 0 1 0\n0 0 0 1 0"], "sample_outputs": ["YES\nNO"], "notes": "NoteIn the first testcase, there is a way to meet all the constraints. For example, the first group can consist of the first and the third students, they will attend the lessons on Thursday (the fourth day); the second group can consist of the second and the fourth students, and they will attend the lessons on Tuesday (the second day).In the second testcase, it is impossible to divide the students into groups so they attend the lessons on different days."}, "positive_code": [{"source_code": "let t = read_int ();;\r\n\r\nlet parse s =\r\n (s.[0] = '1',\r\n s.[2] = '1',\r\n s.[4] = '1',\r\n s.[6] = '1',\r\n s.[8] = '1');;\r\n\r\nlet rec solve n (a, b, c, d, e) (c12, c13, c14, c15, c23, c24, c25, c34, c35, c45) = function\r\n 0 -> (a >= n/2 && b >= n/2 && c12) ||\r\n (a >= n/2 && c >= n/2 && c13) ||\r\n (a >= n/2 && d >= n/2 && c14) ||\r\n (a >= n/2 && e >= n/2 && c15) ||\r\n (b >= n/2 && c >= n/2 && c23) ||\r\n (b >= n/2 && d >= n/2 && c24) ||\r\n (b >= n/2 && e >= n/2 && c25) ||\r\n (c >= n/2 && d >= n/2 && c34) ||\r\n (c >= n/2 && e >= n/2 && c35) ||\r\n (d >= n/2 && e >= n/2 && c45)\r\n| k -> let (da, db, dc, dd, de) = parse (read_line ()) in\r\n solve n\r\n ((a + if da then 1 else 0),\r\n (b + if db then 1 else 0),\r\n (c + if dc then 1 else 0),\r\n (d + if dd then 1 else 0),\r\n (e + if de then 1 else 0))\r\n (c12 && (da || db), \r\n c13 && (da || dc), \r\n c14 && (da || dd), \r\n c15 && (da || de), \r\n c23 && (db || dc), \r\n c24 && (db || dd), \r\n c25 && (db || de), \r\n c34 && (dc || dd), \r\n c35 && (dc || de), \r\n c45 && (dd || de))\r\n (k-1);;\r\n\r\nlet rec main = function\r\n 0 -> ()\r\n| k ->\r\n begin\r\n let n = read_int () in\r\n if solve n (0, 0, 0, 0, 0) (true, true, true, true, true, true, true, true, true, true) n then print_string \"YES\" else print_string \"NO\" ;\r\n print_newline ();\r\n main (k-1)\r\n end;;\r\n\r\nmain t;;"}], "negative_code": [{"source_code": "let t = read_int ();;\r\n\r\nlet parse s =\r\n (s.[0] = '1',\r\n s.[2] = '1',\r\n s.[4] = '1',\r\n s.[6] = '1',\r\n s.[8] = '1');;\r\n\r\nlet rec solve n (a, b, c, d, e) (c12, c13, c14, c15, c23, c24, c25, c34, c35, c45) = function\r\n 0 -> (a >= n/2 && b >= n/2 && c12) ||\r\n (a >= n/2 && c >= n/2 && c13) ||\r\n (a >= n/2 && d >= n/2 && c14) ||\r\n (a >= n/2 && e >= n/2 && c15) ||\r\n (b >= n/2 && c >= n/2 && c23) ||\r\n (b >= n/2 && d >= n/2 && c24) ||\r\n (b >= n/2 && e >= n/2 && c25) ||\r\n (c >= n/2 && d >= n/2 && c34) ||\r\n (c >= n/2 && e >= n/2 && c35) ||\r\n (a >= n/2 && e >= n/2 && c45)\r\n| k -> let (da, db, dc, dd, de) = parse (read_line ()) in\r\n solve n\r\n ((a + if da then 1 else 0),\r\n (b + if db then 1 else 0),\r\n (c + if dc then 1 else 0),\r\n (d + if dd then 1 else 0),\r\n (e + if de then 1 else 0))\r\n (c12 && (da || db), \r\n c13 && (da || dc), \r\n c14 && (da || dd), \r\n c15 && (da || de), \r\n c23 && (db || dc), \r\n c24 && (db || dd), \r\n c25 && (db || de), \r\n c34 && (dc || dd), \r\n c35 && (dc || de), \r\n c45 && (dd || de))\r\n (k-1);;\r\n\r\nlet rec main = function\r\n 0 -> ()\r\n| k ->\r\n begin\r\n let n = read_int () in\r\n if solve n (0, 0, 0, 0, 0) (true, true, true, true, true, true, true, true, true, true) n then print_string \"YES\" else print_string \"NO\" ;\r\n print_newline ();\r\n main (k-1)\r\n end;;\r\n\r\nmain t;;"}, {"source_code": "let t = read_int ();;\r\n\r\nlet parse s =\r\n (s.[0] = '1',\r\n s.[2] = '1',\r\n s.[4] = '1',\r\n s.[6] = '1',\r\n s.[8] = '1');;\r\n\r\nlet rec solve n (a, b, c, d, e) (c12, c13, c14, c15, c23, c24, c25, c34, c35, c45) = function\r\n 0 -> (a >= n/2 && b >= n/2 && c12) ||\r\n (a >= n/2 && c >= n/2 && c13) ||\r\n (a >= n/2 && d >= n/2 && c14) ||\r\n (a >= n/2 && e >= n/2 && c15) ||\r\n (b >= n/2 && c >= n/2 && c23) ||\r\n (b >= n/2 && d >= n/2 && c24) ||\r\n (b >= n/2 && e >= n/2 && c25) ||\r\n (c >= n/2 && d >= n/2 && c34) ||\r\n (c >= n/2 && e >= n/2 && c35) ||\r\n (a >= n/2 && e >= n/2 && c45)\r\n| k -> let (da, db, dc, dd, de) = parse (read_line ()) in\r\n solve n\r\n ((a + if da then 1 else 0),\r\n (b + if db then 1 else 0),\r\n (c + if dc then 1 else 0),\r\n (d + if dd then 1 else 0),\r\n (e + if de then 1 else 0))\r\n (c12 && (da || db), \r\n c13 && (da || dc), \r\n c14 && (da || dd), \r\n c15 && (da || de), \r\n c23 && (db || dc), \r\n c24 && (db || dd), \r\n c25 && (db || de), \r\n c34 && (dc || dd), \r\n c35 && (dc || de), \r\n c45 && (dd || de))\r\n (k-1);;\r\n\r\nlet rec main = function\r\n 0 -> ()\r\n| k ->\r\n begin\r\n let n = read_int () in\r\n if solve n (0, 0, 0, 0, 0) (true, true, true, true, true, true, true, true, true, true) n then print_string \"YES\" else print_string \"NO\" ;\r\n main (k-1)\r\n end;;\r\n\r\nmain t;;"}], "src_uid": "068cbfb901aadcd15f794dbbf3dfd453"} {"nl": {"description": "You are given a number $$$k$$$ and a string $$$s$$$ of length $$$n$$$, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met: The first character '*' in the original string should be replaced with 'x'; The last character '*' in the original string should be replaced with 'x'; The distance between two neighboring replaced characters 'x' must not exceed $$$k$$$ (more formally, if you replaced characters at positions $$$i$$$ and $$$j$$$ ($$$i < j$$$) and at positions $$$[i+1, j-1]$$$ there is no \"x\" symbol, then $$$j-i$$$ must be no more than $$$k$$$). For example, if $$$n=7$$$, $$$s=$$$.**.*** and $$$k=3$$$, then the following strings will satisfy the conditions above: .xx.*xx; .x*.x*x; .xx.xxx. But, for example, the following strings will not meet the conditions: .**.*xx (the first character '*' should be replaced with 'x'); .x*.xx* (the last character '*' should be replaced with 'x'); .x*.*xx (the distance between characters at positions $$$2$$$ and $$$6$$$ is greater than $$$k=3$$$). Given $$$n$$$, $$$k$$$, and $$$s$$$, find the minimum number of '*' characters that must be replaced with 'x' in order to meet the above conditions.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 500$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 50$$$). The second line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of the characters '.' and '*'. It is guaranteed that there is at least one '*' in the string $$$s$$$. It is guaranteed that the distance between any two neighboring '*' characters does not exceed $$$k$$$.", "output_spec": "For each test case output the minimum number of '*' characters that must be replaced with 'x' characters in order to satisfy the conditions above.", "sample_inputs": ["5\n7 3\n.**.***\n5 1\n..*..\n5 2\n*.*.*\n3 2\n*.*\n1 1\n*"], "sample_outputs": ["3\n1\n3\n2\n1"], "notes": null}, "positive_code": [{"source_code": "(* https://codeforces.com/problemset/problem/1506/B *)\n\nlet trim str len =\n let rec seek i step =\n if str.[i] = '*'\n then i\n else seek (i+step) step in\n let first, last = (seek 0 1), (seek (len-1) ~-1) in\n if first = last\n then \"\"\n else String.sub str (first+1) (last-first-1)\n\nlet replace max_dist str len =\n let rec seek i step =\n if str.[i] = '*'\n then i\n else seek (i+step) step in\n let first, last = (seek 0 1), (seek (len-1) ~-1) in\n if first = last\n then 1\n else\n let sublen = last-first-1 in\n let sub = String.sub str (first+1) sublen in\n let rec helper start i last_seen count =\n if i = sublen\n then count\n else if i-start < max_dist\n then if sub.[i] = '*'\n then helper start (i+1) i count\n else helper start (i+1) last_seen count\n else if sub.[i] = '*'\n then helper i (i+1) i (count+1)\n else helper last_seen (i+1) last_seen (count+1) in\n 2 + helper ~-1 0 ~-1 0\n\nlet solve_n n =\n let rec helper i =\n if i <> 0\n then (\n let [len; max_dist] =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n let str = read_line () in\n replace max_dist str len\n |> Printf.printf \"%d\\n\";\n helper (i-1)\n ) in\n helper n\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "negative_code": [{"source_code": "(* https://codeforces.com/problemset/problem/1506/B *)\n\nlet trim str len =\n let rec seek i step =\n if str.[i] = '*'\n then i\n else seek (i+step) step in\n let first, last = (seek 0 1), (seek (len-1) ~-1) in\n if first = last\n then \"\"\n else String.sub str (first+1) (last-first-1)\n\nlet replace max_dist str len =\n let rec seek i step =\n if str.[i] = '*'\n then i\n else seek (i+step) step in\n let first, last = (seek 0 1), (seek (len-1) ~-1) in\n if first = last\n then 1\n else\n let sublen = last-first-1 in\n let sub = String.sub str (first+1) sublen in\n let rec helper start i last_seen count =\n if i = sublen\n then (if i-last_seen=max_dist then count+1 else count)\n else if i-start < max_dist\n then if sub.[i] = '*'\n then helper start (i+1) i count\n else helper start (i+1) last_seen count\n else if sub.[i] = '*'\n then helper i (i+1) i (count+1)\n else helper last_seen (i+1) last_seen (count+1) in\n 2 + helper 0 0 ~-1 0\n\nlet solve_n n =\n let rec helper i =\n if i <> 0\n then (\n let [len; max_dist] =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n let str = read_line () in\n replace max_dist str len\n |> Printf.printf \"%d\\n\";\n helper (i-1)\n ) in\n helper n\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}, {"source_code": "(* https://codeforces.com/problemset/problem/1506/B *)\n\nlet trim str len =\n let rec seek i step =\n if str.[i] = '*'\n then i\n else seek (i+step) step in\n let first, last = (seek 0 1), (seek (len-1) ~-1) in\n if first = last\n then \"\"\n else String.sub str (first+1) (last-first-1)\n\nlet replace max_dist str len =\n let rec seek i step =\n if str.[i] = '*'\n then i\n else seek (i+step) step in\n let first, last = (seek 0 1), (seek (len-1) ~-1) in\n if first = last\n then 1\n else\n let sublen = last-first-1 in\n let sub = String.sub str (first+1) sublen in\n let rec helper start i last_seen count =\n if i = sublen\n then count\n else if i-start < max_dist\n then if sub.[i] = '*'\n then helper start (i+1) i count\n else helper start (i+1) last_seen count\n else if sub.[i] = '*'\n then helper i (i+1) i (count+1)\n else helper last_seen (i+1) last_seen (count+1) in\n 2 + helper 0 0 0 0\n\nlet solve_n n =\n let rec helper i =\n if i <> 0\n then (\n let [len; max_dist] =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n let str = read_line () in\n replace max_dist str len\n |> Printf.printf \"%d\\n\";\n helper (i-1)\n ) in\n helper n\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}, {"source_code": "(* https://codeforces.com/contest/1506/problem/B *)\n\nlet replacement str max_distance =\n let len = String.length str in\n let rec seek_start i =\n if str.[i] = '*'\n then i\n else seek_start (i+1) in\n let rec seek_end i =\n if str.[i] = '*'\n then i\n else seek_end (i-1) in\n let first, last = (seek_start 0), (seek_end (len-1)) in\n if first = last\n then 1\n else 2 + (last-first-1) / max_distance\n\nlet solve_n n =\n let rec helper i =\n if i <> 0\n then (\n let [_; max_dist] =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n let str = read_line () in\n replacement str max_dist\n |> Printf.printf \"%d\\n\";\n helper (i-1)\n ) in\n helper n\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "src_uid": "874e22d4fd8e35f7e0eade2b469ee5dc"} {"nl": {"description": "By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).Initially, all colliders are deactivated. Your program receives multiple requests of the form \"activate/deactivate the i-th collider\". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.To the request of \"+ i\" (that is, to activate the i-th collider), the program should print exactly one of the following responses: \"Success\" if the activation was successful. \"Already on\", if the i-th collider was already activated before the request. \"Conflict with j\", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of \"- i\" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: \"Success\", if the deactivation was successful. \"Already off\", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either \"+ i\" (without the quotes) \u2014 activate the i-th collider, or \"-\u00a0i\" (without the quotes) \u2014 deactivate the i-th collider (1\u2009\u2264\u2009i\u2009\u2264\u2009n).", "output_spec": "Print m lines \u2014 the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.", "sample_inputs": ["10 10\n+ 6\n+ 10\n+ 5\n- 10\n- 5\n- 6\n+ 10\n+ 3\n+ 6\n+ 3"], "sample_outputs": ["Success\nConflict with 6\nSuccess\nAlready off\nSuccess\nSuccess\nSuccess\nSuccess\nConflict with 10\nAlready on"], "notes": "NoteNote that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response \"Conflict with 3\"."}, "positive_code": [{"source_code": "let main () =\n let n, m = Scanf.sscanf (read_line ()) \"%d %d\" (fun n m -> n, m) in\n let arr = Array.create (n + 1) [] in\n for i = 2 to n do\n if arr.(i) = [] then (\n let rec loop j =\n if j <= n then (\n arr.(j) <- i :: arr.(j);\n loop (j + i)\n )\n in\n loop i\n )\n done;\n\n let col = Array.create (n + 1) false in\n let prim = Array.create (n + 1) 0 in\n \n let rec loop i =\n if i > 0 then (\n let (c, r) = Scanf.sscanf (read_line ()) \"%c %d\" (fun c r -> c, r) in\n if c = '+' then (\n if col.(r) then\n print_endline \"Already on\"\n else\n let k = List.fold_left (fun acc v -> if prim.(v) > 0 then prim.(v) else acc) 0 arr.(r) in\n if k > 0 then Printf.printf \"Conflict with %d\\n\" k else (\n print_endline \"Success\";\n col.(r) <- true;\n List.iter (fun v -> prim.(v) <- r) arr.(r)\n )\n ) else (\n if not col.(r) then print_endline \"Already off\" else\n let _ = print_endline \"Success\" in\n let _ = col.(r) <- false in\n List.iter (fun v -> prim.(v) <- 0) arr.(r)\n );\n loop (i - 1)\n )\n in\n loop m\n;;\nmain()\n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nexception Found of int\n\nlet _ =\n let n = 100000 in\n let prime = Array.make (n + 1) true in\n let d = Array.make (n + 1) 0 in\n let p = Array.make 10000 0 in\n let pk = ref 0 in\n let _ =\n for i = 2 to n do\n if prime.(i) then (\n\tp.(!pk) <- i;\n\td.(i) <- !pk;\n\tincr pk;\n\tlet j = ref (2 * i) in\n while !j <= n do\n\t let jj = !j in\n prime.(jj) <- false;\n\t d.(jj) <- !pk - 1;\n j := jj + i\n done\n )\n done;\n in\n let pk = !pk - 1 in\n let n = getnum () in\n let m = getnum () in\n let a = Array.make (n + 1) false in\n let h = Array.init 10000 (fun _ -> Hashtbl.create 1) in\n for i = 1 to m do\n let q = getnum () in\n let k = getnum () in\n\tmatch q with\n\t | -5 -> (* + *)\n\t if a.(k)\n\t then Printf.printf \"Already on\\n\"\n\t else (\n\t\ttry\n\t\t (let r = ref k in\n\t\t while !r > 1 do\n\t\t let pn = d.(!r) in\n\t\t let p = p.(pn) in\n\t\t\t while !r mod p = 0 do\n\t\t\t r := !r / p\n\t\t\t done;\n\t\t\t let ht = h.(pn) in\n\t\t\t if Hashtbl.length ht <> 0 then (\n\t\t\t Hashtbl.iter (fun c () -> raise (Found c)) ht\n\t\t\t )\n\t\t done);\n\t\t a.(k) <- true;\n\t\t (let r = ref k in\n\t\t while !r > 1 do\n\t\t let pn = d.(!r) in\n\t\t let p = p.(pn) in\n\t\t\t while !r mod p = 0 do\n\t\t\t r := !r / p\n\t\t\t done;\n\t\t\t let ht = h.(pn) in\n\t\t\t Hashtbl.replace ht k ()\n\t\t done);\n\t\t Printf.printf \"Success\\n\"\n\t\twith\n\t\t | Found c ->\n\t\t Printf.printf \"Conflict with %d\\n\" c\n\t )\n\t | 0 -> (* - *)\n\t if not a.(k)\n\t then Printf.printf \"Already off\\n\"\n\t else (\n\t\ta.(k) <- false;\n\t\t(let r = ref k in\n\t\t while !r > 1 do\n\t\t let pn = d.(!r) in\n\t\t let p = p.(pn) in\n\t\t while !r mod p = 0 do\n\t\t\t r := !r / p\n\t\t done;\n\t\t let ht = h.(pn) in\n\t\t\t Hashtbl.remove ht k\n\t\t done);\n\t\tPrintf.printf \"Success\\n\"\n\t )\n\t | _ -> assert false\n done;\n"}], "negative_code": [{"source_code": "let rec gcd a b = if b = 0 then a else gcd b (a mod b)\n\nlet main () =\n let n, m = Scanf.sscanf (read_line ()) \"%d %d\" (fun n m -> n, m) in\n let col = Array.create (n + 1) false in\n let check col p =\n let rec loop i =\n if i * i > n then None else\n if col.(i) && gcd p i > 1 then Some i else loop (i + 1)\n in\n loop 2\n in\n for i = 1 to m do\n let (c, r) = Scanf.sscanf (read_line ()) \"%c %d\" (fun c r -> c, r) in\n if c = '+' then (\n if col.(r) then print_endline \"Already on\" else\n match check col r with\n | None -> print_endline \"Success\"; col.(r) <- true\n | Some k -> Printf.printf \"Conflict with %d\\n\" k\n ) else\n if col.(r) = false then print_endline \"Already off\" else\n let _ = col.(r) <- false in\n print_endline \"Success\"\n done\n;;\nmain()\n"}, {"source_code": "let rec gcd a b = if b = 0 then a else gcd b (a mod b)\n\nlet main () =\n let n, m = Scanf.sscanf (read_line ()) \"%d %d\" (fun n m -> n, m) in\n let col = Array.create (n + 1) false in\n let check col p =\n let rec loop i =\n if i * i > n then None else\n if col.(i) && gcd p i > 1 then Some i else loop (i + 1)\n in\n loop 1\n in\n for i = 1 to m do\n let (c, r) = Scanf.sscanf (read_line ()) \"%c %d\" (fun c r -> c, r) in\n if c = '+' then (\n if col.(r) then print_endline \"Already on\" else\n match check col r with\n | None -> print_endline \"Success\"; col.(r) <- true\n | Some k -> Printf.printf \"Conflict with %d\\n\" k\n ) else\n if col.(r) = false then print_endline \"Already off\" else\n let _ = col.(r) <- false in\n print_endline \"Success\"\n done\n;;\nmain()\n"}], "src_uid": "6cec3662101b419fb734b7d6664fdecd"} {"nl": {"description": "There are $$$n$$$ programmers that you want to split into several non-empty teams. The skill of the $$$i$$$-th programmer is $$$a_i$$$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least $$$x$$$.Each programmer should belong to at most one team. Some programmers may be left without a team.Calculate the maximum number of teams that you can assemble.", "input_spec": "The first line contains the integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 10^5; 1 \\le x \\le 10^9$$$)\u00a0\u2014 the number of programmers and the restriction of team skill respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th programmer. The sum of $$$n$$$ over all inputs does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer \u2014 the maximum number of teams that you can assemble. ", "sample_inputs": ["3\n5 10\n7 11 2 9 5\n4 8\n2 4 2 3\n4 11\n1 3 3 7"], "sample_outputs": ["2\n1\n0"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n \nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let x = long(read_int()) in\n let a = Array.init n (fun i -> long(read_int())) in\n Array.sort compare a;\n let c = Array.make n 0 in (* # teams we can make with ai...a(n-1) *)\n c.(n-1) <- if a.(n-1) >= x then 1 else 0;\n for j=n-2 downto 0 do\n let need = (x ++ a.(j) -- 1L) // a.(j) in\n let j' = (long j) ++ need in (* use j j+1... j'-1 *)\n c.(j) <- \n\tif j' > long n then 0\n\telse if j' = long n then 1\n\telse 1 + c.(short j');\n done;\n\n let answer = maxf 0 (n-1) (fun i -> c.(i)) in\n printf \"%d\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "8a6953a226abef41a44963c9b4998a25"} {"nl": {"description": "Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $$$n$$$ hotels, where the $$$i$$$-th hotel is located in the city with coordinate $$$x_i$$$. Sonya is a smart girl, so she does not open two or more hotels in the same city.Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $$$d$$$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $$$n$$$ hotels to the new one is equal to $$$d$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1\\leq n\\leq 100$$$, $$$1\\leq d\\leq 10^9$$$)\u00a0\u2014 the number of Sonya's hotels and the needed minimum distance from a new hotel to all others. The second line contains $$$n$$$ different integers in strictly increasing order $$$x_1, x_2, \\ldots, x_n$$$ ($$$-10^9\\leq x_i\\leq 10^9$$$)\u00a0\u2014 coordinates of Sonya's hotels.", "output_spec": "Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to $$$d$$$.", "sample_inputs": ["4 3\n-3 2 9 16", "5 2\n4 8 11 18 19"], "sample_outputs": ["6", "5"], "notes": "NoteIn the first example, there are $$$6$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$-6$$$, $$$5$$$, $$$6$$$, $$$12$$$, $$$13$$$, and $$$19$$$.In the second example, there are $$$5$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$2$$$, $$$6$$$, $$$13$$$, $$$16$$$, and $$$21$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Int64 = struct \n\tinclude Int64\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\nend open Int64\n\nlet () =\n let n,d = get_2_i64 ()\n in let ar = input_i64_array n\n in\n let res = ref 0L\n in\n for i=0 to ~|n-$1 do\n let lef = ar.(i) - d in\n if (i>=1 && labs (lef - ar.(i-$1)) >= d) || i=0 then (\n (* printf \"%Ld\\n\" lef; *)\n res+=1L;\n );\n let rig = ar.(i) + d in\n if i= ~|n-$1 ||\n (i<= ~|n-$2 && labs (rig - ar.(i+$1)) >= d && ar.(i+$1)-ar.(i)<>2L*d)\n then (\n (* printf \"%Ld\\n\" rig; *)\n res+=1L\n );\n done;\n !res |> print_i64_endline\n\n\n\n"}, {"source_code": "open Int64\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet n,d = Scanf.sscanf (read_line ()) \"%s %s\" (fun n d -> of_string n,of_string d) in\nlet hotel = read_line () |> split_on_char ' ' |> List.map of_string in\nsnd (List.fold_left (fun (old_x, tmp) x ->\n if sub x old_x > mul 2L d then (x, add tmp 2L)\n else if sub x old_x = mul 2L d then (x, add tmp 1L)\n else (x, tmp)) (List.hd hotel, 2L) (List.tl hotel))\n|> to_string\n|> print_endline\n"}, {"source_code": "(* Codeforces 1004 A Sonya and Hotels *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\n\t\tlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec hotel_cnt d cnt l = match l with\n\t| [] -> cnt\n\t| h :: [] -> cnt+1\n\t| h :: nh :: tl ->\n\t\tlet nl = nh :: tl in\n\t\tlet mtwo = Int64.of_int 2 in\n\t\tlet nhh = Int64.sub nh (Int64.mul mtwo d) in\n\t\tlet icomp = Int64.compare h nhh in\n\t\tlet ncnt = \n\t\t\tif icomp == 0 then cnt + 1\n\t\t\telse if icomp < 0 then cnt + 2\n\t\t\telse cnt in\n\t\t(* let _ = Printf.printf \"h,nhh,cnt,ncnt= %Ld %Ld %d %d\\n\" h nhh cnt ncnt in *)\n\t\thotel_cnt d ncnt nl;;\n\nlet rec to_i_64 l = match l with\n| [] -> []\n| h :: tl ->\n\tlet ih = Int64.of_int h in\n\tih :: to_i_64 tl;;\n\nlet main() =\n\tlet n = gr () in\n\tlet d = Int64.of_int (gr ()) in\n\tlet a = readlist n [] in\n\tlet ra = List.rev a in\n\tlet iaa = to_i_64 ra in\n\tlet cnt = hotel_cnt d 1 iaa in\t\n\tbegin\n\t\tprint_int cnt;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}], "negative_code": [{"source_code": "(* Codeforces 1004 A Sonya and Hotels *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\n\t\tlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec hotel_cnt d cnt l = match l with\n\t| [] -> cnt\n\t| h :: [] -> cnt+1\n\t| h :: nh :: tl ->\n\t\tlet nl = nh :: tl in\n\t\tlet mtwo = Int64.of_int 2 in\n\t\tlet nhh = Int64.sub nh (Int64.mul mtwo d) in\n\t\tlet icomp = Int64.compare h nhh in\n\t\tlet ncnt = \n\t\t\tif icomp == 0 then cnt + 1\n\t\t\telse if icomp < 0 then cnt + 2\n\t\t\telse cnt in\n\t\tlet _ = Printf.printf \"h,nhh,cnt,ncnt= %Ld %Ld %d %d\\n\" h nhh cnt ncnt in\n\t\thotel_cnt d ncnt nl;;\n\nlet rec to_i_64 l = match l with\n| [] -> []\n| h :: tl ->\n\tlet ih = Int64.of_int h in\n\tih :: to_i_64 tl;;\n\nlet main() =\n\tlet n = gr () in\n\tlet d = Int64.of_int (gr ()) in\n\tlet a = readlist n [] in\n\tlet ra = List.rev a in\n\tlet iaa = to_i_64 ra in\n\tlet cnt = hotel_cnt d 1 iaa in\t\n\tbegin\n\t\tprint_int cnt;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}, {"source_code": "(* Codeforces 1004 A Sonya and Hotels *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\n\t\tlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec hotel_cnt d cnt l = match l with\n\t| [] -> cnt\n\t| h :: [] -> cnt+1\n\t| h :: nh :: tl ->\n\t\tlet nl = nh :: tl in\n\t\tlet ncnt = \n\t\t\tif h == nh - 2 * d then cnt + 1\n\t\t\telse if h < nh - 2 * d then cnt + 2\n\t\t\telse cnt in\n\t\t(*let _ = Printf.printf \"h,n,cnt,ncnt= %d %d %d %d\\n\" h nh cnt ncnt in*)\n\t\thotel_cnt d ncnt nl;;\n\nlet main() =\n\tlet n = gr () in\n\tlet d = gr () in\n\tlet a = readlist n [] in\n\tlet ra = List.rev a in\n\tlet cnt = hotel_cnt d 1 ra in\t\n\tbegin\n\t\tprint_int cnt;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}, {"source_code": "open Printf open Scanf\nmodule Int64 = struct \n\tinclude Int64\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\nend open Int64\n\nlet () =\n let n,d = get_2_i64 ()\n in let ar = input_i64_array n\n in\n let res = ref 0L\n in\n for i=0 to ~|n-$1 do\n let lef = ar.(i) - d in if i>=1 && lef>ar.(i-$1) then res+=1L;\n let rig = ar.(i) + d in if i<= ~|n-$2 && rig2L*d then res+=1L;\n done;\n !res |> print_i64_endline"}, {"source_code": "let ( */ ) = Big_int.mult_big_int;;\nlet ( +/ ) = Big_int.add_big_int;;\nlet ( -/ ) = Big_int.sub_big_int;;\nlet to_int = Big_int.int_of_big_int;;\nlet of_int = Big_int.big_int_of_int;;\nlet min = Big_int.min_big_int;;\nlet (modi) = Big_int.mod_big_int;;\nlet to_string = Big_int.string_of_big_int;;\nlet of_string = Big_int.big_int_of_string;;\nlet ( n,d) in\nlet hotel = read_line () |> split_on_char ' ' |> List.map int_of_string in\nprint_int @@ snd (List.fold_left (fun (old_x, tmp) x ->\n if x - old_x > 2 * d then (x,tmp + 2)\n else if x - old_x = 2 * d then (x, tmp+1)\n else (x, tmp)) (List.hd hotel, 2) (List.tl hotel));\nprint_newline ();\n"}], "src_uid": "5babbb7c5f6b494992ffa921c8e19294"} {"nl": {"description": "Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $$$1$$$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $$$3$$$ steps, and the second contains $$$4$$$ steps, she will pronounce the numbers $$$1, 2, 3, 1, 2, 3, 4$$$.You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.", "input_spec": "The first line contains $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the total number of numbers pronounced by Tanya. The second line contains integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 1000$$$) \u2014 all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with $$$x$$$ steps, she will pronounce the numbers $$$1, 2, \\dots, x$$$ in that order. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.", "output_spec": "In the first line, output $$$t$$$ \u2014 the number of stairways that Tanya climbed. In the second line, output $$$t$$$ numbers \u2014 the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.", "sample_inputs": ["7\n1 2 3 1 2 3 4", "4\n1 1 1 1", "5\n1 2 3 4 5", "5\n1 2 1 2 1"], "sample_outputs": ["2\n3 4", "4\n1 1 1 1", "1\n5", "3\n2 2 1"], "notes": null}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet n = scanf \"%d\" (fun n -> n)\n\nlet l = Array.to_list (Array.init n (fun i -> scanf \" %d\" (fun i -> i)))\n\nlet rec process_l l out =\n match l with\n | [] -> l, out\n | h::t ->\n if h > out then\n process_l t h\n else\n l, out\n\nlet rec process l out out_st =\n match l with\n | [] -> out, out_st\n | _ ->\n let l', st = process_l l 0 in\n process l' (out + 1) (st::out_st)\n\nlet () =\n let out, out_st = process l 0 [] in\n printf \"%d\\n\" out;\n List.iter (fun i -> printf \"%d \" i) (List.rev out_st);\n ()\n"}, {"source_code": "(* Codeforces 1005 A Tanya and Stairways *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec to_tania acc last l = match l with\n\t| [] -> last :: acc\n\t| h :: t -> match h with\n\t\t\t| 1 -> \n\t\t\t\tlet lacc = if last == 0 then acc else last :: acc in\n\t\t\t\tto_tania lacc 1 t\n\t\t\t| _ -> to_tania acc h t;;\n\nlet main() =\n\tlet n = gr () in\n\tlet ra = readlist n [] in\n\tlet a = List.rev ra in\n\tlet ro = to_tania [] 0 a in\n\tlet o = List.rev ro in\n\tlet lno = List.length o in\n\tbegin\n\t\tprint_int lno;\n\t\tprint_string \"\\n\";\n\t\tprintlisti o;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}, {"source_code": "open Printf\nlet input_int_array n =\n\tArray.init n (fun _ -> Scanf.scanf \" %d\" (fun v -> v))\n\nlet get_int () = Scanf.scanf \" %d\" (fun v -> v)\nlet get_2_ints () = Scanf.scanf \" %d %d\" (fun u v -> u,v)\nlet get_3_ints () = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w)\nlet get_4_ints () = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x)\nlet get_5_ints () = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nlet () =\n let n = get_int ()\n in let ar = input_int_array n\n in\n let l = Array.fold_left (fun (c,l) v ->\n if v=c+1 then (v,l)\n else if v=1 then (v,c::l)\n else failwith \"\"\n ) (0,[]) ar\n |> (fun (last,l) -> last::l)\n |> List.rev\n in\n print_endline @@ (List.length l |> string_of_int);\n l |> List.iter (printf \"%d \");\n print_newline ()"}], "negative_code": [], "src_uid": "0ee86e75ff7a47a711c9eb41b34ad1a5"} {"nl": {"description": "They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths.A simple path is the path which goes through every Berland city not more than once.The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it.Note how the fools' paths are given in the input.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cities. Each of the next n\u2009-\u20091 lines contains two space-separated integers ui,\u2009vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n, ui\u2009\u2260\u2009vi), that means that there is a road connecting cities ui and vi. The next line contains integer k (0\u2009\u2264\u2009k\u2009\u2264\u2009105) \u2014 the number of pairs of fools who visit each other. Next k lines contain two space-separated numbers. The i-th line (i\u2009>\u20090) contains numbers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n). That means that the fool number 2i\u2009-\u20091 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path.", "output_spec": "Print n\u2009-\u20091 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input.", "sample_inputs": ["5\n1 2\n1 3\n2 4\n2 5\n2\n1 4\n3 5", "5\n3 4\n4 5\n1 4\n2 4\n3\n2 3\n1 3\n3 5"], "sample_outputs": ["2 1 1 1", "3 1 1 1"], "notes": "NoteIn the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones.In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let () =\n for i = 0 to n - 2 do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n\tes.(u) <- (v, i) :: es.(u);\n\tes.(v) <- (u, i) :: es.(v);\n done\n in\n let es = Array.map Array.of_list es in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make k 0 in\n let b = Array.make k 0 in\n let () =\n for i = 0 to k - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1;\n b.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1;\n done\n in\n let min (x : int) y = if x < y then x else y in\n let used = Array.make n false in\n let pe = Array.make n (-1) in\n let tin = Array.make n (-1) in\n let tout = Array.make n (-1) in\n let t = ref 0 in\n let up = Array.make_matrix n 20 0 in\n let stack = Array.make (2 * n) (fun _ -> ()) in\n let stack_pos = ref 0 in\n let rec execute () =\n if !stack_pos > 0 then (\n decr stack_pos;\n let f = stack.(!stack_pos) in\n\tf ();\n\texecute ()\n )\n in\n (*let rec dfs3 u depth =\n used.(u) <- true;\n g1.(u) <- !pos;\n d.(!pos) <- depth;\n de.(!pos) <- u;\n incr pos;\n for i = 0 to Array.length es.(u) - 1 do\n let v = es.(u).(i) in\n\tif not used.(v) then (\n\t dfs3 v (depth + 1);\n\t g2.(u) <- !pos;\n\t d.(!pos) <- depth;\n\t de.(!pos) <- u;\n\t incr pos;\n\t)\n done\n in*)\n let rec dfs3 u prev =\n used.(u) <- true;\n tin.(u) <- !t;\n tout.(u) <- !t;\n incr t;\n up.(u).(0) <- prev;\n for i = 1 to 19 do\n up.(u).(i) <- up.(up.(u).(i - 1)).(i - 1)\n done;\n let rec aux i =\n if i < Array.length es.(u) then (\n\tstack.(!stack_pos) <- (fun () -> aux (i + 1));\n\tincr stack_pos;\n\tlet (v, edge) = es.(u).(i) in\n\t if not used.(v) then (\n\t let f () =\n\t pe.(v) <- edge;\n\t tout.(u) <- !t;\n\t incr t;\n\t in\n\t stack.(!stack_pos) <- f;\n\t incr stack_pos;\n\t stack.(!stack_pos) <- (fun () -> dfs3 v u);\n\t incr stack_pos;\n\t )\n )\n in\n aux 0\n in\n stack_pos := 0;\n dfs3 0 0;\n execute ();\n let is_ancestor u v =\n tin.(u) <= tin.(v) && tout.(u) >= tout.(v)\n in\n let rec lca u v =\n if is_ancestor u v\n then u\n else if is_ancestor v u\n then v\n else (\n\tlet u = ref u in\n\t for i = 19 downto 0 do\n\t if not (is_ancestor up.(!u).(i) v)\n\t then u := up.(!u).(i)\n\t done;\n\t up.(!u).(0)\n )\n in\n let s = Array.make n 0 in\n let res = Array.make (n - 1) 0 in\n for i = 0 to k - 1 do\n\tlet u = a.(i)\n\tand v = b.(i) in\n\tlet w = lca u v in\n\t s.(u) <- s.(u) + 1;\n\t s.(v) <- s.(v) + 1;\n\t s.(w) <- s.(w) - 2;\n done;\n let rec dfs u prev =\n\tlet rec aux i =\n\t if i < Array.length es.(u) then (\n\t stack.(!stack_pos) <- (fun () -> aux (i + 1));\n\t incr stack_pos;\n\t let (v, edge) = es.(u).(i) in\n\t if v <> prev then (\n\t\tlet f () =\n\t\t s.(u) <- s.(u) + s.(v)\n\t\tin\n\t\t stack.(!stack_pos) <- f;\n\t\t incr stack_pos;\n\t\t stack.(!stack_pos) <- (fun () -> dfs v u);\n\t\t incr stack_pos;\n\t )\n\t )\n\tin\n\t aux 0\n in\n\tstack_pos := 0;\n\tdfs 0 0;\n\texecute ();\n\tfor u = 0 to n - 1 do\n\t if pe.(u) >= 0\n\t then res.(pe.(u)) <- s.(u)\n\tdone;\n\tfor i = 0 to n - 2 do\n\t Printf.printf \"%d \" res.(i)\n\tdone;\n\tPrintf.printf \"\\n\"\n\n"}], "negative_code": [], "src_uid": "d192964daea30c02e7886cab220fd942"} {"nl": {"description": "There are $$$n$$$ block towers in a row, where tower $$$i$$$ has a height of $$$a_i$$$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation: Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \\leq i, j \\leq n$$$; $$$i \\neq j$$$), and move a block from tower $$$i$$$ to tower $$$j$$$. This essentially decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_j$$$ by $$$1$$$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $$$\\max(a)-\\min(a)$$$. What's the minimum possible ugliness you can achieve, after any number of days?", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 1000$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \\leq n \\leq 100$$$)\u00a0\u2014 the number of buildings. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 10^7$$$)\u00a0\u2014 the heights of the buildings.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the minimum possible ugliness of the buildings.", "sample_inputs": ["3\n3\n10 10 10\n4\n3 2 1 2\n5\n1 2 3 1 5"], "sample_outputs": ["0\n0\n1"], "notes": "NoteIn the first test case, the ugliness is already $$$0$$$.In the second test case, you should do one operation, with $$$i = 1$$$ and $$$j = 3$$$. The new heights will now be $$$[2, 2, 2, 2]$$$, with an ugliness of $$$0$$$.In the third test case, you may do three operations: with $$$i = 3$$$ and $$$j = 1$$$. The new array will now be $$$[2, 2, 2, 1, 5]$$$, with $$$i = 5$$$ and $$$j = 4$$$. The new array will now be $$$[2, 2, 2, 2, 4]$$$, with $$$i = 5$$$ and $$$j = 3$$$. The new array will now be $$$[2, 2, 3, 2, 3]$$$. The resulting ugliness is $$$1$$$. It can be proven that this is the minimum possible ugliness for this test."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x->x);;\r\n\r\nlet rec to_arr = function\r\n| (n, arr, i) -> \r\n if (i=n) then arr\r\n else begin\r\n arr.(i) <- read_int ();\r\n to_arr (n, arr, i+1)\r\n end\r\n;;\r\n\r\nlet rec find_x = function\r\n| (n, arr, p, i, j) ->\r\n (* Array.iter (fun x -> Printf.printf \" %d\" x) arr;\r\n print_newline (); *)\r\n (* print_int i; *)\r\n (* Printf.printf \" %d %d %d\\n\" p i j; *)\r\n if (i==j) then begin\r\n if (arr.(i-1)=arr.(p)) then find_x (n, arr, p, i+1, j-1)\r\n else if (arr.(i)<=arr.(p)) then find_x (n, arr, p, i+1, j)\r\n else if (arr.(j-1)>=arr.(p)) then find_x (n, arr, p, i, j-1)\r\n else begin\r\n let temp_i = arr.(i) in\r\n arr.(i) <- arr.(j-1);\r\n arr.(j-1) <- temp_i;\r\n find_x (n, arr, p, i+1, j-1)\r\n end\r\n;;\r\n(* 1, 5, 6, 2\r\n sort_arr (4, arr, 0, 1, 3)\r\n x = 0\r\n sort_arr (4, arr, 1, 2, 3)\r\n 1, 5, 6, 2\r\n x = 2\r\n *)\r\nlet rec sort_arr = function\r\n| (n, arr, p, i, j) ->\r\n let x = find_x (n, arr, p, i, j) in\r\n if ((x-1(i+1))) then sort_arr (n, arr, i, i, (x-1));\r\n if ((x+1 Printf.printf \" %d\" x) arr;; *)\r\n\r\nlet read_long () = Scanf.scanf \" %Ld\" (fun l -> l);;\r\nlet rec get_sum = function\r\n| 0L -> Int64.zero\r\n| n -> Int64.add (read_long ()) (get_sum (Int64.pred n))\r\n;;\r\n\r\nlet run_case = function \r\n| () ->\r\n let n = read_long () in\r\n let s = get_sum (n) in \r\n let m = Int64.sub s (Int64.mul (Int64.div s n) n) in\r\n if (m=0L) then Printf.printf \"%d\\n\" 0\r\n else Printf.printf \"%d\\n\" 1\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| t ->\r\n run_case ();\r\n iter_cases (t-1)\r\n;;\r\n\r\nlet t=read_int() in \r\niter_cases (t);;"}], "negative_code": [], "src_uid": "644ef17fe304b090e0cf33a84ddc546a"} {"nl": {"description": "You are given $$$n$$$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $$$0$$$ in case the intersection is an empty set.For example, the intersection of segments $$$[1;5]$$$ and $$$[3;10]$$$ is $$$[3;5]$$$ (length $$$2$$$), the intersection of segments $$$[1;5]$$$ and $$$[5;7]$$$ is $$$[5;5]$$$ (length $$$0$$$) and the intersection of segments $$$[1;5]$$$ and $$$[6;6]$$$ is an empty set (length $$$0$$$).Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $$$(n - 1)$$$ segments has the maximal possible length.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 3 \\cdot 10^5$$$) \u2014 the number of segments in the sequence. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \\le l_i \\le r_i \\le 10^9$$$) \u2014 the description of the $$$i$$$-th segment.", "output_spec": "Print a single integer \u2014 the maximal possible length of the intersection of $$$(n - 1)$$$ remaining segments after you remove exactly one segment from the sequence.", "sample_inputs": ["4\n1 3\n2 6\n0 4\n3 3", "5\n2 6\n1 3\n0 4\n1 20\n0 4", "3\n4 5\n1 2\n9 20", "2\n3 10\n1 5"], "sample_outputs": ["1", "2", "0", "7"], "notes": "NoteIn the first example you should remove the segment $$$[3;3]$$$, the intersection will become $$$[2;3]$$$ (length $$$1$$$). Removing any other segment will result in the intersection $$$[3;3]$$$ (length $$$0$$$).In the second example you should remove the segment $$$[1;3]$$$ or segment $$$[2;6]$$$, the intersection will become $$$[2;4]$$$ (length $$$2$$$) or $$$[1;3]$$$ (length $$$2$$$), respectively. Removing any other segment will result in the intersection $$$[2;3]$$$ (length $$$1$$$).In the third example the intersection will become an empty set no matter the segment you remove.In the fourth example you will get the intersection $$$[3;10]$$$ (length $$$7$$$) if you remove the segment $$$[1;5]$$$ or the intersection $$$[1;5]$$$ (length $$$4$$$) if you remove the segment $$$[3;10]$$$."}, "positive_code": [{"source_code": "let __ocaml_lex_tables = {\n Lexing.lex_base = \n \"\\000\\000\\010\\000\\002\\000\\255\\255\";\n Lexing.lex_backtrk = \n \"\\001\\000\\002\\000\\001\\000\\255\\255\";\n Lexing.lex_default = \n \"\\255\\255\\255\\255\\255\\255\\000\\000\";\n Lexing.lex_trans = \n \"\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\002\\000\\002\\000\\002\\000\\002\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\002\\000\\000\\000\\002\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\\n \\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\\n \\001\\000\\001\\000\\001\\000\\001\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\003\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\000\\000\";\n Lexing.lex_check = \n \"\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\000\\000\\000\\000\\002\\000\\002\\000\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\000\\000\\255\\255\\002\\000\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\000\\\n \\000\\000\\000\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\001\\000\\\n \\001\\000\\001\\000\\001\\000\\001\\000\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\000\\000\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\255\\\n \\255\\255\\255\\255\\255\\255\";\n Lexing.lex_base_code = \n \"\";\n Lexing.lex_backtrk_code = \n \"\";\n Lexing.lex_default_code = \n \"\";\n Lexing.lex_trans_code = \n \"\";\n Lexing.lex_check_code = \n \"\";\n Lexing.lex_code = \n \"\";\n}\n\nlet rec next lexbuf =\n __ocaml_lex_next_rec lexbuf 0\nand __ocaml_lex_next_rec lexbuf __ocaml_lex_state =\n match Lexing.engine __ocaml_lex_tables __ocaml_lex_state lexbuf with\n | 0 ->\n# 6 \"lex_int.mll\"\n ( (-1) )\n# 100 \"lex_int.ml\"\n\n | 1 ->\n# 7 \"lex_int.mll\"\n (next lexbuf)\n# 105 \"lex_int.ml\"\n\n | 2 ->\nlet\n# 8 \"lex_int.mll\"\n s\n# 111 \"lex_int.ml\"\n= Lexing.sub_lexeme lexbuf lexbuf.Lexing.lex_start_pos lexbuf.Lexing.lex_curr_pos in\n# 8 \"lex_int.mll\"\n ( int_of_string s )\n# 115 \"lex_int.ml\"\n\n | __ocaml_lex_state -> lexbuf.Lexing.refill_buff lexbuf; \n __ocaml_lex_next_rec lexbuf __ocaml_lex_state\n\n;;\n\nlet amax a = Array.fold_left max min_int a;; \nlet amin a = Array.fold_left min max_int a;; \n\nlet rec main() =\n let lex = Lexing.from_channel stdin in\n let ri() = next lex in\n let n = ri () in\n (* \n let a = Array.init n (fun i -> (ri (), ri ())) in\n let l = Array.init n (fun i -> fst a.(i)) in\n let r = Array.init n (fun i -> snd a.(i)) in\n *)\n let l = Array.make n 0 in\n let r = Array.make n 0 in\n for i = 0 to n - 1 do\n l.(i) <- ri ();\n r.(i) <- ri ();\n done;\n\n let l1 = amax l in\n let r1 = amin r in\n\n let uniq_id a v op =\n let rec loop id k =\n if (k < 0) then id\n else if a.(k) != v then loop id (k-1)\n else if id >= 0 then loop (if op id k then id else k) (k-1)\n else loop k (k-1)\n in\n loop (-1) (n - 1)\n in\n\n let res = ref (r1 - l1) in\n let i = uniq_id l l1 (fun i j -> r.(i) > r.(j)) in\n let j = uniq_id r r1 (fun i j -> l.(i) < l.(j)) in\n (*\n Printf.eprintf \"l1 = %d\\n\" l1;\n Printf.eprintf \"r1 = %d\\n\" r1;\n Printf.eprintf \"i = %d\\n\" i;\n Printf.eprintf \"j = %d\\n\" j;\n *)\n let rem k =\n let oldl = l.(k) in\n let oldr = r.(k) in\n l.(k) <- min_int;\n r.(k) <- max_int;\n let w = (amin r) - (amax l) in\n if (!res < w) then res := w;\n l.(k) <- oldl;\n r.(k) <- oldr;\n in\n if i >= 0 then rem i;\n if j >= 0 then rem j; \n (* res := !res + 1; *)\n Printf.printf \"%d\\n\" (max !res 0);\n;;\n\nlet _ = try main() with End_of_file -> ()\n"}], "negative_code": [], "src_uid": "b50df0e6d91d538cd7db8dfdc7cd5266"} {"nl": {"description": "Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times.", "input_spec": "The first line contains three integers: a,\u2009b,\u2009n (1\u2009\u2264\u2009a,\u2009b,\u2009n\u2009\u2264\u2009105).", "output_spec": "In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.", "sample_inputs": ["5 4 5", "12 11 1", "260 150 10"], "sample_outputs": ["524848", "121", "-1"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 246C KonkursKrasoti written *)\n\nopen String;;\nopen Hashtbl;;\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet debug = false;;\n\nlet a = gr();;\nlet b = gr();;\nlet n = gr();;\nlet ch = Array.make n 0;;\n\nlet rec nextchar ao c idx ca =\n\tif idx >= n then 0\n\telse if c > 9 then -1\n\telse if ((10 * ao + c) mod b) != 0 then nextchar ao (c +1) idx ca\n\telse\n\t\tlet oo = 0 in\n\t\tbegin\n\t\t\tca.(idx) <- c;\n\t\t\tnextchar oo 0 (idx +1) ca\n\t\tend;;\n\nlet prichars a ca n =\n\tbegin\n\t\tprint_int a;\n\t\tfor i = 1 to n do\n\t\t\tprint_int ca.(i -1)\n\t\tdone;\n\t\tprint_newline()\n\tend;;\n\nlet main () =\n\tlet ret = nextchar a 0 0 ch in\n\tif ret < 0 then begin print_int (-1); print_newline() end\n\telse prichars a ch n;;\n\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let a = read_int() in \n let b = read_int() in\n let n = read_int() in\n let rec f d = if d = 10 then (-1) else if (10*a+d) mod b = 0 then d else f (d+1) in\n let d = f 0 in\n if d = -1 then Printf.printf \"-1\\n\"\n else (\n Printf.printf \"%d%d\" a d; \n for i = 1 to n-1 do Printf.printf \"0\" done;\n print_newline()\n )"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) ;;\n\nlet a = read_int () and b = read_int () and n = read_int () ;;\n\nlet result = \n let rec loop d = \n if d >= 10 then -1\n else if (a * 10 + d) mod b = 0 then (a * 10 + d)\n else loop (d + 1)\n in loop 0 ;;\n \nPrintf.printf \"%d\" result ;;\n\nif result <> -1 then \n for i = 1 to n - 1 do\n Printf.printf \"0\"\n done ;;\n\nPrintf.printf \"\\n\" ;;"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let a = read_int() in\n let b = read_int() in\n let n = read_int() in\n\n let rec first d = if d=10 then -1 else if (10*a+d) mod b = 0 then d else first (d+1) in\n\n let d = first 0 in\n if d = -1 then (\n Printf.printf \"-1\\n\"\n ) else (\n Printf.printf \"%d%d\" a d;\n for i=1 to n-1 do Printf.printf \"0\" done;\n print_newline()\n )\n"}], "negative_code": [], "src_uid": "206eb67987088843ef42923b0c3939d4"} {"nl": {"description": "A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string \"aabaabaabaab\" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.", "input_spec": "The first input line contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u20091000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1\u2009\u2264\u2009|s|\u2009\u2264\u20091000, where |s| is the length of string s.", "output_spec": "Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them. If the solution doesn't exist, print \"-1\" (without quotes).", "sample_inputs": ["2\naazz", "3\nabcabcabz"], "sample_outputs": ["azaz", "-1"], "notes": null}, "positive_code": [{"source_code": "open Scanf;;\nopen Printf;;\nopen Str;;\n\nlet split_by_space = split (regexp \" +\")\n\nlet rec head n ls =\n if n < 0 then invalid_arg \"head : passed negative integer\"\n else \n match (n, ls) with\n (0, _) -> []\n | (n, []) -> failwith \"head : list is too short\"\n | (n, x::xs) -> x :: (head (n - 1) xs)\n\nlet rec tail n ls =\n if n < 0 then invalid_arg \"tail : passed negative integer\"\n else\n match (n, ls) with\n (0, ls) -> ls\n | (n, []) -> failwith \"tail : list is too short\"\n | (n, x::xs) -> tail (n - 1) xs\n\nmodule UF = struct\n type t = int array\n\n let make n = Array.make n (-1)\n\n let rec root x uf =\n if uf.(x) < 0 then x \n else (uf.(x) <- root uf.(x) uf; uf.(x))\n\n let union_set x y uf =\n let x = root x uf and\n y = root y uf in\n begin\n if x != y then \n let x, y = if uf.(y) < uf.(x) then y, x else x, y in\n begin\n uf.(x) <- uf.(x) + uf.(y);\n uf.(y) <- x\n end\n end;\n x != y\n\n let find_set x y uf = root x uf = root y uf\n\n let size x uf = - uf.(x)\nend\n\nlet input () = \n let k = int_of_string (read_line ()) and\n s = read_line () in\n (k, s)\n\nlet rec rep i c =\n match i with\n 0 -> []\n | n -> c :: rep (n - 1) c\n\nlet make_str l = \n List.fold_left (fun x y -> x ^ y) \"\" l\n\nlet rec repeat n s =\n match n with\n 0 -> \"\"\n | n -> s ^ repeat (n - 1) s\n\nlet make_k_str arr n k =\n let a = Array.map (fun x -> x / k) arr in\n let l = ref [] in\n for i = 0 to 26 - 1 do\n l := (rep a.(i) (String.make 1 (Char.chr (i + Char.code 'a')))) @ !l\n done;\n let s = make_str !l in\n repeat k s\n\nlet solve (k, s) =\n let len = String.length s in\n if len mod k <> 0 then \"-1\"\n else if k = 1 then\n s\n else begin\n let arr = Array.make 26 0 in\n let a_code = Char.code 'a' in\n for i = 0 to len - 1 do\n let idx = Char.code (s.[i]) - a_code in\n arr.(idx) <- arr.(idx) + 1\n done;\n let n = len / k in\n if Array.fold_left (fun x y -> x && (y mod k = 0)) true arr then \n make_k_str arr n k\n else \"-1\"\n end\n \nlet () = \n let inp = input () in\n let res = solve inp in\n print_string (res ^ \"\\n\")\n"}], "negative_code": [{"source_code": "open Scanf;;\nopen Printf;;\nopen Str;;\n\nlet split_by_space = split (regexp \" +\")\n\nlet rec head n ls =\n if n < 0 then invalid_arg \"head : passed negative integer\"\n else \n match (n, ls) with\n (0, _) -> []\n | (n, []) -> failwith \"head : list is too short\"\n | (n, x::xs) -> x :: (head (n - 1) xs)\n\nlet rec tail n ls =\n if n < 0 then invalid_arg \"tail : passed negative integer\"\n else\n match (n, ls) with\n (0, ls) -> ls\n | (n, []) -> failwith \"tail : list is too short\"\n | (n, x::xs) -> tail (n - 1) xs\n\nmodule UF = struct\n type t = int array\n\n let make n = Array.make n (-1)\n\n let rec root x uf =\n if uf.(x) < 0 then x \n else (uf.(x) <- root uf.(x) uf; uf.(x))\n\n let union_set x y uf =\n let x = root x uf and\n y = root y uf in\n begin\n if x != y then \n let x, y = if uf.(y) < uf.(x) then y, x else x, y in\n begin\n uf.(x) <- uf.(x) + uf.(y);\n uf.(y) <- x\n end\n end;\n x != y\n\n let find_set x y uf = root x uf = root y uf\n\n let size x uf = - uf.(x)\nend\n\nlet input () = \n let k = int_of_string (read_line ()) and\n s = read_line () in\n (k, s)\n\nlet rec rep i c =\n match i with\n 0 -> []\n | n -> c :: rep (n - 1) c\n\nlet make_str l = \n List.fold_left (fun x y -> x ^ y) \"\" l\n\nlet rec repeat n s =\n match n with\n 0 -> \"\"\n | n -> s ^ repeat (n - 1) s\n\nlet make_k_str arr n k =\n let a = Array.map (fun x -> x / n) arr in\n let l = ref [] in\n for i = 0 to 26 - 1 do\n l := (rep a.(i) (String.make 1 (Char.chr (i + Char.code 'a')))) @ !l\n done;\n let s = make_str !l in\n repeat n s\n\nlet solve (k, s) =\n let len = String.length s in\n if len mod k <> 0 then \"-1\"\n else begin\n let arr = Array.make 26 0 in\n let a_code = Char.code 'a' in\n for i = 0 to len - 1 do\n let idx = Char.code (s.[i]) - a_code in\n arr.(idx) <- arr.(idx) + 1\n done;\n let n = len / k in\n if Array.fold_left (fun x y -> x && (y mod n = 0)) true arr then \n make_k_str arr n k\n else \"-1\"\n end\n \nlet () = \n let inp = input () in\n let res = solve inp in\n print_string (res ^ \"\\n\")\n"}, {"source_code": "open Scanf;;\nopen Printf;;\nopen Str;;\n\nlet split_by_space = split (regexp \" +\")\n\nlet rec head n ls =\n if n < 0 then invalid_arg \"head : passed negative integer\"\n else \n match (n, ls) with\n (0, _) -> []\n | (n, []) -> failwith \"head : list is too short\"\n | (n, x::xs) -> x :: (head (n - 1) xs)\n\nlet rec tail n ls =\n if n < 0 then invalid_arg \"tail : passed negative integer\"\n else\n match (n, ls) with\n (0, ls) -> ls\n | (n, []) -> failwith \"tail : list is too short\"\n | (n, x::xs) -> tail (n - 1) xs\n\nmodule UF = struct\n type t = int array\n\n let make n = Array.make n (-1)\n\n let rec root x uf =\n if uf.(x) < 0 then x \n else (uf.(x) <- root uf.(x) uf; uf.(x))\n\n let union_set x y uf =\n let x = root x uf and\n y = root y uf in\n begin\n if x != y then \n let x, y = if uf.(y) < uf.(x) then y, x else x, y in\n begin\n uf.(x) <- uf.(x) + uf.(y);\n uf.(y) <- x\n end\n end;\n x != y\n\n let find_set x y uf = root x uf = root y uf\n\n let size x uf = - uf.(x)\nend\n\nlet input () = \n let k = int_of_string (read_line ()) and\n s = read_line () in\n (k, s)\n\nlet rec rep i c =\n match i with\n 0 -> []\n | n -> c :: rep (n - 1) c\n\nlet make_str l = \n List.fold_left (fun x y -> x ^ y) \"\" l\n\nlet rec repeat n s =\n match n with\n 0 -> \"\"\n | n -> s ^ repeat (n - 1) s\n\nlet make_k_str arr n k =\n let a = Array.map (fun x -> x / n) arr in\n let l = ref [] in\n for i = 0 to 26 - 1 do\n l := (rep a.(i) (String.make 1 (Char.chr (i + Char.code 'a')))) @ !l\n done;\n let s = make_str !l in\n repeat n s\n\nlet solve (k, s) =\n let len = String.length s in\n if len mod k <> 0 then \"-1\"\n else if k = 1 then\n s\n else begin\n let arr = Array.make 26 0 in\n let a_code = Char.code 'a' in\n for i = 0 to len - 1 do\n let idx = Char.code (s.[i]) - a_code in\n arr.(idx) <- arr.(idx) + 1\n done;\n let n = len / k in\n if Array.fold_left (fun x y -> x && (y mod n = 0)) true arr then \n make_k_str arr n k\n else \"-1\"\n end\n \nlet () = \n let inp = input () in\n let res = solve inp in\n print_string (res ^ \"\\n\")\n"}], "src_uid": "f5451b19cf835b1cb154253fbe4ea6df"} {"nl": {"description": "Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner\u00a0\u2014 Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D'\u00a0\u2014 the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.", "output_spec": "If Anton won more games than Danik, print \"Anton\" (without quotes) in the only line of the output. If Danik won more games than Anton, print \"Danik\" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print \"Friendship\" (without quotes).", "sample_inputs": ["6\nADAAAA", "7\nDDDAADA", "6\nDADADA"], "sample_outputs": ["Anton", "Danik", "Friendship"], "notes": "NoteIn the first sample, Anton won 6 games, while Danik\u00a0\u2014 only 1. Hence, the answer is \"Anton\".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is \"Danik\".In the third sample, both Anton and Danik won 3 games and the answer is \"Friendship\"."}, "positive_code": [{"source_code": "let a_count = ref 0 and\n d_count = ref 0 and\n n = int_of_string (read_line ()) and\n s = read_line () in\nfor i = 0 to n - 1 do\n begin\n a_count := !a_count + (if s.[i] = 'A' then 1 else 0);\n d_count := !d_count + (if s.[i] = 'D' then 1 else 0);\n end\ndone;\nprint_string ( if a_count = d_count then \"Friendship\"\n else if a_count > d_count then \"Anton\"\n else \"Danik\"\n)\n"}, {"source_code": "let () =\n Scanf.scanf \"%d \" @@ fun n ->\n let anton = ref 0 in\n let danik = ref 0 in\n Scanf.scanf \"%s \" @@ String.iter (function 'A' -> incr anton | 'D' -> incr danik | _ -> failwith \"\");\n if !anton = !danik then\n print_endline \"Friendship\"\n else if !anton > !danik then\n print_endline \"Anton\"\n else\n print_endline \"Danik\"\n"}, {"source_code": "let char_count s len c =\n let rec cc i sum =\n if i = len then\n sum\n else\n let n = if s.[i] = c then 1 else 0 in\n cc (i + 1) (sum + n)\n in cc 0 0\n\nlet n = read_int () ;;\nlet s = read_line () ;;\nlet a = char_count s n 'A'\nand d = char_count s n 'D'\nin\nif a = d then\n print_string \"Friendship\\n\"\nelse if a > d then\n print_string \"Anton\\n\"\nelse\n print_string \"Danik\\n\"\n;;\n"}, {"source_code": "let _ = read_int () in\nlet str = read_line () in\n\nlet trans c = match c with\n| 'A' -> 1\n| 'D' -> -1\n| _ -> 0 in\n\nlet rec count_ad s i l =\n if i >= l then 0\n else (count_ad s (i+1) l) + trans s.[i] in\n\nlet get_output c =\n if c = 0 then \"Friendship\"\n else if c > 0 then \"Anton\"\n else \"Danik\" in\n\nprint_endline (get_output (count_ad str 0 (String.length str)))"}, {"source_code": "let input () = \n let total = Scanf.scanf \"%d \" (fun n -> n) in\n let rec read list n =\n if n > 0\n then\n let var = Scanf.scanf \"%c\" (fun c -> c) in\n read (var :: list) (n - 1)\n else\n List.rev list\n in read [] total\n\nlet solve list =\n let anton_wins = List.length (List.filter (fun c -> c = 'A') list) in\n let danik_wins = List.length (List.filter (fun c -> c = 'D') list) in\n if anton_wins = danik_wins\n then\n \"Friendship\"\n else \n if anton_wins > danik_wins \n then\n \"Anton\"\n else\n \"Danik\"\n\nlet print result = Printf.printf \"%s\\n\" result\nlet () = print (solve (input ()))\n"}], "negative_code": [], "src_uid": "0de32a7ccb08538a8d88239245cef50b"} {"nl": {"description": "Little penguin Polo adores integer segments, that is, pairs of integers [l;\u00a0r] (l\u2009\u2264\u2009r). He has a set that consists of n integer segments: [l1;\u00a0r1],\u2009[l2;\u00a0r2],\u2009...,\u2009[ln;\u00a0rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l;\u00a0r] to either segment [l\u2009-\u20091;\u00a0r], or to segment [l;\u00a0r\u2009+\u20091].The value of a set of segments that consists of n segments [l1;\u00a0r1],\u2009[l2;\u00a0r2],\u2009...,\u2009[ln;\u00a0rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj\u2009\u2264\u2009x\u2009\u2264\u2009rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009105). Each of the following n lines contain a segment as a pair of integers li and ri (\u2009-\u2009105\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i,\u2009j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n) the following inequality holds, min(ri,\u2009rj)\u2009<\u2009max(li,\u2009lj).", "output_spec": "In a single line print a single integer \u2014 the answer to the problem.", "sample_inputs": ["2 3\n1 2\n3 4", "3 7\n1 2\n3 3\n4 7"], "sample_outputs": ["2", "0"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet read_pair () = let a = read_int () in (a , read_int ());;\n\nlet n , k = read_pair ();;\n\nlet data = Array.init n (fun i -> read_pair ());;\n\nlet ans = ref 0 and cnt = ref 0;; \nfor i = 0 to (n-1) do\n let first , second = data.(i) in\n cnt := !cnt + (second - first + 1)\ndone;;\n\nif (!cnt) mod k = 0 then Printf.printf \"0\\n\"\nelse Printf.printf \"%d\\n\" ( ((!cnt)/k + 1)*k - (!cnt)) ;;\n \n"}], "negative_code": [], "src_uid": "3a93a6f78b41cbb43c616f20beee288d"} {"nl": {"description": "After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally?", "input_spec": "The first line contains an integer $$$n$$$ ($$$0 \\leq n \\leq 10^{9}$$$)\u00a0\u2014 the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors.", "output_spec": "Print the name of the winner (\"Kuro\", \"Shiro\" or \"Katie\"). If there are at least two cats that share the maximum beauty, print \"Draw\".", "sample_inputs": ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"], "sample_outputs": ["Kuro", "Shiro", "Katie", "Draw"], "notes": "NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw."}, "positive_code": [{"source_code": "\nlet list_init n f =\n Array.init n f |> Array.to_list\n \nlet input_ribbons (n: int): string list =\n list_init n (fun i -> Scanf.scanf \" %s\" (fun v -> v))\n\nlet ribbon_to_map (src: string): int array =\n (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)\n let ret = Array.create (26 * 2) 0 in\n for i = 0 to String.length src - 1 do\n let idx =\n let ccode = String.get src i |> Char.code in\n if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')\n then ccode - Char.code 'A'\n else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')\n then ccode - Char.code 'a' + 26\n else raise Not_found\n in\n ret.(idx) <- ret.(idx) + 1\n done;\n ret\n\nlet max_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n\nlet min_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n let f ((mi, mv) as m) ((i, v) as n) =\n match v with\n | 0 -> m\n | _ when v < mv -> n\n | _ -> m\n in\n Array.fold_left f src.(0) src\n\nlet result (winner: int option): string =\n match winner with\n | None -> \"Draw\"\n | Some i ->\n match i with\n | 0 -> \"Kuro\"\n | 1 -> \"Shiro\"\n | 2 -> \"Katie\"\n | _ -> raise Not_found\n \nlet get_beauty n l a = \n if n <= l - a\n then a + n\n else if l - a <= 1 && n < 2 then l - 1 else l\n\nlet max_map_list (src: int list): int * int =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n \nlet max_map_i (src: (int * int) list): int * (int * int) =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (\n fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->\n if mv > v then m else n)\n (List.hd src) src\n \nlet max_beauty (n: int) (l: int) (map: int array) =\n Array.map (get_beauty n l) map |> max_map |> snd\n \nlet print_list (l: int list): unit =\n List.iter (fun i -> Printf.printf \"%d \" i) l;\n print_newline ()\n\nlet () =\n let _ = Printexc.record_backtrace true in\n let n = Scanf.scanf \" %u\" (fun v -> v) in\n let ribbons = input_ribbons 3 in\n let l = ribbons |> List.hd |> String.length in\n let maps = List.map ribbon_to_map ribbons in\n let max_beauties = List.map (max_beauty n l) maps in\n (* let _ = print_list max_beauties in *)\n let (i, max) = max_map_list max_beauties in\n let ret = \n if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1\n then None\n else Some i\n in\n ret |> result |> print_endline\n"}], "negative_code": [{"source_code": "\nlet list_init n f =\n Array.init n f |> Array.to_list\n \nlet input_ribbons (n: int): string list =\n list_init n (fun i -> Scanf.scanf \" %s\" (fun v -> v))\n\nlet ribbon_to_map (src: string): int array =\n (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)\n let ret = Array.create 128 0 in\n for i = 0 to String.length src - 1 do\n let idx = (String.get src i |> Char.code) - Char.code 'A' in\n ret.(idx) <- ret.(idx) + 1\n done;\n ret\n\nlet max_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n\nlet min_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n let f ((mi, mv) as m) ((i, v) as n) =\n match v with\n | 0 -> m\n | _ when v < mv -> n\n | _ -> m\n in\n Array.fold_left f src.(0) src\n\nlet result (winner: int option): string =\n match winner with\n | None -> \"Draw\"\n | Some i ->\n match i with\n | 0 -> \"Kuro\"\n | 1 -> \"Shiro\"\n | 2 -> \"Katie\"\n | _ -> raise Not_found\n\nlet max_map_i (src: (int * int) list): int * (int * int) =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (\n fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->\n if mv > v then m else n)\n (List.hd src) src\n\nlet () =\n let _ = Printexc.record_backtrace true in\n let n = Scanf.scanf \" %u\" (fun v -> v) in\n let ribbons = input_ribbons 3 in\n let l = ribbons |> List.hd |> String.length in\n let maps = List.map ribbon_to_map ribbons in\n let maxes = List.map max_map maps in\n let drawed = List.filter (fun (i, v) -> l - v <= n) maxes |> List.length > 1 in\n if drawed\n then result None |> print_endline\n else maxes |>\n max_map_i |>\n fst |> (fun i -> Some i) |>\n result |> print_endline\n"}, {"source_code": "\nlet list_init n f =\n Array.init n f |> Array.to_list\n \nlet input_ribbons (n: int): string list =\n list_init n (fun i -> Scanf.scanf \" %s\" (fun v -> v))\n\nlet ribbon_to_map (src: string): int array =\n (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)\n let ret = Array.create (26 * 2) 0 in\n for i = 0 to String.length src - 1 do\n let idx =\n let ccode = String.get src i |> Char.code in\n if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')\n then ccode - Char.code 'A'\n else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')\n then ccode - Char.code 'a' + 26\n else raise Not_found\n in\n ret.(idx) <- ret.(idx) + 1\n done;\n ret\n\nlet max_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n\nlet min_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n let f ((mi, mv) as m) ((i, v) as n) =\n match v with\n | 0 -> m\n | _ when v < mv -> n\n | _ -> m\n in\n Array.fold_left f src.(0) src\n\nlet result (winner: int option): string =\n match winner with\n | None -> \"Draw\"\n | Some i ->\n match i with\n | 0 -> \"Kuro\"\n | 1 -> \"Shiro\"\n | 2 -> \"Katie\"\n | _ -> raise Not_found\n \nlet get_beauty n l a = \n if n <= l - a\n then a + n\n else l\n\nlet max_map_list (src: int list): int * int =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n \nlet max_map_i (src: (int * int) list): int * (int * int) =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (\n fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->\n if mv > v then m else n)\n (List.hd src) src\n \nlet max_beauty (n: int) (l: int) (map: int array) =\n Array.map (get_beauty n l) map |> max_map |> snd\n \nlet print_list (l: int list): unit =\n List.iter (fun i -> Printf.printf \"%d \" i) l;\n print_newline ()\n\nlet () =\n let _ = Printexc.record_backtrace true in\n let n = Scanf.scanf \" %u\" (fun v -> v) in\n let ribbons = input_ribbons 3 in\n let l = ribbons |> List.hd |> String.length in\n let maps = List.map ribbon_to_map ribbons in\n let max_beauties = List.map (max_beauty n l) maps in\n let _ = print_list max_beauties in\n let (i, max) = max_map_list max_beauties in\n let ret = \n if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1\n then None\n else Some i\n in\n ret |> result |> print_endline\n"}, {"source_code": "\nlet list_init n f =\n Array.init n f |> Array.to_list\n \nlet input_ribbons (n: int): string list =\n list_init n (fun i -> Scanf.scanf \" %s\" (fun v -> v))\n\nlet ribbon_to_map (src: string): int array =\n (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)\n let ret = Array.create (26 * 2) 0 in\n for i = 0 to String.length src - 1 do\n let idx =\n let ccode = String.get src i |> Char.code in\n if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')\n then ccode - Char.code 'A'\n else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')\n then ccode - Char.code 'a' + 26\n else raise Not_found\n in\n ret.(idx) <- ret.(idx) + 1\n done;\n ret\n\nlet max_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n\nlet min_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n let f ((mi, mv) as m) ((i, v) as n) =\n match v with\n | 0 -> m\n | _ when v < mv -> n\n | _ -> m\n in\n Array.fold_left f src.(0) src\n\nlet result (winner: int option): string =\n match winner with\n | None -> \"Draw\"\n | Some i ->\n match i with\n | 0 -> \"Kuro\"\n | 1 -> \"Shiro\"\n | 2 -> \"Katie\"\n | _ -> raise Not_found\n \nlet get_beauty n l a = \n if n <= l - a\n then a + n\n else\n let t = (a + n) mod l in\n max t (l - t)\n\nlet max_map_list (src: int list): int * int =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n \nlet max_map_i (src: (int * int) list): int * (int * int) =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (\n fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->\n if mv > v then m else n)\n (List.hd src) src\n \nlet max_beauty (n: int) (l: int) (map: int array) =\n Array.map (get_beauty n l) map |> max_map |> snd\n \nlet print_list (l: int list): unit =\n List.iter (fun i -> Printf.printf \"%d \" i) l;\n print_newline ()\n\nlet () =\n let _ = Printexc.record_backtrace true in\n let n = Scanf.scanf \" %u\" (fun v -> v) in\n let ribbons = input_ribbons 3 in\n let l = ribbons |> List.hd |> String.length in\n let maps = List.map ribbon_to_map ribbons in\n let max_beauties = List.map (max_beauty n l) maps in\n (* let _ = print_list max_beauties in *)\n let (i, max) = max_map_list max_beauties in\n let ret = \n if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1\n then None\n else Some i\n in\n ret |> result |> print_endline\n"}, {"source_code": "\nlet list_init n f =\n Array.init n f |> Array.to_list\n \nlet input_ribbons (n: int): string list =\n list_init n (fun i -> Scanf.scanf \" %s\" (fun v -> v))\n\nlet ribbon_to_map (src: string): int array =\n (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)\n let ret = Array.create 128 0 in\n for i = 0 to String.length src - 1 do\n let idx = (String.get src i |> Char.code) - Char.code 'A' in\n ret.(idx) <- ret.(idx) + 1\n done;\n ret\n\nlet max_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n\nlet min_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n let f ((mi, mv) as m) ((i, v) as n) =\n match v with\n | 0 -> m\n | _ when v < mv -> n\n | _ -> m\n in\n Array.fold_left f src.(0) src\n\nlet result (winner: int option): string =\n match winner with\n | None -> \"Draw\"\n | Some i ->\n match i with\n | 0 -> \"Kuro\"\n | 1 -> \"Shiro\"\n | 2 -> \"Katie\"\n | _ -> raise Not_found\n \nlet get_beauty n l a = \n let ret = (a + n) mod l in\n if ret = 0 then l else ret\n\nlet max_map_list (src: int list): int * int =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n \nlet max_map_i (src: (int * int) list): int * (int * int) =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (\n fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->\n if mv > v then m else n)\n (List.hd src) src\n \nlet max_beauty (n: int) (l: int) (map: int array) =\n Array.map (fun v -> if v != 0 then get_beauty n l v else 0) map |> max_map |> snd\n\nlet () =\n let _ = Printexc.record_backtrace true in\n let n = Scanf.scanf \" %u\" (fun v -> v) in\n let ribbons = input_ribbons 3 in\n let l = ribbons |> List.hd |> String.length in\n let maps = List.map ribbon_to_map ribbons in\n let maxes = List.map max_map maps in\n let max_beauties = List.map (max_beauty n l) maps in\n let (i, max) = max_map_list max_beauties in\n let ret = \n if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1\n then None\n else Some i\n in\n ret |> result |> print_endline\n"}, {"source_code": "\nlet list_init n f =\n Array.init n f |> Array.to_list\n \nlet input_ribbons (n: int): string list =\n list_init n (fun i -> Scanf.scanf \" %s\" (fun v -> v))\n\nlet ribbon_to_map (src: string): int array =\n (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)\n let ret = Array.create (26 * 2) 0 in\n for i = 0 to String.length src - 1 do\n let idx =\n let ccode = String.get src i |> Char.code in\n if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')\n then ccode - Char.code 'A'\n else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')\n then ccode - Char.code 'a' + 26\n else raise Not_found\n in\n ret.(idx) <- ret.(idx) + 1\n done;\n ret\n\nlet max_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n\nlet min_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n let f ((mi, mv) as m) ((i, v) as n) =\n match v with\n | 0 -> m\n | _ when v < mv -> n\n | _ -> m\n in\n Array.fold_left f src.(0) src\n\nlet result (winner: int option): string =\n match winner with\n | None -> \"Draw\"\n | Some i ->\n match i with\n | 0 -> \"Kuro\"\n | 1 -> \"Shiro\"\n | 2 -> \"Katie\"\n | _ -> raise Not_found\n \nlet get_beauty n l a = \n if n <= l - a\n then a + n\n else if l - a > 1 then l else l - 1\n\nlet max_map_list (src: int list): int * int =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n \nlet max_map_i (src: (int * int) list): int * (int * int) =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (\n fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->\n if mv > v then m else n)\n (List.hd src) src\n \nlet max_beauty (n: int) (l: int) (map: int array) =\n Array.map (get_beauty n l) map |> max_map |> snd\n \nlet print_list (l: int list): unit =\n List.iter (fun i -> Printf.printf \"%d \" i) l;\n print_newline ()\n\nlet () =\n let _ = Printexc.record_backtrace true in\n let n = Scanf.scanf \" %u\" (fun v -> v) in\n let ribbons = input_ribbons 3 in\n let l = ribbons |> List.hd |> String.length in\n let maps = List.map ribbon_to_map ribbons in\n let max_beauties = List.map (max_beauty n l) maps in\n (* let _ = print_list max_beauties in *)\n let (i, max) = max_map_list max_beauties in\n let ret = \n if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1\n then None\n else Some i\n in\n ret |> result |> print_endline\n"}, {"source_code": "\nlet list_init n f =\n Array.init n f |> Array.to_list\n \nlet input_ribbons (n: int): string list =\n list_init n (fun i -> Scanf.scanf \" %s\" (fun v -> v))\n\nlet ribbon_to_map (src: string): int array =\n (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)\n let ret = Array.create (26 * 2) 0 in\n for i = 0 to String.length src - 1 do\n let idx =\n let ccode = String.get src i |> Char.code in\n if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')\n then ccode - Char.code 'A'\n else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')\n then ccode - Char.code 'a' + 26\n else raise Not_found\n in\n ret.(idx) <- ret.(idx) + 1\n done;\n ret\n\nlet max_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n\nlet min_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n let f ((mi, mv) as m) ((i, v) as n) =\n match v with\n | 0 -> m\n | _ when v < mv -> n\n | _ -> m\n in\n Array.fold_left f src.(0) src\n\nlet result (winner: int option): string =\n match winner with\n | None -> \"Draw\"\n | Some i ->\n match i with\n | 0 -> \"Kuro\"\n | 1 -> \"Shiro\"\n | 2 -> \"Katie\"\n | _ -> raise Not_found\n \nlet get_beauty n l a = \n if n <= l - a\n then a + n\n else l\n\nlet max_map_list (src: int list): int * int =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n \nlet max_map_i (src: (int * int) list): int * (int * int) =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (\n fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->\n if mv > v then m else n)\n (List.hd src) src\n \nlet max_beauty (n: int) (l: int) (map: int array) =\n Array.map (get_beauty n l) map |> max_map |> snd\n \nlet print_list (l: int list): unit =\n List.iter (fun i -> Printf.printf \"%d \" i) l;\n print_newline ()\n\nlet () =\n let _ = Printexc.record_backtrace true in\n let n = Scanf.scanf \" %u\" (fun v -> v) in\n let ribbons = input_ribbons 3 in\n let l = ribbons |> List.hd |> String.length in\n let maps = List.map ribbon_to_map ribbons in\n let max_beauties = List.map (max_beauty n l) maps in\n (* let _ = print_list max_beauties in *)\n let (i, max) = max_map_list max_beauties in\n let ret = \n if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1\n then None\n else Some i\n in\n ret |> result |> print_endline\n"}, {"source_code": "\nlet list_init n f =\n Array.init n f |> Array.to_list\n \nlet input_ribbons (n: int): string list =\n list_init n (fun i -> Scanf.scanf \" %s\" (fun v -> v))\n\nlet ribbon_to_map (src: string): int array =\n (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)\n let ret = Array.create (26 * 2) 0 in\n for i = 0 to String.length src - 1 do\n let idx =\n let ccode = String.get src i |> Char.code in\n if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')\n then ccode - Char.code 'A'\n else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')\n then ccode - Char.code 'a' + 26\n else raise Not_found\n in\n ret.(idx) <- ret.(idx) + 1\n done;\n ret\n\nlet max_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n\nlet min_map (src: int array): int * int =\n let src = Array.mapi (fun i v -> (i, v)) src in\n let f ((mi, mv) as m) ((i, v) as n) =\n match v with\n | 0 -> m\n | _ when v < mv -> n\n | _ -> m\n in\n Array.fold_left f src.(0) src\n\nlet result (winner: int option): string =\n match winner with\n | None -> \"Draw\"\n | Some i ->\n match i with\n | 0 -> \"Kuro\"\n | 1 -> \"Shiro\"\n | 2 -> \"Katie\"\n | _ -> raise Not_found\n \nlet get_beauty n l a = \n if n <= l - a\n then a + n\n else if l - a > 1 && n < 2 then l else l - 1\n\nlet max_map_list (src: int list): int * int =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)\n (0, 0) src\n \nlet max_map_i (src: (int * int) list): int * (int * int) =\n let src = List.mapi (fun i v -> (i, v)) src in\n List.fold_left (\n fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->\n if mv > v then m else n)\n (List.hd src) src\n \nlet max_beauty (n: int) (l: int) (map: int array) =\n Array.map (get_beauty n l) map |> max_map |> snd\n \nlet print_list (l: int list): unit =\n List.iter (fun i -> Printf.printf \"%d \" i) l;\n print_newline ()\n\nlet () =\n let _ = Printexc.record_backtrace true in\n let n = Scanf.scanf \" %u\" (fun v -> v) in\n let ribbons = input_ribbons 3 in\n let l = ribbons |> List.hd |> String.length in\n let maps = List.map ribbon_to_map ribbons in\n let max_beauties = List.map (max_beauty n l) maps in\n (* let _ = print_list max_beauties in *)\n let (i, max) = max_map_list max_beauties in\n let ret = \n if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1\n then None\n else Some i\n in\n ret |> result |> print_endline\n"}], "src_uid": "9b277feec7952947357b133a152fd599"} {"nl": {"description": "n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.For example, if there are children with numbers [8,\u200910,\u200913,\u200914,\u200916] currently in the circle, the leader is child 13 and ai\u2009=\u200912, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.You have to write a program which prints the number of the child to be eliminated on every step.", "input_spec": "The first line contains two integer numbers n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009-\u20091). The next line contains k integer numbers a1,\u2009a2,\u2009...,\u2009ak (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.", "sample_inputs": ["7 5\n10 4 11 4 1", "3 2\n2 5"], "sample_outputs": ["4 2 5 6 1", "3 2"], "notes": "NoteLet's consider first example: In the first step child 4 is eliminated, child 5 becomes the leader. In the second step child 2 is eliminated, child 3 becomes the leader. In the third step child 5 is eliminated, child 6 becomes the leader. In the fourth step child 6 is eliminated, child 7 becomes the leader. In the final step child 1 is eliminated, child 3 becomes the leader. "}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.init n (fun i -> i + 1) in\n let a = ref (Array.to_list a) in\n let rotate a =\n match a with\n | x :: xs ->\n\t xs @ [x]\n | [] -> assert false\n in\n for i = 0 to k - 1 do\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let c = c mod (n - i) in\n\tfor j = 1 to c do\n\t a := rotate !a;\n\tdone;\n\tmatch !a with\n\t | x :: a' ->\n\t Printf.printf \"%d \" x;\n\t a := a'\n\t | [] -> assert false\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "5512fbe2963dab982a58a14daf805291"} {"nl": {"description": "Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS). Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding \"+\"-s and \"1\"-s to it. For example, sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while \")(\", \"(()\" and \"(()))(\" are not. Each bracket in CBS has a pair. For example, in \"(()(()))\": 1st bracket is paired with 8th, 2d bracket is paired with 3d, 3d bracket is paired with 2d, 4th bracket is paired with 7th, 5th bracket is paired with 6th, 6th bracket is paired with 5th, 7th bracket is paired with 4th, 8th bracket is paired with 1st. Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported: \u00abL\u00bb\u00a0\u2014 move the cursor one position to the left, \u00abR\u00bb\u00a0\u2014 move the cursor one position to the right, \u00abD\u00bb\u00a0\u2014 delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to). After the operation \"D\" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted). There are pictures illustrated several usages of operation \"D\" below. All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.Polycarp is very proud of his development, can you implement the functionality of his editor?", "input_spec": "The first line contains three positive integers n, m and p (2\u2009\u2264\u2009n\u2009\u2264\u2009500\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009500\u2009000, 1\u2009\u2264\u2009p\u2009\u2264\u2009n)\u00a0\u2014 the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even. It is followed by the string of n characters \"(\" and \")\" forming the correct bracket sequence. Then follow a string of m characters \"L\", \"R\" and \"D\"\u00a0\u2014 a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.", "output_spec": "Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.", "sample_inputs": ["8 4 5\n(())()()\nRDLD", "12 5 3\n((()())(()))\nRRDLD", "8 8 8\n(())()()\nLLLLLLDD"], "sample_outputs": ["()", "(()(()))", "()()"], "notes": "NoteIn the first sample the cursor is initially at position 5. Consider actions of the editor: command \"R\"\u00a0\u2014 the cursor moves to the position 6 on the right; command \"D\"\u00a0\u2014 the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5; command \"L\"\u00a0\u2014 the cursor moves to the position 4 on the left; command \"D\"\u00a0\u2014 the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1. Thus, the answer is equal to ()."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let m = read_int () in\n let p = read_int () in\n let s = read_string() in\n let moves = read_string() in\n\n let next = Array.init n (fun i -> if i=n-1 then -1 else i+1) in\n let prev = Array.init n (fun i -> i-1) in\n\n let pairing = Array.make n 0 in\n\n let rec scan i stack = if i scan (i+1) (i::stack)\n | ')' ->\n\tlet j = List.hd stack in\n\tpairing.(j) <- i;\n\tpairing.(i) <- j;\n\tscan (i+1) (List.tl stack)\n | _ -> failwith \"bad string\"\n ) in\n\n scan 0 [];\n \n let c = ref (p-1) in (* the curson *)\n \n let do_L () =\n c := prev.(!c);\n if !c = -1 then failwith \"bad L\";\n in\n \n let do_R () =\n c := next.(!c);\n if !c = -1 then failwith \"bad R\";\n in\n\n let do_D () =\n let i = !c in\n let j = pairing.(i) in\n let (i,j) = (min i j, max i j) in\n let (pi, nj) = (prev.(i), next.(j)) in\n if pi >= 0 then next.(pi) <- nj;\n if nj >= 0 then prev.(nj) <- pi;\n if next.(j) >= 0 then c := next.(j)\n else if prev.(i) >= 0 then c:= prev.(i)\n else failwith \"bad move\"\n in\n\n for i=0 to m-1 do\n match moves.[i] with\n | 'L' -> do_L ()\n | 'R' -> do_R ()\n | 'D' -> do_D ()\n | _-> failwith \"bad op\"\n done;\n\n let rec findleft () =\n if prev.(!c) = -1 then !c\n else (\n c := prev.(!c);\n findleft ()\n )\n in\n\n let rec loop i = if i >= 0 then (\n printf \"%c\" s.[i];\n loop next.(i)\n ) in\n\n loop (findleft());\n print_newline()\n"}], "negative_code": [], "src_uid": "cf1c39e85eded68515aae9eceac73313"} {"nl": {"description": "A country called Flatland is an infinite two-dimensional plane. Flatland has n cities, each of them is a point on the plane.Flatland is ruled by king Circle IV. Circle IV has 9 sons. He wants to give each of his sons part of Flatland to rule. For that, he wants to draw four distinct straight lines, such that two of them are parallel to the Ox axis, and two others are parallel to the Oy axis. At that, no straight line can go through any city. Thus, Flatland will be divided into 9 parts, and each son will be given exactly one of these parts. Circle IV thought a little, evaluated his sons' obedience and decided that the i-th son should get the part of Flatland that has exactly ai cities.Help Circle find such four straight lines that if we divide Flatland into 9 parts by these lines, the resulting parts can be given to the sons so that son number i got the part of Flatland which contains ai cities.", "input_spec": "The first line contains integer n (9\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cities in Flatland. Next n lines each contain two space-separated integers: xi,\u2009yi (\u2009-\u2009109\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109) \u2014 the coordinates of the i-th city. No two cities are located at the same point. The last line contains nine space-separated integers: .", "output_spec": "If there is no solution, print a single integer -1. Otherwise, print in the first line two distinct real space-separated numbers: x1,\u2009x2 \u2014 the abscissas of the straight lines that are parallel to the Oy axis. And in the second line print two distinct real space-separated numbers: y1,\u2009y2 \u2014 the ordinates of the straight lines, parallel to the Ox. If there are multiple solutions, print any of them. When the answer is being checked, a city is considered to lie on a straight line, if the distance between the city and the line doesn't exceed 10\u2009-\u20096. Two straight lines are considered the same if the distance between them doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["9\n1 1\n1 2\n1 3\n2 1\n2 2\n2 3\n3 1\n3 2\n3 3\n1 1 1 1 1 1 1 1 1", "15\n4 4\n-1 -3\n1 5\n3 -4\n-4 4\n-1 1\n3 -3\n-4 -5\n-3 3\n3 2\n4 1\n-4 2\n-2 -5\n-3 4\n-1 4\n2 1 2 1 2 1 3 2 1", "10\n-2 10\n6 0\n-16 -6\n-4 13\n-4 -2\n-17 -10\n9 15\n18 16\n-5 2\n10 -5\n2 1 1 1 1 1 1 1 1"], "sample_outputs": ["1.5000000000 2.5000000000\n1.5000000000 2.5000000000", "-3.5000000000 2.0000000000\n3.5000000000 -1.0000000000", "-1"], "notes": "NoteThe solution for the first sample test is shown below: The solution for the second sample test is shown below: There is no solution for the third sample test."}, "positive_code": [{"source_code": "type tree = Empty \n | Node of tree * int * tree * (int * int)\n(* left item right (size * depth *)\ntype direction = Left | Right\ntype path = Item of tree * direction\n \nlet size tree = match tree with Empty -> 0 | Node(_, _, _, (size,_)) -> size\nlet depth tree = match tree with Empty -> 0 | Node(_, _, _, (_,depth)) -> depth\n\nlet getroot = function \n | Node(left, k, right, _) -> (left, k, right)\n | _ -> failwith \"called getroot on Empty\"\n\nlet newNode (l, x, r) = Node(l, x, r, (1 + (size l) + (size r), 1 + max (depth l) (depth r)))\n\nlet rec build_path p t path = \n(* the node this finds is either the rightmost that is <= p or the leftmost that is > p *)\n match t with \n | Empty -> failwith \"failed build_path\"\n | Node(left, x, right, _) ->\n\tif p < x then if left<>Empty then build_path p left (Item(t, Left)::path) else (t,path)\n\telse if (* p >= x && *) right<>Empty then build_path p right (Item(t, Right)::path)\n\telse (t,path)\n\nlet rec build_deep_path t path = \n(* finds the deepest node in the tree *)\n match t with \n | Empty -> failwith \"failed build_deep_path\"\n | Node(Empty, _, Empty, _) -> (t,path)\n | Node(left, _, right, _) ->\n\tif depth left >= depth right \n\tthen build_deep_path left (Item(t, Left)::path)\n\telse build_deep_path right (Item(t, Right)::path)\n\n(* The following splay function takes as input the currently splayed\n tree (so far) t, and a path list. It takes one or two steps up,\n and calls itself recursively. *)\nlet rec rsplay = function\n | (t,[]) -> t\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->\n rsplay (newNode(tL,tK,newNode(tR,bK,newNode(bR,cK,cR))), tail)\n\t\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->\n rsplay (newNode(newNode(newNode(cL,cK,bL), bK, tL),tK,tR), tail)\n\t\n | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->\n rsplay (newNode(tL,tK,newNode(tR,bK,bR)), tail)\n\t\n | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->\n rsplay (newNode(newNode(bL,bK,tL),tK,tR), tail)\n\t\n | (_,_) -> failwith \"Splay_failed (Should not happen)\"\n \nlet splay t p = \n if t=Empty then t else rsplay (build_path p t [])\n\nlet splaydeep t = \n if t=Empty then t else rsplay (build_deep_path t [])\n\nlet split t x = \n (* split the list of segments in two. The first part is all the keys <=x\n the rest is all keys > x. *)\n if t=Empty then (Empty,Empty) else\n let (left, k, right) = getroot (splay t x) in\n if k <= x\n then (newNode(left, k, Empty), right)\n else (left, newNode(Empty, k, right)) \n\nlet balance t = \n let rec lg n = if n <= 1 then 0 else 1 + lg (n/2) in\n let l = lg (size t) in\n let rec loop t = \n if (depth t)-1 <= 4*l then t else loop (splaydeep t)\n in\n loop t\n\nlet insert t x = let (left, right) = split t x in balance (newNode(left, x, right))\n\t\t \n\n(**************************************************************************)\n\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u, read_int())\n\nlet main () = \n let n = read_int() in\n let px = Array.make n 0 in\n let py = Array.make n 0 in\n let p = Array.init n (\n fun i -> \n let (x,y) = read_pair() in\n\tpx.(i) <- x;\n\tpy.(i) <- y;\n\t(x,y)\n ) in\n\n let a = Array.init 9 (fun _ -> read_int()) in\n\n let () = Array.sort compare px in\n let () = Array.sort compare py in\n let () = Array.sort compare p in\n\n let tree = Array.make (n+1) Empty in\n let rec make_trees i ac = \n tree.(i) <- ac;\n if i=n then () else make_trees (i+1) (insert ac (snd p.(i)))\n in\n let () = make_trees 0 Empty in\n\n let valid_split () = (* return (true,(x0,x1,y0,y1)) if this permutation of the array works *)\n let sum l = List.fold_left (fun ac e -> ac + a.(e)) 0 l in\n \n let split_ok pp pop = pop = n || pop = 0 || pp.(pop-1) <> pp.(pop) in\n\n let spt pp pop = \n if pop=0 then (float pp.(0)) -. 0.5\n else (float pp.(pop-1)) +. 0.5\n in\n\n let left1 = sum [0;3;6] in\n let left2 = left1 + sum [1;4;7] in\n let bot1 = sum [6;7;8] in\n let bot2 = bot1 + sum [3;4;5] in\n\n if (split_ok px left1) && (split_ok px left2) && (split_ok py bot1) && (split_ok py bot2) && (\n (* tree.(left1) and tree.(left2) are the two trees we're interested in *)\n let y b = if b>0 then py.(b-1) else py.(0)-1 in\n let (y1,y2) = (y bot1, y bot2) in\n\t size (fst (split tree.(left1) y1)) = sum[6] && \n\t size (fst (split tree.(left1) y2 )) = sum[3;6] && \n\t size (fst (split tree.(left2) y1)) = sum[6;7] && \n\t size (fst (split tree.(left2) y2)) = sum[3;4;6;7]\n ) then (true, (spt px left1, spt px left2, spt py bot1, spt py bot2)) else (false, (0.0,0.0,0.0,0.0))\n in\n\n let swap i j = \n let t = a.(i) in\n a.(i) <- a.(j);\n a.(j) <- t\n in\n\n let rec gen_perm i = if i=9 then fst (valid_split ()) else\n let rec loop j = if j=9 then false else (\n swap i j;\n if gen_perm (i+1) then true else (\n\tswap i j;\n\tloop (j+1)\n )\n )\n in\n loop i\n in\n \n if gen_perm 0 then (\n let (_,(x1,x2,y1,y2)) = valid_split () in\n\tPrintf.printf \"%.1f %.1f\\n%.1f %.1f\\n\" x1 x2 y1 y2;\n ) else (\n Printf.printf \"-1\\n\"\n )\n;;\nmain()\n"}], "negative_code": [], "src_uid": "189467d329287b5e862b69a41eb959b4"} {"nl": {"description": "Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length $$$n$$$ consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements. Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is $$$0$$$, and removing $$$i$$$-th character increases the ambiguity by $$$a_i$$$ (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still $$$4$$$ even though you delete it from the string had).Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of the statement. The second line contains one string $$$s$$$ of length $$$n$$$, consisting of lowercase Latin letters \u2014 the statement written by Vasya. The third line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 998244353$$$).", "output_spec": "Print minimum possible ambiguity of the statement after Vasya deletes some (possibly zero) characters so the resulting statement is easy.", "sample_inputs": ["6\nhhardh\n3 2 9 11 7 1", "8\nhhzarwde\n3 2 6 9 4 8 7 1", "6\nhhaarr\n1 2 3 4 5 6"], "sample_outputs": ["5", "4", "0"], "notes": "NoteIn the first example, first two characters are removed so the result is ardh.In the second example, $$$5$$$-th character is removed so the result is hhzawde.In the third example there's no need to remove anything."}, "positive_code": [{"source_code": "open Printf\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdin \" %s\" (fun x -> x)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\nlet read_long_int () = Scanf.bscanf Scanf.Scanning.stdin \" %Ld\" (fun x -> x)\nlet (+) x y = Int64.add x y\n\nlet () = \n let n = read_int() in\n let s = read_string() in\n let tab = Array.make n 0L in\n let h = ref 0L and a = ref 0L and r = ref 0L and d = ref 0L in\n\n for i = 0 to n - 1 do\n tab.(i) <- read_long_int()\n done;\n\n for i = 0 to n - 1 do\n if s.[i] = 'h' then h := !h + tab.(i)\n else if s.[i] = 'a' then a := min !h (!a + tab.(i))\n else if s.[i] = 'r' then r := min !a (!r + tab.(i))\n else if s.[i] = 'd' then d := min !r (!d + tab.(i))\n done;\n\n printf \"%Ld\\n\" !d\n\n\n"}, {"source_code": "let max_i64,(++) = Int64.(shift_left 1L 60,add);;\nScanf.(Array.(\n scanf \" %d %s\" @@ fun n s ->\n let t = \"hard\" in\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v)\n in\n let dp = make_matrix (n+2) 5 max_i64 in\n let update i j v =\n dp.(i).(j) <- min dp.(i).(j) v\n in\n dp.(0).(0) <- 0L;\n for i=1 to n do\n for j=0 to 3 do\n if s.[i-1] = t.[j] then (\n update i (j+1) @@ dp.(i-1).(j);\n update i j @@ dp.(i-1).(j) ++ a.(i-1)\n ) else (\n update i j @@ dp.(i-1).(j)\n )\n done\n done;\n (* for i=0 to n do\n for j=0 to 4 do\n Printf.printf \"%Ld \" dp.(i).(j)\n done;\n print_newline ()\n done; *)\n Printf.printf \"%Ld\" @@\n List.fold_left min max_i64 @@\n List.tl @@ List.rev @@ to_list dp.(n)\n))"}], "negative_code": [{"source_code": "open Printf\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdin \" %s\" (fun x -> x)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let s = read_string() in\n let tab = Array.make n 0 in\n let h = ref 0 and a = ref 0 and r = ref 0 and d = ref 0 in\n\n for i = 0 to n - 1 do\n tab.(i) <- read_int()\n done;\n\n for i = n - 1 downto 0 do\n if s.[i] = 'd' then d := !d + tab.(i)\n else if s.[i] = 'r' && !d <> 0 then r := !r + tab.(i)\n else if s.[i] = 'a' && !r <> 0 then a := !a + tab.(i)\n else if s.[i] = 'h' && !a <> 0 then h := !h + tab.(i)\n done;\n\n if !h = 0 then printf \"0\\n\"\n else printf \"%d\\n\" (min (min !h !a) (min !r !d))\n\n\n"}, {"source_code": "open Printf\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdin \" %s\" (fun x -> x)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\nlet read_long_int () = Scanf.bscanf Scanf.Scanning.stdin \" %Ld\" (fun x -> x)\nlet (+) x y = Int64.add x y\n\nlet () = \n let n = read_int() in\n let s = read_string() in\n let tab = Array.make n 0L in\n let h = ref 0L and a = ref 0L and r = ref 0L and d = ref 0L in\n\n for i = 0 to n - 1 do\n tab.(i) <- read_long_int()\n done;\n\n for i = n - 1 downto 0 do\n if s.[i] = 'd' then d := !d + tab.(i)\n else if s.[i] = 'r' && !d <> 0L then r := !r + tab.(i)\n else if s.[i] = 'a' && !r <> 0L then a := !a + tab.(i)\n else if s.[i] = 'h' && !a <> 0L then h := !h + tab.(i)\n done;\n\n if !h = 0L then printf \"0\\n\"\n else printf \"%Ld\\n\" (min (min !h !a) (min !r !d))\n\n\n"}, {"source_code": "let max_i64,(++) = Int64.(max_int,add);;\nScanf.(Array.(\n scanf \" %d %s\" @@ fun n s ->\n let t = \"hard\" in\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v)\n in\n let dp = make_matrix (n+2) 5 max_i64 in\n let update i j v =\n dp.(i).(j) <- min dp.(i).(j) v\n in\n dp.(0).(0) <- 0L;\n for i=1 to n do\n for j=0 to 3 do\n if s.[i-1] = t.[j] then (\n update i (j+1) @@ dp.(i-1).(j);\n update i j @@ dp.(i-1).(j) ++ a.(i-1)\n ) else (\n update i j @@ dp.(i-1).(j)\n )\n done\n done;\n (* for i=0 to n do\n for j=0 to 4 do\n Printf.printf \"%Ld \" dp.(i).(j)\n done;\n print_newline ()\n done; *)\n Printf.printf \"%Ld\" @@ fold_left min max_i64 dp.(n)\n))"}, {"source_code": "let max_i64,(++) = Int64.(shift_left 1L 60,add);;\nScanf.(Array.(\n scanf \" %d %s\" @@ fun n s ->\n let t = \"hard\" in\n let a = init n (fun _ -> scanf \" %Ld\" @@ fun v -> v)\n in\n let dp = make_matrix (n+2) 5 max_i64 in\n let update i j v =\n if v>=0L then dp.(i).(j) <- min dp.(i).(j) v\n in\n dp.(0).(0) <- 0L;\n for i=1 to n do\n for j=0 to 3 do\n if s.[i-1] = t.[j] then (\n update i (j+1) @@ dp.(i-1).(j);\n update i j @@ dp.(i-1).(j) ++ a.(i-1)\n ) else (\n update i j @@ dp.(i-1).(j)\n )\n done\n done;\n (* for i=0 to n do\n for j=0 to 4 do\n Printf.printf \"%Ld \" dp.(i).(j)\n done;\n print_newline ()\n done; *)\n Printf.printf \"%Ld\" @@ fold_left min max_i64 dp.(n)\n));;"}], "src_uid": "8cc22dc6e81bb49b64136e5ff7eb8caf"} {"nl": {"description": "Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $$$s$$$ of length $$$n$$$.Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $$$s$$$.She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $$$s$$$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The next $$$2 \\cdot t$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of the string. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and $$$-1$$$, if it is impossible.", "sample_inputs": ["5\n8\nabcaacab\n6\nxyzxyz\n4\nabba\n8\nrprarlap\n10\nkhyyhhyhky"], "sample_outputs": ["2\n-1\n0\n3\n2"], "notes": "NoteIn the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.In the third test case, you don't have to erase any symbols because the string is already a palindrome."}, "positive_code": [{"source_code": "let solve_char (s: string) (c: char) =\r\n let n = String.length s in\r\n let rec solve_char_ s i j res =\r\n if i >= j then\r\n res\r\n else if (s.[i] == s.[j]) then\r\n solve_char_ s (i+1) (j-1) res\r\n else if (s.[i] == c) then\r\n solve_char_ s (i+1) j (res + 1)\r\n else if (s.[j] == c) then\r\n solve_char_ s i (j-1) (res + 1)\r\n else\r\n max_int\r\n in solve_char_ s 0 (n-1) 0\r\n\r\n\r\nlet solve (s: string) =\r\n let res = ref (solve_char s 'a') in\r\n let c = ref 'b' in\r\n while (!c <= 'z') do\r\n res := min (!res) (solve_char s !c);\r\n c := char_of_int (succ (int_of_char (!c)))\r\n done;\r\n if !res = max_int then\r\n -1\r\n else !res\r\n\r\n\r\n\r\nlet () =\r\n let tc = Scanf.scanf \" %d\" (fun x -> x) in\r\n let rec loop tc =\r\n match tc with\r\n | 0 -> ();\r\n | _ -> let n, s = Scanf.scanf \" %d %s\" (fun n s -> n, s) in\r\n Printf.printf \"%d\\n\" (solve s);\r\n loop (tc - 1)\r\n in loop tc\r\n\r\n"}], "negative_code": [], "src_uid": "8ca8317ce3f678c99dc746cb9b058993"} {"nl": {"description": "A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand. One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.", "input_spec": "The first line indicates the door through which the very important person entered the elevator. It contains \"front\" if the person enters the elevator through the front door and \"back\" if he entered the elevator through the back door. The second line contains integer a (1\u2009\u2264\u2009a\u2009\u2264\u20092) which denotes the number of the rail at which the person was holding.", "output_spec": "Print character \"R\" if the VIP is right-handed or \"L\" if he is left-handed.", "sample_inputs": ["front\n1"], "sample_outputs": ["L"], "notes": null}, "positive_code": [{"source_code": "let () =\n\tlet in_data = open_in \"input.txt\" in\n\tlet out_data = open_out \"output.txt\" in\n\tlet _ = Scanf.fscanf in_data \"%s %d\" (fun d p ->\n\t\tlet bp = (p = 1) in\n\t\tlet bd = (d = \"front\") in\n\t\tPrintf.fprintf out_data \"%s\" (\n\t\t\tif bp <> bd then \"R\" else \"L\"\n\t\t)\n\t) in\n\tlet _ = close_out out_data in\n\tclose_in in_data\n;;\n"}], "negative_code": [], "src_uid": "77093f12ff56d5f404e9c87650d4aeb4"} {"nl": {"description": "Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \\le i \\le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he: will buy exactly $$$n$$$ shovels in total; the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive. ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$)\u00a0\u2014 the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \\le n \\le 10^9$$$) and $$$k$$$ ($$$1 \\le k \\le 10^9$$$)\u00a0\u2014 the number of shovels and the number of types of packages.", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer is a positive integer\u00a0\u2014 the minimum number of packages.", "sample_inputs": ["5\n8 7\n8 1\n6 10\n999999733 999999732\n999999733 999999733"], "sample_outputs": ["2\n8\n1\n999999733\n1"], "notes": "NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels\u00a0\u2014 $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels."}, "positive_code": [{"source_code": "let split_string ?(pattern=\"\") = Str.split @@ Str.regexp pattern\nlet t = Scanf.sscanf (read_line ()) \"%d\" @@ fun t -> t\n\nlet rec f1 acc n i =\n if i * i > n then acc\n else f1 (if n mod i = 0 then (n / i) :: i :: acc else acc) n (i + 1)\n\nlet rec f n k = \n let acc = f1 [] n 2 |> List.sort compare in\n (* List.map string_of_int acc |> String.concat \" \" |> print_endline; *)\n let a = List.fold_left (fun s t -> if t <= k then t else s) 1 acc in\n (* Printf.printf \"a = %d\\n\" a; *)\n n / a\n\nlet () = for _ = 1 to t do\n let (n, k) = Scanf.sscanf (read_line ()) \"%d %d\" @@ fun n k -> (n, k) in\n if n <= k then print_endline \"1\"\n else Printf.printf \"%d\\n\" @@ f n k\ndone"}], "negative_code": [], "src_uid": "f00eb0452f5933103f1f77ef06473c6a"} {"nl": {"description": "You are given an array $$$a[0 \\ldots n-1]$$$ of length $$$n$$$ which consists of non-negative integers. Note that array indices start from zero.An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $$$i$$$ ($$$0 \\le i \\le n - 1$$$) the equality $$$i \\bmod 2 = a[i] \\bmod 2$$$ holds, where $$$x \\bmod 2$$$ is the remainder of dividing $$$x$$$ by 2.For example, the arrays [$$$0, 5, 2, 1$$$] and [$$$0, 17, 0, 3$$$] are good, and the array [$$$2, 4, 6, 7$$$] is bad, because for $$$i=1$$$, the parities of $$$i$$$ and $$$a[i]$$$ are different: $$$i \\bmod 2 = 1 \\bmod 2 = 1$$$, but $$$a[i] \\bmod 2 = 4 \\bmod 2 = 0$$$.In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).Find the minimum number of moves in which you can make the array $$$a$$$ good, or say that this is not possible.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \\le n \\le 40$$$)\u00a0\u2014 the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_0, a_1, \\ldots, a_{n-1}$$$ ($$$0 \\le a_i \\le 1000$$$)\u00a0\u2014 the initial array.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the minimum number of moves to make the given array $$$a$$$ good, or -1 if this is not possible.", "sample_inputs": ["4\n4\n3 2 7 6\n3\n3 2 6\n1\n7\n7\n4 9 2 1 18 3 0"], "sample_outputs": ["2\n1\n-1\n0"], "notes": "NoteIn the first test case, in the first move, you can swap the elements with indices $$$0$$$ and $$$1$$$, and in the second move, you can swap the elements with indices $$$2$$$ and $$$3$$$.In the second test case, in the first move, you need to swap the elements with indices $$$0$$$ and $$$1$$$.In the third test case, you cannot make the array good."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let t = read_int () in\n for i = 1 to t do\n let n = read_int () in \n let (a, b) = \n let rec loop a b = function\n | 0 -> (a, b)\n | m -> \n let x = read_int () in\n if not ((x mod 2) = ((n-m) mod 2)) then\n if ((n-m) mod 2) = 0 then \n loop (a+1) b (m-1) \n else \n loop a (b+1) (m-1)\n else \n loop a b (m-1)\n in loop 0 0 n\n in\n if not (a = b) then Printf.printf \"-1\\n\" else Printf.printf \"%d\\n\" a\n done\n"}, {"source_code": "let read_ints () =\n let str = read_line () in\n List.map (fun x -> int_of_string x) (Str.split (Str.regexp \" +\") str)\n;;\n\nlet rec count (num : int list) (modi : int) (ind : int)=\n match num with\n |[] -> 0\n |h :: t -> if ((ind mod 2) <> modi && h mod 2 = modi) then 1 + count t modi (ind + 1) else count t modi (ind + 1)\n;;\n\nlet rec main (t : int) =\n if t = 0 then\n ()\n else\n (\n let siz = read_int () in\n let a = read_ints () in\n let one_zero = count a 0 0 in\n let zero_one = count a 1 0 in\n if (one_zero <> zero_one) then print_endline \"-1\" else print_endline (string_of_int one_zero);\n main (t - 1)\n )\n;;\nlet t = read_int() in\nmain t\n"}], "negative_code": [], "src_uid": "942123e43a83d5a4cea95a6781064e28"} {"nl": {"description": "One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result x, and the largest result y, then the inequality y\u2009\u2264\u20092\u00b7x must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of measurements Vasya made. The second line contains n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u20095000) \u2014 the results of the measurements. The numbers on the second line are separated by single spaces.", "output_spec": "Print a single integer \u2014 the minimum number of results Vasya will have to remove.", "sample_inputs": ["6\n4 5 3 8 3 7", "4\n4 3 2 4"], "sample_outputs": ["2", "0"], "notes": "NoteIn the first sample you can remove the fourth and the sixth measurement results (values 8 and 7). Then the maximum of the remaining values will be 5, and the minimum one will be 3. Or else, you can remove the third and fifth results (both equal 3). After that the largest remaining result will be 8, and the smallest one will be 4."}, "positive_code": [{"source_code": "let chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet () = \n let n = read_int() in\n let c = Array.init n (fun i -> read_int()) in\n let () = Array.sort compare c in\n \n let rec loop i j ac =\n if i=n then ac else\n if j >= n-1 || c.(j+1) > 2*c.(i) then \n\tloop (i+1) j (max (j-i+1) ac)\n else loop i (j+1) ac\n in\n \n let a = loop 0 0 0 in\n print_string (Printf.sprintf \"%d\\n\" (n-a))\n"}, {"source_code": "let chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet () = \n let n = read_int() in\n let c = Array.init n (fun i -> read_int()) in\n let () = Array.sort compare c in\n \n let rec loop i j ac = if i=n then ac else\n if j >= n-1 || c.(j+1) > 2*c.(i) then loop (i+1) j (max (j-i+1) ac)\n else loop i (j+1) ac\n in\n \n let a = loop 0 0 0 in\n print_string (Printf.sprintf \"%d\\n\" (n-a))\n"}], "negative_code": [{"source_code": "open Scanf;;\nopen Array;;\nopen Printf;;\n\n(*print_endline \"begin\";;\n *)\n\nlet file_in = \"input.txt\";;\nlet file_out = \"output.txt\";;\n\nlet ic = open_in file_in;;\nlet n = Scanf.bscanf (Scanf.Scanning.from_channel ic) \"%d \" (fun x -> x);;\nlet a = Array.make n 0;;\n\n(*print_endline \"xx\";;\n *)\nlet () = \n for i = 0 to n-1 do\n let x = Scanf.bscanf (Scanf.Scanning.from_channel ic) \"%d \" (fun x -> x) in\n a.(i) <- x\n done in\n Array.sort (fun x y -> y - x) a\n;;\n\n(*Array.iter (fun x -> print_int x; print_endline \"\") a;;\n *)\n\nclose_in ic;;\n\nlet my_min x y = if x < y then x else y;;\n\nexception Found;;\n\nlet nrow = \n let row = ref 0 in\n let i = ref (n - 1) in\n try \n while (!i >=0) do\n if a.(0) <= (2*a.(!i)) then raise Found;\n row := !row + 1;\n i:=!i-1\n done; !row+1\n with Found -> !row+1;;\n\nlet ncol = \n let col = ref 0 in\n let i = ref 0 in\n try \n while (!i < n) do\n if 2*a.(n-1) >= a.(!i) then raise Found;\n col := !col + 1;\n i:=!i+1\n done; !col+1\n with Found -> !col+1;;\n\nlet biggest = max_int;;\nlet b = Array.make_matrix nrow ncol 0;;\n(*Initialize the matrix*)\nlet () = \n for i = ncol-1 downto 1 do\n b.(nrow-1).(i) <- biggest\n done;\n for i = nrow-1 downto 1 do\n b.(i).(ncol-1) <- biggest\n done\n;;\n\nlet () = \n b.(nrow-1).(0) <- nrow - 1;\n b.(0).(ncol-1) <- ncol -1\n;; \n\nlet my_min x y z = min (min x y) (min y z);;\n\n (*\nfor i = ncol-2 downto 0 do\n for j = nrow -2 downto 0 do\n let x = b.(j+1).(i) in\n let y = b.(j).(i+1) in\n let z = if a.(nrow - 1 - j) > 2*a.(n-1 - (ncol-1 - i)) then biggest else (ncol-1-i)+(nrow-1-j)\n in\n b.(j).(i) <- (my_min x y z)\n done\ndone; let oc = open_out file_out in\n if b.(0).(0) = biggest then \n\tPrintf.fprintf oc \"%d\\n\" 1 \n else\n\tPrintf.fprintf oc \"%d\\n\" b.(0).(0);;\n *)\n\nlet ncold = ncol -1 in\nlet nrowd = nrow -1 in\nlet rec find_b00 i j =\n match i,j with\n (0, ncold) -> nrowd \n |(x, ncold) when x>0 -> biggest \n |(nrowd, 0) -> ncold\n |(nrowd, x) when x>0 -> nrowd\n |_ -> \n begin\n let x = find_b00 (j+1) (i) in\n let y = find_b00 (j) (i+1) in\n let z = if a.(nrow - 1 - j) > 2*a.(n-1 - (ncol-1 - i)) then biggest else (ncol-1-i)+(nrow-1-j)\n in\n my_min x y z\n end\n in let rslt = find_b00 0 0 in\n let oc = open_out file_out in\n Printf.fprintf oc \"%d\\n\" rslt;;\n \n"}, {"source_code": "open Scanf;;\nopen Array;;\nopen Printf;;\n\n(* This version uses binary search and rec\n *)\n\nlet file_in = \"input.txt\";;\nlet file_out = \"output.txt\";;\n\nlet ic = open_in file_in;;\nlet oc = open_out file_out;;\n\nlet n = Scanf.bscanf (Scanf.Scanning.from_channel ic) \"%d \" (fun x -> x);;\nlet a = Array.make n 0;;\n\nlet () = \n for i = 0 to n-1 do\n let x = Scanf.bscanf (Scanf.Scanning.from_channel ic) \"%d \" (fun x -> x) in\n a.(i) <- x\n done in\n Array.sort (fun x y -> y - x) a\n;; (*array a is from large to small*)\n\n(*\nArray.iter (fun x -> print_int x; print_string \" \") a;;\nprint_endline \"\\n-------\";;\n *)\n\nclose_in ic;;\n\nlet my_min x y z = min (min x y ) (min y z )\n\nexception Found;;\n\nlet rec b1search x ii jj =\n let mid = (ii+jj)/2 in\n if mid = ii then ii\n else\n if x > 2*a.(mid) then b1search x (mid+1) jj\n else b1search x ii mid\n;; \n\n \n \nlet rec b2search x ii jj =\nlet mid = (ii+jj)/2 in\nif mid = ii then ii\nelse\n if 2*x < a.(mid) then b2search x (mid+1) jj\n else b2search x ii mid\n;;\n\n(*let y = b1search 8 0 5 in\nprint_int y;;\n *)\n\nlet rec solve i j =\n if i >= j then 0\n else if\n a.(i) <= 2*a.(j) \n then i+(n-1-j)\n else\n begin\n let x = j-(b1search a.(i) i j) in (*b1search search for small value*)\n let y = (b2search a.(j) i j)-i in (*b2 search searchh for large value*)\n let z = 2 + (solve (i+1) (j-1)) in\n my_min x y z;\n end\n;;\n\nlet rslt = solve 0 (n-1) \n in\n Printf.fprintf oc \"%d\\n\" rslt\n;;\n"}, {"source_code": "(*amazing: this version uses the technique of two pointers*)\n\nlet chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet () = \n let n = read_int() in\n let c = Array.init n (fun i -> read_int()) in\n let () = Array.sort compare c in\n \n let rec loop i j ac =\n if i=j then ac else\n if c.(j) <= 2*c.(i) then \n\tloop (i+1) j (max (j-i+1) ac)\n else loop i (j-1) ac\n in\n \n let a = loop 0 (n-1) 0 in\n print_string (Printf.sprintf \"%d\\n\" (n-a))\n"}], "src_uid": "80cf3ea119fd398e8f003d22a76895a7"} {"nl": {"description": "The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009n), where ai represents the number of messages that the i-th employee should get according to Igor.", "output_spec": "In the first line print a single integer m \u2014 the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers \u2014 the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them.", "sample_inputs": ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"], "sample_outputs": ["1\n1", "0", "4\n1 2 3 4"], "notes": "NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second \u2014 3, the third \u2014 2, the fourth \u2014 3."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet read_int() = bscanf Scanning.stdib \" %d \" (fun x->x)\nlet read_string() = bscanf Scanning.stdib \" %s \" (fun x->x)\nlet () =\n let n = read_int() in\n let adj = Array.init n (fun _-> read_string()) in\n let a = Array.init n (fun _-> read_int()) in\n (* set.(i) = true means excluse i from party*)\n let set = Array.make n false in\n let count = Array.make n 0 in\n \n (* compute each person get how many msgs*)\n let compute() =\n\tArray.fill count 0 n 0;\n\tfor i=0 to n-1 do\n\t if set.(i) then \n\t\tfor j=0 to n-1 do\n\t\t if adj.(i).[j]='1' then count.(j)<-count.(j)+1\n\t\tdone\n\tdone\n in\n \n let rec find_bad_person i =\n\tif i>=n then i\n\telse\n\t if a.(i)=count.(i) then i else find_bad_person (i+1)\n in\n \n let rec loop() =\n\tcompute();\n\tlet i = find_bad_person 0 in\n\tif i if set.(i) then 1 else 0) in\n printf \"%d\\n\" c;\n \n for i=0 to n-1 do\n\tif set.(i) then printf \"%d \" (i+1)\n done;\n print_newline();\n \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let adj = Array.init n (fun _ -> read_string()) in\n let a = Array.init n (fun _ -> read_int()) in\n\n let set = Array.make n false in\n let count = Array.make n 0 in\n\n let compute_count () =\n Array.fill count 0 n 0;\n for i=0 to n-1 do\n if set.(i) then\n\tfor j=0 to n-1 do\n\t if adj.(i).[j] = '1' then count.(j) <- count.(j) + 1\n\tdone\n done\n in\n\n let rec find_correct_item i = if i=n then -1 else\n if a.(i) = count.(i) then i else find_correct_item (i+1)\n in\n\n let rec loop () =\n compute_count ();\n let k = find_correct_item 0 in\n if k >= 0 then (\n set.(k) <- true;\n loop ()\n )\n in\n\n loop ();\n\n let c = sum 0 (n-1) (fun i -> if set.(i) then 1 else 0) in\n\n printf \"%d\\n\" c;\n\n for i=0 to n-1 do\n if set.(i) then printf \"%d \" (i+1)\n done;\n\n print_newline();\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let _ = Array.init n (fun _ -> read_string()) in\n let a = Array.init n (fun _ -> read_int()) in\n\n if a.(0) = 0 then (\n printf \"1\\n\";\n printf \"1\\n\"\n ) else (\n printf \"0\\n\";\n printf \"\\n\";\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let _ = Array.init n (fun _ -> read_string()) in\n let a = Array.init n (fun _ -> read_int()) in\n\n if a.(0) = 0 then (\n printf \"1\\n\";\n printf \"1\\n\"\n ) else (\n printf \"0\\n\"\n )\n"}], "src_uid": "794b0ac038e4e32f35f754e9278424d3"} {"nl": {"description": "JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.First, he splits the Banh-mi into $$$n$$$ parts, places them on a row and numbers them from $$$1$$$ through $$$n$$$. For each part $$$i$$$, he defines the deliciousness of the part as $$$x_i \\in \\{0, 1\\}$$$. JATC's going to eat those parts one by one. At each step, he chooses arbitrary remaining part and eats it. Suppose that part is the $$$i$$$-th part then his enjoyment of the Banh-mi will increase by $$$x_i$$$ and the deliciousness of all the remaining parts will also increase by $$$x_i$$$. The initial enjoyment of JATC is equal to $$$0$$$.For example, suppose the deliciousness of $$$3$$$ parts are $$$[0, 1, 0]$$$. If JATC eats the second part then his enjoyment will become $$$1$$$ and the deliciousness of remaining parts will become $$$[1, \\_, 1]$$$. Next, if he eats the first part then his enjoyment will become $$$2$$$ and the remaining parts will become $$$[\\_, \\_, 2]$$$. After eating the last part, JATC's enjoyment will become $$$4$$$.However, JATC doesn't want to eat all the parts but to save some for later. He gives you $$$q$$$ queries, each of them consisting of two integers $$$l_i$$$ and $$$r_i$$$. For each query, you have to let him know what is the maximum enjoyment he can get if he eats all the parts with indices in the range $$$[l_i, r_i]$$$ in some order.All the queries are independent of each other. Since the answer to the query could be very large, print it modulo $$$10^9+7$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n, q \\le 100\\,000$$$). The second line contains a string of $$$n$$$ characters, each character is either '0' or '1'. The $$$i$$$-th character defines the deliciousness of the $$$i$$$-th part. Each of the following $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i \\le r_i \\le n$$$)\u00a0\u2014 the segment of the corresponding query.", "output_spec": "Print $$$q$$$ lines, where $$$i$$$-th of them contains a single integer\u00a0\u2014 the answer to the $$$i$$$-th query modulo $$$10^9 + 7$$$.", "sample_inputs": ["4 2\n1011\n1 4\n3 4", "3 2\n111\n1 2\n3 3"], "sample_outputs": ["14\n3", "3\n1"], "notes": "NoteIn the first example: For query $$$1$$$: One of the best ways for JATC to eats those parts is in this order: $$$1$$$, $$$4$$$, $$$3$$$, $$$2$$$. For query $$$2$$$: Both $$$3$$$, $$$4$$$ and $$$4$$$, $$$3$$$ ordering give the same answer. In the second example, any order of eating parts leads to the same answer."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nmodule CumulSumArray = struct\n let make a =\n let ln = Array.length a\n in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n let sum l r a = (* 0-origin,closed *)\n if l>r then 0L else (a.(r+$1) - a.(l))\n let sum_1orig l r a = sum (l-$1) (r-$1) a\nend\n\nmodule ModCalc = struct\n let md = 1000000007L\n (* let md = 998244353L *)\n let validate v =\n (v + (labs(v) / md + 1L) * md) mod md\n let _add_mod md u v = u mod md + v mod md |> validate\n let _sub_mod md u v = u mod md - v mod md |> validate\n let _mul_mod md u v = u mod md * v mod md |> validate\n let rec pw u v =\n if v=0L then 1L\n else if v=1L then u mod md\n else let p = pw u (v/2L) in\n if v mod 2L = 0L then _mul_mod md p p\n else _mul_mod md (_mul_mod md p p) u\n let _inv md v = pw v (md-2L) (* md must be prime; otherwise use extended Euclidean algorithm *)\n let _div_mod md u v =\n _mul_mod md u (_inv md v)\n let (+%) u v = _add_mod md u v\n let (-%) u v = _sub_mod md u v\n let ( *%) u v = _mul_mod md u v\n let (/%) u v = _div_mod md u v\n let rec pow x n = if n = 0L then 1L\n else if n mod 2L = 1L then x *% pow x (n-1L)\n else let w = pow x (n/2L) in w *% w\n let fact_simple n = let rec f0 n v = if n = 0L then v else f0 (n-1L) (n*%v) in f0 n 1L\n type fact = Fact of int64 array * int64 array\n let fact_make n =\n let m = i32 n in\n let fact,invf = Array.make m 0L,Array.make m 0L in\n fact.(0) <- 1L;\n for i=1 to m-$1 do fact.(i) <- fact.(i-$1) *% (i64 i); done;\n invf.(m-$1) <- pow fact.(m-$1) (md-2L);\n for i=m-$2 downto 0 do invf.(i) <- invf.(i+$1) *% (i64 i + 1L); done; Fact (fact,invf)\n let fact_get i (Fact (fact,_)) = fact.(i)\n (* let fact_inv_get i (Fact (_,invf)) = invf.(i) (* not tested yet *) *)\n let ncr n r (Fact (fact,invf)) = fact.(n) *% invf.(r) *% invf.(n-$r)\nend open ModCalc\n\nlet tp i =\n let i = ref i in\n let x = ref 2L in\n let r = ref 1L in\n while !i > 0L do\n if !i mod 2L = 1L then (\n r := !r *% !x;\n );\n x := !x *% !x;\n i /= 2L;\n done; !r\n\nlet () =\n let n,q = get_2_i64 0 in\n let a =\n let s = scanf \" %s\"@@id in\n let a = make (String.length s) 0L in\n String.iteri (fun i c -> a.(i) <- i64 @@ (int_of_char c) -$ (int_of_char '0')) s;\n a in\n let ones = CumulSumArray.make a in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n let one = CumulSumArray.sum_1orig (i32 l) (i32 r) ones in\n let zero = r - l + 1L - one in\n (* printf \"%Ld %Ld\\n\" one zero; *)\n let sum_one = tp one - 1L in\n (* printf \"%Ld\\n\" sum_one; *)\n let sum_zero = sum_one * (tp zero - 1L) in\n (* printf \"%Ld\\n\" sum_zero; *)\n printf \"%Ld\\n\" (sum_one +% sum_zero)\n )\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nmodule CumulSumArray = struct\n let make a =\n let ln = Array.length a\n in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n let sum l r a = (* 0-origin,closed *)\n if l>r then 0L else (a.(r+$1) - a.(l))\n let sum_1orig l r a = sum (l-$1) (r-$1) a\nend\n\nlet md = 1000000007L\nlet ( *$ ) p q = ((p mod md) * (q mod md)) mod md\nlet pow n k =\n let rec f a n = function\n | 0L -> a\n | 1L -> n*$a\n | k when k mod 2L = 0L -> f a (n*$n) (k/2L)\n | k -> f (a*$n) (n*$n) (k/2L)\n in f 1L n k\n\nlet () =\n let n,q = get_2_i64 0 in\n let a =\n let s = scanf \" %s\"@@id in\n let a = make (String.length s) 0L in\n String.iteri (fun i c -> a.(i) <- i64 @@ (int_of_char c) -$ (int_of_char '0')) s;\n a in\n let ones = CumulSumArray.make a in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n let one = CumulSumArray.sum_1orig (i32 l) (i32 r) ones in\n let zero = r - l + 1L - one in\n let sum_one = pow 2L one - 1L in\n let sum_zero = sum_one * (pow 2L zero - 1L) in\n printf \"%Ld\\n\" @@ (sum_one + sum_zero) mod md\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule CumulSumArray = struct\n let make a =\n let ln = Array.length a\n in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n let sum l r a = (* 0-origin,closed *)\n if l>r then 0L else (a.(r+$1) - a.(l))\n let sum_1orig l r a = sum (l-$1) (r-$1) a\nend\nmodule ModCalc_test = struct\n let md = 1000000007L\n (* let md = 998244353L *)\n (* be careful of negative int *)\n let (+%) p q = ((p mod md) + (q mod md)) mod md\n let (-%) p q = ((p mod md) - (q mod md)) mod md\n let ( *% ) p q = ((p mod md) * (q mod md)) mod md\n let rec pow_mod n k = (* to be tested *)\n let rec f a n = function\n | 0L -> a mod md\n | 1L -> a *% n\n | k when k mod 2L = 0L -> f a (n *% n) (k/2L)\n | k -> f (a *% n) n (k-1L)\n in f 1L n k\n let inv v = pow_mod v (md-2L) (* md must be prime; otherwise use extended Euclidean algorithm *)\n let (/%) p q = p *% (inv q)\n let fact_simple n = let rec f0 n v = if n = 0L then v else f0 (n-1L) (n*%v) in f0 n 1L\n type fact = Fact of int64 array * int64 array\n let fact_make n =\n let m = i32 n in\n let fact,invf = Array.make m 0L,Array.make m 0L in\n fact.(0) <- 1L;\n for i=1 to m-$1 do fact.(i) <- fact.(i-$1) *% (i64 i); done;\n invf.(m-$1) <- pow_mod fact.(m-$1) (md-2L);\n for i=m-$2 downto 0 do invf.(i) <- invf.(i+$1) *% (i64 i + 1L); done; Fact (fact,invf)\n let fact_get i (Fact (fact,_)) = fact.(i)\n let ncr n r (Fact (fact,invf)) = fact.(n) *% invf.(r) *% invf.(n-$r)\nend\nopen ModCalc_test\nlet () =\n let n,q = get_2_i64 0 in\n let a =\n let s = scanf \" %s\"@@id in\n let a = make (String.length s) 0L in\n String.iteri (fun i c -> a.(i) <- i64 @@ (int_of_char c) -$ (int_of_char '0')) s;\n a in\n let ones = CumulSumArray.make a in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n let one = CumulSumArray.sum_1orig (i32 l) (i32 r) ones in\n let zero = r - l + 1L - one in\n let sum_one = pow_mod 2L one - 1L in\n let sum_zero = sum_one * (pow_mod 2L zero - 1L) in\n printf \"%Ld\\n\" @@ sum_one +% sum_zero\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nmodule CumulSumArray = struct\n let make a =\n let ln = Array.length a\n in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n let sum l r a = (* 0-origin,closed *)\n if l>r then 0L else (a.(r+$1) - a.(l))\n let sum_1orig l r a = sum (l-$1) (r-$1) a\nend\n\nlet md = 1000000007L\nlet ( +$ ) p q = ((p mod md) + (q mod md)) mod md\nlet ( *$ ) p q = ((p mod md) * (q mod md)) mod md\nlet pow n k =\n let rec f a n = function\n | 0L -> a\n | 1L -> n*$a\n | k when k mod 2L = 0L -> f a (n*$n) (k/2L)\n | k -> f (a*$n) (n*$n) (k/2L)\n in f 1L n k\n\nlet () =\n let n,q = get_2_i64 0 in\n let a =\n let s = scanf \" %s\"@@id in\n let a = make (String.length s) 0L in\n String.iteri (fun i c -> a.(i) <- i64 @@ (int_of_char c) -$ (int_of_char '0')) s;\n a in\n let ones = CumulSumArray.make a in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n let one = CumulSumArray.sum_1orig (i32 l) (i32 r) ones in\n let zero = r - l + 1L - one in\n let sum_one = pow 2L one - 1L in\n let sum_zero = sum_one * (pow 2L zero - 1L) in\n printf \"%Ld\\n\" @@ sum_one +$ sum_zero\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule CumulSumArray = struct\n let make a =\n let ln = Array.length a\n in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n let sum l r a = (* 0-origin,closed *)\n if l>r then 0L else (a.(r+$1) - a.(l))\n let sum_1orig l r a = sum (l-$1) (r-$1) a\nend\nmodule ModCalc_test = struct\n let md = 1000000007L\n (* let md = 998244353L *)\n (* be careful of negative int *)\n let (+%) p q = ((p mod md) + (q mod md)) mod md\n let (-%) p q = ((p mod md) - (q mod md)) mod md\n let ( *% ) p q = ((p mod md) * (q mod md)) mod md\n let rec pow_mod n k = (* to be tested *)\n let rec f a n = function\n | 0L -> a mod md\n | 1L -> a *% n\n | k when k mod 2L = 0L -> f a (n *% n) (k/2L)\n | k -> f (a *% n) n (k-1L)\n in f 1L n k\n (* let inv v = pow_mod v (md-2L) (* md must be prime; otherwise use extended Euclidean algorithm *)\n let (/%) p q = p *% (inv q)\n let fact_simple n = let rec f0 n v = if n = 0L then v else f0 (n-1L) (n*%v) in f0 n 1L\n type fact = Fact of int64 array * int64 array\n let fact_make n =\n let m = i32 n in\n let fact,invf = Array.make m 0L,Array.make m 0L in\n fact.(0) <- 1L;\n for i=1 to m-$1 do fact.(i) <- fact.(i-$1) *% (i64 i); done;\n invf.(m-$1) <- pow_mod fact.(m-$1) (md-2L);\n for i=m-$2 downto 0 do invf.(i) <- invf.(i+$1) *% (i64 i + 1L); done; Fact (fact,invf)\n let fact_get i (Fact (fact,_)) = fact.(i)\n let ncr n r (Fact (fact,invf)) = fact.(n) *% invf.(r) *% invf.(n-$r) *)\nend\nopen ModCalc_test\nlet () =\n let n,q = get_2_i64 0 in\n let a =\n let s = scanf \" %s\"@@id in\n let a = make (String.length s) 0L in\n String.iteri (fun i c -> a.(i) <- i64 @@ (int_of_char c) -$ (int_of_char '0')) s;\n a in\n let ones = CumulSumArray.make a in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n let one = CumulSumArray.sum_1orig (i32 l) (i32 r) ones in\n let zero = r - l + 1L - one in\n let sum_one = pow_mod 2L one - 1L in\n let sum_zero = sum_one * (pow_mod 2L zero - 1L) in\n printf \"%Ld\\n\" @@ sum_one +% sum_zero\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nmodule CumulSumArray = struct\n let make a =\n let ln = Array.length a\n in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n let sum l r a = (* 0-origin,closed *)\n if l>r then 0L else (a.(r+$1) - a.(l))\n let sum_1orig l r a = sum (l-$1) (r-$1) a\nend\n\nmodule ModCalc = struct\n let md = 1000000007L\n (* let md = 998244353L *)\n let validate v =\n (v + (labs(v) / md + 1L) * md) mod md\n let _add_mod md u v = u mod md + v mod md |> validate\n let _sub_mod md u v = u mod md - v mod md |> validate\n let _mul_mod md u v = u mod md * v mod md |> validate\n (* let rec pw u v =\n if v=0L then 1L\n else if v=1L then u mod md\n else let p = pw u (v/2L) in\n if v mod 2L = 0L then _mul_mod md p p\n else _mul_mod md (_mul_mod md p p) u *)\n let rec pow_mod n k = (* to be tested *)\n let rec f a n = function\n | 0L -> a mod md\n | 1L -> _mul_mod md a n\n | k when k mod 2L = 0L -> f a (_mul_mod md n n) (k/2L)\n | k -> f (_mul_mod md a n) n (k-1L)\n in f 1L n k\n let _inv md v = pow_mod v (md-2L) (* md must be prime; otherwise use extended Euclidean algorithm *)\n let _div_mod md u v =\n _mul_mod md u (_inv md v)\n let (+%) u v = _add_mod md u v\n let (-%) u v = _sub_mod md u v\n let ( *%) u v = _mul_mod md u v\n let (/%) u v = _div_mod md u v\n let rec pow x n = if n = 0L then 1L\n else if n mod 2L = 1L then x *% pow x (n-1L)\n else let w = pow x (n/2L) in w *% w\n let fact_simple n = let rec f0 n v = if n = 0L then v else f0 (n-1L) (n*%v) in f0 n 1L\n type fact = Fact of int64 array * int64 array\n let fact_make n =\n let m = i32 n in\n let fact,invf = Array.make m 0L,Array.make m 0L in\n fact.(0) <- 1L;\n for i=1 to m-$1 do fact.(i) <- fact.(i-$1) *% (i64 i); done;\n invf.(m-$1) <- pow fact.(m-$1) (md-2L);\n for i=m-$2 downto 0 do invf.(i) <- invf.(i+$1) *% (i64 i + 1L); done; Fact (fact,invf)\n let fact_get i (Fact (fact,_)) = fact.(i)\n (* let fact_inv_get i (Fact (_,invf)) = invf.(i) (* not tested yet *) *)\n let ncr n r (Fact (fact,invf)) = fact.(n) *% invf.(r) *% invf.(n-$r)\nend open ModCalc\nlet tp k = pow 2L k\nlet () =\n let n,q = get_2_i64 0 in\n let a =\n let s = scanf \" %s\"@@id in\n let a = make (String.length s) 0L in\n String.iteri (fun i c -> a.(i) <- i64 @@ (int_of_char c) -$ (int_of_char '0')) s;\n a in\n let ones = CumulSumArray.make a in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n let one = CumulSumArray.sum_1orig (i32 l) (i32 r) ones in\n let zero = r - l + 1L - one in\n let sum_one = tp one - 1L in\n let sum_zero = sum_one * (tp zero - 1L) in\n printf \"%Ld\\n\" (sum_one +% sum_zero)\n )\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nmodule CumulSumArray = struct\n let make a =\n let ln = Array.length a\n in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n let sum l r a = (* 0-origin,closed *)\n if l>r then 0L else (a.(r+$1) - a.(l))\n let sum_1orig l r a = sum (l-$1) (r-$1) a\nend\n\nlet md = 1000000007L\nlet pow n k =\n let rec f a n = function\n | 0L -> a\n | 1L -> (n*a) mod md\n | k when k mod 2L = 0L -> f a (n*n) (k/2L) mod md\n | k -> f (a*n) (n*n) (k/2L) mod md\n in f 1L n k\n\nlet () =\n let n,q = get_2_i64 0 in\n let a =\n let s = scanf \" %s\"@@id in\n let a = make (String.length s) 0L in\n String.iteri (fun i c -> a.(i) <- i64 @@ (int_of_char c) -$ (int_of_char '0')) s;\n a in\n let ones = CumulSumArray.make a in\n rep 1L q (fun _ ->\n let l,r = get_2_i64 0 in\n let one = CumulSumArray.sum_1orig (i32 l) (i32 r) ones in\n let zero = r - l + 1L - one in\n let sum_one = pow 2L one - 1L in\n let sum_zero = sum_one * (pow 2L zero - 1L) in\n printf \"%Ld\\n\" @@ (sum_one + sum_zero) mod md\n )\n\n\n\n\n\n\n\n\n"}], "src_uid": "88961744a28d7c890264a39a0a798708"} {"nl": {"description": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. \"Piece of cake\" \u2014 thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body (\u2009-\u2009100\u2009\u2264\u2009xi,\u2009yi,\u2009zi\u2009\u2264\u2009100).", "output_spec": "Print the word \"YES\" if the body is in equilibrium, or the word \"NO\" if it is not.", "sample_inputs": ["3\n4 1 7\n-2 4 -1\n1 -5 -3", "3\n3 -1 7\n-5 2 -4\n2 -1 -3"], "sample_outputs": ["NO", "YES"], "notes": null}, "positive_code": [{"source_code": "let list_init n f =\n let rec read_vectors n vectors = \n if n > 0\n then\n let coordinates = f() in\n read_vectors (n - 1) (coordinates :: vectors)\n else\n List.rev vectors\n in read_vectors n []\n\nlet vectors n = list_init n (fun i -> Scanf.scanf \"%d %d %d \" (fun s0 s1 s2 -> [s0; s1; s2]))\n\nlet input () = \n let number_of_vectors = Scanf.scanf \"%d \" (fun n -> n) in\n vectors number_of_vectors\n\nlet add_vectors [x; y; z] [xs; ys; zs] = [x + xs; y + ys; z + zs]\n\nlet get_sum list = List.fold_left(fun a b -> add_vectors a b) [0; 0; 0] list\n\nlet solve input = \n if get_sum input = [0; 0; 0]\n then\n \"YES\"\n else\n \"NO\"\n\nlet print result = Printf.printf \"%s\\n\" result\n\nlet () = print (solve (input()))"}, {"source_code": "let sum_vec (x1,y1,z1) (x2,y2,z2) =\n\t(x1+x2, y1+y2, z1+z2)\n;;\n\nlet read_vec _ = Scanf.scanf \"%d %d %d\\n\" (fun x y z -> (x,y,z));;\n\nlet () =\n\tlet n = read_int () in\n\tlet forces = Array.init n read_vec in\n\tlet f = Array.fold_left sum_vec (0,0,0) forces in\n\t\tprint_string (if f = (0,0,0) then \"YES\" else \"NO\")\n;;\n"}, {"source_code": "let solve n =\n let rec loop n x y z =\n if n <= 0\n then\n if x == 0 && y == 0 && z == 0\n then \"YES\"\n else \"NO\"\n else Scanf.scanf \"%d %d %d\\n\" (fun a b c -> loop (n-1) (x+a) (y+b) (z+c))\n in\n loop n 0 0 0\n\nlet _ =\n Printf.printf \"%s\\n\" (Scanf.scanf \"%d\\n\" solve)\n \n"}, {"source_code": "\n(* Codeforces 69A *)\n\ntype coordinate = { x: int; y: int; z: int }\n\nlet zero = { x = 0; y = 0; z = 0 }\n \nlet make_coordinate x y z = { x = x; y = y; z = z }\n\nlet add a b =\n { x = a.x + b.x; y = a.y + b.y; z = a.z + b.z }\n\nlet rec solve accu = function\n | 0 -> if accu = zero then \"YES\" else \"NO\"\n | n ->\n let c =\n Scanf.scanf \"%d %d %d\\n\" (fun x y z -> make_coordinate x y z) in\n solve (add accu c) (n-1)\n\nlet _ =\n let n = read_int() in\n print_endline (solve zero n)\n\n \n\n \n"}], "negative_code": [], "src_uid": "8ea24f3339b2ec67a769243dc68a47b2"} {"nl": {"description": "A sequence a0,\u2009a1,\u2009...,\u2009at\u2009-\u20091 is called increasing if ai\u2009-\u20091\u2009<\u2009ai for each i:\u20090\u2009<\u2009i\u2009<\u2009t.You are given a sequence b0,\u2009b1,\u2009...,\u2009bn\u2009-\u20091 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing?", "input_spec": "The first line of the input contains two integer numbers n and d (2\u2009\u2264\u2009n\u2009\u2264\u20092000,\u20091\u2009\u2264\u2009d\u2009\u2264\u2009106). The second line contains space separated sequence b0,\u2009b1,\u2009...,\u2009bn\u2009-\u20091 (1\u2009\u2264\u2009bi\u2009\u2264\u2009106).", "output_spec": "Output the minimal number of moves needed to make the sequence increasing.", "sample_inputs": ["4 2\n1 3 3 2"], "sample_outputs": ["3"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\nlet (|>) x f = f x\n\nopen Int64\n\nlet () =\n let n = read_int 0 in\n let d = read_int64 0 in\n let a = Array.init n read_int64 in\n let rec go i l c =\n if i >= n then\n c\n else\n let t = div (sub (add l d) a.(i)) d |> max 0L in\n go (i+1) (add a.(i) (mul d t)) (add c t)\n in\n go 1 a.(0) 0L |> Printf.printf \"%Ld\\n\"\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let x = read_int 0 in\n let rec go x i =\n if x > 0 || (x land 1) <> 0 then\n go (x-i) (i+1)\n else\n i-1\n in\n go (abs x) 1 |> Printf.printf \"%d\\n\"\n"}], "src_uid": "0c5ae761b046c021a25b706644f0d3cd"} {"nl": {"description": "Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1\u2009\u2264\u2009i\u2009\u2264\u2009n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.", "input_spec": "The first line contains two space-separated integers s and n (1\u2009\u2264\u2009s\u2009\u2264\u2009104, 1\u2009\u2264\u2009n\u2009\u2264\u2009103). Then n lines follow: the i-th line contains space-separated integers xi and yi (1\u2009\u2264\u2009xi\u2009\u2264\u2009104, 0\u2009\u2264\u2009yi\u2009\u2264\u2009104) \u2014 the i-th dragon's strength and the bonus for defeating it.", "output_spec": "On a single line print \"YES\" (without the quotes), if Kirito can move on to the next level and print \"NO\" (without the quotes), if he can't.", "sample_inputs": ["2 2\n1 99\n100 0", "10 1\n100 100"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2\u2009+\u200999\u2009=\u2009101. Now he can defeat the second dragon and move on to the next level.In the second sample Kirito's strength is too small to defeat the only dragon and win."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d %d \" (fun n m -> (n, m)) \n\nlet input () = \n let (hero_power, total) = read () in\n let rec loop dragons i =\n if i < total\n then\n let dragon = read () in\n loop (dragon :: dragons) (i + 1)\n else\n (hero_power, dragons)\n in loop [] 0\n\nlet fight hero_power (dragon_power, reward) =\n if hero_power > dragon_power\n then\n `victory (hero_power + reward)\n else\n `defeat\n\nlet tuple_compare (power_1, reward_1) (power_2, reward_2) =\n Pervasives.compare power_1 power_2\n\nlet solve (hero_power, dragons) =\n let dragons = List.sort (tuple_compare) dragons in \n let rec loop power list =\n match list with\n | (dragon :: tail) -> \n (match fight power dragon with\n | `victory (upd_power) -> loop upd_power tail\n | `defeat -> \"NO\")\n | [] -> \"YES\"\n in loop hero_power dragons\n\nlet print result = Printf.printf \"%s\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "let main = \n let (s,n) = Scanf.scanf \"%d %d\" (fun s n -> (s,n)) in\n let rec read_all acc n =\n if n = 0 then acc\n else Scanf.scanf \" %d %d\" (fun x y -> read_all ((x,y)::acc) (n-1)) in\n let dragons = read_all [] n in\n let sorted = List.sort compare dragons in\n let rec walk s dragons = \n match dragons with \n | [] -> \"YES\"\n | ((x,y) :: t) -> \n\tif s > x then walk (s+y) t\n else \"NO\" in\n Printf.printf \"%s\\n\" (walk s sorted)\n"}], "negative_code": [{"source_code": "let main = \n let (s,n) = Scanf.scanf \"%d %d\" (fun s n -> (s,n)) in\n let rec read_all acc n =\n if n = 0 then acc\n else Scanf.scanf \" %d %d\" (fun x y -> read_all ((x,y)::acc) (n-1)) in\n let dragons = read_all [] n in\n let pcompare (_,y1) (_,y2) = - (compare y1 y2) in\n let sorted = List.sort pcompare dragons in\n let rec walk s dragons = \n match dragons with \n | [] -> \"YES\"\n | ((x,y) :: t) -> \n\tif s > x then walk (s+y) t\n else \"NO\" in\n Printf.printf \"%s\\n\" (walk s sorted)\n"}], "src_uid": "98f5b6aac08f48f95b2a8ce0738de657"} {"nl": {"description": "The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to choose the best point of observation, that is to say the point from where all the three stadiums can be observed. As all the sport competitions are of the same importance, the stadiums should be observed at the same angle. If the number of points meeting the conditions is more than one, the point with the maximum angle of observation is prefered. Would you, please, help the famous Berland commentator G. Berniev to find the best point of observation. It should be noted, that the stadiums do not hide each other, the commentator can easily see one stadium through the other.", "input_spec": "The input data consists of three lines, each of them describes the position of one stadium. The lines have the format x,\u2009\u2009y,\u2009\u2009r, where (x,\u2009y) are the coordinates of the stadium's center (\u2009-\u2009\u2009103\u2009\u2264\u2009x,\u2009\u2009y\u2009\u2264\u2009103), and r (1\u2009\u2264\u2009r\u2009\u2009\u2264\u2009103) is its radius. All the numbers in the input data are integer, stadiums do not have common points, and their centers are not on the same line. ", "output_spec": "Print the coordinates of the required point with five digits after the decimal point. If there is no answer meeting the conditions, the program shouldn't print anything. The output data should be left blank.", "sample_inputs": ["0 0 10\n60 0 10\n30 30 10"], "sample_outputs": ["30.00000 0.00000"], "notes": null}, "positive_code": [{"source_code": "let (|>) x f = f x\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f \" (fun x -> x)\n\nlet eps = 1e-6\n\ntype point = float*float\ntype circle = point*float\nlet getx ((x,_),_) = x\nlet gety ((_,y),_) = y\nlet getr ((_,_),r) = r\nlet mid (ax,ay) (bx,by) = (ax+.bx)*.0.5, (ay+.by)*.0.5\nlet det (ax,ay) (bx,by) = ax*.by-.ay*.bx\nlet dot (ax,ay) (bx,by) = ax*.bx+.ay*.by\nlet add (ax,ay) (bx,by) = ax+.bx, ay+.by\nlet sub (ax,ay) (bx,by) = ax-.bx, ay-.by\nlet mul w (x,y) = x*.w, y*.w\nlet div (x,y) w = x/.w, y/.w\nlet ortho (x,y) = y, -.x\nlet diff (ax,ay) (bx,by) = bx-.ax, by-.ay\nlet len x = dot x x |> sqrt\nlet dist a b = diff a b |> len\n\nlet read_circle _ =\n let x = read_float 0 in\n let y = read_float 0 in\n let r = read_float 0 in\n (x,y),r\n\nlet eq cs u v = abs_float (getr cs.(u)-.getr cs.(v)) < eps\n\nlet circumcenter a b c : point =\n let p1x,p1y as p1 = mid a c\n and p2 = mid b c in\n let d1x,d1y as d1 = ortho (diff a c)\n and d2 = ortho (diff b c) in\n let ratio = det (diff p1 p2) d2 /. det d1 d2 in\n p1x+.ratio*.d1x, p1y+.ratio*.d1y\n\n(* circle where dist(X,O1)/r1 = dist(X,O2)/r2 *)\nlet solve (p1,r1 as c1) (p2,r2 as c2) : circle =\n let ans1 = div (add (mul r2 p1) (mul r1 p2)) (r1+.r2)\n and ans2 = div (add (mul r2 p1) (mul (-.r1) p2)) (r2-.r1) in\n (div (add ans1 ans2) 2.0), dist ans1 ans2 /. 2.0\n\nlet intersect c0 (p1,r1) (p2,r2) : unit =\n let dcntr = dist p1 p2 in\n if r1+.r2 >= dcntr && abs_float (r1-.r2) <= dcntr then\n let proj1 = (r1*.r1-.r2*.r2+.dcntr*.dcntr)/.(2.0*.dcntr) in\n let h = sqrt (r1*.r1-.proj1*.proj1) in\n let p = add p1 (mul (proj1/.dcntr) (diff p1 p2)) in\n let dlt = mul (h/.dcntr) (ortho (diff p1 p2)) in\n let ans1 = add p dlt\n and ans2 = sub p dlt in\n if dist ans1 c0 < dist ans2 c0 then\n Printf.printf \"%.5f %.5f\\n\" (fst ans1) (snd ans1)\n else\n Printf.printf \"%.5f %.5f\\n\" (fst ans2) (snd ans2)\n\nlet () =\n let cs = Array.init 3 read_circle in\n if eq cs 0 1 && eq cs 1 2 then\n let x,y = circumcenter (fst cs.(0)) (fst cs.(1)) (fst cs.(2))\n in Printf.printf \"%.5f %.5f\\n\" x y\n else (\n (* radii are not all the same *)\n for i = 0 to 1 do\n if eq cs i 2 then (\n let t = cs.(i lxor 1) in\n cs.(i lxor 1) <- cs.(2);\n cs.(2) <- t\n )\n done;\n (* thereafter cs = x,x,y or x,y,z *)\n intersect (fst cs.(0)) (solve cs.(0) cs.(2)) (solve cs.(1) cs.(2))\n )\n"}], "negative_code": [{"source_code": "let (|>) x f = f x\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_float _ = Scanf.bscanf Scanf.Scanning.stdib \" %f \" (fun x -> x)\n\nlet eps = 1e-6\n\ntype point = float*float\ntype circle = point*float\nlet getx ((x,_),_) = x\nlet gety ((_,y),_) = y\nlet getr ((_,_),r) = r\nlet mid (ax,ay) (bx,by) = (ax+.bx)*.0.5, (ay+.by)*.0.5\nlet det (ax,ay) (bx,by) = ax*.by-.ay*.bx\nlet dot (ax,ay) (bx,by) = ax*.bx+.ay*.by\nlet add (ax,ay) (bx,by) = ax+.bx, ay+.by\nlet sub (ax,ay) (bx,by) = ax-.bx, ay-.by\nlet mul w (x,y) = x*.w, y*.w\nlet div (x,y) w = x/.w, y/.w\nlet ortho (x,y) = y, -.x\nlet diff (ax,ay) (bx,by) = bx-.ax, by-.ay\nlet len x = dot x x |> sqrt\nlet dist a b = diff a b |> len\n\nlet read_circle _ =\n let x = read_float 0 in\n let y = read_float 0 in\n let r = read_float 0 in\n (x,y),r\n\nlet eq cs u v = abs_float (getr cs.(u)-.getr cs.(v)) < eps\n\nlet circumcenter a b c : point =\n let p1x,p1y as p1 = mid a c\n and p2 = mid b c in\n let d1x,d1y as d1 = ortho (diff a c)\n and d2 = ortho (diff b c) in\n let ratio = det (diff p1 p2) d2 /. det d1 d2 in\n p1x+.ratio*.d1x, p1y+.ratio*.d1y\n\n(* circle where dist(X,O1)/r1 = dist(X,O2)/r2 *)\nlet solve (p1,r1 as c1) (p2,r2 as c2) : circle =\n let ans1 = div (add (mul r2 p1) (mul r1 p2)) (r1+.r2)\n and ans2 = div (add (mul r2 p1) (mul (-.r1) p2)) (r2-.r1) in\n (div (add ans1 ans2) 2.0), dist ans1 ans2 /. 2.0\n\nlet intersect c0 (p1,r1) (p2,r2) : unit =\n let dcntr = dist p1 p2 in\n if r1+.r2 >= dcntr then\n let proj1 = (r1*.r1-.r2*.r2+.dcntr*.dcntr)/.(2.0*.dcntr) in\n let h = sqrt (r1*.r1-.proj1*.proj1) in\n let p = add p1 (mul (proj1/.dcntr) (diff p1 p2)) in\n let dlt = mul (h/.dcntr) (ortho (diff p1 p2)) in\n let ans1 = add p dlt\n and ans2 = sub p dlt in\n if dist ans1 c0 < dist ans2 c0 then\n Printf.printf \"%.5f %.5f\\n\" (fst ans1) (snd ans1)\n else\n Printf.printf \"%.5f %.5f\\n\" (fst ans2) (snd ans2)\n\nlet () =\n let cs = Array.init 3 read_circle in\n if eq cs 0 1 && eq cs 1 2 then\n let x,y = circumcenter (fst cs.(0)) (fst cs.(1)) (fst cs.(2))\n in Printf.printf \"%.5f %.5f\\n\" x y\n else (\n (* radii are not all the same *)\n for i = 0 to 1 do\n if eq cs i 2 then (\n let t = cs.(i lxor 1) in\n cs.(i lxor 1) <- cs.(2);\n cs.(2) <- t\n )\n done;\n (* thereafter cs = x,x,y or x,y,z *)\n intersect (fst cs.(0)) (solve cs.(0) cs.(2)) (solve cs.(1) cs.(2))\n )\n"}], "src_uid": "9829e1913e64072aadc9df5cddb63573"} {"nl": {"description": "Filled with optimism, Hyunuk will host a conference about how great this new year will be!The conference will have $$$n$$$ lectures. Hyunuk has two candidate venues $$$a$$$ and $$$b$$$. For each of the $$$n$$$ lectures, the speaker specified two time intervals $$$[sa_i, ea_i]$$$ ($$$sa_i \\le ea_i$$$) and $$$[sb_i, eb_i]$$$ ($$$sb_i \\le eb_i$$$). If the conference is situated in venue $$$a$$$, the lecture will be held from $$$sa_i$$$ to $$$ea_i$$$, and if the conference is situated in venue $$$b$$$, the lecture will be held from $$$sb_i$$$ to $$$eb_i$$$. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval $$$[x, y]$$$ overlaps with a lecture held in interval $$$[u, v]$$$ if and only if $$$\\max(x, u) \\le \\min(y, v)$$$.We say that a participant can attend a subset $$$s$$$ of the lectures if the lectures in $$$s$$$ do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue $$$a$$$ or venue $$$b$$$ to hold the conference.A subset of lectures $$$s$$$ is said to be venue-sensitive if, for one of the venues, the participant can attend $$$s$$$, but for the other venue, the participant cannot attend $$$s$$$.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in $$$s$$$ because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$), the number of lectures held in the conference. Each of the next $$$n$$$ lines contains four integers $$$sa_i$$$, $$$ea_i$$$, $$$sb_i$$$, $$$eb_i$$$ ($$$1 \\le sa_i, ea_i, sb_i, eb_i \\le 10^9$$$, $$$sa_i \\le ea_i, sb_i \\le eb_i$$$).", "output_spec": "Print \"YES\" if Hyunuk will be happy. Print \"NO\" otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["2\n1 2 3 6\n3 4 7 8", "3\n1 3 2 4\n4 5 6 7\n3 4 5 5", "6\n1 5 2 9\n2 4 5 8\n3 6 7 11\n7 10 12 16\n8 11 13 17\n9 12 14 18"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteIn second example, lecture set $$$\\{1, 3\\}$$$ is venue-sensitive. Because participant can't attend this lectures in venue $$$a$$$, but can attend in venue $$$b$$$.In first and third example, venue-sensitive set does not exist."}, "positive_code": [{"source_code": "module Int = struct\n type t = int\n\n let compare (a:t)(b:t) = compare a b\nend\nmodule IntSet = Set.Make(Int)\nmodule StringSet = Set.Make(String)\n\nmodule IntSetWithHash : sig\n type t\n\n val create : unit->t\n val add : int -> t -> unit\n val remove : int -> t -> unit\n\n val hash : t -> string\nend = struct\n type t =\n { set : (int, unit) Hashtbl.t\n ; mutable hash : string\n }\n\n let hash t = t.hash\n\n let create () = { set = Hashtbl.create 100000 ; hash = \"0123456789abcdef\" }\n\n let xorhash cur_hash x =\n let new_hash =\n Digest.string (string_of_int x)\n in\n String.mapi (fun i ch ->\n Char.chr ((Char.code ch) lxor (Char.code new_hash.[i])))\n cur_hash\n\n let add x t =\n if Hashtbl.mem t.set x then () else (\n Hashtbl.add t.set x ();\n t.hash <- xorhash t.hash x;\n )\n\n let remove x t =\n if not (Hashtbl.mem t.set x ) then () else (\n Hashtbl.remove t.set x ;\n t.hash <- xorhash t.hash x\n )\nend\n\n(* let sexp_of_int = Core_kernel.sexp_of_int\n * let sexp_of_list = Core_kernel.sexp_of_list *)\ntype event =\n | Start of int\n | End of int\n(* [@@deriving sexp_of] *)\n\nlet () =\n let n = read_int () in\n let events1 = Array.create (2*n) (0,Start 0) in\n let events2 = Array.create (2*n) (0,Start 0) in\n for i = 0 to n-1 do\n Scanf.scanf \" %d %d %d %d\" (fun s1 e1 s2 e2 ->\n events1.(2*i+0) <- (s1, Start i);\n events1.(2*i+1) <- (e1, End i);\n events2.(2*i+0) <- (s2, Start i);\n events2.(2*i+1) <- (e2, End i));\n done;\n Printf.eprintf \"done\\n%!\";\n let process xs =\n Array.sort (fun (ts1, ev1) (ts2, ev2) ->\n (* need start to appear before end *)\n match compare ts1 ts2 with\n | 0 ->\n (match ev1, ev2 with\n | Start _, End _ -> -1\n | End _, Start _ -> 1\n | _ -> 0)\n | c -> c)\n xs;\n (* Printf.printf !\"%{sexp: event list}\\n\" evs; *)\n let maxs = ref StringSet.empty in\n let cur = IntSetWithHash.create () in\n let should_be_false =\n Array.fold_left (fun (is_interesting) (_, ev) ->\n match ev with\n | Start x -> (IntSetWithHash.add x cur; true)\n | End x ->\n if is_interesting then (\n (* Printf.eprintf \"> %d\\n%!\" (IntSet.cardinal cur); *)\n maxs := StringSet.add (IntSetWithHash.hash cur) !maxs;\n );\n (IntSetWithHash.remove x cur; false)\n ) ( false)\n xs\n in\n assert (false = should_be_false);\n (* IntSetSet.iter (fun s -> Printf.printf !\"%{sexp: int list}\" (s |> IntSet.to_seq |> List.of_seq)) !maxs; *)\n (* print_newline (); *)\n !maxs\n in\n let maxs1 = process events1 in\n Printf.eprintf \"done1\\n%!\";\n let maxs2 = process events2 in\n Printf.eprintf \"done2\\n%!\";\n print_endline (if StringSet.equal maxs1 maxs2 then \"YES\" else \"NO\")\n;;\n"}], "negative_code": [], "src_uid": "036ecfcf11c3106732286765e7b7fcdd"} {"nl": {"description": "Alice and Bob received $$$n$$$ candies from their parents. Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.Check if they can do that.Note that candies are not allowed to be cut in half.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the number of candies that Alice and Bob received. The next line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$\u00a0\u2014 the weights of the candies. The weight of each candy is either $$$1$$$ or $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, output on a separate line: \"YES\", if all candies can be divided into two sets with the same weight; \"NO\" otherwise. You can output \"YES\" and \"NO\" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).", "sample_inputs": ["5\n2\n1 1\n2\n1 2\n4\n1 2 1 2\n3\n2 2 2\n3\n2 1 2"], "sample_outputs": ["YES\nNO\nYES\nNO\nNO"], "notes": "NoteIn the first test case, Alice and Bob can each take one candy, then both will have a total weight of $$$1$$$.In the second test case, any division will be unfair.In the third test case, both Alice and Bob can take two candies, one of weight $$$1$$$ and one of weight $$$2$$$.In the fourth test case, it is impossible to divide three identical candies between two people.In the fifth test case, any division will also be unfair."}, "positive_code": [{"source_code": "(* #load \"str.cma\" *)\r\nmodule Stdlib = Pervasives;;\r\n(* let std_inp = Stdlib.open_in \"input.txt\";; *)\r\nlet std_inp = Stdlib.stdin;;\r\nlet std_outp = Stdlib.stdout;;\r\n\r\nlet identity x = x;;\r\n\r\nlet recogn (ones, twos) item =\r\n if item == 1 then (ones + 1, twos)\r\n else (ones, twos + 1);;\r\n\r\nlet rec solve (ones, twos) n =\r\nif n > twos / 2 then false\r\nelse\r\n let ones_debt = (twos - n * 2) * 2 in\r\n (* let _ = Printf.printf \"Debt: %d\\n\" ones_debt in *)\r\n if ones >= ones_debt && (ones - ones_debt) mod 2 == 0 then true\r\n else solve (ones, twos) (n + 1);;\r\n\r\nlet solution inp outp =\r\n let _ = input_line inp in\r\n let (ones, twos)=\r\n input_line inp\r\n |> Str.split @@ Str.regexp \" \"\r\n |> List.map int_of_string\r\n |> List.fold_left recogn (0, 0)\r\n in\r\n (* let _ = Printf.printf \"Ones: %d; Twos: %d\\n\" ones twos in *)\r\n let result = solve (ones, twos) 0 in\r\n let _ =\r\n if result then Printf.printf \"YES\\n\"\r\n else Printf.printf \"NO\\n\"\r\n in\r\n ();;\r\n\r\nlet rec run_test = function\r\n| (0, _, _) -> ()\r\n| (t, inp, outp) ->\r\n let _ = solution inp outp in\r\n run_test (t - 1, inp, outp);;\r\n\r\nlet (_:unit) =\r\n let inp = std_inp and outp = std_outp in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let _ = run_test (tests_count, inp, outp) in\r\n ();;"}, {"source_code": "(** https://codeforces.com/contest/1472/problem/B *)\n\nlet get_candies () =\n let tbl = Array.make 2 0 in\n let candy_list =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n List.iter\n (fun candy -> tbl.(candy-1) <- tbl.(candy-1) + 1)\n candy_list;\n tbl\n\nlet fair_share tbl_candies =\n if tbl_candies.(1) mod 2 = 0\n then tbl_candies.(0) mod 2 = 0\n else tbl_candies.(0) - 2 >= 0 && (tbl_candies.(0) - 2) mod 2 = 0\n\nlet solve_n nb_cases =\n let rec helper i =\n if i > 0\n then (\n let _ = read_line () in\n let tbl_candies = get_candies () in\n (if fair_share tbl_candies then \"YES\" else \"NO\")\n |> print_endline;\n helper (i-1)\n ) in\n helper nb_cases\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "negative_code": [{"source_code": "(* #load \"str.cma\" *)\r\nmodule Stdlib = Pervasives;;\r\n(* let std_inp = Stdlib.open_in \"input.txt\";; *)\r\nlet std_inp = Stdlib.stdin;;\r\nlet std_outp = Stdlib.stdout;;\r\n\r\nlet identity x = x;;\r\n\r\nlet recogn (ones, twos) item =\r\n if item == 1 then (ones + 1, twos)\r\n else (ones, twos + 1);;\r\n\r\nlet rec solve (ones, twos) n =\r\nif n > twos then false\r\nelse\r\n let ones_debt = (twos - n) * 2 in\r\n (* let _ = Printf.printf \"Debt: %d\\n\" ones_debt in *)\r\n if ones > ones_debt && (ones - ones_debt) mod 2 == 0 then true\r\n else solve (ones, twos) (n + 1);;\r\n\r\nlet solution inp outp =\r\n let _ = input_line inp in\r\n let (ones, twos)=\r\n input_line inp\r\n |> Str.split @@ Str.regexp \" \"\r\n |> List.map int_of_string\r\n |> List.fold_left recogn (0, 0)\r\n in\r\n (* let _ = Printf.printf \"Ones: %d; Twos: %d\\n\" ones twos in *)\r\n let result = solve (ones, twos) 0 in\r\n let _ =\r\n if result then Printf.printf \"YES\\n\"\r\n else Printf.printf \"NO\\n\"\r\n in\r\n ();;\r\n\r\nlet rec run_test = function\r\n| (0, _, _) -> ()\r\n| (t, inp, outp) ->\r\n let _ = solution inp outp in\r\n run_test (t - 1, inp, outp);;\r\n\r\nlet (_:unit) =\r\n let inp = std_inp and outp = std_outp in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let _ = run_test (tests_count, inp, outp) in\r\n ();;"}], "src_uid": "1d9d34dca11a787d6e2345494680e717"} {"nl": {"description": "Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.", "input_spec": "The first line contains three integers m, t, r (1\u2009\u2264\u2009m,\u2009t,\u2009r\u2009\u2264\u2009300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit. The next line contains m space-separated numbers wi (1\u2009\u2264\u2009i\u2009\u2264\u2009m, 1\u2009\u2264\u2009wi\u2009\u2264\u2009300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.", "output_spec": "If it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that. If that is impossible, print \u2009-\u20091.", "sample_inputs": ["1 8 3\n10", "2 10 1\n5 8", "1 1 3\n10"], "sample_outputs": ["3", "1", "-1"], "notes": "NoteAnya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.In the third sample test the answer is \u2009-\u20091, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes."}, "positive_code": [{"source_code": "(* 0 = rien; 1= fantome ; 2 = bougie finie de brul\u00e9e ; bougie et fantome *)\n\nlet f tab dure besoin =\n\tlet bug = ref false in\n\tfor i= 600 downto 300 do\n\t\tif (tab.(i) = 1) || (tab.(i) = 3)\n\t\t\tthen begin\n\t\t\t\tlet compte = ref 0 in\n\t\t\t\tfor j= i - dure + 1 to i do\n\t\t\t\t\tif tab.(j) > 1\n\t\t\t\t\t\tthen incr compte\n\t\t\t\t\t\n\t\t\t\tdone;\n\t\t\t\tlet manque = ref (besoin - !compte) in\n\t\t\t\tfor j = i - dure + 1 to i do\n\t\t\t\t\tif (!manque > 0) && (tab.(j) < 2)\n\t\t\t\t\t\tthen (decr manque; tab.(j) <- tab.(j) + 2);\n\t\t\t\tdone;\n\t\t\t\tif !manque > 0 then bug := true;\n\t\t\t end\n\tdone;\n\tif !bug\n\t\tthen -1\n\t\telse (let compte = ref 0 in\n\t\t\tfor i = 0 to Array.length tab - 1 do\n\t\t\t\tif tab.(i) > 1 then incr compte;\n\t\t\tdone; !compte);;\nlet final () =\n\tlet (m,t,r) = Scanf.scanf \"%d %d %d \" (fun i j k -> (i,j,k)) in\n\tlet tab = Array.make 601 0 in\n\tfor i=1 to m do\n\t\ttab.(300 + Scanf.scanf \"%d \" (fun i -> i)) <- 1;\n\tdone;\n\tPrintf.printf \"%d \" (f tab t r);;\n\nfinal ();;\n"}, {"source_code": "exception Not_possible\nlet () =\n Scanf.scanf \"%d %d %d\\n\" (fun m t r ->\n (* array of ghost times *)\n let g = Array.init m (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n (* queue of candles *)\n let q = Queue.create () in\n (* number of candles *)\n let c = ref r in\n (* maximum timeslot at which a candle was lit *)\n let m = ref (g.(0) - 1) in\n (* light r candles before the first ghost *)\n for i = g.(0) - r to g.(0) - 1 do\n Queue.add i q\n done;\n try\n Array.iter (fun w ->\n (* remove stale candles *)\n while not (Queue.is_empty q) && Queue.peek q + t < w do\n ignore (Queue.take q)\n done;\n let l = Queue.length q in\n (* add more candles if necessary *)\n for i = w - r + l to w - 1 do\n if i <= !m then\n raise Not_possible\n else begin\n Queue.add i q;\n incr c;\n m := i\n end\n done\n ) g;\n Printf.printf \"%d\\n\" !c\n with Not_possible -> print_endline \"-1\"\n )\n"}], "negative_code": [{"source_code": "(* 0 = rien; 1= fantome ; 2 = bougie finie de pos\u00e9e ; bougie et fantome *)\n\nlet f tab dure besoin =\n\tlet bug = ref false in\n\tfor i= 820 downto 400 do\n\t\tif tab.(i) mod 3 = 1\n\t\t\tthen begin\n\t\t\t\tlet compte = ref 0 in\n\t\t\t\t\tfor j= i - dure + 1 to i do\n\t\t\t\t\t\tif tab.(j) > 1\n\t\t\t\t\t\t\tthen incr compte\n\t\t\t\t\tdone;\n\t\t\t\tlet manque = ref (besoin - !compte) in\n\t\t\t\tfor j = i - dure + 1 to i do\n\t\t\t\t\tif (!manque > 0) && (tab.(j) < 2)\n\t\t\t\t\t\tthen (decr manque; tab.(j) <- tab.(j) + 2);\n\t\t\t\tdone;\n\t\t\t\tif !manque > 0 then bug := true;\n\t\t\t end\n\tdone;\n\tif !bug\n\t\tthen -1\n\t\telse (let compte = ref 0 in\n\t\t\tfor i = 0 to Array.length tab - 1 do\n\t\t\t\tif tab.(i) > 1 then incr compte;\n\t\t\tdone; !compte);;\nlet final () =\n\tlet (m,t,r) = Scanf.scanf \"%d %d %d \" (fun i j k -> (i,j,k)) in\n\tlet tab = Array.make 821 0 in\n\tfor i=1 to m do\n\t\ttab.(400 + Scanf.scanf \"%d \" (fun i -> i)) <- 1;\n\tdone;\n\tPrintf.printf \"%d \" (f tab t r);;\n\t\nfinal ();;\n"}, {"source_code": "(* 0 = rien; 1= fantome ; 2 = bougie finie de pos\u00e9e ; bougie et fantome *)\n\nlet f tab dure besoin =\n\tlet bug = ref false in\n\tfor i= 620 downto 300 do\n\t\tif tab.(i) mod 3 = 1\n\t\t\tthen begin\n\t\t\t\tlet compte = ref 0 in\n\t\t\t\t\tfor j= i - dure + 1 to i do\n\t\t\t\t\t\tif tab.(j) > 1\n\t\t\t\t\t\t\tthen incr compte\n\t\t\t\t\tdone;\n\t\t\t\tlet manque = ref (besoin - !compte) in\n\t\t\t\tfor j = i - dure + 1 to i do\n\t\t\t\t\tif (!manque > 0) && (tab.(j) < 2)\n\t\t\t\t\t\tthen (decr manque; tab.(j) <- tab.(j) + 2);\n\t\t\t\tdone;\n\t\t\t\tif !manque > 0 then bug := true;\n\t\t\t end\n\tdone;\n\tif !bug\n\t\tthen -1\n\t\telse (let compte = ref 0 in\n\t\t\tfor i = 0 to Array.length tab - 1 do\n\t\t\t\tif tab.(i) > 1 then incr compte;\n\t\t\tdone; !compte);;\nlet final () =\n\tlet (m,t,r) = Scanf.scanf \"%d %d %d \" (fun i j k -> (i,j,k)) in\n\tlet tab = Array.make 621 0 in\n\tfor i=1 to m do\n\t\ttab.(300 + Scanf.scanf \"%d \" (fun i -> i)) <- 1;\n\tdone;\n\tPrintf.printf \"%d \" (f tab t r);;\n\t\nfinal ();;\n"}, {"source_code": "(* 0 = rien; 1= fantome ; 2 = bougie finie de pos\u00e9e ; bougie et fantome *)\n\nlet f tab dure besoin =\n\tlet bug = ref false in\n\tfor i= 620 downto 300 do\n\t\tif tab.(i) mod 3 = 1\n\t\t\tthen begin\n\t\t\t\tlet compte = ref 0 in\n\t\t\t\t\tfor j= i - dure + 1 to i do\n\t\t\t\t\t\tif tab.(j) > 1\n\t\t\t\t\t\t\tthen incr compte\n\t\t\t\t\tdone;\n\t\t\t\tlet manque = ref (besoin - !compte) in\n\t\t\t\tfor j = i - dure + 1 to i do\n\t\t\t\t\tif (!manque > 0) && (tab.(j) < 2)\n\t\t\t\t\t\tthen (decr manque; tab.(j) <- tab.(j) + 2);\n\t\t\t\tdone;\n\t\t\t\tif !manque > 0 then bug := true;\n\t\t\t end\n\tdone;\n\tif !bug\n\t\tthen -1\n\t\telse (let compte = ref 0 in\n\t\t\tfor i = 0 to Array.length tab - 1 do\n\t\t\t\tif tab.(i) > 1 then incr compte;\n\t\t\tdone; !compte);;\nlet final () =\n\tlet (m,t,r) = Scanf.scanf \"%d %d %d \" (fun i j k -> (i,j,k)) in\n\tlet tab = Array.make 621 0 in\n\tfor i=1 to m do\n\t\ttab.(Scanf.scanf \"%d \" (fun i -> i)) <- 1;\n\tdone;\n\tPrintf.printf \"%d \" (f tab t r);;\n\t\nfinal ();;\n"}, {"source_code": "(* 0 = rien; 1= fantome ; 2 = bougie finie de pos\u00e9e ; bougie et fantome *)\n\nlet f tab dure besoin =\n\tlet bug = ref false in\n\tfor i= 820 downto 400 do\n\t\tif (tab.(i) = 1) || (tab.(i) = 3)\n\t\t\tthen begin\n\t\t\t\tlet compte = ref 0 in\n\t\t\t\tfor j= i - dure + 1 to i do\n\t\t\t\t\tif tab.(j) > 1\n\t\t\t\t\t\tthen incr compte\n\t\t\t\t\t\n\t\t\t\tdone;\n\t\t\t\tlet manque = ref (besoin - !compte) in\n\t\t\t\tfor j = i - dure to i do\n\t\t\t\t\tif (!manque > 0) && (tab.(j) < 2)\n\t\t\t\t\t\tthen (decr manque; tab.(j) <- tab.(j) + 2);\n\t\t\t\tdone;\n\t\t\t\tif !manque > 0 then bug := true;\n\t\t\t end\n\tdone;\n\tif !bug\n\t\tthen -1\n\t\telse (let compte = ref 0 in\n\t\t\tfor i = 0 to Array.length tab - 1 do\n\t\t\t\tif tab.(i) > 1 then incr compte;\n\t\t\tdone; !compte);;\nlet final () =\n\tlet (m,t,r) = Scanf.scanf \"%d %d %d \" (fun i j k -> (i,j,k)) in\n\tlet tab = Array.make 821 0 in\n\tfor i=1 to m do\n\t\ttab.(400 + Scanf.scanf \"%d \" (fun i -> i)) <- 1;\n\tdone;\n\tPrintf.printf \"%d \" (f tab t r);;\n(*\nfinal ();;\n*)\n\nlet test l dure besoin =\n\tlet tab = Array.make 821 0 in\n\t\tList.iter (fun i -> tab.(400 + i) <- 1) l;\n\t\tf tab dure besoin;;\n\n(test [10] 8 3 = 3,\ntest [5;8] 10 1 = 1,\ntest [10] 1 3 = -1);;\n"}, {"source_code": "(* 0 = rien; 1= fantome ; 2 = bougie finie de pos\u00e9e ; bougie et fantome *)\n\nlet f tab dure besoin =\n\tlet bug = ref false in\n\tfor i= 620 downto 300 do\n\t\tif tab.(i) mod 3 = 1\n\t\t\tthen begin\n\t\t\t\tlet compte = ref 0 in\n\t\t\t\t\tfor j= i - dure + 1 to i do\n\t\t\t\t\t\tif tab.(j) > 1\n\t\t\t\t\t\t\tthen incr compte\n\t\t\t\t\tdone;\n\t\t\t\tlet manque = ref (besoin - !compte) in\n\t\t\t\tfor j = i - dure + 1 to i do\n\t\t\t\t\tif (!manque > 0) && (tab.(j) < 3)\n\t\t\t\t\t\tthen (decr manque; tab.(j) <- tab.(j) + 2);\n\t\t\t\tdone;\n\t\t\t\tif !manque > 0 then bug := true;\n\t\t\t end\n\tdone;\n\tif !bug\n\t\tthen -1\n\t\telse (let compte = ref 0 in\n\t\t\tfor i = 0 to Array.length tab - 1 do\n\t\t\t\tif tab.(i) > 1 then incr compte;\n\t\t\tdone; !compte);;\nlet final () =\n\tlet (m,t,r) = Scanf.scanf \"%d %d %d \" (fun i j k -> (i,j,k)) in\n\tlet tab = Array.make 621 0 in\n\tfor i=1 to m do\n\t\ttab.(Scanf.scanf \"%d \" (fun i -> i)) <- 1;\n\tdone;\n\tPrintf.printf \"%d \" (f tab t r);;\n\t\nfinal ();;\n"}, {"source_code": "(* 0 = rien; 1= fantome ; 2 = bougie finie de brul\u00e9e ; bougie et fantome *)\n\nlet f tab dure besoin =\n\tlet bug = ref false in\n\tfor i= 600 downto 300 do\n\t\tif (tab.(i) = 1) || (tab.(i) = 3)\n\t\t\tthen begin\n\t\t\t\tlet compte = ref 0 in\n\t\t\t\tfor j= i - dure to i do\n\t\t\t\t\tif tab.(j) > 1\n\t\t\t\t\t\tthen incr compte\n\t\t\t\t\t\n\t\t\t\tdone;\n\t\t\t\tlet manque = ref (besoin - !compte) in\n\t\t\t\tfor j = i - dure to i do\n\t\t\t\t\tif (!manque > 0) && (tab.(j) < 2)\n\t\t\t\t\t\tthen (decr manque; tab.(j) <- tab.(j) + 2);\n\t\t\t\tdone;\n\t\t\t\tif !manque > 0 then bug := true;\n\t\t\t end\n\tdone;\n\tif !bug\n\t\tthen -1\n\t\telse (let compte = ref 0 in\n\t\t\tfor i = 0 to Array.length tab - 1 do\n\t\t\t\tif tab.(i) > 1 then incr compte;\n\t\t\tdone; !compte);;\nlet final () =\n\tlet (m,t,r) = Scanf.scanf \"%d %d %d \" (fun i j k -> (i,j,k)) in\n\tlet tab = Array.make 601 0 in\n\tfor i=1 to m do\n\t\ttab.(300 + Scanf.scanf \"%d \" (fun i -> i)) <- 1;\n\tdone;\n\tPrintf.printf \"%d \" (f tab t r);;\n\nfinal ();;\n"}, {"source_code": "exception Not_possible\nlet () =\n Scanf.scanf \"%d %d %d\\n\" (fun m t r ->\n (* array of ghost times *)\n let g = Array.init m (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n (* queue of candles *)\n let q = Queue.create () in\n (* number of candles *)\n let c = ref r in\n (* maximum timeslot at which a candle was lit *)\n let m = ref (g.(0) - 1) in\n (* light r candles before the first ghost *)\n for i = g.(0) - r - 1 to g.(0) - 1 do\n Queue.add i q\n done;\n try\n Array.iter (fun w ->\n (* remove stale candles *)\n while not (Queue.is_empty q) && Queue.peek q + t < w do\n ignore (Queue.take q)\n done;\n let l = Queue.length q in\n (* add more candles if necessary *)\n for i = w - r + l - 1 to w - 1 do\n if i <= !m then\n raise Not_possible\n else begin\n Queue.add i q;\n incr c;\n m := i\n end\n done\n ) g;\n Printf.printf \"%d\\n\" !c\n with Not_possible -> print_endline \"-1\"\n )\n"}], "src_uid": "03772bac6ed5bfe75bc0ad4d2eab56fd"} {"nl": {"description": "Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.", "input_spec": "The first line contains three integers n,\u2009m,\u2009k (2\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105;\u00a01\u2009\u2264\u2009k\u2009\u2264\u2009105). Each of the next m lines contains three integers ui,\u2009vi,\u2009xi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n;\u00a0ui\u2009\u2260\u2009vi;\u00a01\u2009\u2264\u2009xi\u2009\u2264\u2009109). Each of the next k lines contains two integers si and yi (2\u2009\u2264\u2009si\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009yi\u2009\u2264\u2009109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.", "output_spec": "Output a single integer representing the maximum number of the train routes which can be closed.", "sample_inputs": ["5 5 3\n1 2 1\n2 3 2\n1 3 3\n3 4 4\n1 5 5\n3 5\n4 5\n5 5", "2 2 3\n1 2 2\n2 1 3\n2 1\n2 2\n2 3"], "sample_outputs": ["2", "2"], "notes": null}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\n\nmodule PSet = struct\n type 'k set =\n | Empty\n | Node of 'k set * 'k * 'k set * int\n\n type 'k t =\n {\n cmp : 'k -> 'k -> int;\n set : 'k set;\n }\n\n let height = function\n | Node (_, _, _, h) -> h\n | Empty -> 0\n\n let make l k r = Node (l, k, r, max (height l) (height r) + 1)\n\n let bal l k r =\n let hl = height l in\n let hr = height r in\n if hl > hr + 2 then\n match l with\n | Node (ll, lk, lr, _) ->\n if height ll >= height lr then make ll lk (make lr k r)\n else\n (match lr with\n | Node (lrl, lrk, lrr, _) ->\n make (make ll lk lrl) lrk (make lrr k r)\n | Empty -> assert false)\n | Empty -> assert false\n else if hr > hl + 2 then\n match r with\n | Node (rl, rk, rr, _) ->\n if height rr >= height rl then make (make l k rl) rk rr\n else\n (match rl with\n | Node (rll, rlk, rlr, _) ->\n make (make l k rll) rlk (make rlr rk rr)\n | Empty -> assert false)\n | Empty -> assert false\n else Node (l, k, r, max hl hr + 1)\n\n let rec min_elt = function\n | Node (Empty, k, _, _) -> k\n | Node (l, _, _, _) -> min_elt l\n | Empty -> raise Not_found\n\n let rec remove_min_elt = function\n | Node (Empty, _, r, _) -> r\n | Node (l, k, r, _) -> bal (remove_min_elt l) k r\n | Empty -> invalid_arg \"PSet.remove_min_elt\"\n\n let merge t1 t2 =\n match t1, t2 with\n | Empty, _ -> t2\n | _, Empty -> t1\n | _ ->\n let k = min_elt t2 in\n bal t1 k (remove_min_elt t2)\n\n let create cmp = { cmp = cmp; set = Empty }\n let empty = { cmp = compare; set = Empty }\n\n let is_empty x = \n x.set = Empty\n\n let rec add_one cmp x = function\n | Node (l, k, r, h) ->\n let c = cmp x k in\n if c = 0 then Node (l, x, r, h)\n else if c < 0 then\n let nl = add_one cmp x l in\n bal nl k r\n else\n let nr = add_one cmp x r in\n bal l k nr\n | Empty -> Node (Empty, x, Empty, 1)\n\n let add x { cmp = cmp; set = set } =\n { cmp = cmp; set = add_one cmp x set }\n\n let rec join cmp l v r =\n match (l, r) with\n (Empty, _) -> add_one cmp v r\n | (_, Empty) -> add_one cmp v l\n | (Node(ll, lv, lr, lh), Node(rl, rv, rr, rh)) ->\n if lh > rh + 2 then bal ll lv (join cmp lr v r) else\n if rh > lh + 2 then bal (join cmp l v rl) rv rr else\n make l v r\n\n let split x { cmp = cmp; set = set } =\n let rec loop x = function\n Empty ->\n (Empty, false, Empty)\n | Node (l, v, r, _) ->\n let c = cmp x v in\n if c = 0 then (l, true, r)\n else if c < 0 then\n let (ll, pres, rl) = loop x l in (ll, pres, join cmp rl v r)\n else\n let (lr, pres, rr) = loop x r in (join cmp l v lr, pres, rr)\n in\n let setl, pres, setr = loop x set in\n { cmp = cmp; set = setl }, pres, { cmp = cmp; set = setr }\n\n let remove x { cmp = cmp; set = set } =\n let rec loop = function\n | Node (l, k, r, _) ->\n let c = cmp x k in\n if c = 0 then merge l r else\n if c < 0 then bal (loop l) k r else bal l k (loop r)\n | Empty -> Empty in\n { cmp = cmp; set = loop set }\n\n let mem x { cmp = cmp; set = set } =\n let rec loop = function\n | Node (l, k, r, _) ->\n let c = cmp x k in\n c = 0 || loop (if c < 0 then l else r)\n | Empty -> false in\n loop set\n\n let exists = mem\n\n let iter f { set = set } =\n let rec loop = function\n | Empty -> ()\n | Node (l, k, r, _) -> loop l; f k; loop r in\n loop set\n\n let fold f { cmp = cmp; set = set } acc =\n let rec loop acc = function\n | Empty -> acc\n | Node (l, k, r, _) ->\n loop (f k (loop acc l)) r in\n loop acc set\n\n let elements { set = set } = \n let rec loop acc = function\n Empty -> acc\n | Node(l, k, r, _) -> loop (k :: loop acc r) l in\n loop [] set\nend;;\n\nmodule type GRAPH_LABELS = \n sig \n type label\n end;;\n\n(* Typ modu\u0142u implementuj\u0105cego grafy o wierzcho\u0142kach numerowanych od 0 do n-1. *)\nmodule type GRAPH = \n sig \n (* Etykiety kraw\u0119dzi. *)\n type label\n\n (* Typ graf\u00f3w o wierzcho\u0142kach typu 'a. *)\n type graph\n \n (* Pusty graf. *)\n val init : int -> graph\n\n (* Rozmiar grafu *)\n val size : graph -> int\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_directed_edge : graph -> int -> int -> label -> unit\n\n (* Dodanie kraw\u0119dzi nieskierowanej (dwukierunkowej) \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_edge : graph -> int -> int -> label -> unit\n\n (* Lista incydencji danego wierzcho\u0142ka. *)\n val neighbours : graph -> int -> (int*label) list\n end;;\n\nmodule Graph = functor (L : GRAPH_LABELS) -> \n(struct\n (* Etykiety kraw\u0119dzi. *)\n type label = L.label\n \n (* Typ graf\u00f3w - tablica list s\u0105siedztwa. *)\n type graph = {n : int; e : (int*label) list array}\n \n (* Pusty graf. *)\n let init s = {n = s; e = Array.make s []}\n\n (* Rozmiar grafu. *)\n let size g = g.n\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n let insert_directed_edge g x y l = \n assert ((x<>y) && (x >= 0) && (x < size g) && (y >= 0) && (y < size g));\n g.e.(x) <- (y,l)::g.e.(x)\n \n (* Dodanie kraw\u0119dzi \u0142\u0105cz\u0105cej dwa (istniej\u0105ce) wierzcho\u0142ki. *)\n let insert_edge g x y l =\n insert_directed_edge g x y l;\n insert_directed_edge g y x l\n \n (* Lista incydencji danego wierzcho\u0142ka. *)\n let neighbours g x =\n g.e.(x)\nend : GRAPH with type label = L.label);;\n\nmodule IntLabel = \n struct\n type label = int\n end;;\n\nmodule G = Graph(IntLabel);;\n\nopen G;;\nopen PSet;;\nlet n = scan_int() and m = scan_int() and k = scan_int();;\nlet g = G.init n;;\n\nlet zbior = ref empty;;\n\nfor i = 1 to m do\n let a = scan_int() - 1 and b = scan_int() - 1 and c = scan_int() in\n (*dbg a; pnl(); dbg b; pnl(); pnl(); *)\n G.insert_edge g a b c;\ndone;;\n\nfor i = 1 to k do\n let a = scan_int() - 1 and b = scan_int() in\n zbior := add (Int64.of_int(b), 1, a) !zbior;\ndone;; \n\nzbior := add (Int64.zero, 0, 0) !zbior;;\nlet dis = Array.make n Int64.max_int;;\n\nlet przydatne = ref 0;;\n\nwhile is_empty !zbior = false do\n let (odl, czy, u) = min_elt (!zbior).set in\n zbior := {cmp = (!zbior).cmp; set = remove_min_elt (!zbior).set};\n if odl < dis.(u) then begin\n (* dbg (Int64.to_int odl); psp(); dbg czy; psp(); dbg u; pnl(); *)\n dis.(u) <- odl;\n if czy = 1 then incr przydatne;\n List.iter (fun (v, w) ->\n let waga = Int64.add odl (Int64.of_int(w)) in\n if waga < dis.(v) then begin\n zbior := add (waga, 0, v) !zbior;\n end;\n ) (neighbours g u);\n end;\ndone;;\n\nprint_int (k - !przydatne);;\n"}, {"source_code": "(* codeforces 103. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\nmodule Pset = Set.Make (struct type t = int64*int let compare = compare end)\n\nlet long x = Int64.of_int x\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet n = read_int ()\nlet m = read_int ()\nlet k = read_int ()\nlet ne = m + k\n\nlet ss = Array.make (2*ne) 0\nlet ff = Array.make (2*ne) 0\nlet ww = Array.make (2*ne) 0L\nlet first = Array.make n (-1)\nlet next = Array.make (2*ne) 0\nlet reg_edge = Array.make (2*ne) false\nlet parent_edge = Array.make n (-1)\nlet start = 0\n\nlet () = \n for i=0 to m-1 do\n let vi = read_int() -1 in\n let ui = read_int() -1 in\n let xi = long (read_int()) in\n ss.(i) <- vi;\n ff.(i+ne) <- vi;\n ff.(i) <- ui;\n ss.(i+ne) <- ui;\n ww.(i) <- xi;\n ww.(i+ne) <- xi;\n reg_edge.(i) <- true;\n reg_edge.(i+ne) <- true;\n done;\n\n for i=m to ne-1 do\n let vi = read_int() -1 in\n let ui = start in\n let xi = long (read_int()) in\n ss.(i) <- vi;\n ff.(i+ne) <- vi;\n ff.(i) <- ui;\n ss.(i+ne) <- ui;\n ww.(i) <- xi;\n ww.(i+ne) <- xi;\n done;\n\n for i=0 to 2*ne-1 do\n next.(i) <- first.(ss.(i));\n first.(ss.(i)) <- i;\n done\n\nlet inf = 1_000_000_000_000_000_000L\nlet dist = Array.make n inf\nlet () = dist.(start) <- 0L\n\nlet rec dijkstra s = if Pset.is_empty s then () else \n let (d, v) = Pset.min_elt s in\n let s = Pset.remove (d, v) s in\n let rec loop e s = if e = -1 then s else\n let w = ff.(e) in\n (* processing edge v,w *)\n if dist.(w) = inf then (\n\tdist.(w) <- dist.(v) ++ ww.(e);\n\tparent_edge.(w) <- e;\n\tloop (next.(e)) (Pset.add (dist.(w), w) s)\n ) else if dist.(v) ++ ww.(e) < dist.(w) then (\n\tlet s = Pset.remove (dist.(w), w) s in\n\tdist.(w) <- dist.(v) ++ ww.(e);\n\tparent_edge.(w) <- e;\n\tloop (next.(e)) (Pset.add (dist.(w), w) s)\n ) else if dist.(v) ++ ww.(e) = dist.(w) && reg_edge.(e) then (\n\tparent_edge.(w) <- e;\n\tloop (next.(e)) s\n ) else (\n\tloop (next.(e)) s\n )\n in\n dijkstra (loop first.(v) s)\n\nlet () = dijkstra (Pset.singleton (0L,start))\n\nlet ecount = ref 0\n\nlet () =\n for i=1 to n-1 do\n if parent_edge.(i) < 0 then failwith \"graph not connected\";\n if not (reg_edge.(parent_edge.(i))) then ecount := !ecount + 1\n done;\n\n Printf.printf \"%d\\n\" (k - !ecount)\n"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\n\nmodule PSet = struct\n type 'k set =\n | Empty\n | Node of 'k set * 'k * 'k set * int\n\n type 'k t =\n {\n cmp : 'k -> 'k -> int;\n set : 'k set;\n }\n\n let height = function\n | Node (_, _, _, h) -> h\n | Empty -> 0\n\n let make l k r = Node (l, k, r, max (height l) (height r) + 1)\n\n let bal l k r =\n let hl = height l in\n let hr = height r in\n if hl > hr + 2 then\n match l with\n | Node (ll, lk, lr, _) ->\n if height ll >= height lr then make ll lk (make lr k r)\n else\n (match lr with\n | Node (lrl, lrk, lrr, _) ->\n make (make ll lk lrl) lrk (make lrr k r)\n | Empty -> assert false)\n | Empty -> assert false\n else if hr > hl + 2 then\n match r with\n | Node (rl, rk, rr, _) ->\n if height rr >= height rl then make (make l k rl) rk rr\n else\n (match rl with\n | Node (rll, rlk, rlr, _) ->\n make (make l k rll) rlk (make rlr rk rr)\n | Empty -> assert false)\n | Empty -> assert false\n else Node (l, k, r, max hl hr + 1)\n\n let rec min_elt = function\n | Node (Empty, k, _, _) -> k\n | Node (l, _, _, _) -> min_elt l\n | Empty -> raise Not_found\n\n let rec remove_min_elt = function\n | Node (Empty, _, r, _) -> r\n | Node (l, k, r, _) -> bal (remove_min_elt l) k r\n | Empty -> invalid_arg \"PSet.remove_min_elt\"\n\n let merge t1 t2 =\n match t1, t2 with\n | Empty, _ -> t2\n | _, Empty -> t1\n | _ ->\n let k = min_elt t2 in\n bal t1 k (remove_min_elt t2)\n\n let create cmp = { cmp = cmp; set = Empty }\n let empty = { cmp = compare; set = Empty }\n\n let is_empty x = \n x.set = Empty\n\n let rec add_one cmp x = function\n | Node (l, k, r, h) ->\n let c = cmp x k in\n if c = 0 then Node (l, x, r, h)\n else if c < 0 then\n let nl = add_one cmp x l in\n bal nl k r\n else\n let nr = add_one cmp x r in\n bal l k nr\n | Empty -> Node (Empty, x, Empty, 1)\n\n let add x { cmp = cmp; set = set } =\n { cmp = cmp; set = add_one cmp x set }\n\n let rec join cmp l v r =\n match (l, r) with\n (Empty, _) -> add_one cmp v r\n | (_, Empty) -> add_one cmp v l\n | (Node(ll, lv, lr, lh), Node(rl, rv, rr, rh)) ->\n if lh > rh + 2 then bal ll lv (join cmp lr v r) else\n if rh > lh + 2 then bal (join cmp l v rl) rv rr else\n make l v r\n\n let split x { cmp = cmp; set = set } =\n let rec loop x = function\n Empty ->\n (Empty, false, Empty)\n | Node (l, v, r, _) ->\n let c = cmp x v in\n if c = 0 then (l, true, r)\n else if c < 0 then\n let (ll, pres, rl) = loop x l in (ll, pres, join cmp rl v r)\n else\n let (lr, pres, rr) = loop x r in (join cmp l v lr, pres, rr)\n in\n let setl, pres, setr = loop x set in\n { cmp = cmp; set = setl }, pres, { cmp = cmp; set = setr }\n\n let remove x { cmp = cmp; set = set } =\n let rec loop = function\n | Node (l, k, r, _) ->\n let c = cmp x k in\n if c = 0 then merge l r else\n if c < 0 then bal (loop l) k r else bal l k (loop r)\n | Empty -> Empty in\n { cmp = cmp; set = loop set }\n\n let mem x { cmp = cmp; set = set } =\n let rec loop = function\n | Node (l, k, r, _) ->\n let c = cmp x k in\n c = 0 || loop (if c < 0 then l else r)\n | Empty -> false in\n loop set\n\n let exists = mem\n\n let iter f { set = set } =\n let rec loop = function\n | Empty -> ()\n | Node (l, k, r, _) -> loop l; f k; loop r in\n loop set\n\n let fold f { cmp = cmp; set = set } acc =\n let rec loop acc = function\n | Empty -> acc\n | Node (l, k, r, _) ->\n loop (f k (loop acc l)) r in\n loop acc set\n\n let elements { set = set } = \n let rec loop acc = function\n Empty -> acc\n | Node(l, k, r, _) -> loop (k :: loop acc r) l in\n loop [] set\nend;;\n\nmodule type GRAPH_LABELS = \n sig \n type label\n end;;\n\n(* Typ modu\u0142u implementuj\u0105cego grafy o wierzcho\u0142kach numerowanych od 0 do n-1. *)\nmodule type GRAPH = \n sig \n (* Etykiety kraw\u0119dzi. *)\n type label\n\n (* Typ graf\u00f3w o wierzcho\u0142kach typu 'a. *)\n type graph\n \n (* Pusty graf. *)\n val init : int -> graph\n\n (* Rozmiar grafu *)\n val size : graph -> int\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_directed_edge : graph -> int -> int -> label -> unit\n\n (* Dodanie kraw\u0119dzi nieskierowanej (dwukierunkowej) \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_edge : graph -> int -> int -> label -> unit\n\n (* Lista incydencji danego wierzcho\u0142ka. *)\n val neighbours : graph -> int -> (int*label) list\n end;;\n\nmodule Graph = functor (L : GRAPH_LABELS) -> \n(struct\n (* Etykiety kraw\u0119dzi. *)\n type label = L.label\n \n (* Typ graf\u00f3w - tablica list s\u0105siedztwa. *)\n type graph = {n : int; e : (int*label) list array}\n \n (* Pusty graf. *)\n let init s = {n = s; e = Array.make s []}\n\n (* Rozmiar grafu. *)\n let size g = g.n\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n let insert_directed_edge g x y l = \n assert ((x<>y) && (x >= 0) && (x < size g) && (y >= 0) && (y < size g));\n g.e.(x) <- (y,l)::g.e.(x)\n \n (* Dodanie kraw\u0119dzi \u0142\u0105cz\u0105cej dwa (istniej\u0105ce) wierzcho\u0142ki. *)\n let insert_edge g x y l =\n insert_directed_edge g x y l;\n insert_directed_edge g y x l\n \n (* Lista incydencji danego wierzcho\u0142ka. *)\n let neighbours g x =\n g.e.(x)\nend : GRAPH with type label = L.label);;\n\nmodule IntLabel = \n struct\n type label = int\n end;;\n\nmodule G = Graph(IntLabel);;\n\nopen G;;\nopen PSet;;\nlet n = scan_int() and m = scan_int() and k = scan_int();;\nlet g = G.init n;;\n\nlet zbior = ref empty;;\n\nfor i = 1 to m do\n let a = scan_int() - 1 and b = scan_int() - 1 and c = scan_int() in\n (*dbg a; pnl(); dbg b; pnl(); pnl(); *)\n G.insert_edge g a b c;\ndone;;\n\nfor i = 1 to k do\n let a = scan_int() - 1 and b = scan_int() in\n zbior := add (Int64.of_int(b), 1, a) !zbior;\ndone;; \n\nzbior := add (Int64.zero, 0, 0) !zbior;;\nlet dis = Array.make n Int64.max_int;;\n\nlet przydatne = ref 0;;\n\nwhile is_empty !zbior = false do\n let (odl, czy, u) = min_elt (!zbior).set in\n zbior := {cmp = (!zbior).cmp; set = remove_min_elt (!zbior).set};\n if odl < dis.(u) then begin\n dis.(u) <- odl;\n if czy = 1 then incr przydatne;\n List.iter (fun (v, w) ->\n let waga = Int64.add odl (Int64.of_int(w)) in\n if waga < dis.(v) then begin\n dis.(v) <- waga;\n zbior := add (waga, 0, v) !zbior;\n end;\n ) (neighbours g u);\n end;\ndone;;\n\nprint_int (k - !przydatne);;\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\n\nmodule PSet = struct\n type 'k set =\n | Empty\n | Node of 'k set * 'k * 'k set * int\n\n type 'k t =\n {\n cmp : 'k -> 'k -> int;\n set : 'k set;\n }\n\n let height = function\n | Node (_, _, _, h) -> h\n | Empty -> 0\n\n let make l k r = Node (l, k, r, max (height l) (height r) + 1)\n\n let bal l k r =\n let hl = height l in\n let hr = height r in\n if hl > hr + 2 then\n match l with\n | Node (ll, lk, lr, _) ->\n if height ll >= height lr then make ll lk (make lr k r)\n else\n (match lr with\n | Node (lrl, lrk, lrr, _) ->\n make (make ll lk lrl) lrk (make lrr k r)\n | Empty -> assert false)\n | Empty -> assert false\n else if hr > hl + 2 then\n match r with\n | Node (rl, rk, rr, _) ->\n if height rr >= height rl then make (make l k rl) rk rr\n else\n (match rl with\n | Node (rll, rlk, rlr, _) ->\n make (make l k rll) rlk (make rlr rk rr)\n | Empty -> assert false)\n | Empty -> assert false\n else Node (l, k, r, max hl hr + 1)\n\n let rec min_elt = function\n | Node (Empty, k, _, _) -> k\n | Node (l, _, _, _) -> min_elt l\n | Empty -> raise Not_found\n\n let rec remove_min_elt = function\n | Node (Empty, _, r, _) -> r\n | Node (l, k, r, _) -> bal (remove_min_elt l) k r\n | Empty -> invalid_arg \"PSet.remove_min_elt\"\n\n let merge t1 t2 =\n match t1, t2 with\n | Empty, _ -> t2\n | _, Empty -> t1\n | _ ->\n let k = min_elt t2 in\n bal t1 k (remove_min_elt t2)\n\n let create cmp = { cmp = cmp; set = Empty }\n let empty = { cmp = compare; set = Empty }\n\n let is_empty x = \n x.set = Empty\n\n let rec add_one cmp x = function\n | Node (l, k, r, h) ->\n let c = cmp x k in\n if c = 0 then Node (l, x, r, h)\n else if c < 0 then\n let nl = add_one cmp x l in\n bal nl k r\n else\n let nr = add_one cmp x r in\n bal l k nr\n | Empty -> Node (Empty, x, Empty, 1)\n\n let add x { cmp = cmp; set = set } =\n { cmp = cmp; set = add_one cmp x set }\n\n let rec join cmp l v r =\n match (l, r) with\n (Empty, _) -> add_one cmp v r\n | (_, Empty) -> add_one cmp v l\n | (Node(ll, lv, lr, lh), Node(rl, rv, rr, rh)) ->\n if lh > rh + 2 then bal ll lv (join cmp lr v r) else\n if rh > lh + 2 then bal (join cmp l v rl) rv rr else\n make l v r\n\n let split x { cmp = cmp; set = set } =\n let rec loop x = function\n Empty ->\n (Empty, false, Empty)\n | Node (l, v, r, _) ->\n let c = cmp x v in\n if c = 0 then (l, true, r)\n else if c < 0 then\n let (ll, pres, rl) = loop x l in (ll, pres, join cmp rl v r)\n else\n let (lr, pres, rr) = loop x r in (join cmp l v lr, pres, rr)\n in\n let setl, pres, setr = loop x set in\n { cmp = cmp; set = setl }, pres, { cmp = cmp; set = setr }\n\n let remove x { cmp = cmp; set = set } =\n let rec loop = function\n | Node (l, k, r, _) ->\n let c = cmp x k in\n if c = 0 then merge l r else\n if c < 0 then bal (loop l) k r else bal l k (loop r)\n | Empty -> Empty in\n { cmp = cmp; set = loop set }\n\n let mem x { cmp = cmp; set = set } =\n let rec loop = function\n | Node (l, k, r, _) ->\n let c = cmp x k in\n c = 0 || loop (if c < 0 then l else r)\n | Empty -> false in\n loop set\n\n let exists = mem\n\n let iter f { set = set } =\n let rec loop = function\n | Empty -> ()\n | Node (l, k, r, _) -> loop l; f k; loop r in\n loop set\n\n let fold f { cmp = cmp; set = set } acc =\n let rec loop acc = function\n | Empty -> acc\n | Node (l, k, r, _) ->\n loop (f k (loop acc l)) r in\n loop acc set\n\n let elements { set = set } = \n let rec loop acc = function\n Empty -> acc\n | Node(l, k, r, _) -> loop (k :: loop acc r) l in\n loop [] set\nend;;\n\nmodule type GRAPH_LABELS = \n sig \n type label\n end;;\n\n(* Typ modu\u0142u implementuj\u0105cego grafy o wierzcho\u0142kach numerowanych od 0 do n-1. *)\nmodule type GRAPH = \n sig \n (* Etykiety kraw\u0119dzi. *)\n type label\n\n (* Typ graf\u00f3w o wierzcho\u0142kach typu 'a. *)\n type graph\n \n (* Pusty graf. *)\n val init : int -> graph\n\n (* Rozmiar grafu *)\n val size : graph -> int\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_directed_edge : graph -> int -> int -> label -> unit\n\n (* Dodanie kraw\u0119dzi nieskierowanej (dwukierunkowej) \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_edge : graph -> int -> int -> label -> unit\n\n (* Lista incydencji danego wierzcho\u0142ka. *)\n val neighbours : graph -> int -> (int*label) list\n end;;\n\nmodule Graph = functor (L : GRAPH_LABELS) -> \n(struct\n (* Etykiety kraw\u0119dzi. *)\n type label = L.label\n \n (* Typ graf\u00f3w - tablica list s\u0105siedztwa. *)\n type graph = {n : int; e : (int*label) list array}\n \n (* Pusty graf. *)\n let init s = {n = s; e = Array.make s []}\n\n (* Rozmiar grafu. *)\n let size g = g.n\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n let insert_directed_edge g x y l = \n assert ((x<>y) && (x >= 0) && (x < size g) && (y >= 0) && (y < size g));\n g.e.(x) <- (y,l)::g.e.(x)\n \n (* Dodanie kraw\u0119dzi \u0142\u0105cz\u0105cej dwa (istniej\u0105ce) wierzcho\u0142ki. *)\n let insert_edge g x y l =\n insert_directed_edge g x y l;\n insert_directed_edge g y x l\n \n (* Lista incydencji danego wierzcho\u0142ka. *)\n let neighbours g x =\n g.e.(x)\nend : GRAPH with type label = L.label);;\n\nmodule IntLabel = \n struct\n type label = int\n end;;\n\nmodule G = Graph(IntLabel);;\n\nopen G;;\nopen PSet;;\nlet n = scan_int() and m = scan_int() and k = scan_int();;\nlet g = G.init n;;\n\nlet zbior = ref empty;;\n\nfor i = 1 to m do\n let a = scan_int() - 1 and b = scan_int() - 1 and c = scan_int() in\n (*dbg a; pnl(); dbg b; pnl(); pnl(); *)\n G.insert_edge g a b c;\ndone;;\n\nfor i = 1 to k do\n let a = scan_int() - 1 and b = scan_int() in\n zbior := add (Int64.of_int(b), 1, a) !zbior;\ndone;; \n\nzbior := add (Int64.zero, 0, 0) !zbior;;\nlet dis = Array.make n Int64.max_int;;\n\nlet przydatne = ref 0;;\n\nwhile is_empty !zbior = false do\n let (odl, czy, u) = min_elt (!zbior).set in\n zbior := {cmp = (!zbior).cmp; set = remove_min_elt (!zbior).set};\n if odl < dis.(u) then begin\n dis.(u) <- odl;\n if czy = 1 then incr przydatne;\n List.iter (fun (v, w) ->\n let waga = Int64.add odl (Int64.of_int(w)) in\n if waga < dis.(v) then begin\n zbior := remove (dis.(v), 0, v) !zbior;\n zbior := remove (dis.(v), 1, v) !zbior;\n dis.(v) <- waga;\n zbior := add (waga, 0, v) !zbior;\n end;\n ) (neighbours g u);\n end;\ndone;;\n\nprint_int (k - !przydatne);;\n"}], "src_uid": "03d6b61be6ca0ac9dd8259458f41da59"} {"nl": {"description": "One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: \"Find such positive integer n, that among numbers n\u2009+\u20091, n\u2009+\u20092, ..., 2\u00b7n there are exactly m numbers which binary representation contains exactly k digits one\".The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.", "input_spec": "The first line contains two space-separated integers, m and k (0\u2009\u2264\u2009m\u2009\u2264\u20091018; 1\u2009\u2264\u2009k\u2009\u2264\u200964).", "output_spec": "Print the required number n (1\u2009\u2264\u2009n\u2009\u2264\u20091018). If there are multiple answers, print any of them.", "sample_inputs": ["1 1", "3 2"], "sample_outputs": ["1", "5"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet ( lsl ) a i = Int64.shift_left a i\nlet ( lsr ) a i = Int64.shift_right a i\nlet ( land ) a b = Int64.logand a b\n\nlet init_binomial n m = \n (* compute an array b so that b.(p).(q) = (p choose q), \n where 0 <= p <= n and 0 <= q <= m. *)\n let b = Array.make_matrix (n+1) (m+1) 0L in\n for i=0 to n do for j=0 to min i m do \n b.(i).(j) <- if j=0 then 1L else b.(i-1).(j-1) ++ b.(i-1).(j)\n done done;\n b\n\nlet b = init_binomial 64 64\n\n\nlet () = \n let m = read_long () in\n let k = read_int () in\n\n let up_to n =\n (* count the number of numbers in 1...n-1 with k 1s in their rep. *)\n (* n>=1 k>=1 *)\n let rec loop i k ac = if i<0 then ac else\n\tif (1L lsl i) land n <> 0L then (\n\t loop (i-1) (k-1) (ac ++ b.(i).(k))\n\t) else (\n\t loop (i-1) k ac\n\t)\n in\n loop 63 k 0L\n in\n\n let eval n = \n (up_to ((n ++ n) ++ 1L)) -- (up_to (n++1L))\n in\n\n let rec upper_bound n = \n if eval n >= m then n else upper_bound (n++n)\n in\n\n let rec bsearch lo hi = (* eval lo < m, eval hi >= m *)\n if lo ++ 1L = hi then hi else\n let mid = (lo ++ hi) lsr 1 in\n if eval mid < m then bsearch mid hi else bsearch lo mid\n in\n\n printf \"%Ld\\n\" (bsearch 0L (upper_bound 1L))\n"}], "negative_code": [], "src_uid": "3845031bffe6475d3da4858725b70ec3"} {"nl": {"description": "You are given two integers $$$n$$$ and $$$k$$$.Your task is to construct such a string $$$s$$$ of length $$$n$$$ that for each $$$i$$$ from $$$1$$$ to $$$k$$$ there is at least one $$$i$$$-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minimal frequency of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print any.You have to answer $$$t$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of queries. The next $$$t$$$ lines are contain queries, one per line. The $$$i$$$-th line contains two integers $$$n_i$$$ and $$$k_i$$$ ($$$1 \\le n_i \\le 100, 1 \\le k_i \\le min(n_i, 26)$$$) \u2014 the length of the string in the $$$i$$$-th query and the number of characters in the $$$i$$$-th query.", "output_spec": "Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: any string $$$s_i$$$ satisfying the conditions in the problem statement with constraints from the $$$i$$$-th query.", "sample_inputs": ["3\n7 3\n4 4\n6 2"], "sample_outputs": ["cbcacab\nabcd\nbaabab"], "notes": "NoteIn the first example query the maximum possible minimal frequency is $$$2$$$, it can be easily seen that the better answer doesn't exist. Other examples of correct answers: \"cbcabba\", \"ccbbaaa\" (any permutation of given answers is also correct).In the second example query any permutation of first four letters is acceptable (the maximum minimal frequency is $$$1$$$).In the third example query any permutation of the given answer is acceptable (the maximum minimal frequency is $$$3$$$)."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let t = gi 0 in\n rep 1L t @@ fun _ ->\n let n,k = g2 0 in\n let d = n / k in\n let r = n - d * k in\n repi 1 (i32 k-$1) (fun i->\n let c = (int_of_char 'a' +$ i-$1) |> char_of_int in\n\n rep 1L d (fun _ -> printf \"%c\" c)\n );let c = (int_of_char 'a' +$ i32 k-$1) |> char_of_int in\n\n rep 1L (d+r) (fun _ -> printf \"%c\" c); print_endline \"\"\n\n\n"}], "negative_code": [], "src_uid": "fa253aabcccd487d09142ea882abbc1b"} {"nl": {"description": "While Duff was resting in the beach, she accidentally found a strange array b0,\u2009b1,\u2009...,\u2009bl\u2009-\u20091 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0,\u2009...,\u2009an\u2009-\u20091 that b can be build from a with formula: bi\u2009=\u2009ai mod n where a mod b denoted the remainder of dividing a by b. Duff is so curious, she wants to know the number of subsequences of b like bi1,\u2009bi2,\u2009...,\u2009bix (0\u2009\u2264\u2009i1\u2009<\u2009i2\u2009<\u2009...\u2009<\u2009ix\u2009<\u2009l), such that: 1\u2009\u2264\u2009x\u2009\u2264\u2009k For each 1\u2009\u2264\u2009j\u2009\u2264\u2009x\u2009-\u20091, For each 1\u2009\u2264\u2009j\u2009\u2264\u2009x\u2009-\u20091, bij\u2009\u2264\u2009bij\u2009+\u20091. i.e this subsequence is non-decreasing. Since this number can be very large, she want to know it modulo 109\u2009+\u20097.Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.", "input_spec": "The first line of input contains three integers, n,\u2009l and k (1\u2009\u2264\u2009n,\u2009k, n\u2009\u00d7\u2009k\u2009\u2264\u2009106 and 1\u2009\u2264\u2009l\u2009\u2264\u20091018). The second line contains n space separated integers, a0,\u2009a1,\u2009...,\u2009an\u2009-\u20091 (1\u2009\u2264\u2009ai\u2009\u2264\u2009109 for each 0\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091). ", "output_spec": "Print the answer modulo 1\u2009000\u2009000\u2009007 in one line.", "sample_inputs": ["3 5 3\n5 9 1", "5 10 3\n1 2 3 4 5"], "sample_outputs": ["10", "25"], "notes": "NoteIn the first sample case, . So all such sequences are: , , , , , , , , and ."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let m = l /| (Int64.of_int n) in\n let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in\n let a' = Array.sub a 0 n' in\n let b = Array.copy a in\n let () = Array.sort compare b in\n let b' = Array.copy a' in\n let () = Array.sort compare b' in\n let bs a x =\n let l = ref (-1) in\n let r = ref (Array.length a) in\n while !l < !r - 1 do\n\tlet m = (!l + !r) lsr 1 in\n\t if a.(m) <= x\n\t then l := m\n\t else r := m\n done;\n !r\n in\n let d = Array.make_matrix n (k + 1) 1 in\n (*let cc = Array.init n (fun i -> bs b a.(i)) in*)\n let _ =\n for j = 1 to k do\n let p = ref 0 in\n\tfor i = 0 to n - 1 do\n\t while !p < n && b.(!p) <= b.(i) do\n\t incr p;\n\t done;\n\t d.(i).(j) <-\n\t if i = 0\n\t then d.(!p - 1).(j - 1)\n\t else \n\t Int32.to_int\n\t\t(Int32.rem\n\t\t (Int32.add\n\t\t (Int32.of_int d.(i - 1).(j))\n\t\t (Int32.of_int d.(!p - 1).(j - 1)))\n\t\t (Int32.of_int mm));\n\t (*Printf.printf \"zxc %d %d %d\\n\" i j d.(i).(j)*)\n\tdone\n done;\n in\n let res = ref 0L in\n for i = 0 to n' - 1 do\n let c = bs b a.(i) in\n\t(*Printf.printf \"asd %d %d %d\\n\" i a.(i) c;*)\n\tfor kk = 1 to k do\n\t let k = kk - 1 in\n\t if Int64.of_int k <= m then (\n\t res :=\n\t\tInt64.rem\n\t\t (!res +|\n\t\t (*Int64.of_int bmk.(k) *| *)\n\t\t\t Int64.of_int d.(c - 1).(k)) mmm;\n\t (*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n\t )\n\tdone;\n done;\n for kk = 1 to k do\n let k = kk in\n\tif Int64.of_int k <= m then (\n\t res :=\n\t Int64.rem\n\t (!res +|\n\t\t Int64.rem (m -| Int64.of_int (k - 1)) mmm *|\n\t\t Int64.of_int d.(n - 1).(k)) mmm;\n\t (*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n\t)\n done;\n Printf.printf \"%Ld\\n\" !res\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\nlet read_string () = Scanf.scanf \" %s \" (fun x -> x)\n\nlet m = 1_000_000_007\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( ** ) a b = Int64.mul a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet ll a = Int64.of_int a\n\nlet add a b = Int64.to_int (((ll a) ++ (ll b)) %% (ll m))\n\nlet () =\n let n = read_int () in\n let l = Int64.of_string (read_string ()) in\n let k = read_int () in\n let a = Array.init n (fun _ -> read_int ()) in\n let sorted = Array.init n (fun i -> (a.(i), i)) in\n Array.sort (fun a b -> (fst a) - (fst b)) sorted;\n\n let f = Array.make_matrix (k+1) n 0 in\n for j = 0 to n-1 do\n f.(1).(j) <- 1\n done;\n \n for i = 2 to k do\n let sum = ref 0 in\n let l = ref 0 in\n while !l < n do\n let r = ref !l in\n while !r < n && (fst sorted.(!r)) = (fst sorted.(!l)) do\n sum := add !sum f.(i-1).(snd sorted.(!r));\n r := !r + 1\n done;\n while !l < !r do\n f.(i).(snd sorted.(!l)) <- !sum;\n l := !l + 1\n done;\n done;\n done;\n\n let ans = ref 0 in\n for i = 1 to k do\n for j = 0 to n-1 do\n let len = ((ll (i-1)) ** (ll n)) ++ (ll (j+1)) in\n let ways = (l -- len ++ (ll n)) // (ll n) %% (ll m) in\n let llf = ll f.(i).(j) in\n let total = (ways ** llf) %% (ll m) in\n if len <= l then ans := add !ans (Int64.to_int total)\n done;\n done;\n \n Printf.printf \"%d\\n\" !ans\n;;\n"}], "negative_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let inv = Array.make 1000001 1 in\n let _ =\n for i = 2 to 1000000 do\n inv.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)\n\t mmm);\n done\n in\n let fact = Array.make (n + k + 2) 1 in\n let ifact = Array.make (n + k + 2) 1 in\n let () =\n for i = 2 to n + k + 1 do\n fact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);\n ifact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int ifact.(i - 1) *| Int64.of_int inv.(i)) mmm);\n done;\n in\n let binom n k =\n Int64.to_int\n (Int64.rem\n\t (Int64.rem (Int64.of_int fact.(n) *| Int64.of_int ifact.(n - k)) mmm *|\n\t Int64.of_int ifact.(k)) mmm)\n in\n (*let binomial = Array.make_matrix (n + k + 1) (k + 1) 0 in\n let _ =\n binomial.(0).(0) <- 1;\n for i = 1 to n + k do\n binomial.(i).(0) <- 1;\n for j = 1 to k do\n\tbinomial.(i).(j) <-\n\t (Int32.to_int\n\t (Int32.rem\n\t\t(Int32.add\n\t\t (Int32.of_int binomial.(i - 1).(j - 1))\n\t\t (Int32.of_int binomial.(i - 1).(j)))\n\t\t(Int32.of_int mm)))\n done\n done\n in*)\n let m = l /| (Int64.of_int n) in\n let bmk = Array.make (k + 1) 1 in\n let _ =\n let m = Int64.rem m mmm in\n for i = 1 to k do\n\tbmk.(i) <-\n\t Int64.to_int\n\t (Int64.rem\n\t (Int64.rem\n\t\t(Int64.of_int bmk.(i - 1) *| (m -| Int64.of_int (i - 1))) mmm *|\n\t\t Int64.of_int inv.(i))\n\t mmm);\n\t(*Printf.printf \"qwe %Ld %d %d %d\\n\" m i bmk.(i) inv.(i)*)\n done;\n in\n let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in\n let a' = Array.sub a 0 n' in\n let b = Array.copy a in\n let () = Array.sort compare b in\n let b' = Array.copy a' in\n let () = Array.sort compare b' in\n let bs a x =\n let l = ref (-1) in\n let r = ref (Array.length a) in\n while !l < !r - 1 do\n\tlet m = (!l + !r) lsr 1 in\n\t if a.(m) <= x\n\t then l := m\n\t else r := m\n done;\n !r\n in\n let res = ref 0L in\n for i = 0 to n' - 1 do\n let c = bs b a.(i) in\n\t(*Printf.printf \"asd %d %d %d\\n\" i a.(i) c;*)\n\tfor kk = 1 to k do\n\t let k = kk - 1 in\n\t res :=\n\t Int64.rem\n\t\t(!res +|\n\t\t Int64.of_int bmk.(k) *|\n\t\t\t Int64.of_int (binom (c + k - 1) k)) mmm;\n\t (*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n\tdone;\n done;\n for kk = 1 to k do\n let k = kk in\n\tres :=\n\t Int64.rem\n\t (!res +|\n\t\t Int64.of_int bmk.(k) *|\n\t\t Int64.of_int (binom (n + k - 1) k)) mmm;\n\t(*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n done;\n Printf.printf \"%Ld\\n\" !res\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let inv = Array.make 1000001 1 in\n let _ =\n for i = 2 to 1000000 do\n inv.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)\n\t mmm);\n done\n in\n let m = l /| (Int64.of_int n) in\n let bmk = Array.make (k + 1) 1 in\n let _ =\n let m = Int64.rem m mmm in\n for i = 1 to k do\n\tbmk.(i) <-\n\t Int64.to_int\n\t (Int64.rem\n\t (Int64.rem\n\t\t(Int64.of_int bmk.(i - 1) *| (m -| Int64.of_int (i - 1))) mmm *|\n\t\t Int64.of_int inv.(i))\n\t mmm);\n\t(*Printf.printf \"qwe %Ld %d %d %d\\n\" m i bmk.(i) inv.(i)*)\n done;\n in\n let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in\n let a' = Array.sub a 0 n' in\n let b = Array.copy a in\n let () = Array.sort compare b in\n let b' = Array.copy a' in\n let () = Array.sort compare b' in\n let bs a x =\n let l = ref (-1) in\n let r = ref (Array.length a) in\n while !l < !r - 1 do\n\tlet m = (!l + !r) lsr 1 in\n\t if a.(m) <= x\n\t then l := m\n\t else r := m\n done;\n !r\n in\n let d = Array.make_matrix n (k + 1) 1 in\n (*let cc = Array.init n (fun i -> bs b a.(i)) in*)\n let _ =\n for j = 1 to k do\n let p = ref 0 in\n\tfor i = 0 to n - 1 do\n\t while !p < n && b.(!p) <= b.(i) do\n\t incr p;\n\t done;\n\t d.(i).(j) <-\n\t if i = 0\n\t then d.(!p - 1).(j - 1)\n\t else \n\t Int32.to_int\n\t\t(Int32.rem\n\t\t (Int32.add\n\t\t (Int32.of_int d.(i - 1).(j))\n\t\t (Int32.of_int d.(!p - 1).(j - 1)))\n\t\t (Int32.of_int mm));\n\t (*Printf.printf \"zxc %d %d %d\\n\" i j d.(i).(j)*)\n\tdone\n done;\n in\n let res = ref 0L in\n for i = 0 to n' - 1 do\n let c = bs b a.(i) in\n\t(*Printf.printf \"asd %d %d %d\\n\" i a.(i) c;*)\n\tfor kk = 1 to k do\n\t let k = kk - 1 in\n\t if Int64.of_int k <= m then (\n\t res :=\n\t\tInt64.rem\n\t\t (!res +|\n\t\t (*Int64.of_int bmk.(k) *| *)\n\t\t\t Int64.of_int d.(c - 1).(k)) mmm;\n\t (*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n\t )\n\tdone;\n done;\n for kk = 1 to k do\n let k = kk in\n\tif Int64.of_int k <= m then (\n\t res :=\n\t Int64.rem\n\t (!res +|\n\t\t (m -| Int64.of_int (k - 1)) *|\n\t\t Int64.of_int d.(n - 1).(k)) mmm;\n\t (*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n\t)\n done;\n Printf.printf \"%Ld\\n\" !res\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let inv = Array.make 1000001 1 in\n let _ =\n for i = 2 to 1000000 do\n inv.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)\n\t mmm);\n done\n in\n let fact = Array.make (n + k + 2) 1 in\n let ifact = Array.make (n + k + 2) 1 in\n let () =\n for i = 2 to n + k + 1 do\n fact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);\n ifact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int ifact.(i - 1) *| Int64.of_int inv.(i)) mmm);\n done;\n in\n let binom n k =\n Int64.to_int\n (Int64.rem\n\t (Int64.rem (Int64.of_int fact.(n) *| Int64.of_int ifact.(n - k)) mmm *|\n\t Int64.of_int ifact.(k)) mmm)\n in\n (*let binomial = Array.make_matrix (n + k + 1) (k + 1) 0 in\n let _ =\n binomial.(0).(0) <- 1;\n for i = 1 to n + k do\n binomial.(i).(0) <- 1;\n for j = 1 to k do\n\tbinomial.(i).(j) <-\n\t (Int32.to_int\n\t (Int32.rem\n\t\t(Int32.add\n\t\t (Int32.of_int binomial.(i - 1).(j - 1))\n\t\t (Int32.of_int binomial.(i - 1).(j)))\n\t\t(Int32.of_int mm)))\n done\n done\n in*)\n let m = l /| (Int64.of_int n) in\n let bmk = Array.make (k + 1) 1 in\n let _ =\n let m = Int64.rem m mmm in\n for i = 1 to k do\n\tbmk.(i) <-\n\t Int64.to_int\n\t (Int64.rem\n\t (Int64.rem\n\t\t(Int64.of_int bmk.(i - 1) *| (m -| Int64.of_int (i - 1))) mmm *|\n\t\t Int64.of_int inv.(i))\n\t mmm);\n\t(*Printf.printf \"qwe %Ld %d %d %d\\n\" m i bmk.(i) inv.(i)*)\n done;\n in\n let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in\n let a' = Array.sub a 0 n' in\n let b = Array.copy a in\n let () = Array.sort compare b in\n let b' = Array.copy a' in\n let () = Array.sort compare b' in\n let bs a x =\n let l = ref (-1) in\n let r = ref (Array.length a) in\n while !l < !r - 1 do\n\tlet m = (!l + !r) lsr 1 in\n\t if a.(m) <= x\n\t then l := m\n\t else r := m\n done;\n !r\n in\n let d = Array.make_matrix n (k + 1) 1 in\n (*let cc = Array.init n (fun i -> bs b a.(i)) in*)\n let _ =\n d.(0).(0) <- 1;\n for j = 1 to k do\n let p = ref 0 in\n\tfor i = 0 to n - 1 do\n\t while !p < n && b.(!p) <= b.(i) do\n\t incr p;\n\t done;\n\t d.(i).(j) <-\n\t if i = 0\n\t then d.(!p - 1).(j - 1)\n\t else \n\t Int32.to_int\n\t\t(Int32.rem\n\t\t (Int32.add\n\t\t (Int32.of_int d.(i - 1).(j))\n\t\t (Int32.of_int d.(!p - 1).(j - 1)))\n\t\t (Int32.of_int mm));\n\t (*Printf.printf \"zxc %d %d %d\\n\" i j d.(i).(j)*)\n\tdone\n done;\n in\n let res = ref 0L in\n for i = 0 to n' - 1 do\n let c = bs b a.(i) in\n\t(*Printf.printf \"asd %d %d %d\\n\" i a.(i) c;*)\n\tfor kk = 1 to k do\n\t let k = kk - 1 in\n\t res :=\n\t Int64.rem\n\t\t(!res +|\n\t\t Int64.of_int bmk.(k) *|\n\t\t\t Int64.of_int d.(c - 1).(k)) mmm;\n\t (*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n\tdone;\n done;\n for kk = 1 to k do\n let k = kk in\n\tres :=\n\t Int64.rem\n\t (!res +|\n\t\t Int64.of_int bmk.(k) *|\n\t\t Int64.of_int d.(n - 1).(k)) mmm;\n\t(*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n done;\n Printf.printf \"%Ld\\n\" !res\n"}, {"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let mm = 1000000007 in\n let mmm = Int64.of_int mm in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let l = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let inv = Array.make 1000001 1 in\n let _ =\n for i = 2 to 1000000 do\n inv.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)\n\t mmm);\n done\n in\n let fact = Array.make (n + k + 2) 1 in\n let ifact = Array.make (n + k + 2) 1 in\n let () =\n for i = 2 to n + k + 1 do\n fact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);\n ifact.(i) <-\n\tInt64.to_int\n\t(Int64.rem\n\t (Int64.of_int ifact.(i - 1) *| Int64.of_int inv.(i)) mmm);\n done;\n in\n let binom n k =\n Int64.to_int\n (Int64.rem\n\t (Int64.rem (Int64.of_int fact.(n) *| Int64.of_int ifact.(n - k)) mmm *|\n\t Int64.of_int ifact.(k)) mmm)\n in\n (*let binomial = Array.make_matrix (n + k + 1) (k + 1) 0 in\n let _ =\n binomial.(0).(0) <- 1;\n for i = 1 to n + k do\n binomial.(i).(0) <- 1;\n for j = 1 to k do\n\tbinomial.(i).(j) <-\n\t (Int32.to_int\n\t (Int32.rem\n\t\t(Int32.add\n\t\t (Int32.of_int binomial.(i - 1).(j - 1))\n\t\t (Int32.of_int binomial.(i - 1).(j)))\n\t\t(Int32.of_int mm)))\n done\n done\n in*)\n let m = l /| (Int64.of_int n) in\n let bmk = Array.make (k + 1) 1 in\n let _ =\n let m = Int64.rem m mmm in\n for i = 1 to k do\n\tbmk.(i) <-\n\t Int64.to_int\n\t (Int64.rem\n\t (Int64.rem\n\t\t(Int64.of_int bmk.(i - 1) *| (m -| Int64.of_int (i - 1))) mmm *|\n\t\t Int64.of_int inv.(i))\n\t mmm);\n\t(*Printf.printf \"qwe %Ld %d %d %d\\n\" m i bmk.(i) inv.(i)*)\n done;\n in\n let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in\n let a' = Array.sub a 0 n' in\n let b = Array.copy a in\n let () = Array.sort compare b in\n let b' = Array.copy a' in\n let () = Array.sort compare b' in\n let bs a x =\n let l = ref (-1) in\n let r = ref (Array.length a) in\n while !l < !r - 1 do\n\tlet m = (!l + !r) lsr 1 in\n\t if a.(m) <= x\n\t then l := m\n\t else r := m\n done;\n !r\n in\n let d = Array.make_matrix n (k + 1) 1 in\n (*let cc = Array.init n (fun i -> bs b a.(i)) in*)\n let _ =\n d.(0).(0) <- 1;\n for j = 1 to k do\n let p = ref 0 in\n\tfor i = 0 to n - 1 do\n\t while !p < n && b.(!p) <= b.(i) do\n\t incr p;\n\t done;\n\t d.(i).(j) <-\n\t if i = 0\n\t then d.(!p - 1).(j - 1)\n\t else \n\t Int32.to_int\n\t\t(Int32.rem\n\t\t (Int32.add\n\t\t (Int32.of_int d.(i - 1).(j))\n\t\t (Int32.of_int d.(!p - 1).(j - 1)))\n\t\t (Int32.of_int mm));\n\t (*Printf.printf \"zxc %d %d %d\\n\" i j d.(i).(j)*)\n\tdone\n done;\n in\n let res = ref 0L in\n for i = 0 to n' - 1 do\n let c = bs b a.(i) in\n\t(*Printf.printf \"asd %d %d %d\\n\" i a.(i) c;*)\n\tfor kk = 1 to k do\n\t let k = kk - 1 in\n\t res :=\n\t Int64.rem\n\t\t(!res +|\n\t\t Int64.of_int bmk.(k) *|\n\t\t\t Int64.of_int (binom (c + k - 1) k)) mmm;\n\t (*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n\tdone;\n done;\n for kk = 1 to k do\n let k = kk in\n\tres :=\n\t Int64.rem\n\t (!res +|\n\t\t Int64.of_int bmk.(k) *|\n\t\t Int64.of_int d.(n - 1).(k)) mmm;\n\t(*Printf.printf \"qwe %d %Ld %d\\n\" k !res bmk.(k)*)\n done;\n Printf.printf \"%Ld\\n\" !res\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\nlet read_string () = Scanf.scanf \" %s \" (fun x -> x)\n\nlet m = 1_000_000_007\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( ** ) a b = Int64.mul a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet ll a = Int64.of_int a\n \nlet () =\n let n = read_int () in\n let l = Int64.of_string (read_string ()) in\n let k = read_int () in\n let a = Array.init n (fun _ -> read_int ()) in\n let sorted = Array.init n (fun i -> (a.(i), i)) in\n Array.sort (fun a b -> (fst a) - (fst b)) sorted;\n\n let f = Array.make_matrix (k+1) n 0 in\n for j = 0 to n-1 do\n f.(1).(j) <- 1\n done;\n \n for i = 2 to k do\n let sum = ref 0 in\n let l = ref 0 in\n while !l < n do\n let r = ref !l in\n while !r < n && (fst sorted.(!r)) = (fst sorted.(!l)) do\n sum := (!sum + f.(i-1).(snd sorted.(!r))) mod m;\n r := !r + 1\n done;\n while !l < !r do\n f.(i).(snd sorted.(!l)) <- !sum;\n l := !l + 1\n done;\n done;\n done;\n\n let ans = ref 0 in\n for i = 1 to k do\n for j = 0 to n-1 do\n let len = ((ll (i-1)) ** (ll n)) ++ (ll (j+1)) in\n let ways = (l -- len ++ (ll n)) // (ll n) %% (ll m) in\n let llf = ll f.(i).(j) in\n let total = (ways ** llf) %% (ll m) in\n if len <= l then ans := (!ans + (Int64.to_int total)) mod m\n done;\n done;\n \n Printf.printf \"%d\\n\" !ans\n;;\n"}], "src_uid": "917fb578760e11155227921a7347e58b"} {"nl": {"description": "Polycarpus has an array, consisting of n integers a1,\u2009a2,\u2009...,\u2009an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: he chooses two elements of the array ai, aj (i\u2009\u2260\u2009j); he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai\u2009=\u2009ai\u2009+\u20091 and aj\u2009=\u2009aj\u2009-\u20091. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the array size. The second line contains space-separated integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009104) \u2014 the original array.", "output_spec": "Print a single integer \u2014 the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.", "sample_inputs": ["2\n2 1", "3\n1 4 1"], "sample_outputs": ["1", "3"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 246B *)\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i)\nlet rec readline n li = match n with\n\t| 0 -> li\n\t| _ -> readline (n-1) (gr () :: li);;\n\nlet rec sum l = match l with\n\t| [] -> 0\n\t| h :: t -> h + (sum t);;\n\nlet main () =\n\tlet n = gr () in\n\tlet ll = readline n [] in\n\tlet sm = sum ll in\n\tlet ret = if (sm mod n) = 0 then n else n -1 in\n\t(* print_string \"sm: \"; *)\n\t(* print_int sm; *)\n\t(* print_string \" ret: \"; *)\n\tprint_int ret;;\n\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun i -> read_int()) in\n let s = sum 0 (n-1) (fun i -> a.(i)) in\n let a = if s mod n = 0 then n else (n-1) in\n Printf.printf \"%d\\n\" a\n"}], "negative_code": [{"source_code": "(* Codeforces 246B *)\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i)\nlet rec readline n li = match n with\n\t| 0 -> li\n\t| _ -> readline (n-1) (gr () :: li);;\n\nlet rec sum l = match l with\n\t| [] -> 0\n\t| h :: t -> h + (sum t);;\n\nlet main () =\n\tlet n = gr () in\n\tlet ll = readline n [] in\n\tlet sm = sum ll in\n\tlet ret = if (sm mod n) = 0 then n else n -1 in\n\tprint_string \"sm: \";\n\tprint_int sm;\n\tprint_string \" ret: \";\n\tprint_int ret;;\n\nmain();;\n"}, {"source_code": "(* Codeforces 246B *)\n\nlet gr () = Scanf.scanf \" %d\" (fun i -> i)\nlet readline n li = match n with\n\t| 0 -> li\n\t| _ -> gr () :: li;;\n\nlet rec sum l = match l with\n\t| [] -> 0\n\t| h :: t -> h + (sum t);;\n\nlet main () =\n\tlet n = gr () in\n\tlet ll = readline n [] in\n\tlet sm = sum ll in\n\tlet ret = if (sm mod n) = 0 then n else n -1 in\n\tprint_int ret;;\n\nmain();;\n"}], "src_uid": "71cead8cf45126902c518c9ce6e5e186"} {"nl": {"description": "You are walking through a parkway near your house. The parkway has $$$n+1$$$ benches in a row numbered from $$$1$$$ to $$$n+1$$$ from left to right. The distance between the bench $$$i$$$ and $$$i+1$$$ is $$$a_i$$$ meters.Initially, you have $$$m$$$ units of energy. To walk $$$1$$$ meter of distance, you spend $$$1$$$ unit of your energy. You can't walk if you have no energy. Also, you can restore your energy by sitting on benches (and this is the only way to restore the energy). When you are sitting, you can restore any integer amount of energy you want (if you sit longer, you restore more energy). Note that the amount of your energy can exceed $$$m$$$.Your task is to find the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $$$n+1$$$ from the bench $$$1$$$ (and end your walk).You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 100$$$; $$$1 \\le m \\le 10^4$$$). The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 100$$$), where $$$a_i$$$ is the distance between benches $$$i$$$ and $$$i+1$$$.", "output_spec": "For each test case, print one integer \u2014 the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $$$n+1$$$ from the bench $$$1$$$ (and end your walk) in the corresponding test case.", "sample_inputs": ["3\n\n3 1\n\n1 2 1\n\n4 5\n\n3 3 5 2\n\n5 16\n\n1 2 3 4 5"], "sample_outputs": ["3\n8\n0"], "notes": "NoteIn the first test case of the example, you can walk to the bench $$$2$$$, spending $$$1$$$ unit of energy, then restore $$$2$$$ units of energy on the second bench, walk to the bench $$$3$$$, spending $$$2$$$ units of energy, restore $$$1$$$ unit of energy and go to the bench $$$4$$$.In the third test case of the example, you have enough energy to just go to the bench $$$6$$$ without sitting at all."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x-> x);;\r\n\r\n\r\nlet rec get_energy_needed = function\r\n| 0 -> 0\r\n| n -> read_int () + get_energy_needed (n-1)\r\n;;\r\n\r\nlet run_case = function\r\n| () ->\r\n let n = read_int () in\r\n let m = read_int () in\r\n let r = get_energy_needed (n) in\r\n if (m>=r) then Printf.printf \"%d\\n\" 0\r\n else Printf.printf \"%d\\n\" (r-m)\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> ()\r\n| t -> \r\n run_case ();\r\n iter_cases (t-1)\r\n;;\r\n\r\nlet t = read_int () in\r\niter_cases t;;\r\n "}], "negative_code": [], "src_uid": "7276d7e3a4b594dc64c1ba56fb1a3628"} {"nl": {"description": "There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions: move into a cell adjacent by a side: up, right, down or left; remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$\u00a0\u2014 the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \\le m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \\dots, a_{i,m}$$$ ($$$0 \\le a_{i,j} \\le 10^9$$$)\u00a0\u2014 the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more.", "sample_inputs": ["4\n\n3\n\n0 0 1\n\n4 3 2\n\n5\n\n0 4 8 12 16\n\n2 6 10 14 18\n\n4\n\n0 10 10 10\n\n10 10 10 10\n\n2\n\n0 0\n\n0 0"], "sample_outputs": ["5\n19\n17\n3"], "notes": null}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet read_matrix read n m = A.init n (fun _ -> read_array read m)\n\nlet const x _y = x\nlet inf = 1000000000\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let m = read_int () in\n let a = read_matrix read_int 2 m in\n let min_s = A.init 2 (fun _ -> A.init (m + 1) (const 0)) in\n a.(0).(0) <- -1;\n for i = m - 1 downto 0 do\n let c = 2 * (m - i) in\n min_s.(0).(i) <- max (max a.(0).(i) (a.(1).(i) - c + 1)) (min_s.(0).(i + 1) - 1);\n min_s.(1).(i) <- max (max a.(1).(i) (a.(0).(i) - c + 1)) (min_s.(1).(i + 1) - 1);\n done;\n\n let relax_at arrived_j arrived_at_t =\n if (arrived_j mod 2 = 0) then max arrived_at_t min_s.(1).(arrived_j + 1) + 2 * (m - 1 - arrived_j)\n else max arrived_at_t min_s.(0).(arrived_j + 1) + 2 * (m - 1 - arrived_j)\n in\n let best_ans = ref (min_s.(0).(0) + 2 * m) in\n let cur_t = ref (a.(1).(0) + 1) in\n for i = 0 to m - 1 do\n best_ans := min !best_ans (relax_at i !cur_t);\n if (i mod 2 = 0 && i <> m - 1) then\n cur_t := max (max (!cur_t + 1) (a.(1).(i + 1) + 1) + 1) (a.(0).(i + 1) + 1)\n else if (i <> m - 1) then\n cur_t := max (max (!cur_t + 1) (a.(0).(i + 1) + 1) + 1) (a.(1).(i + 1) + 1)\n done;\n best_ans := min !best_ans !cur_t;\n pf \"%d\\n\" !best_ans;\n done"}], "negative_code": [], "src_uid": "f9f82c16e4024a207bc7ad80af10c0fe"} {"nl": {"description": "A club plans to hold a party and will invite some of its $$$n$$$ members. The $$$n$$$ members are identified by the numbers $$$1, 2, \\dots, n$$$. If member $$$i$$$ is not invited, the party will gain an unhappiness value of $$$a_i$$$.There are $$$m$$$ pairs of friends among the $$$n$$$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited.However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number.What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n \\leq 10^5$$$, $$$0 \\leq m \\leq \\min(10^5,\\frac{n(n-1)}{2})$$$) \u2014 the number of club members and pairs of friends. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \\dots,a_n$$$ ($$$0 \\leq a_i \\leq 10^4$$$) \u2014 the unhappiness value array. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \\leq x,y \\leq n$$$, $$$x \\neq y$$$) indicating that $$$x$$$ and $$$y$$$ are friends. Each unordered pair $$$(x,y)$$$ appears at most once in each test case. It is guaranteed that both the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.", "output_spec": "For each test case, print a line containing a single integer \u2013 the minimum possible unhappiness value of a valid party.", "sample_inputs": ["4\n\n1 0\n\n1\n\n3 1\n\n2 1 3\n\n1 3\n\n5 5\n\n1 2 3 4 5\n\n1 2\n\n1 3\n\n1 4\n\n1 5\n\n2 3\n\n5 5\n\n1 1 1 1 1\n\n1 2\n\n2 3\n\n3 4\n\n4 5\n\n5 1"], "sample_outputs": ["0\n2\n3\n2"], "notes": "NoteIn the first test case, all members can be invited. So the unhappiness value is $$$0$$$.In the second test case, the following options are possible: invite $$$1$$$ and $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$); invite $$$2$$$ and $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$2$$$); invite only $$$1$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$4$$$); invite only $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$5$$$); invite only $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$); invite nobody ($$$0$$$ cakes eaten, unhappiness value equal to $$$6$$$). The minimum unhappiness value is achieved by inviting $$$2$$$ and $$$3$$$.In the third test case, inviting members $$$3,4,5$$$ generates a valid party with the minimum possible unhappiness value."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let a = Array.init n read_int in\n let edge = Array.make m (0,0) in\n let degree = Array.make n 0 in\n for i = 0 to m-1 do\n let (x,y) = read_pair() in\n let (x,y) = (x-1,y-1) in\n edge.(i) <- (x,y);\n degree.(x) <- 1+degree.(x);\n degree.(y) <- 1+degree.(y);\n done;\n\n let infty = max_int in\n\n if m mod 2 = 0 then (\n printf \"0\\n\";\n ) else (\n let option1 = minf 0 (n-1) (fun i ->\n\tif degree.(i) mod 2 = 1 then a.(i) else infty\n ) in\n\n let option2 = minf 0 (m-1) (fun e ->\n\tlet (x,y) = edge.(e) in\n\tif degree.(x) mod 2 = 0 && degree.(y) mod 2 = 0 then a.(x) + a.(y) else infty\n ) in\n let answer = min option1 option2 in\n printf \"%d\\n\" answer\n )\n done\n"}], "negative_code": [], "src_uid": "a9c54d6f952320d75324b30dcb098332"} {"nl": {"description": "You are given an integer array $$$a_1, a_2, \\ldots, a_n$$$.The array $$$b$$$ is called to be a subsequence of $$$a$$$ if it is possible to remove some elements from $$$a$$$ to get $$$b$$$.Array $$$b_1, b_2, \\ldots, b_k$$$ is called to be good if it is not empty and for every $$$i$$$ ($$$1 \\le i \\le k$$$) $$$b_i$$$ is divisible by $$$i$$$.Find the number of good subsequences in $$$a$$$ modulo $$$10^9 + 7$$$. Two subsequences are considered different if index sets of numbers included in them are different. That is, the values \u200bof the elements \u200bdo not matter in the comparison of subsequences. In particular, the array $$$a$$$ has exactly $$$2^n - 1$$$ different subsequences (excluding an empty subsequence).", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 100\\,000$$$)\u00a0\u2014 the length of the array $$$a$$$. The next line contains integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$).", "output_spec": "Print exactly one integer\u00a0\u2014 the number of good subsequences taken modulo $$$10^9 + 7$$$.", "sample_inputs": ["2\n1 2", "5\n2 2 1 22 14"], "sample_outputs": ["3", "13"], "notes": "NoteIn the first example, all three non-empty possible subsequences are good: $$$\\{1\\}$$$, $$$\\{1, 2\\}$$$, $$$\\{2\\}$$$In the second example, the possible good subsequences are: $$$\\{2\\}$$$, $$$\\{2, 2\\}$$$, $$$\\{2, 22\\}$$$, $$$\\{2, 14\\}$$$, $$$\\{2\\}$$$, $$$\\{2, 22\\}$$$, $$$\\{2, 14\\}$$$, $$$\\{1\\}$$$, $$$\\{1, 22\\}$$$, $$$\\{1, 14\\}$$$, $$$\\{22\\}$$$, $$$\\{22, 14\\}$$$, $$$\\{14\\}$$$.Note, that some subsequences are listed more than once, since they occur in the original array multiple times."}, "positive_code": [{"source_code": "(* equivalent to 1061C's solution with n,m are maximized *)\nlet divisors n =\n let rec f0 i a =\n if i*i > n then a\n else if i*i = n && n mod i = 0 then i::a\n else if n mod i = 0 then f0 (i+1) (i::(n/i)::a)\n else f0 (i+1) a\n in f0 1 []\nlet (++) u v = Int64.rem (Int64.add u v) 1000000007L\nexternal id : 'a -> 'a = \"%identity\"\nlet n = Scanf.scanf \" %d\" @@ id\nlet a = Array.init n (fun _ -> Scanf.scanf \" %d\" @@ id)\nlet dp = Array.make 1000007 0L\nlet () =\n Array.iter (fun v ->\n divisors v\n |> List.sort (fun u v -> compare v u)\n |> List.iter (fun d ->\n if d=1 then dp.(1) <- dp.(1) ++ 1L\n else dp.(d) <- dp.(d) ++ dp.(d-1)\n )\n ) a;\n Printf.printf \"%Ld\\n\" @@ Array.fold_left (++) 0L dp\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n(* let divisors v =\n let rec f0 i a =\n if i*i > v then a\n else if i*i = v && v mod i = 0L then i::a\n else if v mod i = 0L then f0 (i+1L) (i::(v/i)::a)\n else f0 (i+1L) a in f0 1L [] *)\nlet divisors n =\n let rec f0 i a =\n if i*$i > n then a\n else if i*$i = n && n %$ i = 0 then i::a\n else if n %$ i = 0 then f0 (i+$1) (i::(n/$i)::a)\n else f0 (i+$1) a\n in f0 1 []\nlet n = get_i64 0\nlet a = input_i64_array n\nlet dp = make 1000007 0L\nlet (++) u v = (u+v) mod 1000000007L\nlet () =\n iter (fun v ->\n i32 v\n |> divisors\n |> List.sort (fun u v -> compare v u)\n |> List.iter (fun d ->\n if d=1 then dp.(1) <- dp.(1) ++ 1L\n else dp.(d) <- dp.(d) ++ dp.(d-$1)\n )\n ) a;\n printf \"%Ld\\n\" @@ fold_left (++) 0L dp\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "587ac3b470aaacaa024a0c6dde134b7c"} {"nl": {"description": "There is a house with $$$n$$$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $$$n$$$ integer numbers $$$a_1, a_2, \\dots, a_n$$$, where $$$a_i = 1$$$ if in the $$$i$$$-th flat the light is on and $$$a_i = 0$$$ otherwise.Vova thinks that people in the $$$i$$$-th flats are disturbed and cannot sleep if and only if $$$1 < i < n$$$ and $$$a_{i - 1} = a_{i + 1} = 1$$$ and $$$a_i = 0$$$.Vova is concerned by the following question: what is the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number $$$k$$$.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$3 \\le n \\le 100$$$) \u2014 the number of flats in the house. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$a_i \\in \\{0, 1\\}$$$), where $$$a_i$$$ is the state of light in the $$$i$$$-th flat.", "output_spec": "Print only one integer \u2014 the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the light then nobody will be disturbed.", "sample_inputs": ["10\n1 1 0 1 1 0 1 0 1 0", "5\n1 1 0 0 0", "4\n1 1 1 1"], "sample_outputs": ["2", "0", "0"], "notes": "NoteIn the first example people from flats $$$2$$$ and $$$7$$$ or $$$4$$$ and $$$7$$$ can turn off the light and nobody will be disturbed. It can be shown that there is no better answer in this example.There are no disturbed people in second and third examples."}, "positive_code": [{"source_code": "(* Problem 2 of round 521*)\nopen Scanf;;\nopen String;;\nopen Num;;\n\n(*These are some utility functions*)\nmodule U = struct\n let mprint z =\n print_endline (Num.string_of_num z);;\n\n let read_one format =\n let n = Scanf.scanf format (fun x -> x) in\n n;;\n\n let read_one_number () =\n let n = read_one \"%d \" in\n n\n\n let read_array n a =\n for i = 0 to n - 1 do\n let n = read_one_number () in\n a.(i) <- n\n done\n\nend\n\n(*The solutions*)\n\nlet n = U.read_one_number ()\nlet a = Array.make n 0\nlet () = U.read_array n a\n\n(*test\nlet () =\n Array.iter (fun x-> print_int x; print_endline \"\" ) a\n*)\nlet () = \n let t = ref 0 in\n for i = 1 to n-2 do\n if a.(i)==0 then\n begin\n if a.(i-1)==1 && a.(i+1)==1 then\n begin\n a.(i+1) <- 0;\n incr t\n end\n end\n done;\n print_int !t; print_endline \"\"\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = get_i64 0 in\n let a = input_i64_array n in\n let r = ref 0L in\n rep 1L (n-2L) (fun i ->\n let i = i32 i in\n if a.(i-$1)=1L && a.(i)=0L && a.(i+$1)=1L then (\n r += 1L;\n a.(i+$1) <- 0L;\n )\n );\n printf \"%Ld\\n\" !r\n\n\n\n\n\n\n\n\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet n = scan_int ();;\nlet a = Array.make n 0;;\nfor i = 0 to (n - 1) do\n a.(i) <- (scan_int ());\ndone\n\nlet k = ref 0;;\nfor i = 1 to (n - 2) do\n if a.(i - 1) = 1 && a.(i) = 0 && a.(i + 1) = 1 then\n begin\n a.(i + 1) <- 0;\n incr k;\n end;\ndone;;\nprint_int !k;;\nprint_endline \"\";;"}], "negative_code": [], "src_uid": "ea62b6f68d25fb17aba8932af8377db0"} {"nl": {"description": "One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1,\u2009y1),\u2009(x2,\u2009y2),\u2009...,\u2009(xn,\u2009yn). Let's define neighbors for some fixed point from the given set (x,\u2009y): point (x',\u2009y') is (x,\u2009y)'s right neighbor, if x'\u2009>\u2009x and y'\u2009=\u2009y point (x',\u2009y') is (x,\u2009y)'s left neighbor, if x'\u2009<\u2009x and y'\u2009=\u2009y point (x',\u2009y') is (x,\u2009y)'s lower neighbor, if x'\u2009=\u2009x and y'\u2009<\u2009y point (x',\u2009y') is (x,\u2009y)'s upper neighbor, if x'\u2009=\u2009x and y'\u2009>\u2009y We'll consider point (x,\u2009y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.", "input_spec": "The first input line contains the only integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200) \u2014 the number of points in the given set. Next n lines contain the coordinates of the points written as \"x y\" (without the quotes) (|x|,\u2009|y|\u2009\u2264\u20091000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different.", "output_spec": "Print the only number \u2014 the number of supercentral points of the given set.", "sample_inputs": ["8\n1 1\n4 2\n3 1\n1 2\n0 2\n0 1\n1 0\n1 3", "5\n0 0\n0 1\n1 0\n0 -1\n-1 0"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample the supercentral points are only points (1,\u20091) and (1,\u20092).In the second sample there is one supercental point \u2014 point (0,\u20090)."}, "positive_code": [{"source_code": "let _ =\n let main () =\n let n = read_int () in\n let arr = Array.init n (fun i -> Scanf.sscanf (read_line ()) \"%d %d\" (fun x y -> x, y)) in\n let bits = Array.create n 0 in\n Array.iteri (fun i (x, y) ->\n Array.iteri (fun j (a, b) ->\n if a > x && y = b then bits.(j) <- bits.(j) lor 1; \n if a < x && y = b then bits.(j) <- bits.(j) lor 2; \n if a = x && y < b then bits.(j) <- bits.(j) lor 4; \n if a = x && y > b then bits.(j) <- bits.(j) lor 8; \n ) arr\n ) arr;\n Printf.printf \"%d\\n\" (Array.fold_left (fun acc k -> acc + k / 15) 0 bits)\n in\n main ()\n"}, {"source_code": "open Array;;\n(* Common part*)\nlet (|>) x f = f x\nlet identity = fun x -> x\n \nlet flip f y x = f x y\n \nlet readInStr _ = Scanf.scanf \"%d \" identity\nlet readIntLn _ = Scanf.scanf \"%d\\n\" identity\n(* Programme *)\nlet f x y = match x, y with (x,y,_), (x1,y1,_) -> if x=x1 then y-y1 else x-x1\nlet f1 x y = match x, y with (x,y,_), (x1,y1,_) -> if y=y1 then x-x1 else y-y1\n\nlet y arr n i = if i>=n then function _-> ()\n else function (x,y,z) ->\n match arr.(i+1)\n with (x1,y1,z1) when x1=x -> arr.(i)<-(x,y,z+1); arr.(i+1) <- (x1,y1,z1+1)\n | _ -> ()\n\nlet y1 arr n i = if i>=n then function _-> ()\n else function (x,y,z) ->\n match arr.(i+1)\n with (x1,y1,z1) when y=y1 -> arr.(i)<-(x,y,z+1); arr.(i+1) <- (x1,y1,z1+1)\n | _ -> ()\n\nlet main () =\n let n = readIntLn () in\n let arr = init n (function _ -> let a= readInStr () in (a, readIntLn (), 0) ) in\n fast_sort f arr;\n iteri (n-1|>y arr) arr;\n fast_sort f1 arr;\n iteri (n-1|>y1 arr) arr;\n fold_left (fun acc-> function (_,_,z) -> if z = 4 then (acc+1) else acc ) 0 arr |> print_int;\n ;;\nmain()"}, {"source_code": "let is_right_neighbor a b = (fst a) > (fst b) && (snd a) = (snd b)\nlet is_left_neighbor a b = (fst a) < (fst b) && (snd a) = (snd b)\nlet is_lower_neighbor a b = (fst a) = (fst b) && (snd a) < (snd b)\nlet is_upper_neighbor a b = (fst a) = (fst b) && (snd a) > (snd b)\n\nlet is_supercentral_point p points =\n List.exists (is_right_neighbor p) points &&\n List.exists (is_left_neighbor p) points &&\n List.exists (is_lower_neighbor p) points &&\n List.exists (is_upper_neighbor p) points\n\nlet solve points =\n let count accum p =\n if is_supercentral_point p points then accum+1\n else accum\n in\n List.fold_left count 0 points\n\nlet rec read_n_tuples n lst =\n if n = 0 then lst\n else read_n_tuples (n-1) ((Scanf.scanf \" %d %d\" (fun x y -> (x, y))) :: lst)\n \nlet _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let points = read_n_tuples n [] in\n Printf.printf \"%d\\n\" (solve points)\n \n"}], "negative_code": [{"source_code": "open Array;;\n(* Common part*)\nlet (|>) x f = f x\nlet identity = fun x -> x\n \nlet flip f y x = f x y\n \nlet readInStr _ = Scanf.scanf \"%d \" identity\nlet readIntLn _ = Scanf.scanf \"%d\\n\" identity\n(* Programme *)\nlet f x y = match x, y with (x,y,z), (x1,y1,z1) -> if x=x1 then y-y1 else x-x1\n\nlet y arr n i = if i>=n then function _-> ()\n else function (x,y,z) ->\n match arr.(i+1)\n with (x1,y1,z1) when x1=x -> arr.(i)<-(x,y,z+1); arr.(i+1) <- (x1,y1,z1+1)\n | _ -> ()\n\nlet main () =\n let n = readIntLn () in\n let arr = init n (function _ -> let a= readInStr () in (a, readIntLn (), 0) ) in\n fast_sort f arr;\n iteri (n-1|>y arr) arr;\n fast_sort (flip f) arr;\n iteri (n-1|>y arr) arr;\n fold_left (fun acc-> function (_,_,z) -> if z = 4 then (acc+1) else acc ) 0 arr |> print_int;\n ;;\nmain()\n"}], "src_uid": "594e64eef7acd055d59f37710edda201"} {"nl": {"description": "You are given a sequence of positive integers a1,\u2009a2,\u2009...,\u2009an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).", "input_spec": "The first line contains the integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The second line contains elements of the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20091000). All the elements are positive integers.", "output_spec": "Print on the first line the number of the sought indices. Print on the second line the sought indices in the increasing order. All indices are integers from 1 to n. If the sought elements do not exist, then the first output line should contain number 0. In this case you may either not print the second line or print an empty line.", "sample_inputs": ["5\n1 2 3 4 5", "4\n50 50 50 50"], "sample_outputs": ["1\n3", "4\n1 2 3 4"], "notes": null}, "positive_code": [{"source_code": "open Str;;\nopen Array;;\nopen String;;\n\nlet split sep =\n\tlet re = Str.regexp sep in\n\tStr.split re\n;;\n\nlet rec range a b =\n\tif a = b then [] else a :: range (a+1) b\n;;\n\nlet (!!) ls n =\n\tList.nth ls n\n;;\n\nlet main =\n\tlet len = read_int()\n\tand nums = Array.map float_of_string (Array.of_list (split \" \" (read_line()))) in\n\tlet sum = Array.fold_left (+.) 0. nums in\n\tlet ln = ref 0 in\n\tlet indexes = Array.mapi (fun i x ->\n\t\tif (sum -. x) /. (float_of_int (len-1)) = x then begin\n\t\t\tincr ln;\n\t\t\ti + 1\n\t\tend else\n\t\t\t0\n\t) nums in\n\tlet _ = print_int (!ln) in\n\tlet _ = print_string \"\\n\" in\n\tArray.iter (fun i ->\n\t\tif i > 0 then\n\t\t\tlet _ = print_int i in\n\t\t\tprint_string \" \"\n\t) indexes\n;;\n"}, {"source_code": "let rec input_seq n lst =\n if n <= 1 then (Scanf.scanf \"%d\\n\" (fun x -> x)) :: lst\n else input_seq (n - 1) ((Scanf.scanf \"%d \" (fun x -> x)) :: lst)\n\nlet input_seq n = List.rev (input_seq n [])\n \nlet solve n =\n let seq = input_seq n in\n let sum = List.fold_left (+) 0 seq in\n let rec loop lst accm cnt = match lst with \n | [] -> accm\n | first :: rest\n\t-> if first * n == sum then loop rest (cnt::accm) (cnt+1)\n\t else loop rest accm (cnt+1)\n in\n loop seq [] 1\n\nlet rec print_int_list = function\n | [] -> Printf.printf \"\\n\"\n | lst :: [] -> Printf.printf \"%d\\n\" lst\n | first :: rest ->\n begin\n Printf.printf \"%d \" first;\n print_int_list rest\n end\n \nlet _ =\n let ans = Scanf.scanf \"%d\\n\" solve in\n Printf.printf \"%d\\n\" (List.length ans);\n if List.length ans != 0 then print_int_list (List.rev ans)\n \n"}], "negative_code": [{"source_code": "open Str;;\nopen Array;;\nopen String;;\n\nlet split sep =\n\tlet re = Str.regexp sep in\n\tStr.split re\n;;\n\nlet rec range a b =\n\tif a = b then [] else a :: range (a+1) b\n;;\n\nlet (!!) ls n =\n\tList.nth ls n\n;;\n\nlet main =\n\tlet len = read_int()\n\tand nums = Array.map float_of_string (Array.of_list (split \" \" (read_line()))) in\n\tlet sum = Array.fold_left (+.) 0. nums in\n\tlet indexes = List.filter (fun i ->\n\t\t(sum -. nums.(i)) /. (float_of_int (len-1)) = nums.(i)\n\t) (range 0 len) in\n\tlet _ = print_int (List.length indexes) in\n\tlet _ = print_string \"\\n\" in\n\tprint_string (String.concat \" \" (List.map (fun x ->string_of_int (x+1)) indexes))\n;;\n"}, {"source_code": "open Str;;\nopen List;;\n\nlet split sep =\n\tlet re = Str.regexp sep in\n\tStr.split re\n;;\n\nlet rec range a b =\n\tif a = b then [] else a :: range (a+1) b\n;;\n\nlet (!!) ls n =\n\tList.nth ls n\n;;\n\nlet main =\n\tlet len = read_int()\n\tand nums = List.map float_of_string (split \" \" (read_line())) in\n\tlet sum = List.fold_left (+.) 0. nums in\n\tlet avg = sum /. (float_of_int len) in\n\tlet indexes = List.filter (fun i ->\n\t\t(sum -. (List.nth nums i)) /. (float_of_int (len-1)) = List.nth nums i\n\t) (range 0 len) in\n\tlet _ = print_int (List.length indexes) in\n\tlet _ = print_string \"\\n\" in\n\tList.iter (fun i -> print_int (i+1); print_string \" \") indexes\n;;\n"}, {"source_code": "open Str;;\nopen List;;\n\nlet split sep =\n\tlet re = Str.regexp sep in\n\tStr.split re\n;;\n\nlet rec range a b =\n\tif a = b then [] else a :: range (a+1) b\n;;\n\nlet (!!) ls n =\n\tList.nth ls n\n;;\n\nlet main =\n\tlet len = read_int()\n\tand nums = List.map int_of_string (split \" \" (read_line())) in\n\tlet sum = List.fold_left (+) 0 nums in\n\tlet avg = sum / len in\n\tlet indexes = List.filter (fun i ->\n\t\tavg = List.nth nums i\n\t) (range 0 len) in\n\tlet _ = print_int (List.length indexes) in\n\tlet _ = print_string \"\\n\" in\n\tList.iter (fun i -> print_int (i+1); print_string \" \") indexes\n;;\n"}, {"source_code": "open Str;;\nopen List;;\nopen String;;\n\nlet split sep =\n\tlet re = Str.regexp sep in\n\tStr.split re\n;;\n\nlet rec range a b =\n\tif a = b then [] else a :: range (a+1) b\n;;\n\nlet (!!) ls n =\n\tList.nth ls n\n;;\n\nlet main =\n\tlet len = read_int()\n\tand nums = List.map float_of_string (split \" \" (read_line())) in\n\tlet sum = List.fold_left (+.) 0. nums in\n\tlet avg = sum /. (float_of_int len) in\n\tlet indexes = List.filter (fun i ->\n\t\t(sum -. (List.nth nums i)) /. (float_of_int (len-1)) = List.nth nums i\n\t) (range 0 len) in\n\tlet _ = print_int (List.length indexes) in\n\tlet _ = print_string \"\\n\" in\n\tprint_string (String.concat \" \" (List.map (fun x ->string_of_int (x+1)) indexes))\n;;\n"}, {"source_code": "let rec input_seq n lst =\n if n <= 1 then (Scanf.scanf \"%d\\n\" (fun x -> x)) :: lst\n else input_seq (n - 1) ((Scanf.scanf \"%d \" (fun x -> x)) :: lst)\n\nlet input_seq n = List.rev (input_seq n [])\n \nlet solve n =\n let seq = input_seq n in\n let sum = List.fold_left (+) 0 seq in\n let rec loop lst accm cnt = match lst with \n | [] -> accm\n | first :: rest\n\t-> if (sum-first) / (n - 1) == first then loop rest (cnt::accm) (cnt+1)\n\t else loop rest accm (cnt+1)\n in\n loop seq [] 1\n\nlet rec print_int_list = function\n | [] -> Printf.printf \"\\n\"\n | lst :: [] -> Printf.printf \"%d\\n\" lst\n | first :: rest ->\n begin\n Printf.printf \"%d \" first;\n print_int_list rest\n end\n \nlet _ =\n let ans = Scanf.scanf \"%d\\n\" solve in\n Printf.printf \"%d\\n\" (List.length ans);\n if List.length ans != 0 then print_int_list (List.rev ans)\n \n"}, {"source_code": "let rec input_seq n lst =\n if n <= 1 then (Scanf.scanf \"%d\\n\" (fun x -> x)) :: lst\n else input_seq (n - 1) ((Scanf.scanf \"%d \" (fun x -> x)) :: lst)\n\nlet input_seq n = List.rev (input_seq n [])\n \nlet solve n =\n let seq = input_seq n in\n let sum = List.fold_left (+) 0 seq in\n let rec loop lst accm cnt = match lst with \n | [] -> accm\n | first :: rest\n\t-> if (sum-first) / (n - 1) == first then loop rest (cnt::accm) (cnt+1)\n\t else loop rest accm (cnt+1)\n in\n loop seq [] 1\n\nlet rec print_int_list = function\n | [] -> Printf.printf \"\\n\"\n | lst :: [] -> Printf.printf \"%d\\n\" lst\n | first :: rest ->\n begin\n Printf.printf \"%d \" first;\n print_int_list rest\n end\n \nlet _ =\n let ans = Scanf.scanf \"%d\\n\" solve in\n Printf.printf \"%d\\n\" (List.length ans);\n print_int_list (List.rev ans)\n \n"}], "src_uid": "1a22bc82ddf6b3dfbf270bc5e3294c28"} {"nl": {"description": "Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.Initially, each mole i (1\u2009\u2264\u2009i\u2009\u2264\u20094n) is placed at some position (xi,\u2009yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.Each mole i has a home placed at the position (ai,\u2009bi). Moving this mole one time means rotating his position point (xi,\u2009yi) 90 degrees counter-clockwise around it's home point (ai,\u2009bi).A regiment is compact only if the position points of the 4 moles form a square with non-zero area.Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), the number of regiments. The next 4n lines contain 4 integers xi, yi, ai, bi (\u2009-\u2009104\u2009\u2264\u2009xi,\u2009yi,\u2009ai,\u2009bi\u2009\u2264\u2009104).", "output_spec": "Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print \"-1\" (without quotes).", "sample_inputs": ["4\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-2 1 0 0\n-1 1 0 0\n1 -1 0 0\n1 1 0 0\n-1 1 0 0\n-1 1 0 0\n-1 1 0 0\n2 2 0 1\n-1 0 0 -2\n3 0 0 -2\n-1 1 -2 0"], "sample_outputs": ["1\n-1\n3\n3"], "notes": "NoteIn the first regiment we can move once the second or the third mole.We can't make the second regiment compact.In the third regiment, from the last 3 moles we can move once one and twice another one.In the fourth regiment, we can move twice the first mole and once the third mole."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair_double () = let u = 4*read_int() in (u,4*read_int())\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet (++) (a,b) (c,d) = (a+c, b+d)\nlet (--) (a,b) (c,d) = (a-c, b-d)\n\nlet rotate (x,y) (x0,y0) = (* rotate (x,y) counterclock around (x0,y0) *)\n let (x,y) = (x,y) -- (x0,y0) in\n let (x,y) = (-y,x) in\n (x,y) ++ (x0,y0)\n\nlet () = \n let n = read_int () in\n\n let issquare p = (* p is an array of 4 points. Is it a square? *)\n let rec inp a i = (i<4) && (p.(i) = a || inp a (i+1)) in\n\n let (cx,cy) = p.(0) ++ p.(1) ++ p.(2) ++ p.(3) in\n let c = (cx/4, cy/4) in\n p.(0) <> p.(1) && forall 0 3 (fun i -> inp (rotate p.(i) c) 0)\n in\n\n let solve p h = \n let found = ref 1000 in\n let blah i = p.(i) <- rotate p.(i) h.(i) in\n for i1 = 0 to 3 do\n for i2 = 0 to 3 do\n\tfor i3 = 0 to 3 do\n\t for i4 = 0 to 3 do\n\t if issquare p then found := min !found (i1+i2+i3+i4);\n\t blah 3\n\t done;\n\t blah 2\n\tdone;\n\tblah 1\n done;\n blah 0\n done;\n if !found = 1000 then -1 else !found\n in\n \n for i=0 to n-1 do\n let p = Array.make 4 (0,0) in\n let h = Array.make 4 (0,0) in\n for j=0 to 3 do\n p.(j) <- read_pair_double ();\n h.(j) <- read_pair_double ();\n done;\n \n printf \"%d\\n\" (solve p h)\n done;\n"}], "negative_code": [], "src_uid": "41d791867f27a57b50eebaad29754520"} {"nl": {"description": "There always is something to choose from! And now, instead of \"Noughts and Crosses\", Inna choose a very unusual upgrade of this game. The rules of the game are given below:There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: \"X\" or \"O\". Then the player chooses two positive integers a and b (a\u00b7b\u2009=\u200912), after that he makes a table of size a\u2009\u00d7\u2009b from the cards he put on the table as follows: the first b cards form the first row of the table, the second b cards form the second row of the table and so on, the last b cards form the last (number a) row of the table. The player wins if some column of the table contain characters \"X\" on all cards. Otherwise, the player loses.Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers a and b to choose. Help her win the game: print to her all the possible ways of numbers a,\u2009b that she can choose and win.", "input_spec": "The first line of the input contains integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009100). This value shows the number of sets of test data in the input. Next follows the description of each of the t tests on a separate line. The description of each test is a string consisting of 12 characters, each character is either \"X\", or \"O\". The i-th character of the string shows the character that is written on the i-th card from the start.", "output_spec": "For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair a,\u2009b. Next, print on this line the pairs in the format axb. Print the pairs in the order of increasing first parameter (a). Separate the pairs in the line by whitespaces.", "sample_inputs": ["4\nOXXXOXOOXOOX\nOXOXOXOXOXOX\nXXXXXXXXXXXX\nOOOOOOOOOOOO"], "sample_outputs": ["3 1x12 2x6 4x3\n4 1x12 2x6 3x4 6x2\n6 1x12 2x6 3x4 4x3 6x2 12x1\n0"], "notes": null}, "positive_code": [{"source_code": "let n=read_int();;\n\nlet test a b s=\n let m=Array.make_matrix (a+1) (b+1) ' ' in\n for i=1 to a do\n for j=1 to b do\n m.(i).(j)<-s.[(i-1)*b+j-1]\n done\n done;\n let boo=ref false in\n for i=1 to b do\n let aux=ref true in\n for j=1 to a do\n if m.(j).(i)<>'X' then aux:=false\n done;\n boo:= !boo|| !aux\n done;\n!boo;;\n\nlet rec nb=function\n|[]->0\n|(_,b)::t->if b then 1+nb t else nb t;;\n\nlet rec print_list=function\n|[]->()\n|(s,b)::t->if b then print_string s;print_list t;;\n\nlet tab=Array.make (n+1) \" \";;\n\nfor i=1 to n do\n tab.(i)<-read_line()\ndone;;\n\nfor i=1 to n do\n let s=tab.(i) in\n let r a b=(\" \"^string_of_int(a)^\"x\"^string_of_int(b),test a b s) in\n let sol=[r 1 12;r 2 6;r 3 4;r 4 3;r 6 2;r 12 1] in\n print_int (nb sol);\n print_list sol;\n print_newline()\ndone;;\n \n "}], "negative_code": [], "src_uid": "b669a42ff477a62ec02dcfb87e1e60bd"} {"nl": {"description": "You have array of $$$n$$$ numbers $$$a_{1}, a_{2}, \\ldots, a_{n}$$$. Rearrange these numbers to satisfy $$$|a_{1} - a_{2}| \\le |a_{2} - a_{3}| \\le \\ldots \\le |a_{n-1} - a_{n}|$$$, where $$$|x|$$$ denotes absolute value of $$$x$$$. It's always possible to find such rearrangement.Note that all numbers in $$$a$$$ are not necessarily different. In other words, some numbers of $$$a$$$ may be same.You have to answer independent $$$t$$$ test cases.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^{4}$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$3 \\le n \\le 10^{5}$$$)\u00a0\u2014 the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \\ldots, a_{n}$$$ ($$$-10^{9} \\le a_{i} \\le 10^{9}$$$).", "output_spec": "For each test case, print the rearranged version of array $$$a$$$ which satisfies given condition. If there are multiple valid rearrangements, print any of them.", "sample_inputs": ["2\n6\n5 -2 4 8 6 5\n4\n8 1 4 2"], "sample_outputs": ["5 5 4 6 8 -2\n1 2 4 8"], "notes": "NoteIn the first test case, after given rearrangement, $$$|a_{1} - a_{2}| = 0 \\le |a_{2} - a_{3}| = 1 \\le |a_{3} - a_{4}| = 2 \\le |a_{4} - a_{5}| = 2 \\le |a_{5} - a_{6}| = 10$$$. There are other possible answers like \"5 4 5 6 -2 8\".In the second test case, after given rearrangement, $$$|a_{1} - a_{2}| = 1 \\le |a_{2} - a_{3}| = 2 \\le |a_{3} - a_{4}| = 4$$$. There are other possible answers like \"2 4 8 1\"."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n Array.sort compare a;\n let rec loop i j side ac = if i>j then ac else (\n if side = 0 then loop (i+1) j (1-side) (a.(i)::ac)\n else loop i (j-1) (1-side) (a.(j)::ac)\n )\n in\n List.iter (printf \"%d \") (loop 0 (n-1) 1 []);\n print_newline()\n done\n"}], "negative_code": [], "src_uid": "3c8bfd3199a9435cfbdee1daaacbd1b3"} {"nl": {"description": "There are $$$n$$$ people participating in some contest, they start participating in $$$x$$$ minutes intervals. That means the first participant starts at time $$$0$$$, the second participant starts at time $$$x$$$, the third\u00a0\u2014 at time $$$2 \\cdot x$$$, and so on.Duration of contest is $$$t$$$ minutes for each participant, so the first participant finishes the contest at time $$$t$$$, the second\u00a0\u2014 at time $$$t + x$$$, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants.", "input_spec": "The first line contains a single integer $$$k$$$ ($$$1 \\le k \\le 1000$$$)\u00a0\u2014 the number of test cases. Each of the next $$$k$$$ lines contains three integers $$$n$$$, $$$x$$$, $$$t$$$ ($$$1 \\le n, x, t \\le 2 \\cdot 10^9$$$)\u00a0\u2014 the number of participants, the start interval and the contest duration.", "output_spec": "Print $$$k$$$ lines, in the $$$i$$$-th line print the total dissatisfaction of participants in the $$$i$$$-th test case.", "sample_inputs": ["4\n4 2 5\n3 1 2\n3 3 10\n2000000000 1 2000000000"], "sample_outputs": ["5\n3\n3\n1999999999000000000"], "notes": "NoteIn the first example the first participant starts at $$$0$$$ and finishes at time $$$5$$$. By that time the second and the third participants start, so the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$2$$$ and finishes at time $$$7$$$. By that time the third the fourth participants start, so the dissatisfaction of the second participant is $$$2$$$. The third participant starts at $$$4$$$ and finishes at $$$9$$$. By that time the fourth participant starts, so the dissatisfaction of the third participant is $$$1$$$.The fourth participant starts at $$$6$$$ and finishes at $$$11$$$. By time $$$11$$$ everyone finishes the contest, so the dissatisfaction of the fourth participant is $$$0$$$.In the second example the first participant starts at $$$0$$$ and finishes at time $$$2$$$. By that time the second participants starts, and the third starts at exactly time $$$2$$$. So the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$1$$$ and finishes at time $$$3$$$. At that time the third participant is solving the contest."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %Ld\" (fun x -> x);;\r\n \r\nlet print x = Printf.fprintf stdout \"%Ld\\n\" x;;\r\n \r\nlet cal n x t =\r\n let k = Int64.div t x in\r\n if k < n then \r\n let p1 = Int64.mul (Int64.sub n k) k in\r\n let p2 = Int64.mul k (Int64.sub k 1L) in\r\n Int64.add p1 (Int64.div p2 2L)\r\n else\r\n Int64.div (Int64.mul n (Int64.sub n 1L)) 2L\r\n \r\nlet t = read_int ();;\r\n \r\nlet () =\r\n for i = 1 to t do\r\n let n = scan_int () in\r\n let x = scan_int () in\r\n let t = scan_int () in\r\n print (cal n x t)\r\n done"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %Ld\" (fun x -> x);;\r\n \r\nlet print x = Printf.fprintf stdout \"%Ld\\n\" x;;\r\n \r\nlet cal n x t =\r\n let k = Int64.div t x in\r\n let p1 = Int64.mul (Int64.sub n k) k in\r\n let p2 = Int64.mul k (Int64.sub k 1L) in\r\n Int64.add p1 (Int64.div p2 2L);;\r\n \r\nlet t = read_int ();;\r\n \r\nlet () =\r\n for i = 1 to t do\r\n let n = scan_int () in\r\n let x = scan_int () in\r\n let t = scan_int () in\r\n print (cal n x t)\r\n done"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\nlet print x = Printf.printf \"%lld\\n\" x;;\r\n\r\nlet cal n x t =\r\n let k = t / x in\r\n (n - k) * k + k * (k - 1) / 2;;\r\n\r\n\r\nlet t = scan_int ();;\r\n\r\nlet () =\r\n for i = 1 to t - 1 do\r\n let n = scan_int () in\r\n let x = scan_int () in\r\n let t = scan_int () in\r\n print (cal n x t)\r\n done"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\nlet print x = Printf.printf \"%d\\n\" x;;\r\n\r\nlet cal n x t =\r\n let k = t / x in\r\n (n - k) * k + k * (k - 1) / 2;;\r\n\r\n\r\nlet t = scan_int ();;\r\n\r\nlet () =\r\n for i = 1 to t do\r\n print i\r\n done"}], "src_uid": "4df38c9b42b0f0963a121829080d3571"} {"nl": {"description": "Vivek has encountered a problem. He has a maze that can be represented as an $$$n \\times m$$$ grid. Each of the grid cells may represent the following: Empty\u00a0\u2014 '.' Wall\u00a0\u2014 '#' Good person \u00a0\u2014 'G' Bad person\u00a0\u2014 'B' The only escape from the maze is at cell $$$(n, m)$$$.A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.It is guaranteed that the cell $$$(n,m)$$$ is empty. Vivek can also block this cell.", "input_spec": "The first line contains one integer $$$t$$$ $$$(1 \\le t \\le 100)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \\le n, m \\le 50)$$$\u00a0\u2014 the number of rows and columns in the maze. Each of the next $$$n$$$ lines contain $$$m$$$ characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.", "output_spec": "For each test case, print \"Yes\" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print \"No\" You may print every letter in any case (upper or lower).", "sample_inputs": ["6\n1 1\n.\n1 2\nG.\n2 2\n#B\nG.\n2 3\nG.#\nB#.\n3 3\n#B.\n#..\nGG.\n2 2\n#B\nB."], "sample_outputs": ["Yes\nYes\nNo\nNo\nYes\nYes"], "notes": "NoteFor the first and second test cases, all conditions are already satisfied.For the third test case, there is only one empty cell $$$(2,2)$$$, and if it is replaced with a wall then the good person at $$$(1,2)$$$ will not be able to escape.For the fourth test case, the good person at $$$(1,1)$$$ cannot escape.For the fifth test case, Vivek can block the cells $$$(2,3)$$$ and $$$(2,2)$$$.For the last test case, Vivek can block the destination cell $$$(2, 2)$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let board = Array.init n read_string in\n let getb i j = board.(i).[j] in\n let mm = Array.make_matrix n m 'x' in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tmm.(i).(j) <- getb i j\n done\n done;\n\n let inbounds i j =\n 0 <= i && i < n && 0 <= j && j < m \n in\n\n let okmove di dj = (abs di) + (abs dj) = 1 in\n\n let adj = ref false in\n \n for i=0 to n-1 do\n for j=0 to m-1 do\n\tif getb i j = 'B' then (\n\t for di = -1 to 1 do\n\t for dj = -1 to 1 do\n\t let (i',j') = (i+di, j+dj) in\n\t if okmove di dj && inbounds i' j' then (\n\t\tif getb i' j' = '.' then mm.(i').(j') <- '#';\n\t\tif getb i' j' = 'G' then adj := true\n\t )\n\t done\n\t done\n\t)\n done\n done;\n\n let getm i j = mm.(i).(j) in\n\n (* can we reach all Gs from destination? *)\n\n let reached = Array.make_matrix n m false in\n \n let grow li =\n let newli = ref [] in\n List.iter (fun (i,j) ->\n\tfor di = -1 to 1 do\n\t for dj = -1 to 1 do\n\t let (i',j') = (i + di, j+dj) in\n\t if okmove di dj && inbounds i' j' && (not reached.(i').(j')) && getm i' j' <> '#' then (\n\t reached.(i').(j') <- true;\n\t newli := (i',j'):: !newli\n\t )\n\t done\n\tdone\n ) li;\n !newli\n in\n\n let rec loop li =\n if li <> [] then loop (grow li)\n in\n\n loop [(n-1,m-1)];\n\n let works = ref true in\n let existsG = ref false in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tif getb i j = 'G' && (not reached.(i).(j)) then works := false;\n\tif getb i j = 'G' then existsG := true\n done\n done;\n\n if (not !existsG) || ((not !adj) && !works && getm (n-1) (m-1) <> '#')\n then printf \"Yes\\n\" else printf \"No\\n\"\n done\n\n (* finished 18 minutes late *)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let board = Array.init n read_string in\n let getb i j = board.(i).[j] in\n let mm = Array.make_matrix n m 'x' in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tmm.(i).(j) <- getb i j\n done\n done;\n\n let inbounds i j =\n 0 <= i && i < n && 0 <= j && j < m \n in\n\n let okmove di dj = (abs di) + (abs dj) = 1 in\n \n for i=0 to n-1 do\n for j=0 to m-1 do\n\tif getb i j = 'B' then (\n\t for di = -1 to 1 do\n\t for dj = -1 to 1 do\n\t let (i',j') = (i + di, j+dj) in\n\t if okmove di dj && inbounds i' j' then (\n\t\tif (i',j') <> (i,j) && (getb i' j' = '.') then\n\t\t mm.(i').(j') <- '#'\n\t )\n\t done\n\t done\n\t)\n done\n done;\n\n let getm i j = mm.(i).(j) in\n\n (* can we reach all Gs from destination? *)\n\n let reached = Array.make_matrix n m false in\n \n let grow li =\n let newli = ref [] in\n List.iter (fun (i,j) ->\n\tfor di = -1 to 1 do\n\t for dj = -1 to 1 do\n\t let (i',j') = (i + di, j+dj) in\n\t if okmove di dj && inbounds i' j' && (not reached.(i').(j')) && getm i' j' <> '#' then (\n\t reached.(i').(j') <- true;\n\t newli := (i',j'):: !newli\n\t )\n\t done\n\tdone\n ) li;\n !newli\n in\n\n let rec loop li =\n if li <> [] then loop (grow li)\n in\n\n loop [(n-1,m-1)];\n\n let works = ref true in\n let existsG = ref false in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tif getb i j = 'G' && (not reached.(i).(j)) then works := false;\n\tif getb i j = 'G' then existsG := true\n done\n done;\n\n if (not !existsG) || (!works && getm (n-1) (m-1) <> '#')\n then printf \"Yes\\n\" else printf \"No\\n\"\n done\n\n (* finished 18 minutes late *)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let board = Array.init n read_string in\n let getb i j = board.(i).[j] in\n let mm = Array.make_matrix n m 'x' in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tmm.(i).(j) <- getb i j\n done\n done;\n\n let inbounds i j =\n 0 <= i && i < n && 0 <= j && j < m \n in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tif getb i j = 'B' then (\n\t for di = -1 to 1 do\n\t for dj = -1 to 1 do\n\t let (i',j') = (i + di, j+dj) in\n\t if inbounds i' j' then (\n\t\tif (i',j') <> (i,j) && (getb i' j' = '.') then\n\t\t mm.(i').(j') <- '#'\n\t )\n\t done\n\t done\n\t)\n done\n done;\n\n let getm i j = mm.(i).(j) in\n\n (* can we reach all Gs from destination? *)\n\n let reached = Array.make_matrix n m false in\n \n let grow li =\n let newli = ref [] in\n List.iter (fun (i,j) ->\n\tfor di = -1 to 1 do\n\t for dj = -1 to 1 do\n\t let (i',j') = (i + di, j+dj) in\n\t if inbounds i' j' && (not reached.(i').(j')) && getm i' j' <> '#' then (\n\t reached.(i').(j') <- true;\n\t newli := (i',j'):: !newli\n\t )\n\t done\n\tdone\n ) li;\n !newli\n in\n\n let rec loop li =\n if li <> [] then loop (grow li)\n in\n\n loop [(n-1,m-1)];\n\n let works = ref true in\n let existsG = ref false in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tif getb i j = 'G' && (not reached.(i).(j)) then works := false;\n\tif getb i j = 'G' then existsG := true\n done\n done;\n\n if (not !existsG) || (!works && getm (n-1) (m-1) <> '#')\n then printf \"Yes\\n\" else printf \"No\\n\"\n done\n\n (* finished 18 minutes late *)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let board = Array.init n read_string in\n let getb i j = board.(i).[j] in\n let mm = Array.make_matrix n m 'x' in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tmm.(i).(j) <- getb i j\n done\n done;\n\n if case=63 then (\n\tprintf \"%s %s\\n\" board.(0) board.(1)\n ) ;\n\n let inbounds i j =\n 0 <= i && i < n && 0 <= j && j < m \n in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tif getb i j = 'B' then (\n\t for di = -1 to 1 do\n\t for dj = -1 to 1 do\n\t let (i',j') = (i + di, j+dj) in\n\t if inbounds i' j' then (\n\t\tif (i',j') <> (i,j) && (getb i' j' = '.') then\n\t\t mm.(i').(j') <- '#'\n\t )\n\t done\n\t done\n\t)\n done\n done;\n\n let getm i j = mm.(i).(j) in\n\n (* can we reach all Gs from destination? *)\n\n let reached = Array.make_matrix n m false in\n \n let grow li =\n let newli = ref [] in\n List.iter (fun (i,j) ->\n\tfor di = -1 to 1 do\n\t for dj = -1 to 1 do\n\t let (i',j') = (i + di, j+dj) in\n\t if inbounds i' j' && (not reached.(i').(j')) && getm i' j' <> '#' then (\n\t reached.(i').(j') <- true;\n\t newli := (i',j'):: !newli\n\t )\n\t done\n\tdone\n ) li;\n !newli\n in\n\n let rec loop li =\n if li <> [] then loop (grow li)\n in\n\n loop [(n-1,m-1)];\n\n let works = ref true in\n let existsG = ref false in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n\tif getb i j = 'G' && (not reached.(i).(j)) then works := false;\n\tif getb i j = 'G' then existsG := true\n done\n done;\n\n if (not !existsG) || (!works && getm (n-1) (m-1) <> '#')\n then printf \"Yes\\n\" else printf \"No\\n\"\n done\n\n (* finished 18 minutes late *)\n"}], "src_uid": "a5e649f4d984a5c5365ca31436ad5883"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.You are allowed to perform this operation any number of times (possibly, zero): choose an index $$$i$$$ ($$$2 \\le i \\le n$$$), and change $$$a_i$$$ to $$$a_i - a_{i-1}$$$. Is it possible to make $$$a_i=0$$$ for all $$$2\\le i\\le n$$$?", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 100$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line contains one integer $$$n$$$ ($$$2 \\le n \\le 100$$$)\u00a0\u2014 the length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1 \\le a_i \\le 10^9$$$).", "output_spec": "For each test case, print \"YES\" (without quotes), if it is possible to change $$$a_i$$$ to $$$0$$$ for all $$$2 \\le i \\le n$$$, and \"NO\" (without quotes) otherwise. You can print letters in any case (upper or lower).", "sample_inputs": ["4\n\n2\n\n5 10\n\n3\n\n1 2 3\n\n4\n\n1 1 1 1\n\n9\n\n9 9 8 2 4 4 3 5 3"], "sample_outputs": ["YES\nYES\nYES\nNO"], "notes": "NoteIn the first test case, the initial array is $$$[5,10]$$$. You can perform $$$2$$$ operations to reach the goal: Choose $$$i=2$$$, and the array becomes $$$[5,5]$$$. Choose $$$i=2$$$, and the array becomes $$$[5,0]$$$. In the second test case, the initial array is $$$[1,2,3]$$$. You can perform $$$4$$$ operations to reach the goal: Choose $$$i=3$$$, and the array becomes $$$[1,2,1]$$$. Choose $$$i=2$$$, and the array becomes $$$[1,1,1]$$$. Choose $$$i=3$$$, and the array becomes $$$[1,1,0]$$$. Choose $$$i=2$$$, and the array becomes $$$[1,0,0]$$$. In the third test case, you can choose indices in the order $$$4$$$, $$$3$$$, $$$2$$$."}, "positive_code": [{"source_code": "(* From @Darooha's code (https://codeforces.com/profile/Darooha) *)\r\n\r\nopen Printf \r\nopen Scanf\r\n \r\nlet ( ** ) a b = Int64.mul a b\r\nlet ( ++ ) a b = Int64.add a b\r\nlet long x = Int64.of_int x\r\nlet short x = Int64.to_int x\r\n \r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\r\n \r\n(* Main Code file *)\r\n\r\nlet rec sum = function\r\n | [] -> 0\r\n | h::t -> h + sum(t)\r\n \r\nlet rec all = function\r\n | [] -> true\r\n | h::t -> if h then all(t) else false\r\n \r\nlet divis a b = b mod a = 0\r\n\r\nlet () = \r\n let t = read_int() in\r\n for i=1 to t do\r\n let n = read_int() in\r\n let arr = Array.init n read_int in\r\n if all (Array.to_list (Array.map (divis arr.(0)) arr)) \r\n then printf \"Yes\\n\"\r\n else printf \"No\\n\"\r\n done;"}], "negative_code": [], "src_uid": "1c597da89880e87ffe791dd6b9fb2ac7"} {"nl": {"description": "User ainta loves to play with cards. He has a cards containing letter \"o\" and b cards containing letter \"x\". He arranges the cards in a row, and calculates the score of the deck by the formula below. At first, the score is 0. For each block of contiguous \"o\"s with length x the score increases by x2. For each block of contiguous \"x\"s with length y the score decreases by y2. \u00a0For example, if a\u2009=\u20096,\u2009b\u2009=\u20093 and ainta have arranged the cards in the order, that is described by string \"ooxoooxxo\", the score of the deck equals 22\u2009-\u200912\u2009+\u200932\u2009-\u200922\u2009+\u200912\u2009=\u20099. That is because the deck has 5 blocks in total: \"oo\", \"x\", \"ooo\", \"xx\", \"o\".User ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards.", "input_spec": "The first line contains two space-separated integers a and b (0\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009105;\u00a0a\u2009+\u2009b\u2009\u2265\u20091) \u2014 the number of \"o\" cards and the number of \"x\" cards.", "output_spec": "In the first line print a single integer v \u2014 the maximum score that ainta can obtain. In the second line print a\u2009+\u2009b characters describing the deck. If the k-th card of the deck contains \"o\", the k-th character must be \"o\". If the k-th card of the deck contains \"x\", the k-th character must be \"x\". The number of \"o\" characters must be equal to a, and the number of \"x \" characters must be equal to b. If there are many ways to maximize v, print any. Please, do not write the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["2 3", "4 0", "0 4"], "sample_outputs": ["-1\nxoxox", "16\noooo", "-16\nxxxx"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet pr sym c = for i=1 to c do printf \"%c\" sym done\nlet sq x = x**x\n\nlet tl x = Int64.of_int x\n\nlet () = \n let a = read_int() in (* number of os *)\n let b = read_int() in (* number of xs *)\n let maxg = min b (a+1) in\n if maxg < 2 then (\n printf \"%Ld\\n\" ((sq (tl a)) -- (sq (tl b)));\n pr 'o' a;\n pr 'x' b;\n printf \"\\n\"\n ) else (\n let rec loop g bestg best_score = if g > maxg then (bestg,best_score) else\n (* g = number of groups of xs. g-1 groups of os. *)\n\tlet oscore = (tl (g-2)) ++ (sq (tl (a-(g-2)))) in\n\tlet lo = b/g in\n\tlet hi = (b+g-1)/g in\n\tlet nhi = (b - g*lo) in\n\tlet nlo = g - nhi in\n(*\tlet xscore = sum 0 (g-1) (fun i -> sq ((b+i)/g)) in *)\n\tlet xscore = (tl nhi) ** (sq (tl hi)) ++ (tl nlo) ** (sq (tl lo)) in\n\tlet score = oscore -- xscore in\n\tif score > best_score then \n\t loop (g+1) g score\n\telse \n\t loop (g+1) bestg best_score\n in\n \n let (g,s) = loop 2 0 (0L -- (sq (tl (a+b)))) in\n printf \"%Ld\\n\" s;\n pr 'x' (b/g);\n for i=1 to g-1 do\n pr 'o' (if i [])};;\n\nlet ($+) {g;_} (u, v) = g.(u) <- (v::g.(u));g.(v) <- (u::g.(v));;\nlet ($-) {g;_} (u, v) =\n let edges = g.(v) in\n let rec aux acc = function\n | [] -> acc\n | hd :: tl when hd = u -> acc @ tl\n | hd :: tl -> aux (hd::acc) tl\n in\n g.(v) <- (aux [] edges)\n\nlet kick_out g =\n let len, hd = List.length, List.hd in\n let k = ref [] in\n Array.iteri (fun u e -> if (len e) = 1 then (k := (u, hd e)::(!k);g.g.(u) <- []) else ()) g.g;\n List.iter (fun e -> g$-e) !k;\n len !k\n\nlet main () =\n let read2 () = scanf \" %d %d \" (fun x y -> x, y) in\n let n, m = read2 () in\n let g = create n in\n let () = for i = 1 to m do\n let u, v = read2 () in\n g$+(u,v)\n done in\n let ans = ref 0 in\n while (kick_out g) > 0 do incr ans done;\n printf \"%d\\n\" !ans\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "f8315dc903b0542c453cab4577bcb20d"} {"nl": {"description": "One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.", "input_spec": "The first input line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.", "output_spec": "Print a single integer \u2014 the number of problems the friends will implement on the contest.", "sample_inputs": ["3\n1 1 0\n1 1 1\n1 0 0", "2\n1 0 0\n0 1 1"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution."}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\n\nlet rec loop n a =\n if n <= 0 then a\n else\n let (x,y,z) = read3() in\n loop (n-1) ( if x+y+z >= 2 then (a+1) else a );;\n\nlet _ = \n let n = read1() in\n Printf.printf \"%d\\n\" ( loop n 0 );;\n\n"}, {"source_code": "let number_of_problems = Scanf.scanf \"%d \" (fun n -> n)\n\nlet if_certain d = match d with\n |0 -> false\n |_-> true\n\nlet remove_uncertainity l = List.filter(if_certain) l\n\nlet rec getting_statuses n k = \n if n > 0\n then\n let status = Scanf.scanf \"%d %d %d \" (fun s0 s1 s2 -> [s0; s1; s2]) in\n if (List.length (remove_uncertainity status)) >= 2\n then \n getting_statuses(n - 1) (k + 1)\n else\n getting_statuses(n - 1) k\n else\n Printf.printf (\"%d\\n\") k\n\nlet () = getting_statuses number_of_problems 0"}, {"source_code": "let input () = let number_of_problems = Scanf.scanf \"%d \" (fun n -> n) in\n let rec getting_statuses n = \n if n > 0\n then\n let status = Scanf.scanf \"%d %d %d \" (fun s0 s1 s2 -> [s0; s1; s2]) in\n let rest = getting_statuses (n - 1) in\n (status :: rest)\n else\n []\n in getting_statuses number_of_problems\n\nlet if_certain d = match d with\n |0 -> false\n |_-> true\n\nlet count f l = List.length (List.filter f l)\n\nlet solve : int list list -> int = count (fun l -> count if_certain l >= 2)\n\nlet print k = Printf.printf \"%d\\n\" k\n\nlet () = print (solve (input ()))\n"}, {"source_code": "let rec loop n = \n if n == 0 then\n 0\n else\n let score = Scanf.scanf \"%d %d %d\\n\" (fun x y z -> if x+y+z >= 2 then 1 else 0) in\n score + loop (n-1);;\n\nlet _ =\n let n = read_int() in\n print_int(loop n) in\n print_newline()\n"}, {"source_code": "let n=Scanf.scanf \"%d\" (fun a->a);;\nlet ans= ref 0;;\nfor i=1 to n do\n ans:=!ans+(Scanf.scanf \" %d %d %d\" (fun a b c->if a+b+c>=2 then 1 else 0)) \ndone;;\nprint_int(!ans)\n"}, {"source_code": "let n=Scanf.scanf \"%d\" (fun a->a);;\nlet ans= ref 0;;\nfor i=1 to n do\n let (a,b,c)=(Scanf.scanf \" %d %d %d\" (fun a b c->(a,b,c))) in\n if a+b+c>=2 then ans:=!ans+1\ndone;;\nprint_int(!ans)\n"}, {"source_code": "\nlet check lst = 2 <= List.fold_left (+) 0 lst\n;;\n\nlet solve llst = List.length (List.filter check llst)\n;;\n\nlet make_nums n =\n let arr = Array.init n (fun _ -> Scanf.scanf \"%d %d %d \"\n (fun n m k -> [n; m; k;]))\n in\n Array.to_list arr\n;;\n\nlet () =\n let nums = Scanf.scanf \"%d \"\n (fun n -> make_nums n)\n in\n Printf.printf \"%d\\n\" (solve nums)\n;;\n \n"}, {"source_code": "let read_int () = Scanf.scanf \"%d \" (fun x -> x);;\nlet read_int3 () = Scanf.scanf \" %d %d %d \" (fun x y z -> (x,y,z) );;\n\nlet n = read_int ();;\n\nlet a = Array.init n (fun i -> (read_int3 () ));;\n\nlet vote = function\n | (0,0,0) -> 0\n | (1,0,0) -> 0\n | (0,1,0) -> 0\n | (0,0,1) -> 0\n | (_,_,_) -> 1\n;;\n\nlet b = Array.map (fun x -> vote x) a\n |> Array.fold_left (+) 0\n in print_int b; print_endline \"\"\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve n =\n let rec check_opinions acc = function\n | 0 -> acc\n | n -> let o1 = read_int ()\n and o2 = read_int ()\n and o3 = read_int () in\n if o1 + o2 + o3 > 1\n then check_opinions (acc + 1) (n - 1)\n else check_opinions acc (n - 1)\n in check_opinions 0 n\n\nlet () =\n let n = read_int () in\n Printf.printf \"%d\\n\" (solve n)\n"}, {"source_code": "open Scanf\n\nlet rec solve n =\n if n = 0 then 0\n else\n begin\n scanf \"%d %d %d\\n\" (fun x y z ->\n\tlet rest = solve (n - 1) in\n\tif (x = 0 && y = 0 || x = 0 && z = 0 || y = 0 && z = 0) then rest\n\telse 1 + rest)\n end\n \nlet _ =\n Printf.printf \"%d\\n\" (scanf \"%d\\n\" solve)\n"}, {"source_code": "let read_one () = Scanf.scanf \" %d\" (fun x -> x)\nlet read_two () = Scanf.scanf \" %d %d\" (fun x y -> (x,y)) \nlet read_three () = Scanf.scanf \" %d %d %d\" (fun x y z -> (x,y,z))\n\nlet read_many n =\n let rec helper i acc =\n if i >= n then List.rev acc\n else Scanf.scanf \" %d\" (fun n -> helper (i+1) (n::acc)) in\n helper 0 []\n\nlet list_iteri f lst = List.fold_left (fun j b -> f j b; j+1) 0 lst\n\nlet main =\n let t = Scanf.scanf \"%d\" (fun t -> t) in\n let sum = ref 0 in\n for case = 1 to t do\n let (a,b,c) = read_three() in\n sum := !sum + if a+b+c >= 2 then 1 else 0;\n done;\n Printf.printf \"%d\\n\" !sum\n"}, {"source_code": "let pf = Printf.printf;;\nlet sf = Scanf.scanf;;\n\nlet (|>) x f = f x;;\nlet (@@) f x = f x;;\nlet read0() = sf \"%d \" (fun x -> x)\nlet read1() = sf \"%d\\n\" (fun x -> x)\nlet read2() = sf \"%d %d\\n\" (fun x y -> x, y)\nlet read3() = sf \"%d %d %d\\n\" (fun x y z -> x, y, z)\n\nexception Error of string\n\nlet inf = 1000000000;;\nlet eps = 1e-11;;\n\nlet _ =\n let n = read1() in\n let res = ref 0 in\n for i = 1 to n do\n let (x, y, z) = read3() in\n if x + y + z >= 2 then res := !res + 1\n done;\n pf \"%d\\n\" !res\n;;\n"}, {"source_code": "let read_int () = \n Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x)\n\nlet rec solve n = \n if n == 0 then 0\n else if read_int () + read_int () + read_int () > 1 then 1 + solve (n - 1)\n else 0 + solve (n - 1)\n \nlet () =\n Printf.printf \"%d\" (solve (read_int ()))\n"}, {"source_code": "let n = int_of_string (input_line stdin) ;;\n\nlet sum a b c = a + b + c ;;\n\nlet rec solve i count =\n if i == 0 then count\n else let input = Scanf.bscanf Scanf.Scanning.stdin \"%d %d %d\\n\" sum in\n if input > 1 then solve (i - 1) (count + 1)\n else solve (i - 1) count ;;\n\nPrintf.printf \"%d\\n\" (solve n 0) ;;"}, {"source_code": "open Printf\n\nlet read_ints() =\n\tArray.map (int_of_string) (Array.of_list (Str.split (Str.regexp \" +\") (read_line())))\n\nlet sum xs = Array.fold_left (+) 0 xs\n\n\nlet main = \n let n = read_int() in\n let answer = ref 0 in\n for i = 1 to n do\n let xs = read_ints() in\n if (sum xs) >= 2 then\n answer := !answer + 1;\n done;\n printf \"%d\\n\" !answer;;\n"}], "negative_code": [{"source_code": "let number_of_problems = Scanf.scanf \"%d \" (fun n -> n)\n\nlet if_certain d = match d with\n |0 -> false\n |_-> true\n\nlet remove_uncertainity l = List.filter(if_certain) l\n\nlet rec getting_statuses n k = \n if n > 0\n then\n let status = Scanf.scanf \"%d %d %d \" (fun s0 s1 s2 -> [s0; s1; s2]) in\n if (List.length (remove_uncertainity status)) >= 2\n then \n getting_statuses(n - 1) (k + 1)\n else\n ()\n else\n Printf.printf (\"%d\\n\") k\n\nlet () = getting_statuses number_of_problems 0"}, {"source_code": "open Scanf\n\nlet rec solve n =\n if n = 0 then 0\n else\n begin\n scanf \"%d %d %d\\n\" (fun x y z ->\n\tlet rest = solve (n - 1) in\n\tif x = 0 && y = 0 && z = 0 then rest\n\telse 1 + rest)\n end\n \nlet _ =\n Printf.printf \"%d\\n\" (scanf \"%d\\n\" solve)\n"}, {"source_code": "let read_int = \n Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x)\n\nlet rec solve n = \n if n == 0 then 0\n else if read_int + read_int + read_int > 1 then 1 + solve (n - 1)\n else 0 + solve (n - 1)\n \nlet () =\n Printf.printf \"%d\" (solve read_int)\n"}], "src_uid": "3542adc74a41ccfd72008faf983ffab5"} {"nl": {"description": "Nick's company employed n people. Now Nick needs to build a tree hierarchy of \u00absupervisor-surbodinate\u00bb relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: \u00abemployee ai is ready to become a supervisor of employee bi at extra cost ci\u00bb. The qualification qj of each employee is known, and for each application the following is true: qai\u2009>\u2009qbi. Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 amount of employees in the company. The following line contains n space-separated numbers qj (0\u2009\u2264\u2009qj\u2009\u2264\u2009106)\u2014 the employees' qualifications. The following line contains number m (0\u2009\u2264\u2009m\u2009\u2264\u200910000) \u2014 amount of received applications. The following m lines contain the applications themselves, each of them in the form of three space-separated numbers: ai, bi and ci (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, 0\u2009\u2264\u2009ci\u2009\u2264\u2009106). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application qai\u2009>\u2009qbi.", "output_spec": "Output the only line \u2014 the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.", "sample_inputs": ["4\n7 2 3 1\n4\n1 2 5\n2 4 1\n3 4 1\n1 3 5", "3\n1 2 3\n2\n3 1 2\n3 1 3"], "sample_outputs": ["11", "-1"], "notes": "NoteIn the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer is -1."}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n for i = 1 to n do read_int 0 |> ignore done;\n let d = Array.make n max_int in\n for i = 1 to read_int 0 do\n read_int 0 |> ignore;\n let x = read_int 0 - 1 in\n let y = read_int 0 in\n d.(x) <- min d.(x) y\n done;\n let t = Array.fold_left (fun x y -> x + (if y = max_int then 1 else 0)) 0 d in\n if t > 1 then\n print_endline \"-1\"\n else\n Array.fold_left (+) (-max_int) d |> Printf.printf \"%d\\n\"\n"}], "negative_code": [], "src_uid": "ddc9b2bacfaa4f4e91d5072240c1e811"} {"nl": {"description": "Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed. Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally: if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$); if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots: 1. Shoot the cannon in the row $$$2$$$. \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 2. Shoot the cannon in the row $$$2$$$. \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \\le n \\le 50$$$)\u00a0\u2014 the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1\u00a0\u2014 the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.", "output_spec": "For each test case print: YES if there is a sequence of shots leading to a given matrix; NO if such a sequence does not exist. The letters in the words YES and NO can be printed in any case.", "sample_inputs": ["5\n4\n0010\n0011\n0000\n0000\n2\n10\n01\n2\n00\n00\n4\n0101\n1111\n0101\n0111\n4\n0100\n1110\n0101\n0111"], "sample_outputs": ["YES\nNO\nYES\nYES\nNO"], "notes": "NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further."}, "positive_code": [{"source_code": "let split_string ?(pattern=\"\") = Str.split @@ Str.regexp pattern\nlet t = Scanf.sscanf (read_line ()) \"%d\" @@ fun t -> t\n\nlet () = for _ = 1 to t do\n let n = Scanf.sscanf (read_line ()) \"%d\" @@ fun n -> n in\n let f = Array.init n @@ fun _ -> read_line () |> split_string |> List.map int_of_string |> Array.of_list in\n let ans = ref true in\n for i = 0 to n - 2 do\n for j = 0 to n - 2 do\n let c = f.(i).(j) in\n if c = 1 && f.(i + 1).(j) = 0 && f.(i).(j + 1) = 0 then ans := false\n done\n done;\n print_endline @@ if !ans then \"YES\" else \"NO\"\ndone"}], "negative_code": [], "src_uid": "eea15ff7e939bfcc7002cacbc8a1a3a5"} {"nl": {"description": "Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i\u2009+\u20091)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.", "input_spec": "The first line contains two integers, n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105; 1\u2009\u2264\u2009k\u2009\u2264\u2009109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.", "output_spec": "If the player who moves first wins, print \"First\", otherwise print \"Second\" (without the quotes).", "sample_inputs": ["2 3\na\nb", "3 1\na\nb\nc", "1 2\nab"], "sample_outputs": ["First", "First", "Second"], "notes": null}, "positive_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nmodule Array = ArrayLabels ;;\nmodule List = struct\n include ListLabels ;;\n let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;\n let rec drop n a =\n if n = 0 then a\n else match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (n - 1) xs ;;\nend\nmodule H = Hashtbl ;;\n\ntype t =\n| Node of (char, t) H.t\n\nlet idx c = Char.code c - Char.code 'a' ;;\n\nlet create (ss : string list) =\n let rec insert tr s i n =\n if i = n then ()\n else\n let Node tr = tr in\n try\n let t = H.find tr s.[i] in\n insert t s (i + 1) n\n with\n | Not_found -> begin\n let nd = Node (H.create 10) in\n H.add tr s.[i] nd;\n insert nd s (i + 1) n;\n end in\n\n let tr = Node (H.create 10) in\n List.iter ss ~f:(fun s -> insert tr s 0 (String.length s));\n tr\n;;\n\nlet is_nil tr = H.length tr = 0 ;;\n\ntype res = W | L | C | NC\n\nlet rec search (Node tr) =\n if is_nil tr then L\n else\n let vs = H.fold (fun c tr acc -> search tr :: acc) tr [] in\n if List.exists vs ~f:(fun v -> v = NC) then C\n else if List.exists vs ~f:(fun v -> v = W) && List.exists vs ~f:(fun v -> v = L) then C\n else if List.exists vs ~f:(fun v -> v = L) then W\n else if List.exists vs ~f:(fun v -> v = W) then L\n else NC\n;;\n\nlet f v = if v = 0 then \"First\" else \"Second\" ;;\n\nlet main k (Node tr) =\n let res = search (Node tr) in\n match res with\n | C -> pf \"First\\n\"\n | NC -> pf \"Second\\n\"\n | W -> pf \"%s\\n\" (f ((k + 1) mod 2))\n | L -> pf \"Second\\n\"\n;;\n\nlet () =\n sf \"%d %d \" (fun n k ->\n let acc = ref [] in\n for i = 0 to n - 1 do\n acc := sf \"%s \" (fun v -> v) :: !acc\n done;\n main k (create !acc))\n;;\n \n"}], "negative_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nmodule Array = ArrayLabels ;;\nmodule List = struct\n include ListLabels ;;\n let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;\n let rec drop n a =\n if n = 0 then a\n else match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (n - 1) xs ;;\nend\nmodule H = Hashtbl ;;\n\ntype t =\n| Node of (char, t) H.t\n\nlet idx c = Char.code c - Char.code 'a' ;;\n\nlet create (ss : string list) =\n let rec insert tr s i n =\n if i = n then ()\n else\n let Node tr = tr in\n try\n let t = H.find tr s.[i] in\n insert t s (i + 1) n\n with\n | Not_found -> begin\n let nd = Node (H.create 10) in\n H.add tr s.[i] nd;\n insert nd s (i + 1) n;\n end in\n\n let tr = Node (H.create 10) in\n List.iter ss ~f:(fun s -> insert tr s 0 (String.length s));\n tr\n;;\n\nlet is_nil tr = H.length tr = 0 ;;\n\ntype res = A | B | AB | ABC\n\nlet rec search (Node tr) =\n if is_nil tr then B\n else\n let vs = H.fold (fun c tr acc -> search tr :: acc) tr [] in\n if List.for_all vs ~f:(fun v -> v = B) then A\n else if List.for_all vs ~f:(fun v -> v = A) then B\n else if List.for_all vs ~f:(fun v -> v = AB) then ABC\n else if List.for_all vs ~f:(fun v -> v = ABC) then AB\n else if List.exists vs ~f:(fun v -> v = A) && List.exists vs ~f:(fun v -> v = B) then AB\n else if List.exists vs ~f:(fun v -> v = ABC) then AB\n else List.find vs ~f:(fun v -> v = A || v = B)\n;;\n\nlet f v = if v = 0 then \"First\" else \"Second\" ;;\n\nlet main k (Node tr) =\n let res = search (Node tr) in\n match res with\n | AB -> pf \"First\\n\"\n | ABC -> pf \"Second\\n\"\n | A -> pf \"%s\\n\" (f ((k + 1) mod 2))\n | B -> pf \"Second\\n\"\n;;\n\nlet () =\n sf \"%d %d \" (fun n k ->\n let acc = ref [] in\n for i = 0 to n - 1 do\n acc := sf \"%s \" (fun v -> v) :: !acc\n done;\n main k (create !acc))\n;;\n \n"}, {"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nmodule Array = ArrayLabels ;;\nmodule List = struct\n include ListLabels ;;\n let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;\n let rec drop n a =\n if n = 0 then a\n else match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (n - 1) xs ;;\nend\nmodule H = Hashtbl ;;\n\ntype t =\n| Node of (char, t) H.t\n\nlet idx c = Char.code c - Char.code 'a' ;;\n\nlet create (ss : string list) =\n let rec insert tr s i n =\n if i = n then ()\n else\n let Node tr = tr in\n try\n let t = H.find tr s.[i] in\n insert t s (i + 1) n\n with\n | Not_found -> begin\n let nd = Node (H.create 10) in\n H.add tr s.[i] nd;\n insert nd s (i + 1) n;\n end in\n\n let tr = Node (H.create 10) in\n List.iter ss ~f:(fun s -> insert tr s 0 (String.length s));\n tr\n;;\n\nlet is_nil tr = H.length tr = 0 ;;\n\ntype res = W | L | C | NC\n\nlet rec search (Node tr) =\n if is_nil tr then L\n else\n let vs = H.fold (fun c tr acc -> search tr :: acc) tr [] in\n if List.for_all vs ~f:(fun v -> v = L) then W\n else if List.for_all vs ~f:(fun v -> v = W) then L\n else if List.for_all vs ~f:(fun v -> v = C) then NC\n else if List.for_all vs ~f:(fun v -> v = NC) then C\n else if List.exists vs ~f:(fun v -> v = W) && List.exists vs ~f:(fun v -> v = L) then C\n else if List.exists vs ~f:(fun v -> v = NC) then C\n else if List.mem W vs then W\n else L\n;;\n\nlet f v = if v = 0 then \"First\" else \"Second\" ;;\n\nlet main k (Node tr) =\n let res = search (Node tr) in\n match res with\n | C -> pf \"First\\n\"\n | NC -> pf \"Second\\n\"\n | W -> pf \"%s\\n\" (f ((k + 1) mod 2))\n | L -> pf \"Second\\n\"\n;;\n\nlet () =\n sf \"%d %d \" (fun n k ->\n let acc = ref [] in\n for i = 0 to n - 1 do\n acc := sf \"%s \" (fun v -> v) :: !acc\n done;\n main k (create !acc))\n;;\n \n"}], "src_uid": "2de867c08946eade5f674a98b377343d"} {"nl": {"description": "Vasya has found a piece of paper with an array written on it. The array consists of n integers a1,\u2009a2,\u2009...,\u2009an. Vasya noticed that the following condition holds for the array ai\u2009\u2264\u2009ai\u2009+\u20091\u2009\u2264\u20092\u00b7ai for any positive integer i (i\u2009<\u2009n).Vasya wants to add either a \"+\" or a \"-\" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs \"+\" and \"-\" before each number so that the value of expression s meets the limits 0\u2009\u2264\u2009s\u2009\u2264\u2009a1. Print a sequence of signs \"+\" and \"-\", satisfying the given limits. It is guaranteed that the solution for the problem exists.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of the array. The second line contains space-separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the original array. It is guaranteed that the condition ai\u2009\u2264\u2009ai\u2009+\u20091\u2009\u2264\u20092\u00b7ai fulfills for any positive integer i (i\u2009<\u2009n).", "output_spec": "In a single line print the sequence of n characters \"+\" and \"-\", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0\u2009\u2264\u2009s\u2009\u2264\u2009a1. If there are multiple solutions, you are allowed to print any of them.", "sample_inputs": ["4\n1 2 3 5", "3\n3 3 5"], "sample_outputs": ["+++-", "++-"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun _ -> read_int()) in \n\n let rec pass i s ac = if i<0 then ac else \n if s <= a.(i) then (\n let ac = 1::ac in\n let s = - (s-a.(i)) in\n\tpass (i-1) s ac\n ) else (\n let ac = 0::ac in\n let s = s-a.(i) in\n\tpass (i-1) s ac\t\n )\n in\n\n let sign_list = pass (n-1) 0 [] in\n\n let rec print p li = match li with [] -> ()\n | h::t -> \n\tlet p = (p+h) mod 2 in\n\t print_char(if p=0 then '+' else '-');\n\t print p t\n in\n print 1 sign_list;\n print_newline()\n"}], "negative_code": [], "src_uid": "30f64b963310911196ebf5d624c01cc3"} {"nl": {"description": "Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors\u00a0\u2014 1 and k. ", "input_spec": "The only line of the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000).", "output_spec": "The first line of the output contains a single integer k\u00a0\u2014 maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.", "sample_inputs": ["5", "6"], "sample_outputs": ["2\n2 3", "3\n2 2 2"], "notes": null}, "positive_code": [{"source_code": "let input () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet print_looper n a = \n let rec loop i =\n if i < n\n then\n (Printf.printf \"%d \" a;\n loop (i + 1))\n else\n ()\n in loop 0\n\nlet wrapper (n, a, b) =\n Printf.printf \"%d\\n\" n;\n print_looper a 2;\n print_looper b 3;\n Printf.printf \"\\n\"\n\nlet solve n = \n let total = n / 2 in\n let modulo = n mod 2 in\n if modulo = 1\n then\n (total, total - 1, 1)\n else\n (total, total, 0)\n\nlet () = wrapper (solve (input ()))"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec print2 k = if k = 0 then () else let () = print2(k-1) in printf \"%d \" 2\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x) in\nlet () = \n let n = read_int() in\n let () = printf \"%d\\n\" (n/2) in\n if n mod 2 = 0 then \n print2 (n/2)\n else let () = print2 (n/2-1) in printf \"%d\" 3 in\n()"}, {"source_code": "let main () =\n let n = read_int () in\n let k = n / 2 in\n print_int k; print_newline ();\n for i = 1 to k-1 do\n print_string \"2 \"\n done;\n print_int (n - 2 * (k-1))\n\n\nlet () = main ()\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\n\n(* int -> int list\n create_range(n) = [2,..., k-1] len = k-2\n *)\nlet rec create_range k = if k <= 2 then [] else\n List.append (create_range (k-1)) [k-1] in\n\n(* int -> bool\n true iff n is a prime\n *)\nlet isPrime n = if n < 2 then false else \n if n == 2 then true else\n let divisible k = if (n mod k) = 0 then true else false in\n let range = create_range n in\n not (List.exists divisible range) in\n\n(* int -> int list\n length(res) = n-1 and res[i] = answer for i+2 *)\n\nlet rec produce_table n range primes = if n = 2 then [1] else \n let res_table = produce_table (n-1) primes range in\n let fold_help prime res = if n-prime < 2 then res else\n let index = n-prime-2 in \n let pot = List.nth res_table index in \n if pot > res then pot else res in\n let new_val = 1 + List.fold_right fold_help primes 0 in\n List.append res_table [new_val] in\n\n(* int -> int list\n returns a list of primes\n *)\n\nlet rec produce_primes n res_table range primes = if n = 2 then [2] else\n let help a = let fst = List.nth res_table (a-2) in\n let snd = List.nth res_table (n-2) in\n if snd = fst + 1 then true else false in\n let fold_help a b = if n-a > 2 && help (n-a) then \n [a] else b in\n let index = List.fold_right fold_help primes [] in\n match index with\n [prime] -> prime::(produce_primes (n-prime) res_table range primes)\n | _ -> [n] in\n\n\n\n(* processing input *)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x) in\nlet () = \n let n = read_int() in\n let range = create_range(n) in\n let primes = List.filter isPrime range in\n let res_table = produce_table n range primes in\n let answer = produce_primes n res_table range primes in\n let len = List.length answer in\n let () = printf \"%d\\n\" len in\n let helpero a = printf \"%d \" a in\n List.iter helpero answer in\n()\n\n"}], "src_uid": "98fd00d3c83d4b3f0511d8afa6fdb27b"} {"nl": {"description": "You are given two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$. Array $$$a$$$ contains each odd integer from $$$1$$$ to $$$2n$$$ in an arbitrary order, and array $$$b$$$ contains each even integer from $$$1$$$ to $$$2n$$$ in an arbitrary order.You can perform the following operation on those arrays: choose one of the two arrays pick an index $$$i$$$ from $$$1$$$ to $$$n-1$$$ swap the $$$i$$$-th and the $$$(i+1)$$$-th elements of the chosen array Compute the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$.For two different arrays $$$x$$$ and $$$y$$$ of the same length $$$n$$$, we say that $$$x$$$ is lexicographically smaller than $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ, the array $$$x$$$ has a smaller element than the corresponding element in $$$y$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 2n$$$, all $$$a_i$$$ are odd and pairwise distinct) \u2014 array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le 2n$$$, all $$$b_i$$$ are even and pairwise distinct) \u2014 array $$$b$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print one integer: the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$. We can show that an answer always exists.", "sample_inputs": ["3\n2\n3 1\n4 2\n3\n5 3 1\n2 4 6\n5\n7 5 9 1 3\n2 4 6 10 8"], "sample_outputs": ["0\n2\n3"], "notes": "NoteIn the first example, the array $$$a$$$ is already lexicographically smaller than array $$$b$$$, so no operations are required.In the second example, we can swap $$$5$$$ and $$$3$$$ and then swap $$$2$$$ and $$$4$$$, which results in $$$[3, 5, 1]$$$ and $$$[4, 2, 6]$$$. Another correct way is to swap $$$3$$$ and $$$1$$$ and then swap $$$5$$$ and $$$1$$$, which results in $$$[1, 5, 3]$$$ and $$$[2, 4, 6]$$$. Yet another correct way is to swap $$$4$$$ and $$$6$$$ and then swap $$$2$$$ and $$$6$$$, which results in $$$[5, 3, 1]$$$ and $$$[6, 2, 4]$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet l2n c = (int_of_char c) - (int_of_char '0')\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n (fun i -> (read_int(), i)) in\n let b = Array.init n (fun j -> (read_int(), j)) in \n\n Array.sort compare a;\n Array.sort compare b;\n\n let sm = Array.make n 0 in (* suffix min *)\n\n sm.(n-1) <- snd b.(n-1);\n for k = n-2 downto 0 do\n sm.(k) <- min sm.(k+1) (snd b.(k))\n done;\n\n let answer = minf 0 (n-1) (fun i -> (snd a.(i)) + sm.(i)) in\n printf \"%d\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "55a1e9236cac9a6044e74b1975331535"} {"nl": {"description": "Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: She will tell you two numbers, l and r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n), and you should tell her . Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say \"fuyukai desu\" and then become unhappy.", "input_spec": "The first line contains an integer n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integers: v1,\u2009v2,\u2009...,\u2009vn\u00a0(1\u2009\u2264\u2009vi\u2009\u2264\u2009109) \u2014 costs of the stones. The third line contains an integer m\u00a0(1\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r\u00a0(1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u2009n;\u00a01\u2009\u2264\u2009type\u2009\u2264\u20092), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.", "output_spec": "Print m lines. Each line must contain an integer \u2014 the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.", "sample_inputs": ["6\n6 4 2 7 2 7\n3\n2 3 6\n1 3 4\n1 1 6", "4\n5 5 2 3\n10\n1 2 4\n2 1 4\n1 1 1\n2 1 4\n2 1 2\n1 1 1\n1 3 3\n1 1 3\n1 4 4\n1 2 2"], "sample_outputs": ["24\n9\n28", "10\n15\n5\n15\n5\n5\n2\n12\n3\n5"], "notes": "NotePlease note that the answers to the questions may overflow 32-bit integer type."}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet tab1=Array.make n 0;;\nlet tab2=Array.make n 0;;\nlet sum1=Array.make n Int64.zero;;\nlet sum2=Array.make n Int64.zero;;\nfor i=0 to n-1 do\n let x=read_int() in tab1.(i)<-x;tab2.(i)<-x\ndone;;\nArray.sort (fun x y -> if x=y then 0 else if xx);;\nlet n=read_int();;\nlet tab1=Array.make n 0;;\nlet tab2=Array.make n 0;;\nlet sum1=Array.make n 0;;\nlet sum2=Array.make n 0;;\nfor i=0 to n-1 do\n let x=read_int() in tab1.(i)<-x;tab2.(i)<-x\ndone;;\nArray.sort (fun x y -> if x=y then 0 else if x m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* input *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\texternal id : 'a -> 'a = \"%identity\"\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet fail _ = failwith \"fail\"\n\tlet dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n\tlet range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n\tlet cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n\tlet shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n\tlet binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n\t\tlet rec f0 ng ok =\n\t\t\tif labs (ok - ng) <= 1L then ok\n\t\t\telse let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n\t\tin f0 (ng-1L*d) (ok+1L*d)\n\t(* imperative *)\n\tlet rep f t fbod =\n\t\tlet rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done\n\t\tin rep0 f t fbod\n\tlet repb f t fbod =\n\t\tlet rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done; !c\n\t\tin if f<=t then rep0 f t fbod\n\t\telse rep0 t f @@ fun v -> fbod @@ f + t - v\n\tlet repm f t m0 fbod =\n\t\tlet rep0 f t m0 fbod =\n\t\t\tlet i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m\n\t\tin if f<=t then rep0 f t m0 fbod\n\t\telse rep0 t f m0 @@ fun u v -> fbod u @@ f + t - v\n\tlet repi f t fbod =\n\t\tlet rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done\n\t\tin if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repb f t fbod =\n\t\tlet rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done\n\t\tin if f<=t then rep0 f t fbod\n\t\telse rep0 t f @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repm f t m0 fbod =\n\t\tlet rep0 f t m0 fbod =\n\t\t\tlet i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m\n\t\tin if f<=t then rep0 f t m0 fbod\n\t\telse rep0 t f m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n\t(* output *)\n\tlet print_list_mle f ls = string_of_list f ls |> print_endline\n\tlet print_array_mle f a = string_of_array f a |> print_endline\n\tlet print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\tlet print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\t(* debug *)\n\tlet dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n\tlet dump_i64_list ls = print_list ist ls\n\tlet dump_i64_array a = print_array ist a\nend open Lib\n\nlet () =\n\tlet n,m = get_2_i64 0 in\n\tlet add = Array.make (i32 n) [] in\n\trep 1L m (fun idx ->\n\t\tlet p,q = get_2_i64 0 in\n\t\tlet i,j = i32 p-$1,i32 q-$1 in \n\t\tadd.(i) <- (10000L+idx)::add.(i);\n\t\tadd.(j) <- (10000L+idx)::add.(j);\n\t);\n\tArray.iteri (fun i v ->\n\t\tlet i=i+$1 in\n\t\tprintf \"%Ld\\n%d %d\\n\" (llen v+1L) i i;\n\t\tList.iter (fun w -> \n\t\t\tprintf \"%d %Ld\\n\" i w\n\t\t) v\n\t) add\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64,ist = Int64.(to_int,of_int,to_string)\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* input *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\texternal id : 'a -> 'a = \"%identity\"\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet fail _ = failwith \"fail\"\n\tlet dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n\tlet range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n\tlet cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n\tlet shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n\tlet binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n\t\tlet rec f0 ng ok =\n\t\t\tif labs (ok - ng) <= 1L then ok\n\t\t\telse let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n\t\tin f0 (ng-1L*d) (ok+1L*d)\n\t(* imperative *)\n\tlet rep f t fbod =\n\t\tlet rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done\n\t\tin if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f + t - v\n\tlet repb f t fbod =\n\t\tlet rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done; !c\n\t\tin if f<=t then rep0 f t fbod\n\t\telse rep0 t f @@ fun v -> fbod @@ f + t - v\n\tlet repm f t m0 fbod =\n\t\tlet rep0 f t m0 fbod =\n\t\t\tlet i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m\n\t\tin if f<=t then rep0 f t m0 fbod\n\t\telse rep0 t f m0 @@ fun u v -> fbod u @@ f + t - v\n\tlet repi f t fbod =\n\t\tlet rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done\n\t\tin if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repb f t fbod =\n\t\tlet rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done\n\t\tin if f<=t then rep0 f t fbod\n\t\telse rep0 t f @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repm f t m0 fbod =\n\t\tlet rep0 f t m0 fbod =\n\t\t\tlet i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m\n\t\tin if f<=t then rep0 f t m0 fbod\n\t\telse rep0 t f m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n\t(* output *)\n\tlet print_list_mle f ls = string_of_list f ls |> print_endline\n\tlet print_array_mle f a = string_of_array f a |> print_endline\n\tlet print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\tlet print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\t(* debug *)\n\tlet dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n\tlet dump_i64_list ls = print_list ist ls\n\tlet dump_i64_array a = print_array ist a\nend open Lib\n\nlet () =\n\tlet n,m = get_2_i64 0 in\n\tlet add = Array.make (i32 n) [] in\n\trep 1L m (fun _ ->\n\t\tlet p,q = get_2_i64 0 in\n\t\tlet i = i32 p -$ 1 in \n\t\tadd.(i) <- q::add.(i);\n\t);\n\tArray.iteri (fun i v ->\n\t\tlet i=i+$1 in\n\t\tprintf \"%Ld\\n%d %d\\n\" (llen v+1L) i i;\n\t\tList.iter (fun w -> \n\t\t\tprintf \"%d %Ld\\n\" i w\n\t\t) v\n\t) add\n"}], "src_uid": "29476eefb914b445f1421d99d928fd5a"} {"nl": {"description": "Notice that the memory limit is non-standard.Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him.All Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the i-th opening bracket he remembers the segment [li,\u2009ri], containing the distance to the corresponding closing bracket.Formally speaking, for the i-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment [li,\u2009ri].Help Arthur restore his favorite correct bracket sequence!", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009600), the number of opening brackets in Arthur's favorite correct bracket sequence. Next n lines contain numbers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009<\u20092n), representing the segment where lies the distance from the i-th opening bracket and the corresponding closing one. The descriptions of the segments are given in the order in which the opening brackets occur in Arthur's favorite sequence if we list them from left to right.", "output_spec": "If it is possible to restore the correct bracket sequence by the given data, print any possible choice. If Arthur got something wrong, and there are no sequences corresponding to the given information, print a single line \"IMPOSSIBLE\" (without the quotes).", "sample_inputs": ["4\n1 1\n1 1\n1 1\n1 1", "3\n5 5\n3 3\n1 1", "3\n5 5\n3 3\n2 2", "3\n2 3\n1 4\n1 4"], "sample_outputs": ["()()()()", "((()))", "IMPOSSIBLE", "(())()"], "notes": null}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let s = Stack.create () in\n let a = Array.create n (0, 0) in\n let b = Buffer.create (2 * n) in\n let p = ref 1 in\n for i = 0 to n - 1 do\n (* add bounds to array *)\n Scanf.scanf \"%d %d\\n\" (fun x y -> a.(i) <- (x + !p, y + !p));\n (* push this bracket to the stack as open *)\n Stack.push i s;\n Buffer.add_char b '(';\n incr p;\n\n (* greedily close brackets *)\n while not (Stack.is_empty s) && !p >= fst a.(Stack.top s) && !p <= snd a.(Stack.top s) do\n Buffer.add_char b ')';\n ignore (Stack.pop s);\n incr p\n done;\n done;\n if Stack.is_empty s then\n print_endline (Buffer.contents b)\n else\n print_endline \"IMPOSSIBLE\"\n)\n"}], "negative_code": [], "src_uid": "416cf0b84fbb17a41ec6c02876b79ce0"} {"nl": {"description": "Pavel has several sticks with lengths equal to powers of two.He has $$$a_0$$$ sticks of length $$$2^0 = 1$$$, $$$a_1$$$ sticks of length $$$2^1 = 2$$$, ..., $$$a_{n-1}$$$ sticks of length $$$2^{n-1}$$$. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.It is forbidden to break sticks, and each triangle should consist of exactly three sticks.Find the maximum possible number of triangles.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 300\\,000$$$)\u00a0\u2014 the number of different lengths of sticks. The second line contains $$$n$$$ integers $$$a_0$$$, $$$a_1$$$, ..., $$$a_{n-1}$$$ ($$$1 \\leq a_i \\leq 10^9$$$), where $$$a_i$$$ is the number of sticks with the length equal to $$$2^i$$$.", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible number of non-degenerate triangles that Pavel can make.", "sample_inputs": ["5\n1 2 2 2 2", "3\n1 1 1", "3\n3 3 3"], "sample_outputs": ["3", "0", "3"], "notes": "NoteIn the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^4, 2^4)$$$, $$$(2^1, 2^3, 2^3)$$$, $$$(2^1, 2^2, 2^2)$$$.In the second example, Pavel cannot make a single triangle.In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^0, 2^0)$$$, $$$(2^1, 2^1, 2^1)$$$, $$$(2^2, 2^2, 2^2)$$$."}, "positive_code": [{"source_code": "let (+) = Int64.add\nlet (--) = Int64.sub\nlet (/) = Int64.div\nlet ( * ) = Int64.mul\n\nlet () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a = Array.make n Int64.zero in\n let res = ref Int64.zero in\n let ones = ref Int64.zero in\n for i = 0 to n-1 do\n let m = Scanf.scanf \"%Ld \" (fun x -> x) in\n let m2 = m / 2L in\n let x = min (m / 2L) !ones in\n res := !res + x;\n ones := !ones -- x;\n let m = m -- x * 2L in\n a.(i) <- m;\n let m3 = m / 3L in\n res := !res + m3;\n ones := !ones + m -- m3 * 3L;\n done;\n Printf.printf \"%Ld\" !res\n;;\n"}, {"source_code": "let (+) = Int64.add\nlet (--) = Int64.sub\nlet (/) = Int64.div\nlet ( * ) = Int64.mul\n\nlet () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a = Array.make n Int64.zero in\n let res = ref Int64.zero in\n let ones = ref Int64.zero in\n for i = 0 to n-1 do\n let m = Scanf.scanf \"%Ld \" (fun x -> x) in\n let m2 = m / (Int64.of_int 2) in\n let x = min (m / (Int64.of_int 2)) !ones in\n res := !res + x;\n ones := !ones -- x;\n let m = m -- x * Int64.of_int 2 in\n a.(i) <- m;\n let m3 = m / (Int64.of_int 3) in\n res := !res + m3;\n ones := !ones + m -- m3 * (Int64.of_int 3);\n done;\n Printf.printf \"%Ld\" !res\n;;\n"}], "negative_code": [{"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a = Array.make n 0 in\n let res = ref 0 in\n let ones = ref 0 in\n for i = 0 to n-1 do\n let m = Scanf.scanf \"%d \" (fun x -> x) in\n let m2 = m / 2 in\n let x = min (m / 2) !ones in\n res := !res + x;\n ones := !ones - x;\n let m = m - x * 2 in\n let m3 = m / 3 in\n res := !res + m3;\n ones := !ones + m - m3 * 3;\n done;\n Printf.printf \"%d\" !res\n;;\n"}, {"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let res = ref 0 in\n for i = 0 to n-1 do\n let m = Scanf.scanf \"%d \" (fun x -> x/3) in\n res := !res + m\n done;\n Printf.printf \"%d\" !res\n;;\n"}, {"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a = Array.make n 0 in\n let res = ref 0 in\n for i = 0 to n-1 do\n let m = Scanf.scanf \"%d \" (fun x -> x) in\n let m3 = m / 3 in\n res := !res + m3;\n a.(i) <- m - m3 * 3;\n done;\n let ones = ref 0 in\n Array.iter (function\n | 2 when !ones > 0 -> decr ones; incr res;\n | 2 -> incr ones; incr ones;\n | 1 -> incr ones;\n | _ -> ()\n ) a;\n Printf.printf \"%d\" !res\n;;\n"}, {"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a = Array.make n 0 in\n let res = ref 0 in\n for i = 0 to n-1 do\n let m = Scanf.scanf \"%d \" (fun x -> x) in\n let m3 = m / 3 in\n res := !res + m3;\n a.(i) <- m - m3;\n done;\n let ones = ref 0 in\n Array.iter (function\n | 2 when !ones > 0 -> decr ones; incr res;\n | 2 -> incr ones; incr ones;\n | 1 -> incr ones;\n | _ -> ()\n ) a;\n Printf.printf \"%d\" !res\n;;\n"}], "src_uid": "a8f3e94845cb15a483ce8f774779efac"} {"nl": {"description": "Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $$$a=[1, 3, 3, 7]$$$ is good because there is the element $$$a_4=7$$$ which equals to the sum $$$1 + 3 + 3$$$.You are given an array $$$a$$$ consisting of $$$n$$$ integers. Your task is to print all indices $$$j$$$ of this array such that after removing the $$$j$$$-th element from the array it will be good (let's call such indices nice).For example, if $$$a=[8, 3, 5, 2]$$$, the nice indices are $$$1$$$ and $$$4$$$: if you remove $$$a_1$$$, the array will look like $$$[3, 5, 2]$$$ and it is good; if you remove $$$a_4$$$, the array will look like $$$[8, 3, 5]$$$ and it is good. You have to consider all removals independently, i.\u2009e. remove the element, check if the resulting array is good, and return the element into the array.", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^6$$$) \u2014 elements of the array $$$a$$$.", "output_spec": "In the first line print one integer $$$k$$$ \u2014 the number of indices $$$j$$$ of the array $$$a$$$ such that after removing the $$$j$$$-th element from the array it will be good (i.e. print the number of the nice indices). In the second line print $$$k$$$ distinct integers $$$j_1, j_2, \\dots, j_k$$$ in any order \u2014 nice indices of the array $$$a$$$. If there are no such indices in the array $$$a$$$, just print $$$0$$$ in the first line and leave the second line empty or do not print it at all.", "sample_inputs": ["5\n2 5 1 2 2", "4\n8 3 5 2", "5\n2 1 2 4 3"], "sample_outputs": ["3\n4 1 5", "2\n1 4", "0"], "notes": "NoteIn the first example you can remove any element with the value $$$2$$$ so the array will look like $$$[5, 1, 2, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 1 + 2 + 2$$$).In the second example you can remove $$$8$$$ so the array will look like $$$[3, 5, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 3 + 2$$$). You can also remove $$$2$$$ so the array will look like $$$[8, 3, 5]$$$. The sum of this array is $$$16$$$ and there is an element equals to the sum of remaining elements ($$$8 = 3 + 5$$$).In the third example you cannot make the given array good by removing exactly one element."}, "positive_code": [{"source_code": "(* Problem 2 of round 521*)\nopen Scanf;;\nopen String;;\nopen Num;;\n\n(*These are some utility functions*)\nmodule U = struct\n let mprint z =\n print_endline (Num.string_of_num z);;\n\n let read_one format =\n let n = Scanf.scanf format (fun x -> x) in\n n;;\n\n let read_one_number () =\n let n = read_one \"%d \" in\n n\n\n let read_array n a =\n for i = 0 to n-1 do\n let n = read_one_number () in\n a.(i) <- n\n done\n\nend\n\n(*The solutions*)\n\nlet n = U.read_one_number ()\nlet a = Array.make n 0\nlet () = U.read_array n a\n\nmodule H = Hashtbl\nlet t = H.create n\n\n(*\nlet () =\n Array.iter (fun x-> print_int x; print_endline \"\") a\n*)\n\nopen Num;;\nlet n1 = num_of_int 1;;\n\nlet total = ref (num_of_int 0)\nlet () =\n Array.iter (fun x-> H.add t (num_of_int x) (num_of_int 0)) a;\n Array.iter (fun x-> H.replace t (num_of_int x) (n1+/(H.find t (num_of_int x)))) a;\n Array.iter (fun x -> total := !total +/ (num_of_int x)) a;;\n\n(*\nprint_int !total; print_endline \"\"\nlet () =\n H.iter (fun k v -> Printf.printf \"%d %d\\n\" k v) t\n*)\n\nlet my_find x =\n try H.find t x\n with Not_found -> num_of_int 0\n\nlet n0 = num_of_int 0;;\n\nlet is_good x =\n let r = !total -/ x in\n let m = int_of_num (mod_num r (num_of_int 2)) in\n match m with\n 1 -> false\n | _ -> begin\n let r1 = r // (num_of_int 2) in\n let rslt = int_of_num (my_find r1) in\n match rslt with\n 0 -> false\n | 1 -> begin\n if eq_num r1 x then\n false\n else\n true\n end\n | _ -> true\n end\n\nlet s = H.create n;;\n\nlet () =\n Array.iteri (fun i x -> if (is_good (num_of_int x)) then\n begin H.add s (num_of_int (i + 1) ) n0 end\n ) a\n;;\n\n\nlet () = \n print_int (H.length s); print_endline \"\";\n H.iter (fun k v -> Printf.printf \"%d \" (int_of_num k)) s\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make (Int64)\nlet count a = (* (value,count) *)\n Array.fold_left (fun u v -> IMap.add v (1L + try IMap.find v u with Not_found -> 0L) u) IMap.empty a\nlet () =\n let n = get_i64 0 in\n let a = input_i64_array n in\n let mp = count a in\n let sum = fold_left (+) 0L a in\n let ans = ref [] in\n iteri (fun i v ->\n let rest = sum - v in\n if rest mod 2L = 0L then\n try\n let c = IMap.find (rest/2L) mp in\n if v = rest/2L then (\n if c >= 2L then ans := (i+$1) :: !ans\n ) else if c >= 1L then ans := (i+$1) :: !ans\n with Not_found -> ()\n ) a;\n printf \"%Ld\\n\" @@ llen !ans;\n print_list string_of_int !ans\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "(* Problem 2 of round 521*)\nopen Scanf;;\nopen String;;\nopen Num;;\n\n(*These are some utility functions*)\nmodule U = struct\n let mprint z =\n print_endline (Num.string_of_num z);;\n\n let read_one format =\n let n = Scanf.scanf format (fun x -> x) in\n n;;\n\n let read_one_number () =\n let n = read_one \"%d \" in\n n\n\n let read_array n a =\n for i = 0 to n-1 do\n let n = read_one_number () in\n a.(i) <- n\n done\n\nend\n\n(*The solutions*)\n\nlet n = U.read_one_number ()\nlet a = Array.make n 0\nlet () = U.read_array n a\n\nmodule H = Hashtbl\nlet t = H.create n\n\n(*\nlet () =\n Array.iter (fun x-> print_int x; print_endline \"\") a\n*)\n\nopen Num;;\nlet n1 = num_of_int 1;;\n\nlet total = ref (num_of_int 0)\nlet () =\n Array.iter (fun x-> H.add t (num_of_int x) (num_of_int 0)) a;\n Array.iter (fun x-> H.replace t (num_of_int x) (n1+/(H.find t (num_of_int x)))) a;\n Array.iter (fun x -> total := !total +/ (num_of_int x)) a;;\n\n(*\nprint_int !total; print_endline \"\"\nlet () =\n H.iter (fun k v -> Printf.printf \"%d %d\\n\" k v) t\n*)\n\nlet my_find x =\n try H.find t x\n with Not_found -> num_of_int 0\n\nlet n0 = num_of_int 0;;\n\nlet is_good x =\n let r = !total -/ x in\n let m = int_of_num (mod_num r (num_of_int 2)) in\n match m with\n 1 -> false\n | _ -> begin\n let r1 = r // (num_of_int 2) in\n let rslt = int_of_num (my_find r1) in\n match rslt with\n 0 -> false\n | 1 -> begin\n if r1 == x then\n false\n else\n true\n end\n | _ -> true\n end\n\nlet s = H.create n;;\n\nlet () =\n Array.iteri (fun i x -> if (is_good (num_of_int x)) then\n begin H.add s (num_of_int (i + 1) ) n0 end\n ) a\n;;\n\n\nlet () = \n print_int (H.length s); print_endline \"\";\n H.iter (fun k v -> Printf.printf \"%d \" (int_of_num k)) s\n"}, {"source_code": "(* Problem 2 of round 521*)\nopen Scanf;;\nopen String;;\nopen Num;;\n\n(*These are some utility functions*)\nmodule U = struct\n let mprint z =\n print_endline (Num.string_of_num z);;\n\n let read_one format =\n let n = Scanf.scanf format (fun x -> x) in\n n;;\n\n let read_one_number () =\n let n = read_one \"%d \" in\n n\n\n let read_array n a =\n for i = 0 to n-1 do\n let n = read_one_number () in\n a.(i) <- n\n done\n\nend\n\n(*The solutions*)\n\nlet n = U.read_one_number ()\nlet a = Array.make n 0\nlet () = U.read_array n a\n\nmodule H = Hashtbl\nlet t = H.create n\n\n(*\nlet () =\n Array.iter (fun x-> print_int x; print_endline \"\") a\n*)\n\nlet total = ref 0\nlet () =\n Array.iter (fun x-> H.add t x 0) a;\n Array.iter (fun x-> H.replace t x (1+(H.find t x))) a;\n Array.iter (fun x -> total := !total + x) a;;\n\n(*\nprint_int !total; print_endline \"\"\nlet () =\n H.iter (fun k v -> Printf.printf \"%d %d\\n\" k v) t\n*)\n\nlet my_find x =\n try H.find t x\n with Not_found -> 0\n\nlet is_good x =\n let r = !total -x in\n match r mod 2 with\n 1 -> false\n | _ -> begin\n let r1 = r / 2 in\n let rslt = my_find r1 in\n match rslt with\n 0 -> false\n | 1 -> begin\n if r1 == x then\n false\n else\n true\n end\n | _ -> true\n end\n\nlet s = H.create n;;\n\nlet () =\n Array.iteri (fun i x -> if (is_good x) then\n begin H.add s (i+1) 0 end\n ) a\n;;\n\nlet () = \n print_int (H.length s); print_endline \"\";\n H.iter (fun k v -> Printf.printf \"%d \" k) s\n"}, {"source_code": "(* Problem 2 of round 521*)\nopen Scanf;;\nopen String;;\nopen Num;;\n\n(*These are some utility functions*)\nmodule U = struct\n let mprint z =\n print_endline (Num.string_of_num z);;\n\n let read_one format =\n let n = Scanf.scanf format (fun x -> x) in\n n;;\n\n let read_one_number () =\n let n = read_one \"%d \" in\n n\n\n let read_array n a =\n for i = 0 to n-1 do\n let n = read_one_number () in\n a.(i) <- n\n done\n\nend\n\n(*The solutions*)\n\nlet n = U.read_one_number ()\nlet a = Array.make n 0\nlet () = U.read_array n a\n\nmodule H = Hashtbl\nlet t = H.create n\n\n(*\nlet () =\n Array.iter (fun x-> print_int x; print_endline \"\") a\n*)\n\nlet total = ref 0\nlet () =\n Array.iter (fun x-> H.add t x 0) a;\n Array.iter (fun x-> H.replace t x (1+(H.find t x))) a;\n Array.iter (fun x -> total := !total + x) a;;\n\n(*\nprint_int !total; print_endline \"\"\nlet () =\n H.iter (fun k v -> Printf.printf \"%d %d\\n\" k v) t\n*)\n\nlet my_find x =\n try H.find t x\n with Not_found -> 0\n\nlet is_good x =\n let r = !total -x in\n match r mod 2 with\n 1 -> false\n | _ -> begin\n let r1 = r / 2 in\n let rslt = my_find r1 in\n match rslt with\n 0 -> false\n | 1 -> begin\n if r1 == x then\n false\n else\n true\n end\n | _ -> true\n end\n\nlet s = H.create n;;\n\nlet () =\n Array.iteri (fun i x -> if (is_good x) then\n begin H.add s (i+1) 0 end\n ) a\n;;\n\n\nlet () = \n print_int (H.length s); print_endline \"\";\n H.iter (fun k v -> Printf.printf \"%d \" k) s\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nmodule CumulSumArray = struct\n let make a =\n let ln = Array.length a\n in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1\n let sum l r a = (* 0-origin,closed *)\n if l>r then 0L else (a.(r+$1) - a.(l))\n let sum_1orig l r a = sum (l-$1) (r-$1) a\nend\nlet () =\n let n = get_i64 0 in\n let a = input_i64_array n in\n let b = init (i32 n) (fun i -> a.(i)) in\n sort compare b;\n (* let c = CumulSumArray.make a in *)\n let s = fold_left (+) 0L a in\n let r = ref [] in\n repi 0 (i32 n-$1) (fun i ->\n (* let rest = CumulSumArray.sum i 0 in *)\n let rest = s - a.(i) in\n let j = lower_bound b (rest/2L) in\n (* printf \"%Ld, %Ld\\n\" rest j; *)\n if 0L<=j && j x)\n\nlet () =\n let n = read_int () and k = read_int () in\n let a = Array.init n read_int\n and h = Array.make 200001 0\n and min_elem = ref 200001\n and max_elem = ref 0\n and cnt = ref 0\n and cur = ref 0\n and ans = ref 0 in\n Array.iter (fun x ->\n min_elem := min !min_elem x;\n max_elem := max !max_elem x;\n h.(x) <- h.(x) + 1\n ) a;\n for i = !max_elem downto !min_elem + 1 do\n cnt := !cnt + h.(i);\n cur := !cur + !cnt;\n if !cur > k then begin\n incr ans;\n cur := !cnt\n end\n done;\n if max_elem <> min_elem then incr ans;\n printf \"%d\\n\" !ans"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nmodule Imos = struct\n\tlet make n = Array.make (i32 n +$ 2) 0L\n\tlet add_destructive_closed l r a =\n\t\ta.(l+$1) <- a.(l+$1) + 1L;\n\t\ta.(r+$2) <- a.(r+$2) - 1L\n\tlet add_destructive_1orig_closed l r a =\n\t\ta.(l) <- a.(l) + 1L;\n\t\ta.(r+$1) <- a.(r+$1) - 1L\n\tlet cumulate_destructive a = for i=1 to Array.length a -$ 2 do\n\t\ta.(i) <- a.(i) + a.(i-$1)\n\tdone\nend\n\n(* let a = Array.make 200000 0L *)\nlet a = Imos.make 2000010L\nlet () =\n\tlet n,k = get_2_i64 0 in\n\tlet mi,mx = ref Int64.max_int,ref 0L in\n\trep 1L n (fun _ ->\n\t\tlet h = get_i64 0 in\n\t\tmi := min h !mi;\n\t\tmx := max h !mx;\n\t\tImos.add_destructive_1orig_closed 1 (i32 h) a;\n\t\t`Ok\n\t);\n\tImos.cumulate_destructive a;\n\tlet i = ref !mx in\n\tlet s = ref 0L in\n\tlet c = ref 0L in\n\twhile !i > !mi do\n\t\t(* printf \"%2Ld >= %2Ld: %Ld, %Ld :: %Ld\\n\" !i !mi !s a.(i32 !i) !c; *)\n\t\ts += a.(i32 !i);\n\t\tif !s > k then (\n\t\t\tc += 1L;\n\t\t\ts := a.(i32 !i)\n\t\t);\n\t\ti -= 1L;\n\tdone;\n\tif !s > 0L then (\n\t\tc += 1L;\n\t);\n\t(* printf \"%Ld %Ld\\n\" !s !c; *)\n\t!c |> printf \"%Ld\\n\";\n\t(* printf \"[%Ld %Ld]: %Ld\\n\" !mi !mx !c; *)\n\n\n\n\n\n\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int() and k = scan_int();;\nlet h = Array.make n 0 ;;\n\nfor i = 0 to n - 1 do\n h.(i) <- scan_int();\ndone;;\n\nArray.sort compare h;;\n\nlet ans = ref 0 and magazyn = ref 0;;\n\nfor i = n - 1 downto 1 do\n let lewy = h.(i - 1) in\n let linia = n - i in\n let odejm = (k - !magazyn) / linia in\n let roz = h.(i) - lewy in\n if odejm <= roz && roz <> 0 then begin\n let wys = k / linia in\n let ile = (roz - if(!magazyn > 0) then odejm else 0) / wys in\n (*print_int(i); psp(); print_int(ile); psp(); print_int(!magazyn); print_newline();*)\n ans := !ans + ile + b2i(!magazyn <> 0);\n magazyn := ((roz - odejm) mod wys) * linia;\n end\n else magazyn := !magazyn + linia * roz;\n (*print_int(!magazyn); print_newline(); *)\ndone;;\n\nprint_int (!ans + b2i(!magazyn <> 0));;\n\n(*\n3 3\n1 2 3\n*)"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nmodule Imos = struct\n\tlet make n = Array.make (i32 n +$ 2) 0L\n\tlet add_destructive_closed l r a =\n\t\ta.(l+$1) <- a.(l+$1) + 1L;\n\t\ta.(r+$2) <- a.(r+$2) - 1L\n\tlet add_destructive_1orig_closed l r a =\n\t\ta.(l) <- a.(l) + 1L;\n\t\ta.(r+$1) <- a.(r+$1) - 1L\n\tlet cumulate_destructive a = for i=1 to Array.length a -$ 2 do\n\t\ta.(i) <- a.(i) + a.(i-$1)\n\tdone\nend\n\n(* let a = Array.make 200000 0L *)\nlet a = Imos.make 2000010L\nlet () =\n\tlet n,k = get_2_i64 0 in\n\tlet mi,mx = ref Int64.max_int,ref 0L in\n\trep 1L n (fun _ ->\n\t\tlet h = get_i64 0 in\n\t\tmi := min h !mi;\n\t\tmx := max h !mx;\n\t\tImos.add_destructive_1orig_closed 1 (i32 h) a;\n\t\t`Ok\n\t);\n\tImos.cumulate_destructive a;\n\tlet i = ref !mx in\n\tlet s = ref 0L in\n\tlet c = ref 0L in\n\twhile !i >= !mi do\n\t\t(* printf \"%Ld >= %Ld: %Ld, %Ld :: %Ld\\n\" !i !mi !s a.(i32 !i) !c; *)\n\t\ts += a.(i32 !i);\n\t\tif !s > k then (\n\t\t\tc += 1L;\n\t\t\ts := a.(i32 !i)\n\t\t);\n\t\ti -= 1L;\n\tdone;\n\t!c |> printf \"%Ld\\n\";\n\t(* printf \"[%Ld %Ld]: %Ld\\n\" !mi !mx !c; *)\n\n\n\n\n\n\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int() and k = scan_int();;\nlet h = Array.make n 0 ;;\n\nfor i = 0 to n - 1 do\n h.(i) <- scan_int();\ndone;;\n\nArray.sort compare h;;\n\nlet ans = ref 0 and magazyn = ref 0;;\n\nfor i = n - 1 downto 1 do\n let lewy = h.(i - 1) in\n let linia = n - i in\n let odejm = (k - !magazyn) / linia in\n let roz = h.(i) - lewy in\n if odejm <= roz && roz <> 0 then begin\n let wys = k / linia in\n let ile = (roz - odejm) / wys in\n (* print_int(ile); psp(); print_int(!magazyn); print_newline(); *)\n ans := !ans + ile + b2i(!magazyn <> 0);\n magazyn := ((roz - odejm) mod wys) * linia;\n end\n else magazyn := !magazyn + linia * roz;\n (*print_int(!magazyn); print_newline(); *)\ndone;;\n\nprint_int (!ans + b2i(!magazyn <> 0));;"}], "src_uid": "676729309dfbdf4c9d9d7c457a129608"} {"nl": {"description": "A schoolboy named Vasya loves reading books on programming and mathematics. He has recently read an encyclopedia article that described the method of median smoothing (or median filter) and its many applications in science and engineering. Vasya liked the idea of the method very much, and he decided to try it in practice.Applying the simplest variant of median smoothing to the sequence of numbers a1,\u2009a2,\u2009...,\u2009an will result a new sequence b1,\u2009b2,\u2009...,\u2009bn obtained by the following algorithm: b1\u2009=\u2009a1, bn\u2009=\u2009an, that is, the first and the last number of the new sequence match the corresponding numbers of the original sequence. For i\u2009=\u20092,\u2009...,\u2009n\u2009-\u20091 value bi is equal to the median of three values ai\u2009-\u20091, ai and ai\u2009+\u20091. The median of a set of three numbers is the number that goes on the second place, when these three numbers are written in the non-decreasing order. For example, the median of the set 5, 1, 2 is number 2, and the median of set 1, 0, 1 is equal to 1.In order to make the task easier, Vasya decided to apply the method to sequences consisting of zeros and ones only.Having made the procedure once, Vasya looked at the resulting sequence and thought: what if I apply the algorithm to it once again, and then apply it to the next result, and so on? Vasya tried a couple of examples and found out that after some number of median smoothing algorithm applications the sequence can stop changing. We say that the sequence is stable, if it does not change when the median smoothing is applied to it.Now Vasya wonders, whether the sequence always eventually becomes stable. He asks you to write a program that, given a sequence of zeros and ones, will determine whether it ever becomes stable. Moreover, if it ever becomes stable, then you should determine what will it look like and how many times one needs to apply the median smoothing algorithm to initial sequence in order to obtain a stable one.", "input_spec": "The first input line of the input contains a single integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009500\u2009000)\u00a0\u2014 the length of the initial sequence. The next line contains n integers a1,\u2009a2,\u2009...,\u2009an (ai\u2009=\u20090 or ai\u2009=\u20091), giving the initial sequence itself.", "output_spec": "If the sequence will never become stable, print a single number \u2009-\u20091. Otherwise, first print a single integer\u00a0\u2014 the minimum number of times one needs to apply the median smoothing algorithm to the initial sequence before it becomes is stable. In the second line print n numbers separated by a space \u00a0\u2014 the resulting sequence itself.", "sample_inputs": ["4\n0 0 1 1", "5\n0 1 0 1 0"], "sample_outputs": ["0\n0 0 1 1", "2\n0 0 0 0 0"], "notes": "NoteIn the second sample the stabilization occurs in two steps: , and the sequence 00000 is obviously stable."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let anchor = Array.make n false in\n\n for i=0 to n-1 do\n if i=0 || i=n-1 then anchor.(i) <- true\n else anchor.(i) <- a.(i-1) = a.(i) || a.(i+1) = a.(i)\n done;\n\n let b = Array.copy a in\n\n let prev_anchor = Array.make n (-1) in\n\n let rec loop i prev = if i=n then () else\n if anchor.(i) then (\n\tprev_anchor.(i) <- prev;\n\tloop (i+1) i\n ) else (\n\tloop (i+1) prev\n )\n in\n\n loop 0 (-1);\n\n let maxl = ref 0 in\n\n for i=0 to n-1 do\n if anchor.(i) && prev_anchor.(i) <> i-1 then (\n let l = i - prev_anchor.(i) -1 in\n maxl := max !maxl l;\n if l land 1 = 0 then (\n\tfor j=i-l to i-(l/2)-1 do\n\t b.(j) <- a.(prev_anchor.(i))\n\tdone;\n\tfor j=i-(l/2) to i-1 do\n\t b.(j) <- a.(i)\t \n\tdone\n ) else (\n\tfor j=i-l to i-1 do\n\t b.(j) <- a.(i)\n\tdone\n )\n )\n done;\n\n let iterations = (!maxl + 1) / 2 in\n\n printf \"%d\\n\" iterations;\n\n for i=0 to n-1 do\n printf \"%d \" b.(i)\n done;\n\n print_newline()\n"}], "negative_code": [], "src_uid": "5da1c96b88b4ac0b698a37e4d2437ccb"} {"nl": {"description": "Tonya was given an array of $$$a$$$ of length $$$n$$$ written on a postcard for his birthday. For some reason, the postcard turned out to be a cyclic array, so the index of the element located strictly to the right of the $$$n$$$-th is $$$1$$$. Tonya wanted to study it better, so he bought a robot \"Burenka-179\".A program for Burenka is a pair of numbers $$$(s, k)$$$, where $$$1 \\leq s \\leq n$$$, $$$1 \\leq k \\leq n-1$$$. Note that $$$k$$$ cannot be equal to $$$n$$$. Initially, Tonya puts the robot in the position of the array $$$s$$$. After that, Burenka makes exactly $$$n$$$ steps through the array. If at the beginning of a step Burenka stands in the position $$$i$$$, then the following happens: The number $$$a_{i}$$$ is added to the usefulness of the program. \"Burenka\" moves $$$k$$$ positions to the right ($$$i := i + k$$$ is executed, if $$$i$$$ becomes greater than $$$n$$$, then $$$i := i - n$$$). Help Tonya find the maximum possible usefulness of a program for \"Burenka\" if the initial usefulness of any program is $$$0$$$.Also, Tony's friend Ilyusha asks him to change the array $$$q$$$ times. Each time he wants to assign $$$a_p := x$$$ for a given index $$$p$$$ and a value $$$x$$$. You need to find the maximum possible usefulness of the program after each of these changes.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) is the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le q \\le 2 \\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 elements of the array. The following $$$q$$$ lines contain changes, each of them contains two integers $$$p$$$ and $$$x$$$ ($$$1 \\leq p \\leq n$$$, $$$1 \\leq x \\leq 10^9$$$), meaning you should assign $$$a_p := x$$$. It is guaranteed that the sum of $$$n$$$ and the sum of $$$q$$$ over all test cases do not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output $$$q+1$$$ numbers\u00a0\u2014 the maximum usefulness of a program initially and after each of the changes.", "sample_inputs": ["4\n\n2 1\n\n1 2\n\n1 3\n\n4 4\n\n4 1 3 2\n\n2 6\n\n4 6\n\n1 1\n\n3 11\n\n9 3\n\n1 7 9 4 5 2 3 6 8\n\n3 1\n\n2 1\n\n9 1\n\n6 3\n\n1 1 1 1 1 1\n\n1 5\n\n4 4\n\n3 8"], "sample_outputs": ["3\n5\n14\n16\n24\n24\n24\n57\n54\n36\n36\n6\n18\n27\n28"], "notes": "NoteIn the first test case, initially and after each request, the answer is achieved at $$$s = 1$$$, $$$k = 1$$$ or $$$s = 2$$$, $$$k = 1$$$.In the second test case, initially, the answer is achieved when $$$s = 1$$$, $$$k = 2$$$ or $$$s = 3$$$, $$$k = 2$$$. After the first request, the answer is achieved at $$$s = 2$$$, $$$k = 2$$$ or $$$s = 4$$$, $$$k = 2$$$."}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n(* module I = Big_int *)\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet maxI x y =\n if (I.compare x y < 0) then y\n else x\n\nmodule SegTree = struct\n type t = {arr: I.t array; size: int}\n\n let init n v: t = {arr = A.make (2 * n) v; size = n}\n\n let inc_pos (i:int) (diff:I.t) (cur: t): unit =\n cur.arr.(i + cur.size) <- I.add cur.arr.(i + cur.size) diff;\n let p = ref ((i + cur.size) / 2) in\n\n while !p > 0 do\n cur.arr.(!p) <- maxI cur.arr.(2 * !p) cur.arr.(2 * !p + 1);\n p := !p lsr 1;\n done\n\n let mx_val (cur: t) = cur.arr.(1)\nend\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n if (!fk_n mod d = 0) then\n divs := n / d ::!divs;\n\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n done;\n !divs\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> SegTree.init (L.nth divs i) I.zero) in\n\n let upd_el pos old_v new_v =\n let diff = I.of_int (new_v - old_v) in\n L.iteri (fun idx d ->\n let delta = I.mul diff (I.of_int d) in\n let r = pos mod d in\n SegTree.inc_pos r delta div_rem.(idx);\n )\n divs in\n\n let best_ans () = A.fold_left maxI I.zero (A.map SegTree.mx_val div_rem) in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n pf \"%Ld\\n\" (best_ans ());\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n upd_el pos a.(pos) v;\n a.(pos) <- v;\n pf \"%Ld\\n\" (best_ans ());\n done;\n done;"}], "negative_code": [{"source_code": "module A = Array\nmodule L = List\n(* module I = Int64 *)\n(* module I = Big_int *)\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule SegTree = struct\n type t = {arr: int array; size: int}\n\n let init n v: t = {arr = A.make (2 * n) v; size = n}\n\n let inc_pos (i:int) (diff:int) (cur: t): unit =\n cur.arr.(i + cur.size) <- cur.arr.(i + cur.size) + diff;\n let p = ref ((i + cur.size) / 2) in\n\n while !p > 0 do\n cur.arr.(!p) <- max cur.arr.(2 * !p) cur.arr.(2 * !p + 1);\n p := !p lsr 1;\n done\n\n let mx_val (cur: t) = cur.arr.(1)\nend\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n if (!fk_n mod d = 0) then\n divs := n / d ::!divs;\n\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n done;\n !divs\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n\n let divs = find_divs n in\n let q = read_int () in\n let a = read_array read_int n in\n\n let div_rem = A.init (L.length divs) (fun i -> SegTree.init (L.nth divs i) 0) in\n\n let upd_el pos old_v new_v =\n let diff = (new_v - old_v) in\n L.iteri (fun idx d ->\n let delta = diff * d in\n let r = pos mod d in\n SegTree.inc_pos r delta div_rem.(idx);\n )\n divs in\n\n let best_ans () = A.fold_left max 0 (A.map SegTree.mx_val div_rem) in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n pf \"%d\\n\" (best_ans ());\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n upd_el pos a.(pos) v;\n a.(pos) <- v;\n pf \"%d\\n\" (best_ans ());\n done;\n done;"}, {"source_code": "module A = Array\nmodule L = List\n(* module I = Int64 *)\n(* module I = Big_int *)\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule SegTree = struct\n type t = {arr: int array; size: int}\n\n let init n v: t = {arr = A.make (2 * n) v; size = n}\n\n let inc_pos (i:int) (diff:int) (cur: t): unit =\n cur.arr.(i + cur.size) <- cur.arr.(i + cur.size) + diff;\n let p = ref ((i + cur.size) / 2) in\n\n while !p > 0 do\n cur.arr.(!p) <- max cur.arr.(2 * !p) cur.arr.(2 * !p + 1);\n p := !p lsr 1;\n done\n\n let mx_val (cur: t) = cur.arr.(1)\nend\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> SegTree.init (L.nth divs i) 0) in\n\n let upd_el pos old_v new_v =\n let diff = (new_v - old_v) in\n L.iteri (fun idx d ->\n let delta = diff * d in\n let r = pos mod d in\n SegTree.inc_pos r delta div_rem.(idx);\n )\n divs in\n\n let _best_ans () = A.fold_left max 0 (A.map SegTree.mx_val div_rem) in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%d\\n\" (best_ans ()); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%d\\n\" (best_ans ()); *)\n done;\n done;\n\n pf \"\n 3\n5\n14\n16\n24\n24\n24\n57\n54\n36\n36\n6\n18\n27\n28\n\""}, {"source_code": "module A = Array\nmodule L = List\n(* module I = Int64 *)\nmodule I = Big_int\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet maxI = I.max_big_int\n\nmodule SegTree = struct\n type t = {arr: I.big_int array; size: int}\n\n let init n v: t = {arr = A.make (2 * n) v; size = n}\n\n let inc_pos (i:int) (diff:I.big_int) (cur: t): unit =\n cur.arr.(i + cur.size) <- I.add_big_int cur.arr.(i + cur.size) diff;\n let p = ref ((i + cur.size) / 2) in\n\n while !p > 0 do\n cur.arr.(!p) <- maxI cur.arr.(2 * !p) cur.arr.(2 * !p + 1);\n p := !p lsr 1;\n done\n\n let mx_val (cur: t) = cur.arr.(1)\nend\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> SegTree.init (L.nth divs i) I.zero_big_int) in\n\n let upd_el pos old_v new_v =\n let diff = I.big_int_of_int (new_v - old_v) in\n L.iteri (fun idx d ->\n let delta = I.mult_big_int diff (I.big_int_of_int d) in\n let r = pos mod d in\n SegTree.inc_pos r delta div_rem.(idx);\n )\n divs in\n\n let best_ans () = A.fold_left maxI I.zero_big_int (A.map SegTree.mx_val div_rem) |> I.int64_of_big_int in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n pf \"%Ld\\n\" (best_ans ());\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n upd_el pos a.(pos) v;\n a.(pos) <- v;\n pf \"%Ld\\n\" (best_ans ());\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet maxI x y =\n if (I.compare x y > 0) then x\n else y\n\nmodule SegTree = struct\n type t = {arr: I.t array; size: int}\n\n let init n v: t = {arr = A.make (2 * n) v; size = n}\n\n let inc_pos (i:int) (diff:I.t) (cur: t): unit =\n cur.arr.(i + cur.size) <- I.add cur.arr.(i + cur.size) diff;\n let p = ref ((i + cur.size) / 2) in\n\n while !p > 0 do\n cur.arr.(!p) <- maxI cur.arr.(2 * !p) cur.arr.(2 * !p + 1);\n p := !p lsr 1;\n done\n\n let mx_val (cur: t) = cur.arr.(1)\nend\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> SegTree.init (L.nth divs i) I.zero) in\n\n let upd_el pos old_v new_v =\n let diff = I.of_int (new_v - old_v) in\n L.iteri (fun idx d ->\n let delta = I.mul diff (I.of_int d) in\n let r = pos mod d in\n (* SegTree.inc_pos r delta div_rem.(idx); *)\n ()\n )\n divs in\n\n let _best_ans () = A.fold_left maxI I.zero (A.map SegTree.mx_val div_rem) in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\nmodule IntSet = Set.Make(Int32)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n let div_sms = ref IntSet.empty in\n let upd_el pos old_v new_v =\n let diff = I.of_int (new_v - old_v) in\n L.iteri (fun idx d ->\n let delta = I.mul diff (I.of_int d) in\n let r = pos mod d in\n let csm = div_rem.(idx).(r) in\n let _new_sm = I.add csm delta in\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n let _x = IntSet.add (Int32.of_int d) !div_sms in\n (* div_rem.(idx).(r) <- new_sm; *)\n ()\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\nmodule IntSet = Set.Make(Int32)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n let div_sms = ref IntSet.empty in\n let upd_el pos old_v new_v =\n let diff = I.of_int (new_v - old_v) in\n L.iteri (fun idx d ->\n let delta = I.mul diff (I.of_int d) in\n let r = pos mod d in\n let csm = div_rem.(idx).(r) in\n let _new_sm = I.add csm delta in\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n div_sms := IntSet.add (Int32.of_int d) !div_sms;\n (* div_rem.(idx).(r) <- new_sm; *)\n ()\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n let _div_sms = ref DivSumSet.empty in\n let upd_el pos old_v new_v =\n let diff = I.of_int (new_v - old_v) in\n L.iteri (fun idx d ->\n let delta = I.mul diff (I.of_int d) in\n let r = pos mod d in\n let csm = div_rem.(idx).(r) in\n let _new_sm = I.add csm delta in\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n (* div_rem.(idx).(r) <- new_sm; *)\n ()\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n (* let div_sms = ref DivSumSet.empty in *)\n let upd_el pos old_v new_v =\n let diff = I.of_int (new_v - old_v) in\n L.iteri (fun idx d ->\n let delta = I.mul diff (I.of_int d) in\n let r = pos mod d in\n let csm = div_rem.(idx).(r) in\n let new_sm = I.add csm delta in\n ()\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n (* div_rem.(idx).(r) <- new_sm; *)\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n (* let div_sms = ref DivSumSet.empty in *)\n let upd_el pos old_v new_v =\n let diff = I.of_int (new_v - old_v) in\n L.iteri (fun idx d ->\n let _delta = I.mul diff (I.of_int d) in\n let r = pos mod d in\n let _csm = div_rem.(idx).(r) in\n ()\n (* let new_sm = I.add csm delta in *)\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n (* div_rem.(idx).(r) <- new_sm; *)\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let _div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n let _div_sms = ref DivSumSet.empty in\n let upd_el pos old_v new_v =\n let diff = I.of_int (new_v - old_v) in\n L.iteri (fun _idx d ->\n let _delta = I.mul diff (I.of_int d) in\n let _r = pos mod d in\n (* let _csm = div_rem.(idx).(r) in *)\n ()\n (* let new_sm = I.add csm delta in *)\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n (* div_rem.(idx).(r) <- new_sm; *)\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let _div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n let _div_sms = ref DivSumSet.empty in\n let upd_el pos old_v new_v = L.iteri (fun _idx d ->\n let _delta = I.mul (I.of_int (new_v - old_v)) (I.of_int d) in\n let _r = pos mod d in\n (* let _csm = div_rem.(idx).(r) in *)\n ()\n (* let new_sm = I.add csm delta in *)\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n (* div_rem.(idx).(r) <- new_sm; *)\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n let _div_sms = ref DivSumSet.empty in\n let upd_el pos old_v new_v = L.iteri (fun idx d ->\n let _delta = I.mul (I.of_int (new_v - old_v)) (I.of_int d) in\n let r = pos mod d in\n let _csm = div_rem.(idx).(r) in\n ()\n (* let new_sm = I.add csm delta in *)\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n (* div_rem.(idx).(r) <- new_sm; *)\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n let _div_sms = ref DivSumSet.empty in\n let upd_el pos _old_v _new_v = L.iteri (fun idx d ->\n (* let delta = I.mul (I.of_int (new_v - old_v)) (I.of_int d) in *)\n let r = pos mod d in\n let _csm = div_rem.(idx).(r) in\n ()\n (* let new_sm = I.add csm delta in *)\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n (* div_rem.(idx).(r) <- new_sm; *)\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n let div_sms = ref DivSumSet.empty in\n let upd_el pos old_v new_v = L.iteri (fun idx d ->\n let delta = I.mul (I.of_int (new_v - old_v)) (I.of_int d) in\n let r = pos mod d in\n let csm = div_rem.(idx).(r) in\n let new_sm = I.add csm delta in\n div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r);\n div_rem.(idx).(r) <- new_sm;\n )\n divs in\n A.iteri (fun i ai -> upd_el i 0 ai) a;\n pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3);\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n (* let v = IntSet.(empty |> IntSet.add 3 |> IntSet.add 4 |> IntSet.add 3 |> IntSet.remove 3) in\n IntSet.iter (pf \"%d \") v; *)\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n let divs = find_divs n in\n let _div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in\n\n (* let div_sms = ref DivSumSet.empty in *)\n (* let upd_el pos old_v new_v = L.iteri (fun idx d ->\n let delta = I.mul (I.of_int (new_v - old_v)) (I.of_int d) in\n let r = pos mod d in\n let csm = div_rem.(idx).(r) in\n let new_sm = I.add csm delta in\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n div_rem.(idx).(r) <- new_sm;\n )\n divs in *)\n (* A.iteri (fun i ai -> upd_el i 0 ai) a; *)\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule DivTriples = struct\n type t = I.t * int * int\n let compare (sd0, d0, r0) (sd1, d1, r1) =\n match compare sd0 sd1 with\n | 0 -> (match compare d0 d1 with\n | 0 -> compare r0 r1\n | c1 -> c1)\n | c -> -c\nend\n\nmodule DivSumSet = Set.Make(DivTriples)\n\nlet rec seq l r =\n if (l == r) then []\n else l :: seq (l + 1) r\n\nlet find_divs n =\n let fk_n = ref n in\n let divs = ref [] in\n for d = 2 to n do\n while (!fk_n mod d = 0) do\n fk_n := !fk_n / d;\n done;\n if (n mod d = 0) then\n divs := n / d :: !divs;\n done;\n !divs\n\nlet fst3 (a, _, _) = a\n\nlet () =\n (* let v = IntSet.(empty |> IntSet.add 3 |> IntSet.add 4 |> IntSet.add 3 |> IntSet.remove 3) in\n IntSet.iter (pf \"%d \") v; *)\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n\n (* let divs = find_divs n in\n let div_rem = A.init (L.length divs) (fun i -> A.make (L.nth divs i) (I.of_int 0)) in *)\n (* let div_sms = ref DivSumSet.empty in *)\n (* let upd_el pos old_v new_v = L.iteri (fun idx d ->\n let delta = I.mul (I.of_int (new_v - old_v)) (I.of_int d) in\n let r = pos mod d in\n let csm = div_rem.(idx).(r) in\n let new_sm = I.add csm delta in\n (* div_sms := DivSumSet.remove (csm, d, r) !div_sms |> DivSumSet.add (new_sm, d, r); *)\n div_rem.(idx).(r) <- new_sm;\n )\n divs in *)\n (* A.iteri (fun i ai -> upd_el i 0 ai) a; *)\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let v = read_int () in\n (* upd_el pos a.(pos) v; *)\n a.(pos) <- v;\n (* pf \"%Ld\\n\" (DivSumSet.min_elt !div_sms |> fst3); *)\n done;\n done;\n\n pf \"3\n 5\n 14\n 16\n 24\n 24\n 24\n 57\n 54\n 36\n 36\n 6\n 18\n 27\n 28\";"}], "src_uid": "560e26bdfab14b919a7deadefa57f2de"} {"nl": {"description": "Let's denote a function You are given an array a consisting of n integers. You have to calculate the sum of d(ai,\u2009aj) over all pairs (i,\u2009j) such that 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200000) \u2014 the number of elements in a. The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 elements of the array. ", "output_spec": "Print one integer \u2014 the sum of d(ai,\u2009aj) over all pairs (i,\u2009j) such that 1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n.", "sample_inputs": ["5\n1 2 3 1 3", "4\n6 6 5 5", "4\n6 6 4 4"], "sample_outputs": ["4", "0", "-8"], "notes": "NoteIn the first example: d(a1,\u2009a2)\u2009=\u20090; d(a1,\u2009a3)\u2009=\u20092; d(a1,\u2009a4)\u2009=\u20090; d(a1,\u2009a5)\u2009=\u20092; d(a2,\u2009a3)\u2009=\u20090; d(a2,\u2009a4)\u2009=\u20090; d(a2,\u2009a5)\u2009=\u20090; d(a3,\u2009a4)\u2009=\u2009\u2009-\u20092; d(a3,\u2009a5)\u2009=\u20090; d(a4,\u2009a5)\u2009=\u20092. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n(*\n let rec scan i j total k ac = if j = n then ac else (\n if i+1 < j && a.(i+1) <= a.(j) - 2 then (\n scan (i+1) j (total ++ (long a.(i+1))) (k+1) ac\n ) else (\n scan i (j+1) total k (ac ++ (long k) ** (long a.(j)) -- total)\n )\n ) in\n*)\n\n let lo = ref 0L in\n let hi = ref 0L in\n let base = 1_000_000_000_000_000L in\n\n let rec print_val () =\n if !lo < 0L && !hi > 0L then (\n lo := !lo ++ base;\n hi := !hi -- 1L;\n print_val()\n ) else if !lo > 0L && !hi < 0L then (\n lo := !lo -- base;\n hi := !hi ++ 1L;\n print_val()\n ) else if !lo >= 0L && !hi >= 0L then (\n if !hi = 0L then\n\tprintf \"%Ld\\n\" !lo\n else \n\tprintf \"%15Ld%015Ld\\n\" !hi !lo\n ) else (\n if !hi = 0L then\n\tprintf \"%Ld\\n\" !lo\n else \n\tprintf \"%15Ld%015Ld\\n\" !hi (0L -- !lo)\n )\n in\n\n let normalize() =\n if !lo >= base then (\n hi := !hi ++ 1L;\n lo := !lo -- base\n ) else if !lo <= (0L -- base) then (\n hi := !hi -- 1L;\n lo := !lo ++ base\n ) else ()\n in\n\n let accum x =\n if x < 0L then (\n let x = 0L -- x in\n let top = x // base in\n let bot = x %% base in\n hi := !hi -- top;\n lo := !lo -- bot;\n normalize()\n ) else (\n let top = x // base in\n let bot = x %% base in\n hi := !hi ++ top;\n lo := !lo ++ bot;\n normalize()\n ) \n in\n\n let h = Hashtbl.create 10 in\n let get t = try Hashtbl.find h t with Not_found -> 0L in\n let increment t = Hashtbl.replace h t ((get t) ++ 1L) in\n\n (*\n let rec scan j total ac = if j = n then ac else (\n increment a.(j);\n let ac = ac ++ (long j) ** (long a.(j)) -- total in\n let adjust1 = get (a.(j) - 1) in\n let adjust2 = get (a.(j) + 1) in\n let ac = ac -- adjust1 ++ adjust2 in\n scan (j+1) (total ++ (long a.(j))) ac\n ) in\n *)\n\n let rec scan j total = if j = n then () else (\n increment a.(j);\n let adjust1 = get (a.(j) - 1) in\n let adjust2 = get (a.(j) + 1) in\n accum ((long j) ** (long a.(j)) -- total -- adjust1 ++ adjust2);\n scan (j+1) (total ++ (long a.(j)))\n ) in\n \n increment a.(0);\n scan 1 (long a.(0));\n print_val()\n"}], "negative_code": [], "src_uid": "c7cca8c6524991da6ea1b423a8182d24"} {"nl": {"description": "There is a string $$$s$$$ of length $$$3$$$, consisting of uppercase and lowercase English letters. Check if it is equal to \"YES\" (without quotes), where each letter can be in any case. For example, \"yES\", \"Yes\", \"yes\" are all allowable.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^3$$$)\u00a0\u2014 the number of testcases. The description of each test consists of one line containing one string $$$s$$$ consisting of three characters. Each character of $$$s$$$ is either an uppercase or lowercase English letter.", "output_spec": "For each test case, output \"YES\" (without quotes) if $$$s$$$ satisfies the condition, and \"NO\" (without quotes) otherwise. You can output \"YES\" and \"NO\" in any case (for example, strings \"yES\", \"yes\" and \"Yes\" will be recognized as a positive response).", "sample_inputs": ["10\n\nYES\n\nyES\n\nyes\n\nYes\n\nYeS\n\nNoo\n\norZ\n\nyEz\n\nYas\n\nXES"], "sample_outputs": ["YES\nYES\nYES\nYES\nYES\nNO\nNO\nNO\nNO\nNO"], "notes": "NoteThe first five test cases contain the strings \"YES\", \"yES\", \"yes\", \"Yes\", \"YeS\". All of these are equal to \"YES\", where each character is either uppercase or lowercase."}, "positive_code": [{"source_code": "(* From @Darooha's code (https://codeforces.com/profile/Darooha) *)\r\n\r\nopen Printf \r\nopen Scanf\r\n \r\nlet ( ** ) a b = Int64.mul a b\r\nlet ( ++ ) a b = Int64.add a b\r\nlet long x = Int64.of_int x\r\nlet short x = Int64.to_int x\r\n \r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\r\n \r\n(* Main Code file *)\r\n\r\nlet () = \r\n let n = read_int() in\r\n for i=1 to n do\r\n let x = read_string() in\r\n if (String.uppercase x) = \"YES\" then \r\n printf \"Yes\\n\"\r\n else \r\n printf \"No\\n\"\r\n done;"}], "negative_code": [], "src_uid": "4c0b0cb8a11cb1fd40fef47616987029"} {"nl": {"description": "An African crossword is a rectangular table n\u2009\u00d7\u2009m in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.", "output_spec": "Print the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.", "sample_inputs": ["3 3\ncba\nbcd\ncbc", "5 5\nfcofd\nooedo\nafaoa\nrdcdf\neofsf"], "sample_outputs": ["abcd", "codeforces"], "notes": null}, "positive_code": [{"source_code": "let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) ;;\n\nlet usage = Array.make_matrix n m true;;\n\nlet chars = Array.init n (fun _ -> Scanf.scanf \"%s\\n\" (fun s->s));;\n\nlet used = Hashtbl.create m;;\n\nfor i = 0 to n-1 do\n for j = 0 to m-1 do\n let x = try Hashtbl.find used chars.(i).[j] with _ -> 0 in\n Hashtbl.replace used chars.(i).[j] (x+1);\n done;\n\n for j = 0 to m-1 do\n if Hashtbl.find used chars.(i).[j] > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor j = 0 to m-1 do\n for i = 0 to n-1 do\n let x = try Hashtbl.find used chars.(i).[j] with _ -> 0 in\n Hashtbl.replace used chars.(i).[j] (x+1);\n done;\n\n for i = 0 to n-1 do\n if Hashtbl.find used chars.(i).[j] > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor i = 0 to n-1 do\n\tfor j = 0 to m-1 do\n\t\tif usage.(i).(j) then print_char chars.(i).[j]\n\tdone\ndone;;\n\n"}], "negative_code": [{"source_code": "let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) ;;\n\nlet usage = Array.make_matrix n m true;;\n\nlet chars = Array.init n (fun _ ->\n\tlet arr = Array.init m (fun _ -> input_char stdin) in\n\tlet _ = input_char stdin in\n\tarr\n);;\n\nlet used = Hashtbl.create m;;\n\nfor i = 0 to n-1 do\n for j = 0 to m-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for j = 0 to m-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor j = 0 to m-1 do\n for i = 0 to n-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for i = 0 to n-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor i = 0 to n-1 do\n\tfor j = 0 to m-1 do\n\t\tif usage.(i).(j) then print_char chars.(i).(j)\t\n\tdone\ndone;;\n\n"}, {"source_code": "print_string \"abcd\";;\n\nlet n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) ;;\n\nlet usage = Array.make_matrix n m true;;\n\nlet chars = Array.init n (fun _ ->\n\tlet arr = Array.init m (fun _ -> input_char stdin) in\n\tlet _ = input_char stdin in\n\tarr\n);;\n\nlet used = Hashtbl.create m;;\n\nfor i = 0 to n-1 do\n for j = 0 to m-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for j = 0 to m-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor j = 0 to m-1 do\n for i = 0 to n-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for i = 0 to n-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor i = 0 to n-1 do\n\tfor j = 0 to m-1 do\n\t\tif usage.(i).(j) then print_char chars.(i).(j)\t\n\tdone\ndone;;\n\n"}, {"source_code": "let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) ;;\n\nlet usage = Array.make_matrix n m true;;\n\nlet chars = Array.init n (fun _ ->\n\tlet line = read_line () in\n\tArray.init m (fun i -> line.[i])\n);;\n\nlet used = Hashtbl.create m;;\n\nfor i = 0 to n-1 do\n for j = 0 to m-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for j = 0 to m-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor j = 0 to m-1 do\n for i = 0 to n-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for i = 0 to n-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor i = 0 to n-1 do\n\tfor j = 0 to m-1 do\n\t\tif usage.(i).(j) then print_char chars.(i).(j)\t\n\tdone\ndone;;\n\n"}, {"source_code": "try while true do\n\tprint_char (input_char stdin);\ndone with _ -> print_string \"\";;\n"}, {"source_code": "let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) ;;\n\nlet usage = Array.make_matrix n m true;;\n\nlet chars = Array.init n (fun _ -> read_line());;\n\nlet used = Hashtbl.create m;;\n\nfor i = 0 to n-1 do\n for j = 0 to m-1 do\n let x = try Hashtbl.find used chars.(i).[j] with _ -> 0 in\n Hashtbl.replace used chars.(i).[j] (x+1);\n done;\n\n for j = 0 to m-1 do\n if Hashtbl.find used chars.(i).[j] > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor j = 0 to m-1 do\n for i = 0 to n-1 do\n let x = try Hashtbl.find used chars.(i).[j] with _ -> 0 in\n Hashtbl.replace used chars.(i).[j] (x+1);\n done;\n\n for i = 0 to n-1 do\n if Hashtbl.find used chars.(i).[j] > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor i = 0 to n-1 do\n\tfor j = 0 to m-1 do\n\t\tif usage.(i).(j) then print_char chars.(i).[j]\n\tdone\ndone;;\n\n"}, {"source_code": "let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) ;;\n\nlet usage = Array.make_matrix n m true;;\n\nlet chars = Array.init n (fun _ ->\n\tlet line = read_line () in\n\tlet arr = Array.init m (fun i -> line.[i]) in\n\tarr\n);;\n\nlet used = Hashtbl.create m;;\n\nfor i = 0 to n-1 do\n for j = 0 to m-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for j = 0 to m-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor j = 0 to m-1 do\n for i = 0 to n-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for i = 0 to n-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor i = 0 to n-1 do\n\tfor j = 0 to m-1 do\n\t\tif usage.(i).(j) then print_char chars.(i).(j)\t\n\tdone\ndone;;\n\n"}, {"source_code": "let n,m = Scanf.scanf \"%d %d\\r\" (fun n m -> (n,m)) ;;\n\nlet usage = Array.make_matrix n m true;;\n\nlet chars = Array.init n (fun _ -> Scanf.scanf \"%s\\r\" (fun s->s));;\n\nlet used = Hashtbl.create m;;\n\nfor i = 0 to n-1 do\n for j = 0 to m-1 do\n let x = try Hashtbl.find used chars.(i).[j] with _ -> 0 in\n Hashtbl.replace used chars.(i).[j] (x+1);\n done;\n\n for j = 0 to m-1 do\n if Hashtbl.find used chars.(i).[j] > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor j = 0 to m-1 do\n for i = 0 to n-1 do\n let x = try Hashtbl.find used chars.(i).[j] with _ -> 0 in\n Hashtbl.replace used chars.(i).[j] (x+1);\n done;\n\n for i = 0 to n-1 do\n if Hashtbl.find used chars.(i).[j] > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor i = 0 to n-1 do\n\tfor j = 0 to m-1 do\n\t\tif usage.(i).(j) then print_char chars.(i).[j]\n\tdone\ndone;;\n\n"}, {"source_code": "let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) ;;\n\nlet usage = Array.make_matrix n m true;;\n\nlet chars = Array.init n (fun _ -> input_line stdin);;\n\nlet used = Hashtbl.create m;;\n\nfor i = 0 to n-1 do\n for j = 0 to m-1 do\n let x = try Hashtbl.find used chars.(i).[j] with _ -> 0 in\n Hashtbl.replace used chars.(i).[j] (x+1);\n done;\n\n for j = 0 to m-1 do\n if Hashtbl.find used chars.(i).[j] > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor j = 0 to m-1 do\n for i = 0 to n-1 do\n let x = try Hashtbl.find used chars.(i).[j] with _ -> 0 in\n Hashtbl.replace used chars.(i).[j] (x+1);\n done;\n\n for i = 0 to n-1 do\n if Hashtbl.find used chars.(i).[j] > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor i = 0 to n-1 do\n\tfor j = 0 to m-1 do\n\t\tif usage.(i).(j) then print_char chars.(i).[j]\n\tdone\ndone;;\n\n"}, {"source_code": "let n,m = Scanf.scanf \"%d %d\\n\" (fun n m -> (n,m)) ;;\n\nlet usage = Array.make_matrix n m true;;\n\nlet chars = Array.init n (fun _ ->\n\tlet arr = Array.init m (fun _ -> input_char stdin) in\n\tlet _ = input_char stdin in\n\tarr\n);;\n\nlet used = Hashtbl.create m;;\n\nfor i = 0 to n-1 do\n for j = 0 to m-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for j = 0 to m-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\n\nfor j = 0 to m-1 do\n for i = 0 to n-1 do\n let x = try Hashtbl.find used chars.(i).(j) with _ -> 0 in\n Hashtbl.replace used chars.(i).(j) (x+1);\n done;\n\n for i = 0 to n-1 do\n if Hashtbl.find used chars.(i).(j) > 1 then usage.(i).(j) <- false\n done;\n\n Hashtbl.clear used;\ndone;;\nprint_string \"abcd\";;\nfor i = 0 to n-1 do\n\tfor j = 0 to m-1 do\n\t\tif usage.(i).(j) then print_char chars.(i).(j)\t\n\tdone\ndone;;\n\n"}], "src_uid": "9c90974a0bb860a5e180760042fd5045"} {"nl": {"description": "You are given a permutation $$$p_1, p_2, \\dots, p_n$$$. Recall that sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Find three indices $$$i$$$, $$$j$$$ and $$$k$$$ such that: $$$1 \\le i < j < k \\le n$$$; $$$p_i < p_j$$$ and $$$p_j > p_k$$$. Or say that there are no such indices.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 200$$$)\u00a0\u2014 the number of test cases. Next $$$2T$$$ lines contain test cases\u00a0\u2014 two lines per test case. The first line of each test case contains the single integer $$$n$$$ ($$$3 \\le n \\le 1000$$$)\u00a0\u2014 the length of the permutation $$$p$$$. The second line contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$; $$$p_i \\neq p_j$$$ if $$$i \\neq j$$$)\u00a0\u2014 the permutation $$$p$$$.", "output_spec": "For each test case: if there are such indices $$$i$$$, $$$j$$$ and $$$k$$$, print YES (case insensitive) and the indices themselves; if there are no such indices, print NO (case insensitive). If there are multiple valid triples of indices, print any of them.", "sample_inputs": ["3\n4\n2 1 4 3\n6\n4 6 1 2 5 3\n5\n5 3 1 2 4"], "sample_outputs": ["YES\n2 3 4\nYES\n3 5 6\nNO"], "notes": null}, "positive_code": [{"source_code": "(* if there is an (i,j,k) where perm.(i) < perm.(j) and perm.(j) > perm.(k)\n then if you let x be the index with the maximum element in the\n range [i,k], then perm.(x-1) < perm.(x) and perm.(x) > perm.(x+1).\n I.e. the condition must hold at three consecutive positions.\n*)\nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let perm = Array.init n read_int in\n let rec loop i = if i >= n-1 then None else\n\tif perm.(i-1) < perm.(i) && perm.(i) > perm.(i+1) then Some i\n\telse loop (i+1)\n in\n match loop 1 with\n |\tNone -> printf \"NO\\n\"\n | Some x -> printf \"YES\\n%d %d %d\\n\" x (x+1) (x+2)\n done\n"}], "negative_code": [], "src_uid": "dd55e29ac9756325530ad2f4479d9f6d"} {"nl": {"description": "It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And yet, the notion of a giveaway is foreign to him. The combination of these features makes the Robo-Wallace the perfect footballer \u2014 as soon as the ball gets to him, he can just aim and hit the goal. He followed this tactics in the first half of the match, but he hit the goal rarely. The opposing team has a very good goalkeeper who catches most of the balls that fly directly into the goal. But Robo-Wallace is a quick thinker, he realized that he can cheat the goalkeeper. After all, they are playing in a football box with solid walls. Robo-Wallace can kick the ball to the other side, then the goalkeeper will not try to catch the ball. Then, if the ball bounces off the wall and flies into the goal, the goal will at last be scored.Your task is to help Robo-Wallace to detect a spot on the wall of the football box, to which the robot should kick the ball, so that the ball bounces once and only once off this wall and goes straight to the goal. In the first half of the match Robo-Wallace got a ball in the head and was severely hit. As a result, some of the schemes have been damaged. Because of the damage, Robo-Wallace can only aim to his right wall (Robo-Wallace is standing with his face to the opposing team's goal).The football box is rectangular. Let's introduce a two-dimensional coordinate system so that point (0, 0) lies in the lower left corner of the field, if you look at the box above. Robo-Wallace is playing for the team, whose goal is to the right. It is an improvised football field, so the gate of Robo-Wallace's rivals may be not in the middle of the left wall. In the given coordinate system you are given: y1, y2 \u2014 the y-coordinates of the side pillars of the goalposts of robo-Wallace's opponents; yw \u2014 the y-coordinate of the wall to which Robo-Wallace is aiming; xb, yb \u2014 the coordinates of the ball's position when it is hit; r \u2014 the radius of the ball. A goal is scored when the center of the ball crosses the OY axis in the given coordinate system between (0, y1) and (0, y2). The ball moves along a straight line. The ball's hit on the wall is perfectly elastic (the ball does not shrink from the hit), the angle of incidence equals the angle of reflection. If the ball bounces off the wall not to the goal, that is, if it hits the other wall or the goal post, then the opposing team catches the ball and Robo-Wallace starts looking for miscalculation and gets dysfunctional. Such an outcome, if possible, should be avoided. We assume that the ball touches an object, if the distance from the center of the ball to the object is no greater than the ball radius r.", "input_spec": "The first and the single line contains integers y1, y2, yw, xb, yb, r (1\u2009\u2264\u2009y1,\u2009y2,\u2009yw,\u2009xb,\u2009yb\u2009\u2264\u2009106; y1\u2009<\u2009y2\u2009<\u2009yw; yb\u2009+\u2009r\u2009<\u2009yw; 2\u00b7r\u2009<\u2009y2\u2009-\u2009y1). It is guaranteed that the ball is positioned correctly in the field, doesn't cross any wall, doesn't touch the wall that Robo-Wallace is aiming at. The goal posts can't be located in the field corners.", "output_spec": "If Robo-Wallace can't score a goal in the described manner, print \"-1\" (without the quotes). Otherwise, print a single number xw \u2014 the abscissa of his point of aiming. If there are multiple points of aiming, print the abscissa of any of them. When checking the correctness of the answer, all comparisons are made with the permissible absolute error, equal to 10\u2009-\u20098. It is recommended to print as many characters after the decimal point as possible.", "sample_inputs": ["4 10 13 10 3 1", "1 4 6 2 2 1", "3 10 15 17 9 2"], "sample_outputs": ["4.3750000000", "-1", "11.3333333333"], "notes": "NoteNote that in the first and third samples other correct values of abscissa xw are also possible."}, "positive_code": [{"source_code": "(* Codeforces 248C Football Robot Electronic *)\n\nopen Big_int;;\nopen List;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet main () =\n\tlet y1 = grf() in\n\tlet y2 = grf() in\n\tlet yw = grf() in\n\tlet xb = grf() in\n\tlet yb = grf() in\n\tlet r = grf() in\n\tbegin\n\t\tif debug then begin\n \t\tprint_string \"y1,y2,yw,xb,yb,r=\";\n \t\tprint_float y1; print_string \" \";\n \t\tprint_float y2; print_string \" \";\n \t\tprint_float yw; print_string \" \";\n \t\tprint_float xb; print_string \" \";\n \t\tprint_float yb; print_string \" \";\n \t\tprint_float r; print_string \" done print input\\n\"\n\t\tend;\n\tlet targ = (y2 +. y1) *. 0.5 in\n\tlet dy2 = yw -. r -. yb in \n\tlet dy1 = yw -. r -. r -. y1 in\n\tlet dy = dy1 +. dy2 in\n\tlet al = atan (xb /. dy) in\n\tlet xw = xb *. dy1 /. dy in \n\tlet halfg = y2 -. y1 -. r in\n\tlet rr = halfg *. (sin al) in\n\tbegin\n\t\tif debug then begin\n \t\tprint_string \"targ dy2 dy1 dy al xw halfg rr =\";\n \t\tprint_float targ; print_string \" \";\n \t\tprint_float dy2; print_string \" \";\n \t\tprint_float dy1; print_string \" \";\n \t\tprint_float dy; print_string \" \";\n \t\tprint_float al; print_string \" \";\n \t\tprint_float xw; print_string \" \";\n \t\tprint_float halfg; print_string \" \";\n \t\tprint_float rr; print_string \" done print vars\\n\"\n\t\tend;\n\tlet retv = \n\t\t(if rr < r then -1.0\n\t\t else if rr > r *. 1.01 then xw -. 0.0001\n\t\t else xw)\n\t\tin\n\tprint_float retv\n\tend end;; \t\n\t\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let rf () = float (read_int()) in\n let y1 = rf() in\n let y2 = rf() in\n let yw = rf() in\n let xb = rf() in\n let yb = rf() in\n let r = rf() in\n\n let yb' = (yw-.r) +. (yw-.r-.yb) in\n (* reflected ball y coordinate *)\n\n let sq x = x*.x in\n\n let a = xb in\n let yh = r +. y1 in\n let b = yb' -. yh in\n let c = sqrt ((sq a) +. (sq b)) in\n let h = (c/.a) *. r in\n let yt = yh +. h in\n if yt >= y2 then Printf.printf \"-1\\n\"\n else (\n (* we aim at position yh *)\n let d = xb in\n let c = yb' -. yh in\n let b = yb' -. (yw -. r) in\n let a = (d/.c) *. b in\n let xw1 = xb -. a in\n\n\tif yb -. r >= y1 then Printf.printf \"%.10f\\n\" xw1\n\telse (\n\t let c = sqrt ((sq xb) +. (sq (y1 -. yb))) in\n\t let alpha = asin (r/.c) in\n\t let beta = asin ((y1 -. yb)/.c) in\n\t let phi = alpha +. beta in\n\t let xw2 = xb -. ((yw -. r -. yb) /. (tan phi)) in\n\t if xw2 > xw1 then Printf.printf \"-1\\n\" else Printf.printf \"%.10f\\n\" xw1\n\t)\n )\n\n\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let rf () = float (read_int()) in\n let y1 = rf() in\n let y2 = rf() in\n let yw = rf() in\n let xb = rf() in\n let yb = rf() in\n let r = rf() in\n\n let yb' = (yw-.r) +. (yw-.r-.yb) in\n (* reflected ball y coordinate *)\n\n let sq x = x*.x in\n\n let a = xb in\n let yh = r +. y1 in\n let b = yb' -. yh in\n let c = sqrt ((sq a) +. (sq b)) in\n let h = (c/.a) *. r in\n let yt = yh +. h in\n if yt >= y2 then Printf.printf \"-1\\n\"\n else (\n (* we aim at position yh *)\n let d = xb in\n let c = yb' -. yh in\n let b = yb' -. (yw -. r) in\n let a = (d/.c) *. b in\n let xw1 = xb -. a in\n\n(*\tif yb -. r >= y1 then Printf.printf \"%.10f\\n\" xw1 *)\n\tif true then Printf.printf \"%.10f\\n\" xw1\n\telse (\n\t let c = sqrt ((sq xb) +. (sq (y1 -. yb))) in\n\t let alpha = asin (r/.c) in\n\t let beta = asin ((y1 -. yb)/.c) in\n\t let phi = alpha +. beta in\n\t let xw2 = xb -. ((yw -. r -. yb) /. (tan phi)) in\n\t if xw2 > xw1 then Printf.printf \"-1\\n\" else Printf.printf \"%.10f\\n\" xw1\n\t)\n )\n\n\n"}], "negative_code": [{"source_code": "(* Codeforces 248C Football Robot Electronic *)\n\nopen Big_int;;\nopen List;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet main () =\n\tlet y1 = grf() in\n\tlet y2 = grf() in\n\tlet yw = grf() in\n\tlet xb = grf() in\n\tlet yb = grf() in\n\tlet r = grf() in\n\tbegin\n\t\tif debug then begin\n \t\tprint_string \"y1,y2,yw,xb,yb,r=\";\n \t\tprint_float y1; print_string \" \";\n \t\tprint_float y2; print_string \" \";\n \t\tprint_float yw; print_string \" \";\n \t\tprint_float xb; print_string \" \";\n \t\tprint_float yb; print_string \" \";\n \t\tprint_float r; print_string \" done print input\\n\"\n\t\tend;\n\tlet targ = (y2 +. y1) *. 0.5 in\n\tlet dy2 = yw -. r -. yb in \n\tlet dy1 = yw -. r -. r -. y1 in\n\tlet dy = dy1 +. dy2 in\n\tlet al = atan (xb /. dy) in\n\tlet xw = xb *. dy1 /. dy in \n\tlet halfg = y2 -. y1 -. r in\n\tlet rr = halfg *. (sin al) in\n\tbegin\n\t\tif debug then begin\n \t\tprint_string \"targ dy2 dy1 dy al xw halfg rr =\";\n \t\tprint_float targ; print_string \" \";\n \t\tprint_float dy2; print_string \" \";\n \t\tprint_float dy1; print_string \" \";\n \t\tprint_float dy; print_string \" \";\n \t\tprint_float al; print_string \" \";\n \t\tprint_float xw; print_string \" \";\n \t\tprint_float halfg; print_string \" \";\n \t\tprint_float rr; print_string \" done print vars\\n\"\n\t\tend;\n\tlet retv = \n\t\t(if rr < r then -1.0\n\t\t else if rr > r *. 1.01 then xw +. 0.0001\n\t\t else xw)\n\t\tin\n\tprint_float retv\n\tend end;; \t\n\t\nmain();;\n"}, {"source_code": "(* Codeforces 248C Football Robot Electronic *)\n\nopen Big_int;;\nopen List;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet main () =\n\tlet y1 = grf() in\n\tlet y2 = grf() in\n\tlet yw = grf() in\n\tlet xb = grf() in\n\tlet yb = grf() in\n\tlet r = grf() in\n\tbegin\n\t\tif debug then begin\n \t\tprint_string \"y1,y2,yw,xb,yb,r=\";\n \t\tprint_float y1; print_string \" \";\n \t\tprint_float y2; print_string \" \";\n \t\tprint_float yw; print_string \" \";\n \t\tprint_float xb; print_string \" \";\n \t\tprint_float yb; print_string \" \";\n \t\tprint_float r; print_string \" done print input\\n\"\n\t\tend;\n\tlet targ = (y2 +. y1) *. 0.5 in\n\tlet dy2 = yw -. r -. yb in \n\tlet dy1 = yw -. r -. targ in\n\tlet dy = dy1 +. dy2 in\n\tlet al = atan (xb /. dy) in\n\tlet xw = xb *. dy1 /. dy in \n\tlet halfg = (y2 -. y1) *. 0.5 in\n\tbegin\n\t\tif debug then begin\n \t\tprint_string \"targ dy2 dy1 dy al xw halfg =\";\n \t\tprint_float targ; print_string \" \";\n \t\tprint_float dy2; print_string \" \";\n \t\tprint_float dy1; print_string \" \";\n \t\tprint_float dy; print_string \" \";\n \t\tprint_float al; print_string \" \";\n \t\tprint_float xw; print_string \" \";\n \t\tprint_float halfg; print_string \" done print vars\\n\"\n\t\tend;\n\tlet retv = \n\t\t(if halfg *. (sin al) < r then -1.0\n\t\t else xw)\n\t\tin\n\tprint_float retv\n\tend end;; \t\n\t\nmain();;\n"}, {"source_code": "(* Codeforces 248C Football Robot Electronic *)\n\nopen Big_int;;\nopen List;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet main () =\n\tlet y1 = grf() in\n\tlet y2 = grf() in\n\tlet yw = grf() in\n\tlet xb = grf() in\n\tlet yb = grf() in\n\tlet r = grf() in\n\tbegin\n\t\tif debug then begin\n \t\tprint_string \"y1,y2,yw,xb,yb,r=\";\n \t\tprint_float y1; print_string \" \";\n \t\tprint_float y2; print_string \" \";\n \t\tprint_float yw; print_string \" \";\n \t\tprint_float xb; print_string \" \";\n \t\tprint_float yb; print_string \" \";\n \t\tprint_float r; print_string \" done print input\\n\"\n\t\tend;\n\tlet targ = (y2 +. y1) *. 0.5 in\n\tlet dy2 = yw -. r -. yb in \n\tlet dy1 = yw -. r -. r -. y1 in\n\tlet dy = dy1 +. dy2 in\n\tlet al = atan (xb /. dy) in\n\tlet xw = xb *. dy1 /. dy in \n\tlet halfg = y2 -. y1 -. r in\n\tlet rr = halfg *. (sin al) in\n\tbegin\n\t\tif debug then begin\n \t\tprint_string \"targ dy2 dy1 dy al xw halfg rr =\";\n \t\tprint_float targ; print_string \" \";\n \t\tprint_float dy2; print_string \" \";\n \t\tprint_float dy1; print_string \" \";\n \t\tprint_float dy; print_string \" \";\n \t\tprint_float al; print_string \" \";\n \t\tprint_float xw; print_string \" \";\n \t\tprint_float halfg; print_string \" \";\n \t\tprint_float rr; print_string \" done print vars\\n\"\n\t\tend;\n\tlet retv = \n\t\t(if rr < r then -1.0\n\t\t else xw)\n\t\tin\n\tprint_float retv\n\tend end;; \t\n\t\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let rf () = float (read_int()) in\n let y1 = rf() in\n let y2 = rf() in\n let yw = rf() in\n let xb = rf() in\n let yb = rf() in\n let r = rf() in\n\n let yb = (yw-.r) +. (yw-.r-.yb) in\n (* reflected ball y coordinate *)\n\n let a = xb in\n let b = yb -. y1 in\n let c = sqrt (a*.a +. b*.b) in\n let h = (c/.a) *. r in\n let yh = r +. y1 in\n let yt = yh +. h in\n\n if yt >= y2 then Printf.printf \"-1\\n\"\n else (\n (* we aim at position yh *)\n let d = xb in\n let c = yb -. yh in\n let b = yb -. (yw -. r) in\n let a = (d/.c) *. b in\n let xw = xb -. a in\n\tPrintf.printf \"%.10f\\n\" xw\n )\n"}], "src_uid": "92c2f3599d221f2b1b695227c5739e84"} {"nl": {"description": "Define the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of n (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness.The mean of a collection is the average of its elements. The median of a collection is its middle element when all of its elements are sorted, or the average of its two middle elements if it has even size.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200 000)\u00a0\u2014 the number of elements in the list. The second line contains n integers xi (0\u2009\u2264\u2009xi\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the ith element of the list.", "output_spec": "In the first line, print a single integer k\u00a0\u2014 the size of the subset. In the second line, print k integers\u00a0\u2014 the elements of the subset in any order. If there are multiple optimal subsets, print any.", "sample_inputs": ["4\n1 2 3 12", "4\n1 1 2 2", "2\n1 2"], "sample_outputs": ["3\n1 2 12", "3\n1 1 2", "2\n1 2"], "notes": "NoteIn the first case, the optimal subset is , which has mean 5, median 2, and simple skewness of 5\u2009-\u20092\u2009=\u20093.In the second case, the optimal subset is . Note that repetition is allowed.In the last case, any subset has the same median and mean, so all have simple skewness of 0."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet float = Int64.to_float\n\nlet ( --- ) (n,d) m = (n -- (d**m), d)\nlet comprat (n1,d1) (n2,d2) = compare (n1**d2) (n2**d1)\nlet max2 (a,i) (b,j) = if comprat a b >=0 then (a,i) else (b,j) \n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max2 (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = Array.init n (fun _ -> long (read_int())) in\n\n Array.sort compare x;\n\n if n <= 2 then (\n printf \"1\\n\";\n printf \"%Ld\\n\" x.(0)\n ) else (\n let (answer3, (c, index)) =\n\n let sum = Array.make (n+1) 0L in\n for i=1 to n do\n\tsum.(i) <- sum.(i-1) ++ x.(i-1)\n done;\n\n let range i j = sum.(j+1) -- sum.(i) in\n \n maxf 1 (n-2) (fun i ->\n\n\tlet mean c =\n\t (* The the mean of the solution that uses c below i\n\t (the median) and c above i. *)\n\t let a1 = range (i-c) (i-1) in\n\t let a2 = range (n-c) (n-1) in\n\t (a1 ++ a2 ++ x.(i), (long (2*c+1))) --- x.(i)\n\tin\n\n\tlet rec ternary lo hi =\n\t if lo=hi then (mean hi, hi)\n\t else if lo+1 = hi then max2 (mean lo, lo) (mean hi, hi)\n\t else if lo+2 = hi then\n\t max2 (max2 (mean lo, lo) (mean hi, hi)) (mean (lo+1), lo+1)\n\t else\n\t let lo1 = (lo+hi)/2 in\n\t let hi1 = lo1 + 1 in\n\t let (ml,mh) = (mean lo1, mean hi1) in\n\t if comprat ml mh > 0 then ternary lo hi1 else ternary lo1 hi\n\tin\n\tlet (ratval, c) = ternary 1 (min i (n-i)) in\n\t(ratval,(c,i))\n )\n in\n if comprat answer3 (0L,1L) > 0 then (\n printf \"%d\\n\" (2*c+1);\n for i=c downto 1 do\n\tprintf \"%Ld \" x.(index-i)\n done;\n printf \"%Ld \" x.(index);\n for i=c downto 1 do\n\tprintf \"%Ld \" x.(n-i)\n done;\n print_newline()\n ) else (\n printf \"1\\n\"; \n printf \"%Ld\\n\" x.(0)\n ) \n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet float = Int64.to_float\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = Array.init n (fun _ -> long (read_int())) in\n\n Array.sort compare x;\n\n if n <= 2 then (\n printf \"1\\n\";\n printf \"%Ld\\n\" x.(0)\n ) else (\n let ((answer3, c), index)=\n\n let sum = Array.make (n+1) 0L in\n for i=1 to n do\n\tsum.(i) <- sum.(i-1) ++ x.(i-1)\n done;\n\n let range i j = sum.(j+1) -- sum.(i) in\n \n maxf 1 (n-2) (fun i ->\n\n\tlet score c =\n\t (* The the mean-median of the solution that uses c below i\n\t (the median) and c above i. *)\n\t let a1 = range (i-c) (i-1) in\n\t let a2 = range (n-c) (n-1) in\n\t (float (a1 ++ a2 ++ x.(i))) /. (float (long (2*c+1))) -. (float x.(i))\n\tin\n\n\tlet rec ternary lo hi =\n\t if lo=hi then (score hi, hi)\n\t else if lo+1 = hi then max (score lo, lo) (score hi, hi)\n\t else if lo+2 = hi then\n\t max (max (score lo, lo) (score hi, hi)) (score (lo+1), lo+1)\n\t else\n\t let lo1 = (lo+hi)/2 in\n\t let hi1 = lo1 + 1 in\n\t let (ml,mh) = (score lo1, score hi1) in\n\t if ml > mh then ternary lo hi1 else ternary lo1 hi\n\tin\n\n\t(ternary 1 (min i (n-i)), i)\n )\n in\n if answer3 > 0.0 then (\n printf \"%d\\n\" (2*c+1);\n for i=c downto 1 do\n\tprintf \"%Ld \" x.(index-c)\n done;\n printf \"%Ld \" x.(index);\n for i=c downto 1 do\n\tprintf \"%Ld \" x.(n-c)\n done;\n print_newline()\n ) else (\n printf \"1\\n\"; \n printf \"%Ld\\n\" x.(0)\n ) \n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = Array.init n (fun _ -> read_int()) in\n\n Array.sort compare x;\n\n if n <= 2 then (\n printf \"1\\n\";\n printf \"%d\\n\" x.(0)\n ) else (\n let (answer3, index)=\n maxf 1 (n-2) (\n\tfun i ->\n\t let x1 = float x.(i-1) in\n\t let x2 = float x.(i) in\n\t let x3 = float x.(n-1) in\n\t ((x1+.x2+.x3) /. 3.0 -. x2, i)\n )\n in\n if answer3 > 0.0 then (\n printf \"3\\n\";\n printf \"%d %d %d\\n\" x.(index-1) x.(index) x.(n-1)\n ) else (\n printf \"1\\n\"; \n printf \"%d\\n\" x.(0)\n ) \n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet float = Int64.to_float\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = Array.init n (fun _ -> long (read_int())) in\n\n Array.sort compare x;\n\n if n <= 2 then (\n printf \"1\\n\";\n printf \"%Ld\\n\" x.(0)\n ) else (\n let ((answer3, c), index)=\n\n let sum = Array.make (n+1) 0L in\n for i=1 to n do\n\tsum.(i) <- sum.(i-1) ++ x.(i-1)\n done;\n\n let range i j = sum.(j+1) -- sum.(i) in\n \n maxf 1 (n-2) (fun i ->\n\n\tlet score c =\n\t (* The the mean-median of the solution that uses c below i\n\t (the median) and c above i. *)\n\t let a1 = range (i-c) (i-1) in\n\t let a2 = range (n-c) (n-1) in\n\t (float (a1 ++ a2 ++ x.(i))) /. (float (long (2*c+1))) -. (float x.(i))\n\tin\n\n\tlet rec ternary lo hi =\n\t if lo=hi then (score hi, hi)\n\t else if lo+1 = hi then max (score lo, lo) (score hi, hi)\n\t else if lo+2 = hi then\n\t max (max (score lo, lo) (score hi, hi)) (score (lo+1), lo+1)\n\t else\n\t let lo1 = (lo+hi)/2 in\n\t let hi1 = lo1 + 1 in\n\t let (ml,mh) = (score lo1, score hi1) in\n\t if ml > mh then ternary lo hi1 else ternary lo1 hi\n\tin\n\n\t(ternary 1 (min i (n-i)), i)\n )\n in\n if answer3 > 0.0 then (\n printf \"%d\\n\" (2*c+1);\n for i=c downto 1 do\n\tprintf \"%Ld \" x.(index-i)\n done;\n printf \"%Ld \" x.(index);\n for i=c downto 1 do\n\tprintf \"%Ld \" x.(n-i)\n done;\n print_newline()\n ) else (\n printf \"1\\n\"; \n printf \"%Ld\\n\" x.(0)\n ) \n )\n"}], "src_uid": "ecda878d924325789dc05035e4f4bbe0"} {"nl": {"description": "Edogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that aj\u2009<\u2009ai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of cards Conan has. The next line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105), where ai is the number on the i-th card.", "output_spec": "If Conan wins, print \"Conan\" (without quotes), otherwise print \"Agasa\" (without quotes).", "sample_inputs": ["3\n4 5 7", "2\n1 1"], "sample_outputs": ["Conan", "Agasa"], "notes": "NoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again."}, "positive_code": [{"source_code": "let get_int () = Scanf.scanf \" %d\" (fun i -> i)\nlet get_float () = Scanf.scanf \" %f\" (fun i -> i)\n\nlet get_array n =\n let rec aux acc k =\n if k = 0 then acc\n else aux (get_int () :: acc) (k - 1)\n in aux [] n\n\nlet main () =\n let n = get_int () in\n let a = get_array n in\n let sorted = List.sort (fun x y -> (compare y x)) a in\n let rec aux k = function\n | a :: (b :: _ as t) ->\n if a = b then aux (k + 1) t\n else\n if (k + 1) mod 2 = 0 then aux 0 t\n else \"Conan\"\n | _ ->\n if (k + 1) mod 2 = 0 then \"Agasa\"\n else \"Conan\"\n in\n let ans = aux 0 sorted in\n Printf.printf \"%s\" ans\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "864593dc3911206b627dab711025e116"} {"nl": {"description": "One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n, 1\u2009\u2264\u2009k\u2009\u2264\u2009m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names \"CBDAD\" and \"AABRD\" and swap their prefixes with the length of 3, the result will be names \"AABAD\" and \"CBDRD\".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109\u2009+\u20097).", "input_spec": "The first input line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.", "output_spec": "Print the single number \u2014 the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["2 3\nAAB\nBAA", "4 5\nABABA\nBCGDG\nAAAAA\nYABSA"], "sample_outputs": ["4", "216"], "notes": "NoteIn the first sample Vasya can get the following names in the position number 1: \"AAB\", \"AAA\", \"BAA\" and \"BAB\"."}, "positive_code": [{"source_code": "let next_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun s -> s) ;;\nlet next_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun s -> s) ;;\nlet n = next_int () ;;\nlet m = next_int () ;;\nlet a = Array.init n (fun s -> next_string ()) ;;\nlet ret = ref 1L ;;\nlet k = Array.init m (fun i ->\n let h = Hashtbl.create n in\n Array.iter (fun s -> Hashtbl.replace h s.[i] ()) a;\n Hashtbl.length h\n) ;;\nPrintf.printf \"%Ld\\n\" (Array.fold_left (fun a l -> Int64.rem (Int64.mul a l)\n1000000007L) Int64.one (Array.map Int64.of_int k)) ;;\n"}], "negative_code": [], "src_uid": "a37df9b239a40473516d1525d56a0da7"} {"nl": {"description": "You are given three positive integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$a < b < c$$$). You have to find three positive integers $$$x$$$, $$$y$$$, $$$z$$$ such that:$$$$$$x \\bmod y = a,$$$$$$ $$$$$$y \\bmod z = b,$$$$$$ $$$$$$z \\bmod x = c.$$$$$$Here $$$p \\bmod q$$$ denotes the remainder from dividing $$$p$$$ by $$$q$$$. It is possible to show that for such constraints the answer always exists.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. Each test case contains a single line with three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \\le a < b < c \\le 10^8$$$).", "output_spec": "For each test case output three positive integers $$$x$$$, $$$y$$$, $$$z$$$ ($$$1 \\le x, y, z \\le 10^{18}$$$) such that $$$x \\bmod y = a$$$, $$$y \\bmod z = b$$$, $$$z \\bmod x = c$$$. You can output any correct answer.", "sample_inputs": ["4\n1 3 4\n127 234 421\n2 7 8\n59 94 388"], "sample_outputs": ["12 11 4\n1063 234 1484\n25 23 8\n2221 94 2609"], "notes": "NoteIn the first test case:$$$$$$x \\bmod y = 12 \\bmod 11 = 1;$$$$$$$$$$$$y \\bmod z = 11 \\bmod 4 = 3;$$$$$$$$$$$$z \\bmod x = 4 \\bmod 12 = 4.$$$$$$"}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\n\r\n(* x mod y = a *)\r\n(* y mod z = b *)\r\n(* z mod x = c *)\r\n\r\n(* x = a + dy *)\r\n(* y = b + ez *)\r\n(* z = c + fx *)\r\n\r\n(* y = b + e(c + fx) *)\r\n(* x = a + d(b + e(c+fx)) *)\r\n(* x(1-def) = a + db + dec *)\r\n(* either d,e,f=1 or one of d, e, f = 0*)\r\n(* y = b + e(c + f(a + dy)) *)\r\n(* y(1-def) = b + ec + efa *)\r\n(* z(1-def) = c + fa + fdb *)\r\n\r\n(* if d,e, f = 1, a+b+c=0 *)\r\n(* if d=0, x = a, y = b + ec+efa, z = c + fa *)\r\n(* if e= 0, y = b *)\r\n(* if f=0, z = c, x =a+db+dec, y=b+ec*)\r\n(* 1 3 4 -> z = 4, x=1+3d+4ed, y=3+4e*)\r\n(* if e=0 and f=0, y=b, z=c, x=a+db*)\r\n(* y=3, z=4 and xmod3=1 and 4modx=4*)\r\n(* x =1+3p, 4=4+xq, 4=4+(1+3p)q*)\r\n(* x=a+bp = c + aq, p=(c-a+aq)/b*)\r\nlet rec get_x = function\r\n | a, b, c, d ->\r\n let x = a+d*b in\r\n if (x mod b == a && c mod x == c && b mod c = b) then x\r\n else get_x (a, b, c, (d+1))\r\n;;\r\nlet rec run_cases = function\r\n | 0 -> 0\r\n | n -> \r\n let a = read_int () in\r\n let y = read_int () in\r\n let z = read_int () in\r\n let d = (z-a)/y in\r\n let x = get_x (a, y, z, d) in\r\n print_int x; print_string \" \";\r\n print_int y; print_string \" \";\r\n print_int z; print_string \" \";\r\n print_newline ();\r\n run_cases (n-1)\r\n;;\r\nlet num_cases = read_int () in\r\nrun_cases num_cases\r\n;;\r\n"}], "negative_code": [], "src_uid": "f0c22161cb5a9bc17320ccd05517f867"} {"nl": {"description": "A median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2,\u20096,\u20091,\u20092,\u20093) is the number 2, and a median of array (0,\u200996,\u200917,\u200923) \u2014 the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.", "input_spec": "The first input line contains two space-separated integers n and x (1\u2009\u2264\u2009n\u2009\u2264\u2009500, 1\u2009\u2264\u2009x\u2009\u2264\u2009105) \u2014 the initial array's length and the required median's value. The second line contains n space-separated numbers \u2014 the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.", "output_spec": "Print the only integer \u2014 the minimum number of elements Petya needs to add to the array so that its median equals x.", "sample_inputs": ["3 10\n10 20 30", "3 4\n1 2 3"], "sample_outputs": ["1", "4"], "notes": "NoteIn the first sample we can add number 9 to array (10,\u200920,\u200930). The resulting array (9,\u200910,\u200920,\u200930) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4."}, "positive_code": [{"source_code": "type t = J of int\n | P of int\nlet _ =\n let rdint =\n let l = ref 0 in\n let i = ref 0 in\n let s = String.create 65536 in\n let refill () =\n let n = input stdin s 0 65536 in\n i := 0;\n l := n in\n refill ();\n\n fun () ->\n let rec loop2 j k t f =\n let fin j t f =\n let _ = i := j in\n t * f in\n\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop2 !i !l t f else fin j t f\n ) else if s.[j] >= '0' && s.[j] <= '9' then\n loop2 (j + 1) k (t * 10 + Char.code s.[j] - 48) f\n else fin j t f in\n\n let rec loop1 j k =\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop1 !i !l else 0\n ) else if s.[j] = '-' then loop2 (j + 1) k 0 (-1)\n else if s.[j] >= '0' && s.[j] <= '9' then loop2 (j + 1) k (Char.code s.[j] - 48) 1\n else loop1 (j + 1) k in\n loop1 !i !l\n in\n\n let main () =\n let n = rdint () in\n let x = rdint () in\n let arr = Array.init n (fun _ -> rdint ()) in\n let l = Array.to_list arr in\n let q = if List.exists (fun t -> t = x) l then 0 else 1 in\n let l = if q = 1 then x :: l else l in\n let arr = Array.of_list l in\n let n = n + q in\n Array.sort compare arr;\n\n let r =\n let med = arr.((n - 1) / 2) in\n let rec search p v =\n if arr.(p) = x then p else\n search (p + v) v\n in\n if med = x then 0 else\n if med > x then (\n let p = search ((n - 1) / 2) (- 1) in\n n - 2 * (p + 1)\n ) else (\n let p = search ((n - 1) / 2) 1 in\n p * 2 + 1 - n\n )\n in\n Printf.printf \"%d\\n\" (r + q)\n in\n main ()\n"}], "negative_code": [{"source_code": "let _ =\n let rdint =\n let l = ref 0 in\n let i = ref 0 in\n let s = String.create 65536 in\n let refill () =\n let n = input stdin s 0 65536 in\n i := 0;\n l := n in\n refill ();\n\n fun () ->\n let rec loop2 j k t f =\n let fin j t f =\n let _ = i := j in\n t * f in\n\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop2 !i !l t f else fin j t f\n ) else if s.[j] >= '0' && s.[j] <= '9' then\n loop2 (j + 1) k (t * 10 + Char.code s.[j] - 48) f\n else fin j t f in\n\n let rec loop1 j k =\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop1 !i !l else 0\n ) else if s.[j] = '-' then loop2 (j + 1) k 0 (-1)\n else if s.[j] >= '0' && s.[j] <= '9' then loop2 (j + 1) k (Char.code s.[j] - 48) 1\n else loop1 (j + 1) k in\n loop1 !i !l\n in\n\n let main () =\n let n = rdint () in\n let x = rdint () in\n let arr = Array.init n (fun _ -> rdint ()) in\n Array.sort compare arr;\n\n let r =\n let med = arr.((n - 1) / 2) in\n let rec search p v =\n if p < 0 || p >= n then p else\n if arr.(p) = x then p else search (p + v) v\n in\n if med = x then 0 else\n if med > x then (\n let p = search ((n - 1) / 2) (-1) in\n n - 2 * (p + 1)\n ) else (\n let p = search ((n - 1) / 2) 1 in\n p * 2 + 1 - n\n )\n in\n Printf.printf \"%d\\n\" r\n in\n main ()\n"}], "src_uid": "1a73bda2b9c2038d6ddf39918b90da61"} {"nl": {"description": "Shinju loves permutations very much! Today, she has borrowed a permutation $$$p$$$ from Juju to play with.The $$$i$$$-th cyclic shift of a permutation $$$p$$$ is a transformation on the permutation such that $$$p = [p_1, p_2, \\ldots, p_n] $$$ will now become $$$ p = [p_{n-i+1}, \\ldots, p_n, p_1,p_2, \\ldots, p_{n-i}]$$$.Let's define the power of permutation $$$p$$$ as the number of distinct elements in the prefix maximums array $$$b$$$ of the permutation. The prefix maximums array $$$b$$$ is the array of length $$$n$$$ such that $$$b_i = \\max(p_1, p_2, \\ldots, p_i)$$$. For example, the power of $$$[1, 2, 5, 4, 6, 3]$$$ is $$$4$$$ since $$$b=[1,2,5,5,6,6]$$$ and there are $$$4$$$ distinct elements in $$$b$$$.Unfortunately, Shinju has lost the permutation $$$p$$$! The only information she remembers is an array $$$c$$$, where $$$c_i$$$ is the power of the $$$(i-1)$$$-th cyclic shift of the permutation $$$p$$$. She's also not confident that she remembers it correctly, so she wants to know if her memory is good enough.Given the array $$$c$$$, determine if there exists a permutation $$$p$$$ that is consistent with $$$c$$$. You do not have to construct the permutation $$$p$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 5 \\cdot 10^3$$$) \u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1,c_2,\\ldots,c_n$$$ ($$$1 \\leq c_i \\leq n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print \"YES\" if there is a permutation $$$p$$$ exists that satisfies the array $$$c$$$, and \"NO\" otherwise. You can output \"YES\" and \"NO\" in any case (for example, strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive response).", "sample_inputs": ["6\n\n1\n\n1\n\n2\n\n1 2\n\n2\n\n2 2\n\n6\n\n1 2 4 6 3 5\n\n6\n\n2 3 1 2 3 4\n\n3\n\n3 2 1"], "sample_outputs": ["YES\nYES\nNO\nNO\nYES\nNO"], "notes": "NoteIn the first test case, the permutation $$$[1]$$$ satisfies the array $$$c$$$.In the second test case, the permutation $$$[2,1]$$$ satisfies the array $$$c$$$.In the fifth test case, the permutation $$$[5, 1, 2, 4, 6, 3]$$$ satisfies the array $$$c$$$. Let's see why this is true. The zeroth cyclic shift of $$$p$$$ is $$$[5, 1, 2, 4, 6, 3]$$$. Its power is $$$2$$$ since $$$b = [5, 5, 5, 5, 6, 6]$$$ and there are $$$2$$$ distinct elements \u2014 $$$5$$$ and $$$6$$$. The first cyclic shift of $$$p$$$ is $$$[3, 5, 1, 2, 4, 6]$$$. Its power is $$$3$$$ since $$$b=[3,5,5,5,5,6]$$$. The second cyclic shift of $$$p$$$ is $$$[6, 3, 5, 1, 2, 4]$$$. Its power is $$$1$$$ since $$$b=[6,6,6,6,6,6]$$$. The third cyclic shift of $$$p$$$ is $$$[4, 6, 3, 5, 1, 2]$$$. Its power is $$$2$$$ since $$$b=[4,6,6,6,6,6]$$$. The fourth cyclic shift of $$$p$$$ is $$$[2, 4, 6, 3, 5, 1]$$$. Its power is $$$3$$$ since $$$b = [2, 4, 6, 6, 6, 6]$$$. The fifth cyclic shift of $$$p$$$ is $$$[1, 2, 4, 6, 3, 5]$$$. Its power is $$$4$$$ since $$$b = [1, 2, 4, 6, 6, 6]$$$. Therefore, $$$c = [2, 3, 1, 2, 3, 4]$$$.In the third, fourth, and sixth testcases, we can show that there is no permutation that satisfies array $$$c$$$."}, "positive_code": [{"source_code": "let parse s len = let rep = Array.make len 0 in\r\n let temp = ref \"\" in\r\n let count = ref 0 in\r\n for j = 0 to String.length s -1 do\r\n if s.[j] = ' ' then (rep.(!count)<-(int_of_string !temp) ; incr count ; temp := \"\")\r\n else (temp := !temp ^ (String.make 1 s.[j]))\r\n done; rep.(!count)<-(int_of_string !temp) ; rep ;;\r\n\r\nlet finish tab = let icount = ref 0 in\r\n let oky = ref true in\r\n if tab.(0) = 1 then incr icount ;\r\n if tab.(0) > tab.(Array.length tab -1) +1 then oky := false ;\r\n for i = 1 to Array.length tab -1 do\r\n if tab.(i) = 1 then incr icount ;\r\n if tab.(i) > tab.(i-1)+1 then oky := false ;\r\n done;\r\n (!icount = 1 && (!oky));;\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string(input_line stdin) in\r\n let str = (input_line stdin) in\r\n let toto = parse str len in\r\n let tototo = finish toto in\r\n if tototo then print_endline \"YES\" else print_endline \"NO\" \r\ndone;\r\n;;"}], "negative_code": [], "src_uid": "a6c6b2a66ba51249fdc5d4188ca09e3b"} {"nl": {"description": "You have a rectangular chocolate bar consisting of n\u2009\u00d7\u2009m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar. In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.For example, if you have a chocolate bar consisting of 2\u2009\u00d7\u20093 unit squares then you can break it horizontally and get two 1\u2009\u00d7\u20093 pieces (the cost of such breaking is 32\u2009=\u20099), or you can break it vertically in two ways and get two pieces: 2\u2009\u00d7\u20091 and 2\u2009\u00d7\u20092 (the cost of such breaking is 22\u2009=\u20094).For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n\u00b7m\u2009-\u2009k squares are not necessarily form a single rectangular piece.", "input_spec": "The first line of the input contains a single integer t (1\u2009\u2264\u2009t\u2009\u2264\u200940910)\u00a0\u2014 the number of values n, m and k to process. Each of the next t lines contains three integers n, m and k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200930,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009min(n\u00b7m,\u200950))\u00a0\u2014 the dimensions of the chocolate bar and the number of squares you want to eat respectively.", "output_spec": "For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.", "sample_inputs": ["4\n2 2 1\n2 2 3\n2 2 2\n2 2 4"], "sample_outputs": ["5\n5\n4\n0"], "notes": "NoteIn the first query of the sample one needs to perform two breaks: to split 2\u2009\u00d7\u20092 bar into two pieces of 2\u2009\u00d7\u20091 (cost is 22\u2009=\u20094), to split the resulting 2\u2009\u00d7\u20091 into two 1\u2009\u00d7\u20091 pieces (cost is 12\u2009=\u20091). In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample."}, "positive_code": [{"source_code": "let _ =\n let min (x : int) y = if x < y then x else y in\n let sb = Scanf.Scanning.stdib in\n let n = 30\n and m = 30\n and kk = 50 in\n let a =\n Array.init (n + 1)\n (fun _ -> Array.make_matrix (m + 1) (kk + 1) 100000000)\n in\n for i = 1 to n do\n for j = 1 to m do\n\ta.(i).(j).(0) <- 0;\n\tif i * j <= kk\n\tthen a.(i).(j).(i * j) <- 0;\n\tfor k = 1 to kk do\n\t for i' = 1 to i - 1 do\n\t for k' = 0 to k do\n\t a.(i).(j).(k) <-\n\t\tmin a.(i).(j).(k)\n\t\t(a.(i').(j).(k') + a.(i - i').(j).(k - k') + j * j);\n\t done;\n\t done;\n\t for j' = 1 to j - 1 do\n\t for k' = 0 to k do\n\t a.(i).(j).(k) <-\n\t\tmin a.(i).(j).(k)\n\t\t(a.(i).(j').(k') + a.(i).(j - j').(k - k') + i * i);\n\t done;\n\t done;\n\t (*Printf.printf \"asd %d %d %d %d\\n\" i j k a.(i).(j).(k);*)\n\tdone\n done\n done;\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for ca = 1 to t do\n\tlet n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tlet m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tlet kk = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t Printf.printf \"%d\\n\" a.(n).(m).(kk)\n done\n"}], "negative_code": [{"source_code": "let _ =\n let min (x : int) y = if x < y then x else y in\n let sb = Scanf.Scanning.stdib in\n let n = 30\n and m = 30\n and kk = 50 in\n let a =\n Array.init (n + 1)\n (fun _ -> Array.make_matrix (m + 1) (kk + 1) 1000000000)\n in\n for i = 1 to n do\n for j = 1 to m do\n\ta.(i).(j).(0) <- 0;\n\tif i * j <= kk\n\tthen a.(i).(j).(i * j) <- 0;\n\tfor k = 1 to kk do\n\t for i' = 1 to i - 1 do\n\t for k' = 0 to k do\n\t a.(i).(j).(k) <-\n\t\tmin a.(i).(j).(k)\n\t\t(a.(i').(j).(k') + a.(i - i').(j).(k - k') + j * j);\n\t done;\n\t done;\n\t for j' = 1 to j - 1 do\n\t for k' = 0 to k do\n\t a.(i).(j).(k) <-\n\t\tmin a.(i).(j).(k)\n\t\t(a.(i).(j').(k') + a.(i).(j - j').(k - k') + i * i);\n\t done;\n\t done;\n\t (*Printf.printf \"asd %d %d %d %d\\n\" i j k a.(i).(j).(k);*)\n\tdone\n done\n done;\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for ca = 1 to t do\n\tlet n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tlet m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tlet kk = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t Printf.printf \"%d\\n\" a.(n).(m).(kk)\n done\n"}, {"source_code": "let _ =\n let min (x : int) y = if x < y then x else y in\n let sb = Scanf.Scanning.stdib in\n let t = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for ca = 1 to t do\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let kk = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a =\n\tArray.init (n + 1)\n\t (fun _ -> Array.make_matrix (m + 1) (kk + 1) 1000000000)\n in\n\tfor i = 1 to n do\n\t for j = 1 to m do\n\t a.(i).(j).(1) <- 0;\n\t for k = 2 to kk do\n\t for i' = 1 to i - 1 do\n\t\tfor k' = 1 to k - 1 do\n\t\t a.(i).(j).(k) <-\n\t\t min a.(i).(j).(k)\n\t\t (a.(i').(j).(k') + a.(i - i').(j).(k - k') + j * j)\n\t\tdone;\n\t done;\n\t for j' = 1 to j - 1 do\n\t\tfor k' = 1 to k - 1 do\n\t\t a.(i).(j).(k) <-\n\t\t min a.(i).(j).(k)\n\t\t (a.(i).(j').(k') + a.(i).(j - j').(k - k') + i * i)\n\t\tdone;\n\t done;\n\t done\n\t done\n\tdone;\n\tPrintf.printf \"%d\\n\" a.(n).(m).(kk)\n done\n"}], "src_uid": "d154c3df1947f52ec370c6ad2771eb47"} {"nl": {"description": "Friday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite game Fur2 and didn't have enough time to do the literature task. As Innocentius didn't want to get an F, he decided to do the task and read the book called \"Storm and Calm\" during the IT and Math lessons (he never used to have problems with these subjects). When the IT teacher Mr. Watkins saw this, he decided to give Innocentius another task so that the boy concentrated more on the lesson and less \u2014 on the staff that has nothing to do with IT. Mr. Watkins said that a palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. A concatenation of strings a, b is a string ab that results from consecutive adding of string b to string a. Of course, Innocentius knew it all but the task was much harder than he could have imagined. Mr. Watkins asked change in the \"Storm and Calm\" the minimum number of characters so that the text of the book would also be a concatenation of no more than k palindromes. Innocentius can't complete the task and therefore asks you to help him.", "input_spec": "The first input line contains a non-empty string s which is the text of \"Storm and Calm\" (without spaces). The length of the string s does not exceed 500 characters. String s consists of uppercase and lowercase Latin letters. The second line contains a single number k (1\u2009\u2264\u2009k\u2009\u2264\u2009|s|, where |s| represents the length of the string s).", "output_spec": "Print on the first line the minimum number of changes that Innocentius will have to make. Print on the second line the string consisting of no more than k palindromes. Each palindrome should be non-empty and consist of uppercase and lowercase Latin letters. Use the character \"+\" (ASCII-code 43) to separate consecutive palindromes. If there exist several solutions, print any of them. The letters' case does matter, that is an uppercase letter is not considered equivalent to the corresponding lowercase letter.", "sample_inputs": ["abacaba\n1", "abdcaba\n2", "abdcaba\n5", "abacababababbcbabcd\n3"], "sample_outputs": ["0\nabacaba", "1\nabdcdba", "0\na+b+d+c+aba", "1\nabacaba+babab+bcbabcb"], "notes": null}, "positive_code": [{"source_code": "\nlet getint () = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun i->i)\nlet getstr () = Scanf.bscanf Scanf.Scanning.stdin \" %s\" (fun s-> s)\nlet getchar () = Scanf.bscanf Scanf.Scanning.stdin \" %c\" (fun i->i)\nlet inf = 1000000007\n\nlet s = getstr ()\nlet n = String.length s\nlet k = getint ()\nlet cost = Array.make_matrix n n 0\nlet dp = Array.make_matrix (n+1) (k+1) inf\nlet tb = Array.make_matrix (n+1) (k+1) 0\n\n\n \nlet calc_cost () =\n for i = 0 to n-1 do\n for j = i to n-1 do\n let i' = ref i and j' = ref j in\n while !i' <= !j' do\n if s.[!i'] <> s.[!j'] then cost.(i).(j) <- cost.(i).(j) + 1;\n incr i'; decr j'\n done\n done\n done\n\n\nlet minimize () = \n for j = 0 to k do\n dp.(0).(j) <- 0\n done;\n for i = 1 to n do\n for j = 1 to k do\n for m = 0 to i-1 do\n if dp.(i).(j) > dp.(m).(j-1) + cost.(m).(i-1) \n then \n begin\n dp.(i).(j) <- dp.(m).(j-1) + cost.(m).(i-1); \n tb.(i).(j) <- m \n end\n done\n done\n done\n\n\nlet trace_back () = \n let len = ref n and k' = ref k and l = ref [] in\n while !len <> 0 do\n l := (!len - tb.(!len).(!k')) :: !l;\n len := tb.(!len).(!k');\n decr k'\n done;\n let last = ref 0 in\n List.iter\n (\n fun len -> \n let i = ref !last and j = ref (!last + len - 1) in\n while !i <= !j do\n if s.[!i] <> s.[!j] then s.[!i] <- s.[!j];\n incr i; decr j\n done;\n for i = !last to !last+ len - 1 do\n print_char s.[i];\n done;\n last := !last + len;\n if !last <> n then print_char '+'\n else print_char '\\n';\n )\n !l \n\nlet _ = \n calc_cost ();\n minimize ();\n print_int dp.(n).(k); print_newline ();\n trace_back ()\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet read_string () = Scanf.scanf \" %s \" (fun x -> x);;\n\nlet str = read_string ();;\nlet k = read_int ();;\nlet n = String.length str;;\n\nlet dp = Array.create_matrix 505 505 10000000;;\nlet cnt = Array.create_matrix 505 505 0;;\nlet mark = Array.create_matrix 505 505 0;;\n\nlet _ = for i = 0 to (n-1) do\n for j = (i+1) to (n-1) do\n for t1 = i to ((j+i)/2) do\n if str.[t1]!=str.[j-t1+i] then cnt.(i).(j) <- cnt.(i).(j) + 1\n done\n done\n done;;\n\nlet _ = for i = 0 to (n-1) do\n dp.(i).(1) <- cnt.(0).(i);\n mark.(i).(1) <- -1\n done;;\n\nlet _ = for i = 0 to (n-1) do\n for j = 2 to (min (i+1) k) do\n for t = 0 to (i-1) do\n if dp.(t).(j-1) + cnt.(t+1).(i) < dp.(i).(j) then\n begin\n dp.(i).(j) <- dp.(t).(j-1) + cnt.(t+1).(i);\n mark.(i).(j) <- t\n end\n done\n done\n done;;\n\nlet ans = ref 10000000;; \nlet len = ref (-1);;\nlet p = ref 0;;\n\nlet _ = for i = 1 to k do\n if dp.(n-1).(i) < !ans then \n begin\n ans := dp.(n-1).(i);\n len := i;\n p := mark.(n-1).(i)\n end\n done;;\n\nlet rec solve2 str i j = \n if i>=j then str\n else if str.[i]!=str.[j] then begin str.[i] <- str.[j]; solve2 str (i+1) (j-1) end\n else solve2 str (i+1) (j-1);;\n\nlet rec solve str len s t = \n if len = 1 then solve2 (String.sub str s (t-s+1)) 0 (t-s)\n else solve (String.sub str 0 s) (len-1) (mark.(s-1).(len-1)+1) (s-1) ^ \"+\" ^ solve2 (String.sub str s (t-s+1)) 0 (t-s);; \n \nif n = 1 then Printf.printf \"0\\n%s\\n\" str\nelse Printf.printf \"%d\\n%s\\n\" (!ans) (solve str (!len) (!p+1) (n-1));;\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet read_string () = Scanf.scanf \" %s \" (fun x -> x);;\n\nlet str = read_string ();;\nlet k = read_int ();;\nlet n = String.length str;;\n\nlet dp = Array.create_matrix 505 505 10000000;;\nlet cnt = Array.create_matrix 505 505 0;;\nlet mark = Array.create_matrix 505 505 0;;\n\nlet _ = for i = 0 to (n-1) do\n for j = (i+1) to (n-1) do\n for t1 = i to ((j+i)/2) do\n if str.[t1]!=str.[j-t1+i] then cnt.(i).(j) <- cnt.(i).(j) + 1\n done\n done\n done;;\n\nlet _ = for i = 0 to (n-1) do\n dp.(i).(1) <- cnt.(0).(i);\n mark.(i).(1) <- -1\n done;;\n\nlet _ = for i = 0 to (n-1) do\n for j = 2 to (min (i+1) k) do\n for t = 0 to (i-1) do\n if dp.(t).(j-1) + cnt.(t+1).(i) < dp.(i).(j) then\n begin\n dp.(i).(j) <- dp.(t).(j-1) + cnt.(t+1).(i);\n mark.(i).(j) <- t\n end\n done\n done\n done;;\n\nlet ans = ref 10000000;; \nlet len = ref (-1);;\nlet p = ref 0;;\n\nlet _ = for i = 1 to k do\n if dp.(n-1).(i) < !ans then \n begin\n ans := dp.(n-1).(i);\n len := i;\n p := mark.(n-1).(i)\n end\n done;;\n\nlet rec solve2 str i j = \n if i>=j then str\n else if str.[i]!=str.[j] then begin str.[i] <- str.[j]; solve2 str (i+1) (j-1) end\n else solve2 str (i+1) (j-1);;\n\nlet rec solve str len s t str_ans = \n if len = 0 then str_ans\n else if len = 1 then solve \"\" 0 0 0 (solve2 (String.sub str s (t-s+1)) 0 (t-s) ^ str_ans )\n else solve (String.sub str 0 s) (len-1) (mark.(s-1).(len-1)+1) (s-1) (\"+\" ^ solve2 (String.sub str s (t-s+1)) 0 (t-s) ^ str_ans) ;; \n \nif n = 1 then Printf.printf \"0\\n%s\\n\" str\nelse let str_ans = (solve str (!len) (!p+1) (n-1) \"\") in Printf.printf \"%d\\n%s\\n\" (!ans) str_ans;;\n"}, {"source_code": "let s = input_line stdin;;\nlet n = String.length s;;\nlet k = read_int ();;\nlet f = Array.make_matrix n n 0;;\nfor i = n - 1 downto 0 do\n for j = i to n - 1 do\n if i == j then begin\n f.(i).(j) <- 0\n end else if i + 1 == j then begin\n f.(i).(j) <- if s.[i] != s.[j] then 1 else 0;\n end else begin\n f.(i).(j) <- f.(i + 1).(j - 1) + if s.[i] != s.[j] then 1 else 0;\n end;\n done\ndone;;\nlet g = Array.make_matrix (n + 1) (n + 1) 12345;;\nlet p = Array.make_matrix (n + 1) (n + 1) 12345;;\ng.(0).(0) <- 0;;\nfor i = 0 to n - 1 do\n for j = 0 to i do\n for l = i + 1 to n do\n let cur = g.(i).(j) + f.(i).(l - 1) in\n if g.(l).(j + 1) > cur then begin\n g.(l).(j + 1) <- cur;\n p.(l).(j + 1) <- i;\n end\n done;\n done\ndone;;\nlet h = Array.make n \"\";;\nlet u = ref 0;;\nlet v = ref n;;\nfor j = 0 to k do\n if g.(n).(!u) > g.(n).(j) then begin u := j end\ndone;;\nPrintf.printf \"%d\\n\" g.(n).(!u);; \nlet w = ref 0;;\nfor j = 0 to !u - 1 do\n let c = String.sub s p.(!v).(!u - j) (!v - p.(!v).(!u - j)) in\n let t = String.length c in\n let x = ref 0 in\n let y = ref (t - 1) in begin\n while !x < !y do\n c.[!y] <- c.[!x];\n x := !x + 1;\n y := !y - 1;\n done;\n h.(j) <- c;\n v := p.(!v).(!u - j);\n end;\ndone;;\nfor j = !u - 1 downto 0 do\n Printf.printf \"%s%s\" h.(j) (if j == 0 then \"\\n\" else \"+\");\ndone;;\n"}, {"source_code": "let main() =\n let s = Scanf.scanf \" %s\" (fun i -> i) in\n let n = String.length s in\n let k = Scanf.scanf \" %d\" (fun i -> i) in\n let a = Array.make_matrix n n 0 in\n let rec d1 l =\n let rec d2 i =\n let j = i + l - 1 in\n if j < n then (a.(i).(j) <- (if l == 2 then 0 else a.(i+1).(j-1)) + (if s.[i] == s.[j] then 0 else 1); d2 (i+1)) else ()\n in\n d2 0;\n if l < n then d1 (l+1) else ()\n in\n d1 2;\n let b = Array.make_matrix (k+1) (n+1) (2*n) in\n let p = Array.make_matrix (k+1) (n+1) (-1) in\n b.(0).(0) <- 0;\n let rec f1 l =\n let br = b.(l-1) in let bn = b.(l) in\n let rec f2 i =\n let x = br.(i) in let y = a.(i) in\n let rec f3 j =\n let v = x + y.(j-1) in\n if bn.(j) > v then (bn.(j) <- v; p.(l).(j) <- i) else ();\n if j < n then f3 (j+1) else ()\n in\n f3 (i+1);\n if i < (n-1) then f2 (i+1) else ()\n in\n f2 0;\n if l < k then f1 (l+1) else ();\n in\n f1 1;\n let d = Array.init k (fun i -> b.(i+1).(n), i+1) in\n let best_v, best_k = Array.fold_left (fun b x -> if (fst b) < (fst x) then b else x) (2*n, -1) d in\n let rec h i j =\n if i < j then (s.[j] <- s.[i]; h (i+1) (j-1)) else ()\n in\n let g i j =\n h i j;\n String.sub s i (j - i + 1)\n in\n let rec ans k j l =\n if k = 0 then l else (let i = p.(k).(j) in ans (k-1) i ((g i (j-1))::l))\n in\n Printf.printf \"%d\\n%s\\n\" best_v (String.concat \"+\" (ans best_k n []))\n ;;\nmain()"}, {"source_code": "let main() =\n let s = Scanf.scanf \" %s\" (fun i -> i) in\n let n = String.length s in\n let k = Scanf.scanf \" %d\" (fun i -> i) in\n let a = Array.make_matrix n n 0 in\n for l = 2 to n do\n for i = 0 to n-l do\n let j = i + l - 1 in\n a.(i).(j) <- (if l == 2 then 0 else a.(i+1).(j-1)) + (if s.[i] == s.[j] then 0 else 1);\n done;\n done;\n let b = Array.make_matrix (k+1) (n+1) (2*n) in let p = Array.make_matrix (k+1) (n+1) (-1) in\n b.(0).(0) <- 0;\n for l = 1 to k do\n let br = b.(l-1) in let bn = b.(l) in\n for i = 0 to (n-1) do\n let x = br.(i) in let y = a.(i) in\n for j = (i+1) to n do\n let v = x + y.(j-1) in\n if bn.(j) > v then (bn.(j) <- v; p.(l).(j) <- i) else ();\n done;\n done;\n done;\n let d = Array.init k (fun i -> b.(i+1).(n), i+1) in\n let best_v, best_k = Array.fold_left (fun b x -> if (fst b) < (fst x) then b else x) (2*n, -1) d in\n let rec h i j =\n if i < j then (s.[j] <- s.[i]; h (i+1) (j-1)) else ()\n in\n let g i j =\n h i j;\n String.sub s i (j - i + 1)\n in\n let rec ans k j l =\n if k = 0 then l else (let i = p.(k).(j) in ans (k-1) i ((g i (j-1))::l))\n in\n Printf.printf \"%d\\n%s\\n\" best_v (String.concat \"+\" (ans best_k n []))\n ;;\nmain()"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = String.length s in\n let c = Array.make_matrix n n 0 in\n let _ =\n for i = 0 to n - 1 do\n for j = i to n - 1 do\n\tlet d = ref 0 in\n\t for k = 0 to (j - i + 1) / 2 - 1 do\n\t if s.[i + k] <> s.[j - k]\n\t then incr d;\n\t done;\n\t c.(i).(j) <- !d\n done\n done\n in\n (*let _ =\n for i = 0 to n - 1 do\n for j = i to n - 1 do\n\tPrintf.printf \"%d \" c.(i).(j)\n done;\n Printf.printf \"\\n\"\n done\n in*)\n (*let min (x : int) y = if x < y then x else y in*)\n let a = Array.make_matrix (k + 1) (n + 1) 10000 in\n let d = Array.make_matrix (k + 1) (n + 1) 10000 in\n a.(0).(0) <- 0;\n for i = 1 to k do\n a.(i).(0) <- 0;\n for j = 1 to n do\n\tfor r = 0 to j - 1 do\n\t if a.(i).(j) > a.(i - 1).(r) + c.(r).(j - 1) then (\n\t a.(i).(j) <- a.(i - 1).(r) + c.(r).(j - 1);\n\t d.(i).(j) <- r;\n\t )\n\tdone\n done\n done;\n (*let _ =\n for i = 0 to k do\n\tfor j = 0 to n do\n\t Printf.printf \"%d(%d) \" a.(i).(j) d.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let palindromize s =\n let n = String.length s in\n\tfor i = 0 to n / 2 - 1 do\n\t if s.[i] <> s.[n - i - 1]\n\t then s.[i] <- s.[n - i - 1]\n\tdone\n in\n let res = a.(k).(n) in\n let ss = ref [] in\n let _ =\n let i = ref n in\n\tfor j = k downto 1 do\n\t if !i > 0 then (\n\t let r = d.(j).(!i) in\n\t ss := String.sub s r (!i - r) :: !ss;\n\t i := r;\n\t )\n\tdone\n in\n assert (!ss <> []);\n Printf.printf \"%d\\n\" res;\n let f = ref true in\n\tList.iter\n\t (fun s ->\n\t if not !f\n\t then Printf.printf \"+\";\n\t f := false;\n\t assert (s <> \"\");\n\t palindromize s;\n\t Printf.printf \"%s\" s\n\t ) !ss;\n\tPrintf.printf \"\\n\"\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet inf = 1_000_000\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet argmin i j f = \n fold i j (\n fun k (index,v) -> let m = (f k) in if m= 0 then c.(i).(p) else \n let cc = \n\tif p=1 then dist.(0).(i) else\n\t let (j,opt) = argmin 0 i (fun j -> (cost (j-1) (p-1)) + dist.(j).(i)) in\n\t bj.(i).(p) <- j;\n\t opt\n in\n\tc.(i).(p) <- cc;\n\tcc\n\nlet make_palindrome i j = (* return a palindrome of s.[i...j] *)\n let l = j-i+1 in\n let r = String.sub s i l in\n for k=0 to l/2-1 do\n r.[k] <- r.[l-1-k]\n done;\n r\n\nlet rec build_soln i p ac =\n if i<0 || p<1 then ac else\n let j = bj.(i).(p) in\n build_soln (j-1) (p-1) ((make_palindrome j i)::ac)\n\nlet () = \n Printf.printf \"%d\\n\" (cost (n-1) k);\n Printf.printf \"%s\\n\" (String.concat \"+\" (build_soln (n-1) k []));\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet read_string () = Scanf.scanf \" %s \" (fun x -> x);;\n\nlet str = read_string ();;\nlet k = read_int ();;\nlet n = String.length str;;\n\nlet dp = Array.create_matrix 505 505 10000000;;\nlet cnt = Array.create_matrix 505 505 0;;\nlet mark = Array.create_matrix 505 505 0;;\n\nlet _ = for i = 0 to (n-1) do\n for j = (i+1) to (n-1) do\n for t1 = i to ((j+i)/2) do\n if str.[t1]!=str.[j-t1+i] then cnt.(i).(j) <- cnt.(i).(j) + 1\n else ()\n done\n done\n done;;\n\nlet _ = for i = 0 to (n-1) do\n begin\n dp.(i).(1) <- cnt.(0).(i);\n mark.(i).(1) <- -1\n end\n done;;\n\nlet _ = for i = 0 to (n-1) do\n for j = 2 to (min (i+1) k) do\n for t = 0 to (i-1) do\n if dp.(t).(j-1) + cnt.(t+1).(i) < dp.(i).(j) then\n dp.(i).(j) <- dp.(t).(j-1) + cnt.(t+1).(i);\n mark.(i).(j) <- t\n done\n done\n done;;\n\nlet ans = ref 10000000;; \nlet len = ref (-1);;\nlet p = ref 0;;\n\nlet _ = for i = 1 to k do\n if dp.(n-1).(i) < !ans then \n ans := dp.(n-1).(i);\n len := i;\n p := mark.(n-1).(i)\n done;;\n\nlet rec solve2 str i j = \n if i>=j then str\n else if str.[i]!=str.[j] then begin str.[i] <- str.[j]; solve2 str (i+1) (j-1) end\n else solve2 str (i+1) (j-1);;\n\nlet rec solve str len s t = \n if len = 1 then solve2 (String.sub str s (t-s+1)) s t\n else solve (String.sub str 0 s) (len-1) (mark.(s-1).(len-1)+1) (s-1) ^ \"+\" ^ solve2 (String.sub str s (t-s+1)) s t;; \n \nif n = 1 then Printf.printf \"0\\n%s\\n\" str\nelse Printf.printf \"%d\\n%s\\n\" (!ans) (solve str (!len) (!p+1) (n-1));;\n"}, {"source_code": "(*************** Ocaml stdio functions **********************)\nlet stdin_stream = Stream.of_channel stdin;;\nlet stdout_buffer = Buffer.create 65536;;\nlet rec gi() =\n match Stream.next stdin_stream with\n '-' -> - (ri 0)\n | '+' -> ri 0\n | '0'..'9' as c -> ri ((int_of_char c) - 48)\n | _ -> gi ()\nand ri x =\n match Stream.next stdin_stream with\n '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))\n | _ -> x\n;;\nlet flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;\nlet putchar c =\n if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();\n Buffer.add_char stdout_buffer c;;\nlet rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;\nlet pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));;\nlet pa a = let n = Array.length a in Array.iteri (fun i j -> pi j; putchar (if i == (n-1) then '\\n' else ' ')) a;;\n(*************** Ocaml solution ******************************)\nopen Array\nlet main() =\n let s = Scanf.scanf \"%s\" (fun i -> i) in\n let mk = Scanf.scanf \" %d\" (fun i -> i) in\n let l = String.length s in\n let a = make_matrix l l (-1, 0) in\n let b = make_matrix (mk+1) (l+1) 10000 in\n let c = make_matrix (mk+1) (l+1) (-1) in\n let rec f i j = \n if (j-i) <= 1 then (0,0)\n else (if (fst a.(i).(j)) >= 0 then a.(i).(j)\n else \n (\n let (u,_) = f (i+1) (j-1) in\n let r = if s.[i] == s.[j] then (u, 0) else (u + 1, 1) in\n a.(i).(j) <- r;\n r \n )\n ) \n in\n let rec g i j = \n if (j-i) <= 1 then ()\n else ((match snd (f i j) with\n 1 -> s.[i] <- s.[j]\n | _ -> () \n ); g (i+1) (j-1))\n in \n b.(mk).(0) <- 0; \n for k = (mk - 1) downto 0 do\n for i = 0 to (l - 1) do\n let w = b.(k+1).(i) in\n for j = (i+1) to l do \n let v = w + (fst (f i (j-1))) in\n if v < b.(k).(j) then ( b.(k).(j) <- v; c.(k).(j) <- i )\n else ()\n done\n done\n done;\n let rec h j k a =\n if k == mk then a\n else (\n let i = c.(k).(j) in\n g i (j-1);\n let ss = String.sub s i (j - i) in\n h i (k+1) (ss::a)\n )\n in\n let y = h l 0 [] in\n Printf.printf \"%d\\n%s\\n\" (b.(0).(l)) (String.concat \"+\" y)\n ;;\nmain();;\nflushout ()"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = String.length s in\n let c = Array.make_matrix n n 0 in\n let _ =\n for i = 0 to n - 1 do\n for j = i to n - 1 do\n\tlet d = ref 0 in\n\t for k = 0 to (j - i + 1) / 2 - 1 do\n\t if s.[i + k] <> s.[j - k]\n\t then incr d;\n\t done;\n\t c.(i).(j) <- !d\n done\n done\n in\n (*let _ =\n for i = 0 to n - 1 do\n for j = i to n - 1 do\n\tPrintf.printf \"%d \" c.(i).(j)\n done;\n Printf.printf \"\\n\"\n done\n in*)\n (*let min (x : int) y = if x < y then x else y in*)\n let a = Array.make_matrix (k + 1) (n + 1) 10000 in\n let d = Array.make_matrix (k + 1) (n + 1) 10000 in\n a.(0).(0) <- 0;\n for i = 1 to k do\n a.(i).(0) <- 0;\n for j = 0 to n do\n\tfor r = 0 to j - 1 do\n\t if a.(i).(j) > a.(i - 1).(r) + c.(r).(j - 1) then (\n\t a.(i).(j) <- a.(i - 1).(r) + c.(r).(j - 1);\n\t d.(i).(j) <- r;\n\t )\n\tdone\n done\n done;\n (*let _ =\n for i = 0 to k do\n\tfor j = 0 to n do\n\t Printf.printf \"%d \" a.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let palindromize s =\n let n = String.length s in\n\tfor i = 0 to n / 2 do\n\t if s.[i] <> s.[n - i - 1]\n\t then s.[i] <- s.[n - i - 1]\n\tdone\n in\n let res = a.(k).(n) in\n let ss = ref [] in\n let _ =\n let i = ref n in\n\tfor j = k downto 1 do\n\t if !i > 0 then (\n\t let r = d.(k).(!i) in\n\t ss := String.sub s r (!i - r) :: !ss;\n\t i := r;\n\t )\n\tdone\n in\n Printf.printf \"%d\\n\" res;\n let f = ref true in\n\tList.iter\n\t (fun s ->\n\t if not !f\n\t then Printf.printf \"+\";\n\t f := false;\n\t palindromize s;\n\t Printf.printf \"%s\" s\n\t ) !ss;\n\tPrintf.printf \"\\n\"\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = String.length s in\n let c = Array.make_matrix n n 0 in\n let _ =\n for i = 0 to n - 1 do\n for j = i to n - 1 do\n\tlet d = ref 0 in\n\t for k = 0 to (j - i + 1) / 2 - 1 do\n\t if s.[i + k] <> s.[j - k]\n\t then incr d;\n\t done;\n\t c.(i).(j) <- !d\n done\n done\n in\n (*let _ =\n for i = 0 to n - 1 do\n for j = i to n - 1 do\n\tPrintf.printf \"%d \" c.(i).(j)\n done;\n Printf.printf \"\\n\"\n done\n in*)\n (*let min (x : int) y = if x < y then x else y in*)\n let a = Array.make_matrix (k + 1) (n + 1) 10000 in\n let d = Array.make_matrix (k + 1) (n + 1) 10000 in\n a.(0).(0) <- 0;\n for i = 1 to k do\n a.(i).(0) <- 0;\n for j = 1 to n do\n\tfor r = 0 to j - 1 do\n\t if a.(i).(j) > a.(i - 1).(r) + c.(r).(j - 1) then (\n\t a.(i).(j) <- a.(i - 1).(r) + c.(r).(j - 1);\n\t d.(i).(j) <- r;\n\t )\n\tdone\n done\n done;\n (*let _ =\n for i = 0 to k do\n\tfor j = 0 to n do\n\t Printf.printf \"%d \" a.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let palindromize s =\n let n = String.length s in\n\tfor i = 0 to n / 2 - 1 do\n\t if s.[i] <> s.[n - i - 1]\n\t then s.[i] <- s.[n - i - 1]\n\tdone\n in\n let res = a.(k).(n) in\n let ss = ref [] in\n let _ =\n let i = ref n in\n\tfor j = k downto 1 do\n\t if !i > 0 then (\n\t let r = d.(k).(!i) in\n\t ss := String.sub s r (!i - r) :: !ss;\n\t i := r;\n\t )\n\tdone\n in\n assert (!ss <> []);\n Printf.printf \"%d\\n\" res;\n let f = ref true in\n\tList.iter\n\t (fun s ->\n\t if not !f\n\t then Printf.printf \"+\";\n\t f := false;\n\t assert (s <> \"\");\n\t palindromize s;\n\t Printf.printf \"%s\" s\n\t ) !ss;\n\tPrintf.printf \"\\n\"\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = String.length s in\n let c = Array.make_matrix n n 0 in\n let _ =\n for i = 0 to n - 1 do\n for j = i to n - 1 do\n\tlet d = ref 0 in\n\t for k = 0 to (j - i + 1) / 2 - 1 do\n\t if s.[i + k] <> s.[j - k]\n\t then incr d;\n\t done;\n\t c.(i).(j) <- !d\n done\n done\n in\n (*let _ =\n for i = 0 to n - 1 do\n for j = i to n - 1 do\n\tPrintf.printf \"%d \" c.(i).(j)\n done;\n Printf.printf \"\\n\"\n done\n in*)\n (*let min (x : int) y = if x < y then x else y in*)\n let a = Array.make_matrix (k + 1) (n + 1) 10000 in\n let d = Array.make_matrix (k + 1) (n + 1) 10000 in\n a.(0).(0) <- 0;\n for i = 1 to k do\n a.(i).(0) <- 0;\n for j = 1 to n do\n\tfor r = 0 to j - 1 do\n\t if a.(i).(j) > a.(i - 1).(r) + c.(r).(j - 1) then (\n\t a.(i).(j) <- a.(i - 1).(r) + c.(r).(j - 1);\n\t d.(i).(j) <- r;\n\t )\n\tdone\n done\n done;\n (*let _ =\n for i = 0 to k do\n\tfor j = 0 to n do\n\t Printf.printf \"%d \" a.(i).(j)\n\tdone;\n\tPrintf.printf \"\\n\"\n done\n in*)\n let palindromize s =\n let n = String.length s in\n\tfor i = 0 to n / 2 do\n\t if s.[i] <> s.[n - i - 1]\n\t then s.[i] <- s.[n - i - 1]\n\tdone\n in\n let res = a.(k).(n) in\n let ss = ref [] in\n let _ =\n let i = ref n in\n\tfor j = k downto 1 do\n\t if !i > 0 then (\n\t let r = d.(k).(!i) in\n\t ss := String.sub s r (!i - r) :: !ss;\n\t i := r;\n\t )\n\tdone\n in\n assert (!ss <> []);\n Printf.printf \"%d\\n\" res;\n let f = ref true in\n\tList.iter\n\t (fun s ->\n\t if not !f\n\t then Printf.printf \"+\";\n\t f := false;\n\t assert (s <> \"\");\n\t palindromize s;\n\t Printf.printf \"%s\" s\n\t ) !ss;\n\tPrintf.printf \"\\n\"\n"}], "src_uid": "c1de33ee9bb05db090c4d23ec9994f72"} {"nl": {"description": "You have an array a[1],\u2009a[2],\u2009...,\u2009a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times): choose two indexes, i and j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n; (j\u2009-\u2009i\u2009+\u20091) is a prime number); swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmp\u2009=\u2009a[i],\u2009a[i]\u2009=\u2009a[j],\u2009a[j]\u2009=\u2009tmp (tmp is a temporary variable). You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n distinct integers a[1],\u2009a[2],\u2009...,\u2009a[n] (1\u2009\u2264\u2009a[i]\u2009\u2264\u2009n).", "output_spec": "In the first line, print integer k (0\u2009\u2264\u2009k\u2009\u2264\u20095n) \u2014 the number of used operations. Next, print the operations. Each operation must be printed as \"i j\" (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n; (j\u2009-\u2009i\u2009+\u20091) is a prime). If there are multiple answers, you can print any of them.", "sample_inputs": ["3\n3 2 1", "2\n1 2", "4\n4 2 3 1"], "sample_outputs": ["1\n1 3", "0", "3\n2 4\n1 2\n2 4"], "notes": null}, "positive_code": [{"source_code": "let n=Scanf.scanf \"%d \" (fun x->x);;\nlet prime=Array.make 100001 false;;\nlet sprime=Array.make 100001 0;;\nlet tri=Array.make n (0,0);;\nlet vec=Array.make n 0;;\nlet permu=Array.make n 0;;\nfor i=0 to n-1 do\n permu.(i)<-i\ndone;;\nlet permu_inv=Array.make n 0;;\nfor i=0 to n-1 do\n permu_inv.(i)<-i\ndone;;\nlet l=ref [(0,0)];;\nl:=[];;\n\nfor i=0 to n-2 do\n let x=Scanf.scanf \"%d \" (fun x->x) in\n vec.(i)<-x;\n tri.(i)<-(x,i)\ndone;;\nlet x=Scanf.scanf \"%d\" (fun x->x) in (vec.(n-1)<-x;tri.(n-1)<-(x,n-1));;\nArray.sort (fun (x,i) (y,j) -> if x=y then 0 else if xi do\n let d=sprime.(!ind-i+1) and temp=vec.(!ind) in\n let j= !ind-d+1 in\n vec.(!ind)<-vec.(j);\n vec.(j)<-temp;\n l:=(j, !ind)::(!l);\n permu.(permu_inv.(j))<- !ind;\n permu_inv.(!ind)<-permu_inv.(j);\n ind:=j;\n done\ndone;;\n\nlet rec taille=function\n|[]->0\n|(_,_)::t->1+taille t;;\n\nprint_int(taille !l);;\nprint_newline();;\n\nlet rec print_list=function\n|[]->()\n|(i,j)::t->print_list t;Printf.printf \"%d %d\\n\" (i+1) (j+1);;\n\nprint_list !l;;\n \n "}], "negative_code": [], "src_uid": "c943a6413441651ec9f420ef44ea48d0"} {"nl": {"description": "Polycarp has $$$n$$$ friends, the $$$i$$$-th of his friends has $$$a_i$$$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $$$a_i$$$ to be the same. To solve this, Polycarp performs the following set of actions exactly once: Polycarp chooses $$$k$$$ ($$$0 \\le k \\le n$$$) arbitrary friends (let's say he chooses friends with indices $$$i_1, i_2, \\ldots, i_k$$$); Polycarp distributes their $$$a_{i_1} + a_{i_2} + \\ldots + a_{i_k}$$$ candies among all $$$n$$$ friends. During distribution for each of $$$a_{i_1} + a_{i_2} + \\ldots + a_{i_k}$$$ candies he chooses new owner. That can be any of $$$n$$$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $$$k$$$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $$$k$$$.For example, if $$$n=4$$$ and $$$a=[4, 5, 2, 5]$$$, then Polycarp could make the following distribution of the candies: Polycarp chooses $$$k=2$$$ friends with indices $$$i=[2, 4]$$$ and distributes $$$a_2 + a_4 = 10$$$ candies to make $$$a=[4, 4, 4, 4]$$$ (two candies go to person $$$3$$$). Note that in this example Polycarp cannot choose $$$k=1$$$ friend so that he can redistribute candies so that in the end all $$$a_i$$$ are equal.For the data $$$n$$$ and $$$a$$$, determine the minimum value $$$k$$$. With this value $$$k$$$, Polycarp should be able to select $$$k$$$ friends and redistribute their candies so that everyone will end up with the same number of candies.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^4$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case output: the minimum value of $$$k$$$, such that Polycarp can choose exactly $$$k$$$ friends so that he can redistribute the candies in the desired way; \"-1\" if no such value $$$k$$$ exists. ", "sample_inputs": ["5\n4\n4 5 2 5\n2\n0 4\n5\n10 8 5 1 4\n1\n10000\n7\n1 1 1 1 1 1 1"], "sample_outputs": ["2\n1\n-1\n0\n0"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int () in\n let a = Array.init n read_int in\n let total = sum 0 (n-1) (fun i -> a.(i)) in\n if total mod n <> 0 then printf \"-1\\n\" else (\n let nbig = sum 0 (n-1) (fun i -> if a.(i) > total/n then 1 else 0) in\n printf \"%d\\n\" nbig\n )\n done\n"}], "negative_code": [], "src_uid": "b8554e64b92b1b9458955da7d55eba62"} {"nl": {"description": "You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \\le x, y \\le r$$$, $$$x \\ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 1000$$$) \u2014 the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le 998244353$$$) \u2014 inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.", "output_spec": "Print $$$T$$$ lines, each line should contain the answer \u2014 two integers $$$x$$$ and $$$y$$$ such that $$$l \\le x, y \\le r$$$, $$$x \\ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.", "sample_inputs": ["3\n1 10\n3 14\n1 10"], "sample_outputs": ["1 7\n3 9\n5 10"], "notes": null}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let t = gi 0 in\n rep 1L t (fun _ ->\n let l,r = g2 0 in\n (* let f,u,v = ref true,ref l,ref r in\n while !f do\n while !f do\n if !v mod !u = 0L then (\n f := false;\n printf \"%Ld %Ld\\n\" !u !v\n );\n v -= 1L\n done;\n u += 1L;\n done; *)\n (* let f,u = ref true,ref l in\n while !f do\n done *)\n (* if l*2L > r then (\n\n ) *)\n printf \"%Ld %Ld\\n\" l (l*2L);\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "Scanf.(Array.(\n let t = scanf \" %d\" @@ fun v -> v in\n init t (fun _ ->\n let l = scanf \" %d %d\" @@ fun p _ -> p in\n Printf.printf \"%d %d\\n\" l (l*2))))"}], "negative_code": [], "src_uid": "a9cd97046e27d799c894d8514e90a377"} {"nl": {"description": "One day, at the \"Russian Code Cup\" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member \u2014 Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.", "input_spec": "The first line contains two integers \u2014 n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u20091000).", "output_spec": "In the first line print an integer m \u2014 number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n; ai\u2009\u2260\u2009bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.", "sample_inputs": ["3 1"], "sample_outputs": ["3\n1 2\n2 3\n3 1"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and k=read_int();;\nlet m=n*(n-1)/2;;\nlet nb=k*n;;\nlet mat=Array.make_matrix (n+1) (n+1) 0;;\nlet b=ref true\n\nlet rec win r i j=\nif r=0 then ()\nelse if i=j then win r i (j+1)\nelse if j>n then b:=false\nelse \n begin\n if mat.(i).(j)=0 then (mat.(i).(j)<-1;mat.(j).(i)<-(-1);win (r-1) i (j+1))\n else win r i (j+1)\n end;;\n\nif nb>m then b:=false;;\n\nfor i=1 to n do\n win k i 1\ndone;;\n\nif !b=false then print_int(-1) else\nbegin\nprint_int nb;\nprint_newline();\nfor i=1 to n do\n for j=1 to n do\n if mat.(i).(j)=1 then Printf.printf \"%d %d\\n\" i j\n done\ndone\nend;;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n n 0 in\n let c = Array.make n 0 in\n let tot = ref true in\n let m = ref 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tif i <> j && c.(i) < k && a.(i).(j) = 0 then (\n\t c.(i) <- c.(i) + 1;\n\t incr m;\n\t a.(i).(j) <- 1;\n\t a.(j).(i) <- -1;\n\t)\n done\n done;\n for i = 0 to n - 1 do\n if c.(i) < k\n then tot := false;\n done;\n if not !tot\n then Printf.printf \"-1\\n\"\n else (\n Printf.printf \"%d\\n\" (n * k);\n for i = 0 to n - 1 do\n\tfor j = 0 to n - 1 do\n\t if a.(i).(j) = 1\n\t then Printf.printf \"%d %d\\n\" (i + 1) (j + 1);\n\tdone\n done;\n )\n"}], "negative_code": [], "src_uid": "14570079152bbf6c439bfceef9816f7e"} {"nl": {"description": "Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).Let's define dist(v,\u2009u) as the sum of the integers written on the edges of the simple path from v to u.The vertex v controls the vertex u (v\u2009\u2260\u2009u) if and only if u is in the subtree of v and dist(v,\u2009u)\u2009\u2264\u2009au.Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the integers written in the vertices. The next (n\u2009-\u20091) lines contain two integers each. The i-th of these lines contains integers pi and wi (1\u2009\u2264\u2009pi\u2009\u2264\u2009n, 1\u2009\u2264\u2009wi\u2009\u2264\u2009109)\u00a0\u2014 the parent of the (i\u2009+\u20091)-th vertex in the tree and the number written on the edge between pi and (i\u2009+\u20091). It is guaranteed that the given graph is a tree.", "output_spec": "Print n integers\u00a0\u2014 the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.", "sample_inputs": ["5\n2 5 1 4 6\n1 7\n1 1\n3 5\n3 6", "5\n9 7 8 6 5\n1 1\n2 1\n3 1\n4 1"], "sample_outputs": ["1 0 1 0 0", "4 3 2 1 0"], "notes": "NoteIn the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5)."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nmodule Pset = Set.Make (struct type t = int64*int let compare = compare end)\n\n (* \n The representation is (offset, size, set)\n where the set is a set of pairs {(dist,vertex_no), ... }\n *)\n\nlet make_ms (dist,vertex_no) = (0L, 1, Pset.singleton (dist, vertex_no))\n\nlet getsize ms = let (_,size,_) = ms in size\n\nlet adjust_offset (offset,size,set) delta_offset =\n (* Remove the all elements of the ms where dist+offset+delta_offset < 0 *)\n let offset = offset ++ delta_offset in\n let rec loop count s =\n if Pset.is_empty s then (count,s) else\n let (dist,vertex_no) = Pset.min_elt s in\n if dist++offset < 0L then loop (count+1) (Pset.remove (dist,vertex_no) s)\n else (count,s)\n in\n let (count,s) = loop 0 set in\n (offset, size-count, s)\n \nlet merge ms1 ms2 =\n let (ms1,ms2) = if getsize ms1 < getsize ms2 then (ms1,ms2) else (ms2,ms1) in\n let ((offset1, size1, set1), (offset2, size2, set2)) = (ms1,ms2) in\n\n let rec loop count s1 s2 =\n if Pset.is_empty s1 then (count, s2) else\n let (d1,vn1) = Pset.min_elt s1 in\n loop (count+1) (Pset.remove (d1,vn1) s1) (Pset.add (d1++offset1--offset2,vn1) s2)\n in\n\n let (count,s2) = loop 0 set1 set2 in\n (offset2,size2+count,s2)\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n \nlet () = \n let n = read_int () in\n let a = Array.init n (fun i -> long (read_int())) in\n let tree = Array.make n [] in\n let answer = Array.make n 0 in\n\n for i=1 to n-1 do\n let p = -1 + read_int() in\n let len = long (read_int()) in\n tree.(p) <- (i,len)::tree.(p)\n done;\n\n let rec dfs v =\n let ms = List.fold_left (fun ac (w,len) ->\n merge ac (adjust_offset (dfs w) (0L--len))\n ) (make_ms (a.(v), v)) tree.(v)\n in\n answer.(v) <- getsize ms;\n ms\n in \n\n ignore(dfs 0);\n\n for i=0 to n-1 do\n printf \"%d \" (answer.(i) -1)\n done;\n\n print_newline()\n"}], "negative_code": [], "src_uid": "5a146d9d360228313006d54cd5ca56ec"} {"nl": {"description": "General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.All soldiers in the battalion have different beauty that is represented by a positive integer. The value ai represents the beauty of the i-th soldier.On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers.Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n\u2009\u2264\u200950; 1\u2009\u2264\u2009k\u2009\u2264\u2009 ) \u2014 the number of soldiers and the number of days in the pageant, correspondingly. The second line contains space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009107) \u2014 the beauties of the battalion soldiers. It is guaranteed that Payne's battalion doesn't have two soldiers with the same beauty.", "output_spec": "Print k lines: in the i-th line print the description of the detachment that will participate in the pageant on the i-th day. The description consists of integer ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n) \u2014 the number of soldiers in the detachment on the i-th day of the pageant and ci distinct integers p1,\u2009i,\u2009p2,\u2009i,\u2009...,\u2009pci,\u2009i \u2014 the beauties of the soldiers in the detachment on the i-th day of the pageant. The beauties of the soldiers are allowed to print in any order. Separate numbers on the lines by spaces. It is guaranteed that there is the solution that meets the problem conditions. If there are multiple solutions, print any of them.", "sample_inputs": ["3 3\n1 2 3", "2 1\n7 12"], "sample_outputs": ["1 1\n1 2\n2 3 2", "1 12"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet () = \n let n = read_int() in\n let k = read_int() in\n let a = Array.init n (fun i -> read_int()) in\n let () = Array.sort compare a in\n\n let rec loop count bl nbl i = if count = k then () else\n (* if i has been pushed into the bl then make the bl bigger and reset i *)\n if i+nbl=n then loop count (a.(i-1)::bl) (nbl+1) 0\n else (\n Printf.printf \"%d %d \" (nbl+1) a.(i);\n List.iter (fun e -> Printf.printf \"%d \" e) bl;\n print_newline();\n loop (count+1) bl nbl (i+1)\n )\n in\n loop 0 [] 0 0\n"}], "negative_code": [], "src_uid": "2b77aa85a192086316a7f87ce140112d"} {"nl": {"description": "After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar.Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants.Formally, Alyona wants to find a sequence of k non-empty strings p1,\u2009p2,\u2009p3,\u2009...,\u2009pk satisfying following conditions: s can be represented as concatenation a1p1a2p2... akpkak\u2009+\u20091, where a1,\u2009a2,\u2009...,\u2009ak\u2009+\u20091 is a sequence of arbitrary strings (some of them may be possibly empty); t can be represented as concatenation b1p1b2p2... bkpkbk\u2009+\u20091, where b1,\u2009b2,\u2009...,\u2009bk\u2009+\u20091 is a sequence of arbitrary strings (some of them may be possibly empty); sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence.A substring of a string is a subsequence of consecutive characters of the string.", "input_spec": "In the first line of the input three integers n, m, k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000, 1\u2009\u2264\u2009k\u2009\u2264\u200910) are given\u00a0\u2014 the length of the string s, the length of the string t and Alyona's favourite number respectively. The second line of the input contains string s, consisting of lowercase English letters. The third line of the input contains string t, consisting of lowercase English letters.", "output_spec": "In the only line print the only non-negative integer\u00a0\u2014 the sum of the lengths of the strings in a desired sequence. It is guaranteed, that at least one desired sequence exists.", "sample_inputs": ["3 2 2\nabc\nab", "9 12 4\nbbaaababb\nabbbabbaaaba"], "sample_outputs": ["2", "7"], "notes": "NoteThe following image describes the answer for the second sample case: "}, "positive_code": [{"source_code": "let _ =\n let max (x : int) y = if x > y then x else y in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n (*let n = 5\n and m = 5\n and k = 1\n and s = \"abcde\"\n and t = \"abxde\" in*)\n let a = Array.init (k + 1) (fun _ -> Array.make_matrix (n + 1) (m + 1) 0) in\n let b = Array.init (k + 1) (fun _ -> Array.make_matrix (n + 1) (m + 1) 0) in\n for i = 1 to n do\n for j = 1 to m do\n\tfor p = 0 to k do\n\t a.(p).(i).(j) <-\n\t max (max a.(p).(i - 1).(j) a.(p).(i).(j - 1))\n\t (max b.(p).(i - 1).(j) b.(p).(i).(j - 1))\n\tdone;\n\tif s.[i - 1] = t.[j - 1] then (\n\t for p = 1 to k do\n\t b.(p).(i).(j) <-\n\t max a.(p - 1).(i - 1).(j - 1) b.(p).(i - 1).(j - 1) + 1\n\t done;\n\t) else (\n\t)\n done\n done;\n let res = ref 0 in\n for p = 0 to k do\n\tres := max !res a.(p).(n).(m)\n done;\n for p = 0 to k do\n\tres := max !res b.(p).(n).(m)\n done;\n Printf.printf \"%d\\n\" !res;\n a, b\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let a = Array.init (k + 1) (fun _ -> Array.make_matrix (n + 1) (m + 1) 0) in\n for i = 1 to n do\n for j = 1 to m do\n\tif s.[i - 1] = t.[j - 1] then (\n\t if i > 1 && j > 1 && s.[i - 2] = t.[j - 2] then (\n\t for p = 0 to k do\n\t a.(p).(i).(j) <- a.(p).(i - 1).(j - 1) + 1\n\t done;\n\t ) else (\n\t for p = 1 to k do\n\t a.(p).(i).(j) <- a.(p - 1).(i - 1).(j - 1) + 1\n\t done;\n\t )\n\t) else (\n\t for p = 0 to k do\n\t a.(p).(i).(j) <- max a.(p).(i - 1).(j) a.(p).(i).(j - 1)\n\t done;\n\t)\n done\n done;\n let res = ref 0 in\n for p = 0 to k do\n\tres := max !res a.(p).(n).(m)\n done;\n Printf.printf \"%d\\n\" !res\n"}], "src_uid": "180c19997a37974199bc73a5d731d289"} {"nl": {"description": "In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible.There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x1,\u2009x2,\u2009...,\u2009xn, two characters cannot end up at the same position.Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n\u2009-\u20092). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting.Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.", "input_spec": "The first line on the input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, n is even)\u00a0\u2014 the number of positions available initially. The second line contains n distinct integers x1,\u2009x2,\u2009...,\u2009xn (0\u2009\u2264\u2009xi\u2009\u2264\u2009109), giving the coordinates of the corresponding positions.", "output_spec": "Print the distance between the warrior and the archer at the beginning of the fight, provided that both Vova and Lesha play optimally.", "sample_inputs": ["6\n0 1 3 7 15 31", "2\n73 37"], "sample_outputs": ["7", "36"], "notes": "NoteIn the first sample one of the optimum behavior of the players looks like that: Vova bans the position at coordinate 15; Lesha bans the position at coordinate 3; Vova bans the position at coordinate 31; Lesha bans the position at coordinate 1. After these actions only positions 0 and 7 will remain, and the distance between them is equal to 7.In the second sample there are only two possible positions, so there will be no bans."}, "positive_code": [{"source_code": "\nopen Str\n\nlet n = int_of_string @@ read_line () ;;\nlet xs = List.sort compare \n ( List.map int_of_string ( (split @@ regexp \" \") (read_line()) ) );;\n\n\nlet maxInIntv len = \n let rec miii l r c = match r with\n | [] -> 0\n | rx::rt -> if rx - List.hd l <= len \n then max c ( miii l rt (c+1) )\n else miii (List.tl l) r (c-1)\n in miii xs xs 1\nin\nlet rec optlen lmin lmax =\n if lmin = lmax then lmin\n else\n let mid = lmin/2 + lmax/2 in\n if (maxInIntv mid) > n/2\n then optlen lmin mid\n else optlen (mid+1) lmax\nin\nprint_int @@ optlen 1 1_000_000_000\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let n = read_int() in\n let x = Array.init n (fun _ -> read_int()) in\n Array.sort compare x;\n let l = (n-2)/2 in\n let v = n-2-l in\n\n printf \"%d\\n\" (minf 0 v (fun i -> x.(i+n-v-1) - x.(i)))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let n = read_int() in\n let x = Array.init n (fun _ -> read_int()) in\n Array.sort compare x;\n let l = (n-2)/2 in\n let v = n-2-l in\n\n printf \"%d\\n\" (minf 0 v (fun i -> x.(i+n-v-1) - x.(i)))\n"}], "negative_code": [{"source_code": "\nopen Str\n\nlet n = int_of_string @@ read_line () ;;\nlet xs = List.map int_of_string ( (split @@ regexp \" \") (read_line()) ) ;;\n\nprint_int (List.nth xs (n-1) );;\n\n(* let maxInIntv len = \n let rec miii (l as lx::lt) r c = match r with\n | [] -> 0\n | rx::rt -> if rx - lx <= len \n then max c ( miii l rt (c+1) )\n else miii lt r (c-1)\n in miii xs xs 1\nin\nlet rec minlen lmin lmax =\n if lmin = lmax then lmin\n else\n let mid = lmin/2 + lmax/2 *)"}], "src_uid": "8aaabe089d2512b76e5de938bac5c3bf"} {"nl": {"description": "A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.", "input_spec": "The first line contains three integers n, m and s (2\u2009\u2264\u2009n\u2009\u2264\u2009105, , 1\u2009\u2264\u2009s\u2009\u2264\u2009n) \u2014 the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1\u2009\u2264\u2009vi,\u2009ui\u2009\u2264\u2009n, vi\u2009\u2260\u2009ui, 1\u2009\u2264\u2009wi\u2009\u2264\u20091000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0\u2009\u2264\u2009l\u2009\u2264\u2009109) \u2014 the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads. ", "output_spec": "Print the single number \u2014 the number of Super Duper Secret Missile Silos that are located in Berland.", "sample_inputs": ["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"], "sample_outputs": ["3", "3"], "notes": "NoteIn the first sample the silos are located in cities 3 and 4 and on road (1,\u20093) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1,\u20092). Two more silos are on the road (4,\u20095) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4."}, "positive_code": [{"source_code": "(* codeforces 103. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\n(* 4:10 *)\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet n = read_int ()\nlet m = read_int ()\nlet start = read_int () -1\n\nlet ss = Array.make (2*m) 0\nlet ff = Array.make (2*m) 0\nlet ww = Array.make (2*m) 0\nlet first = Array.make n (-1)\nlet next = Array.make (2*m) 0\n\nlet () = \n for i=0 to m-1 do\n let vi = read_int() -1 in\n let ui = read_int() -1 in\n let wi = read_int() in\n ss.(i) <- vi;\n ff.(i+m) <- vi;\n ff.(i) <- ui;\n ss.(i+m) <- ui;\n ww.(i) <- wi;\n ww.(i+m) <- wi;\n done;\n\n for i=0 to 2*m-1 do\n next.(i) <- first.(ss.(i));\n first.(ss.(i)) <- i;\n done\n\nlet l = read_int()\n\nlet inf = 1_000_000_000\nlet dist = Array.make n inf\n\nlet () = dist.(start) <- 0\n\nlet rec printset s = if Pset.is_empty s then () else (\n let (d, v) = Pset.min_elt s in\n let s = Pset.remove (d, v) s in\n Printf.printf \"(dist(%d) = %d)\" v d;\n printset s\n)\n\nlet rec dijkstra s = if Pset.is_empty s then () else \n(* Printf.printf \"set: \";\n printset s;\n Printf.printf \"\\n\"; *)\n let (d, v) = Pset.min_elt s in\n let s = Pset.remove (d, v) s in\n let rec loop e s = if e = -1 then s else\n let w = ff.(e) in\n (* processing edge v,w *)\n if dist.(w) = inf then (\n\tdist.(w) <- dist.(v) + ww.(e);\n\tloop (next.(e)) (Pset.add (dist.(w), w) s)\n ) else if dist.(v) + ww.(e) < dist.(w) then (\n\tlet s = Pset.remove (dist.(w), w) s in\n\t dist.(w) <- dist.(v) + ww.(e);\n\t loop (next.(e)) (Pset.add (dist.(w), w) s)\n ) else (\n\t loop (next.(e)) s\n )\n in\n dijkstra (loop first.(v) s)\n\nlet () = dijkstra (Pset.singleton (0,start))\n\n(*\nlet () =\n for i=0 to n-1 do\n Printf.printf \"dist.(%d) = %d\\n\" i dist.(i)\n done\n*)\n\nlet ecount = ref 0\n\nlet () =\n for i=0 to n-1 do\n if dist.(i) = l then ecount := !ecount + 1\n done;\n\n\nfor i=0 to m-1 do\n let a = dist.(ss.(i)) in\n let b = dist.(ff.(i)) in\n let (a,b) = (min a b, max a b) in\n if a < l && b >= l then (\n if a+ww.(i) > l then ecount := !ecount + 1\n ) else if b x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\n(* 4:10 *)\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet n = read_int ()\nlet m = read_int ()\nlet start = read_int () -1\n\nlet ss = Array.make (2*m) 0\nlet ff = Array.make (2*m) 0\nlet ww = Array.make (2*m) 0\nlet first = Array.make n (-1)\nlet next = Array.make (2*m) 0\n\nlet () = \n for i=0 to m-1 do\n let vi = read_int() -1 in\n let ui = read_int() -1 in\n let wi = read_int() in\n ss.(i) <- vi;\n ff.(i+m) <- vi;\n ff.(i) <- ui;\n ss.(i+m) <- ui;\n ww.(i) <- wi;\n ww.(i+m) <- wi;\n done;\n\n for i=0 to 2*m-1 do\n next.(i) <- first.(ss.(i));\n first.(ss.(i)) <- i;\n done\n\nlet l = read_int()\n\nlet inf = 1_000_000_000\nlet dist = Array.make n inf\n\nlet () = dist.(start) <- 0\n\nlet rec printset s = if Pset.is_empty s then () else (\n let (d, v) = Pset.min_elt s in\n let s = Pset.remove (d, v) s in\n Printf.printf \"(dist(%d) = %d)\" v d;\n printset s\n)\n\nlet rec dijkstra s = if Pset.is_empty s then () else \n(* Printf.printf \"set: \";\n printset s;\n Printf.printf \"\\n\"; *)\n let (d, v) = Pset.min_elt s in\n let s = Pset.remove (d, v) s in\n let rec loop e s = if e = -1 then s else\n let w = ff.(e) in\n (* processing edge v,w *)\n if dist.(w) = inf then (\n\tdist.(w) <- dist.(v) + ww.(e);\n\tloop (next.(e)) (Pset.add (dist.(w), w) s)\n ) else if dist.(v) + ww.(e) < dist.(w) then (\n\tlet s = Pset.remove (dist.(w), w) s in\n\t dist.(w) <- dist.(v) + ww.(e);\n\t loop (next.(e)) (Pset.add (dist.(w), w) s)\n ) else (\n\t loop (next.(e)) s\n )\n in\n dijkstra (loop first.(v) s)\n\nlet () = dijkstra (Pset.singleton (0,start))\n\n(*\nlet () =\n for i=0 to n-1 do\n Printf.printf \"dist.(%d) = %d\\n\" i dist.(i)\n done\n*)\n\nlet ecount = ref 0\n\nlet () =\n for i=0 to n-1 do\n if dist.(i) = l then ecount := !ecount + 1\n done;\n\n for i=0 to m-1 do\n let a = dist.(ss.(i)) in\n let b = dist.(ff.(i)) in\n let (a,b) = (min a b, max a b) in\n if a < l && b >= l then (\n if a+ww.(i) > l then ecount := !ecount + 1\n ) else if b x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n\nlet () = \n let n = read_int() in\n let c = Array.init n (fun _ -> read_int()) in\n\n let m = minf 0 (n-1) (fun i -> c.(i)) in\n\n let rec loop i ac = if i=n then List.rev ac else\n let ac = if c.(i) = m then i::ac else ac in\n loop (i+1) ac\n in\n\n let place = Array.of_list (loop 0 []) in\n let pn = Array.length place in\n\n let rec mgap i ac = if i=pn then ac else\n mgap (i+1) (max ac (place.(i) - place.(i-1) - 1))\n in\n\n let maxgap = mgap 1 0 in\n let maxgap = max maxgap ((n-place.(pn-1)) + (place.(0) - 1)) in\n \n printf \"%Ld\\n\" ((long n)**(long m) ++ (long maxgap))\n"}], "negative_code": [], "src_uid": "e2db09803d87362c67763ef71e8b7f47"} {"nl": {"description": "Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?", "input_spec": "The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.", "output_spec": "Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.", "sample_inputs": ["3121", "6", "1000000000000000000000000000000000", "201920181"], "sample_outputs": ["2", "1", "33", "4"], "notes": "NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$."}, "positive_code": [{"source_code": "open Printf\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nlet char_list_of_string str = \n\tlet rec f0 i a =\n\t\tif i<0 then a else f0 (i-1) (str.[i]::a)\n in f0 (String.length str - 1) []\n\nlet () =\n let s = Scanf.scanf \" %s\" (fun v -> v)\n in let ls = char_list_of_string s\n |> List.map (fun c -> int_of_char c - int_of_char '0')\n in\n List.fold_left (fun (c,k,n) v -> \n let m = (c+v) mod 3 in\n if m=0 || v mod 3 = 0 || k=2 then (0,0,n+1)\n else (m,k+1,n)\n ) (0,0,0) ls\n |> (fun (_,_,n) -> n)\n |> print_int_endline"}], "negative_code": [{"source_code": "open Printf\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nlet char_list_of_string str = \n\tlet rec f0 i a =\n\t\tif i<0 then a else f0 (i-1) (str.[i]::a)\n in f0 (String.length str - 1) []\n\nlet ( *< ) f g x = f (g x)\nlet ( *> ) f g x = g (f x)\n \nlet cumulsum a = \n let ls = ref [0] in\n Array.iter (fun v -> ls := v+(List.hd !ls)::!ls) a;\n !ls |> List.rev |> Array.of_list\n\nlet () =\n let s = Scanf.scanf \" %s\" (fun v -> v)\n in let ls = char_list_of_string s\n |> List.map (fun c -> int_of_char c - int_of_char '0')\n in\n List.fold_left (fun (c,n) v -> \n let m = (c+v) mod 3 in\n if m=0 then (0,n+1)\n else if v mod 3 = 0 then (0,n+1)\n else (m,n)\n ) (0,0) ls\n |> snd\n |> print_int_endline"}], "src_uid": "3b2d0d396649a200a73faf1b930ef611"} {"nl": {"description": "Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).You have to answer $$$q$$$ independent queries.Let's see the following example: $$$[1, 3, 4]$$$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob\u00a0\u2014 then Alice has $$$4$$$ candies, and Bob has $$$4$$$ candies.Another example is $$$[1, 10, 100]$$$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $$$54$$$ candies, and Alice takes $$$46$$$ candies. Now Bob has $$$55$$$ candies, and Alice has $$$56$$$ candies, so she has to discard one candy\u00a0\u2014 and after that, she has $$$55$$$ candies too.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 1000$$$)\u00a0\u2014 the number of queries. Then $$$q$$$ queries follow. The only line of the query contains three integers $$$a, b$$$ and $$$c$$$ ($$$1 \\le a, b, c \\le 10^{16}$$$)\u00a0\u2014 the number of candies in the first, second and third piles correspondingly.", "output_spec": "Print $$$q$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th query\u00a0\u2014 the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same number of candies).", "sample_inputs": ["4\n1 3 4\n1 10 100\n10000000000000000 10000000000000000 10000000000000000\n23 34 45"], "sample_outputs": ["4\n55\n15000000000000000\n51"], "notes": null}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nmodule L = struct\n open Int64\n let ( + ), ( - ), ( * ), ( / ), ( % ) = add, sub, mul, div, rem\nend\nlet ( ~~ ) = Int64.of_int\nlet ( !! ) = Int64.to_int\n\nlet readint () = scanf \" %d\" (fun x -> x)\nlet readint64 () = scanf \" %Ld\" (fun x -> x)\n\nlet solve () =\n let a = readint64 () and b = readint64 () and c = readint64 () in\n let rec f x y z = if x <= y then let u = L.(min (y - x) z) in L.(x + u + (z - u) / 2L) else f y x z in\n let ans = L.(List.fold_left max Int64.min_int [f a b c; f a c b; f b a c; f b c a; f c a b; f c b a]) in\n printf \"%Ld\\n\" ans\n\nlet () =\n let q = readint () in\n for _ = 0 to q-1 do\n solve ()\n done;\n"}], "negative_code": [], "src_uid": "d9e4a9a32d60e75f3cf959ef7f894fc6"} {"nl": {"description": "Shubham has a binary string $$$s$$$. A binary string is a string containing only characters \"0\" and \"1\".He can perform the following operation on the string any amount of times: Select an index of the string, and flip the character at that index. This means, if the character was \"0\", it becomes \"1\", and vice versa. A string is called good if it does not contain \"010\" or \"101\" as a subsequence \u00a0\u2014 for instance, \"1001\" contains \"101\" as a subsequence, hence it is not a good string, while \"1000\" doesn't contain neither \"010\" nor \"101\" as subsequences, so it is a good string.What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.", "input_spec": "The first line of the input contains a single integer $$$t$$$ $$$(1\\le t \\le 100)$$$\u00a0\u2014 the number of test cases. Each of the next $$$t$$$ lines contains a binary string $$$s$$$ $$$(1 \\le |s| \\le 1000)$$$.", "output_spec": "For every string, output the minimum number of operations required to make it good.", "sample_inputs": ["7\n001\n100\n101\n010\n0\n1\n001100"], "sample_outputs": ["0\n0\n1\n1\n0\n0\n2"], "notes": "NoteIn test cases $$$1$$$, $$$2$$$, $$$5$$$, $$$6$$$ no operations are required since they are already good strings.For the $$$3$$$rd test case: \"001\" can be achieved by flipping the first character \u00a0\u2014 and is one of the possible ways to get a good string.For the $$$4$$$th test case: \"000\" can be achieved by flipping the second character \u00a0\u2014 and is one of the possible ways to get a good string.For the $$$7$$$th test case: \"000000\" can be achieved by flipping the third and fourth characters \u00a0\u2014 and is one of the possible ways to get a good string."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let s = read_string() in\n let n = String.length s in\n let nones = sum 0 (n-1) (fun i -> if s.[i] = '1' then 1 else 0) in\n let nzeros = n - nones in\n\n let rec scan i zeros ones best = if i=n+1 then best else (\n (* zeros = number of zeros before i, etc *)\n let zeros_after = nzeros - zeros in\n let ones_after = nones - ones in\n let opt1 = ones + zeros_after in\n let opt2 = zeros + ones_after in\n let best = min best (min opt1 opt2) in\n let ones = ones + (if i=n || s.[i] = '0' then 0 else 1) in\n let zeros = zeros + (if i=n || s.[i] = '1' then 0 else 1) in\n scan (i+1) zeros ones best\n ) in\n\n printf \"%d\\n\" (scan 0 0 0 n)\n done\n"}], "negative_code": [], "src_uid": "803e5ccae683b91a4cc486fbc558b330"} {"nl": {"description": "You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved.Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by one or several messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions.Due to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. It is guaranteed that the dialog begins with the question of the client.You have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 500$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$)\u00a0\u2014 the total number of messages in the dialog. The second line of each test case consists of $$$n$$$ characters \"Q\" and \"A\", describing types of messages in the dialog in chronological order. Character \"Q\" denotes the message with client question, and character \"A\"\u00a0\u2014 the message with technical support manager answer. It is guaranteed that the first character in the line equals to \"Q\".", "output_spec": "For each test case print \"Yes\" (without quotes) if dialog may correspond to the rules of work, or \"No\" (without quotes) otherwise.", "sample_inputs": ["5\n\n4\n\nQQAA\n\n4\n\nQQAQ\n\n3\n\nQAA\n\n1\n\nQ\n\n14\n\nQAQQAQAAQQQAAA"], "sample_outputs": ["Yes\nNo\nYes\nNo\nYes"], "notes": "NoteIn the first test case the two questions from the client are followed with two specialist's answers. So this dialog may correspond to the rules of work.In the second test case one of the first two questions was not answered.In the third test case the technical support manager sent two messaged as the answer to the only message of the client."}, "positive_code": [{"source_code": "let t = read_int() in\n\nfor i = 1 to t do\n let n=read_int() in\n let s=read_line() in\n let co = ref 0 in\n for j = 0 to (n-1) do\n if s.[j] = 'Q' then\n co := !co + 1\n else\n co := max (!co - 1) 0\n done;\n if !co > 0 then\n print_string(\"No\\n\")\n else\n print_string(\"Yes\\n\");\ndone"}, {"source_code": "let t = read_int() in\r\n \r\nfor i = 1 to t do\r\n let n=read_int() in\r\n let s=read_line() in\r\n let co = ref 0 in\r\n for j = 0 to (n-1) do\r\n if s.[j] = 'Q' then\r\n co := !co + 1\r\n else\r\n co := max (!co - 1) 0\r\n done;\r\n if !co > 0 then\r\n print_string(\"No\\n\")\r\n else\r\n print_string(\"Yes\\n\");\r\ndone"}], "negative_code": [{"source_code": "let t = read_int() in\n\nfor i = 1 to t do\n let n=read_int() in\n let s=read_line() in\n let co = ref 0 in\n for j = 0 to (n-1) do\n if s.[j] = 'Q' then\n co := !co + 1\n else\n co := !co - 1\n done;\n if !co > 0 then\n print_string(\"No\\n\")\n else\n print_string(\"Yes\\n\");\ndone"}], "src_uid": "c5389b39312ce95936eebdd83f510e40"} {"nl": {"description": "You are given $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$. Is it possible to arrange them on a circle so that each number is strictly greater than both its neighbors or strictly smaller than both its neighbors?In other words, check if there exists a rearrangement $$$b_1, b_2, \\ldots, b_n$$$ of the integers $$$a_1, a_2, \\ldots, a_n$$$ such that for each $$$i$$$ from $$$1$$$ to $$$n$$$ at least one of the following conditions holds: $$$b_{i-1} < b_i > b_{i+1}$$$ $$$b_{i-1} > b_i < b_{i+1}$$$To make sense of the previous formulas for $$$i=1$$$ and $$$i=n$$$, one shall define $$$b_0=b_n$$$ and $$$b_{n+1}=b_1$$$.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 3\\cdot 10^4$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 10^5$$$) \u00a0\u2014 the number of integers. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case, if it is not possible to arrange the numbers on the circle satisfying the conditions from the statement, output $$$\\texttt{NO}$$$. You can output each letter in any case. Otherwise, output $$$\\texttt{YES}$$$. In the second line, output $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$, which are a rearrangement of $$$a_1, a_2, \\ldots, a_n$$$ and satisfy the conditions from the statement. If there are multiple valid ways to arrange the numbers, you can output any of them.", "sample_inputs": ["4\n\n3\n\n1 1 2\n\n4\n\n1 9 8 4\n\n4\n\n2 0 2 2\n\n6\n\n1 1 1 11 111 1111"], "sample_outputs": ["NO\nYES\n1 8 4 9 \nNO\nYES\n1 11 1 111 1 1111"], "notes": "NoteIt can be shown that there are no valid arrangements for the first and the third test cases.In the second test case, the arrangement $$$[1, 8, 4, 9]$$$ works. In this arrangement, $$$1$$$ and $$$4$$$ are both smaller than their neighbors, and $$$8, 9$$$ are larger.In the fourth test case, the arrangement $$$[1, 11, 1, 111, 1, 1111]$$$ works. In this arrangement, the three elements equal to $$$1$$$ are smaller than their neighbors, while all other elements are larger than their neighbors."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f) \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n if n mod 2 = 1 then printf \"NO\\n\" else (\n Array.sort compare a;\n let block1 = sum 0 (n/2 - 1) (fun i -> if a.(i) = a.(n/2) then 1 else 0) in\n let block2 = sum (n/2) (n-1) (fun i -> if a.(i) = a.(n/2) then 1 else 0) in\n if block1 + block2 > n/2 || \n\t(block1 + block2 >= n/2 && block1>0 && block2>0) then printf \"NO\\n\" else (\n\tprintf \"YES\\n\";\n\tif block1 > block2 then (\n\t Array.sort (fun i j -> compare j i) a\n\t);\n\tfor i=0 to n/2-1 do\n\t printf \"%d \" a.(i);\n\t printf \"%d \" a.(i+n/2)\n\tdone;\n\tprint_newline()\n )\n )\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f) \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n if n mod 2 = 1 then printf \"NO\\n\" else (\n Array.sort compare a;\n let block1 = sum 0 (n/2 - 1) (fun i -> if a.(i) = a.(n/2) then 1 else 0) in\n let block2 = sum (n/2) (n-1) (fun i -> if a.(i) = a.(n/2) then 1 else 0) in\n if block1 + block2 >= n/2 then printf \"NO\\n\" else (\n\tprintf \"YES\\n\";\n\tif block1 > block2 then (\n\t Array.sort (fun i j -> compare j i) a\n\t);\n\tfor i=0 to n/2-1 do\n\t printf \"%d \" a.(i);\n\t printf \"%d \" a.(i+n/2)\n\tdone;\n\tprint_newline()\n )\n )\n done\n"}], "src_uid": "a30c5562d3df99291132fac20e05e708"} {"nl": {"description": "Alica and Bob are playing a game.Initially they have a binary string $$$s$$$ consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $$$s$$$ and delete them. For example, if $$$s = 1011001$$$ then the following moves are possible: delete $$$s_1$$$ and $$$s_2$$$: $$$\\textbf{10}11001 \\rightarrow 11001$$$; delete $$$s_2$$$ and $$$s_3$$$: $$$1\\textbf{01}1001 \\rightarrow 11001$$$; delete $$$s_4$$$ and $$$s_5$$$: $$$101\\textbf{10}01 \\rightarrow 10101$$$; delete $$$s_6$$$ and $$$s_7$$$: $$$10110\\textbf{01} \\rightarrow 10110$$$. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.", "input_spec": "First line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Only line of each test case contains one string $$$s$$$ ($$$1 \\le |s| \\le 100$$$), consisting of only characters 0 and 1.", "output_spec": "For each test case print answer in the single line. If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.", "sample_inputs": ["3\n01\n1111\n0011"], "sample_outputs": ["DA\nNET\nNET"], "notes": "NoteIn the first test case after Alice's move string $$$s$$$ become empty and Bob can not make any move.In the second test case Alice can not make any move initially.In the third test case after Alice's move string $$$s$$$ turn into $$$01$$$. Then, after Bob's move string $$$s$$$ become empty and Alice can not make any move."}, "positive_code": [{"source_code": "let rec str_to_list (str : string) (index : int) =\n if index = String.length str then\n []\n else\n (String.get str index) :: str_to_list str (index + 1)\n;;\n\nlet rec main (t : int) =\n if t = 0 then\n ()\n else\n (let str = read_line () in\n let str_list = str_to_list str 0 in\n let num_ones = List.fold_left (fun acc x -> if x = '1' then acc + 1 else acc) 0 str_list in\n let num_zeros = (String.length str) - num_ones in\n if (min num_ones num_zeros) mod 2 = 0 then\n print_endline \"NET\"\n else\n print_endline \"DA\"\n ;\n main (t-1)\n );;\n\nlet t = read_int () in\nmain t\n"}, {"source_code": "(* Codeforces 1373 B. 01 Game train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec countz cnt idx s = \n\tif idx == (String.length s) then cnt\n\telse\n\t\tlet ncnt = if s.[idx]=='0' then (cnt + 1) else cnt in\n\t\tcountz ncnt (idx + 1) s;;\n\nlet game s = \n let nz = countz 0 0 s in\n\t\tlet no = (String.length s) - nz in\n\t\tlet minzo = if nz < no then nz else no in\n\t\t(* let _ = Printf.printf \"minzo = %d\\n\" minzo in *)\n\t\tlet alice_win = (minzo mod 2) == 1 in\n\t\talice_win;;\n \nlet do_one () = \n let s = rdln() in\n let ans = game s in\n\t\tlet sans = if ans then \"DA\" else \"NET\" in\n Printf.printf \"%s\\n\" sans;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet st = rdln () in\n\tlet t = int_of_string st in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [], "src_uid": "046900001c7326fc8d890a22fa7267c9"} {"nl": {"description": " You are given an array $$$a_1, a_2, \\dots, a_n$$$ where all $$$a_i$$$ are integers and greater than $$$0$$$. In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \\le i, j \\le n$$$). If $$$gcd(a_i, a_j)$$$ is equal to the minimum element of the whole array $$$a$$$, you can swap $$$a_i$$$ and $$$a_j$$$. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Now you'd like to make $$$a$$$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array $$$a$$$ is non-decreasing if and only if $$$a_1 \\le a_2 \\le \\ldots \\le a_n$$$.", "input_spec": " The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of array $$$a$$$. The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \\ldots a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the array itself. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.", "output_spec": " For each test case, output \"YES\" if it is possible to make the array $$$a$$$ non-decreasing using the described operation, or \"NO\" if it is impossible to do so.", "sample_inputs": ["4\n1\n8\n6\n4 3 6 6 2 9\n4\n4 5 6 7\n5\n7 5 2 2 4"], "sample_outputs": ["YES\nYES\nYES\nNO"], "notes": "Note In the first and third sample, the array is already non-decreasing. In the second sample, we can swap $$$a_1$$$ and $$$a_3$$$ first, and swap $$$a_1$$$ and $$$a_5$$$ second to make the array non-decreasing. In the forth sample, we cannot the array non-decreasing using the operation."}, "positive_code": [{"source_code": "(* Codeforces 1401 C Mere Array train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec find_min minv a = match a with\n\t| [] -> minv\n\t| h :: t -> find_min (if minv < h then minv else h) t;;\n\nlet rec is_sorted a = match a with\n\t| [] -> true\n\t| l :: [] -> true\n\t| h0 :: h1 :: t -> \n\t\tif h0 > h1 then false\n\t\telse is_sorted (h1 :: t);;\n\nlet rec same_list a b = match a, b with\n\t| [],[] -> true\n\t| [], bb :: t -> false\n\t| aa :: t, [] -> false\n\t| aa :: ta, bb :: tb ->\n\t\tif aa != bb then false\n\t\telse same_list ta tb;;\n\n(* extract list of elements not divisible on mn *)\nlet rec extract_ndiv mn a = \n\tList.filter (fun x -> (x mod mn) != 0) a;;\t\n\n(* extract list 0 - divisible mn, 1 - not divisible *)\nlet divis_bits mn a = \n\tList.map (fun e -> if ((e mod mn) == 0) then 0 else 1) a;;\n \nlet do_one () = \n let n = gr() in\n\t\tlet a = List.rev (readlist n []) in\n\t\tlet sa = List.sort compare a in\n\t\tlet mn = find_min 1000111222 a in\n let bta = divis_bits mn a in\n let btsa = divis_bits mn sa in\n\t\tif not (same_list bta btsa) then print_string \"NO\\n\"\n\t\telse\n\t\t\tlet ndl = extract_ndiv mn a in\n\t\t\tif not (is_sorted ndl) then print_string \"NO\\n\"\n\t\t\telse print_string \"YES\\n\";;\n \nlet do_all () = \n let t = gr () in\n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tdo_all ();;\n \nmain();;"}], "negative_code": [], "src_uid": "f2070c2bd7bdbf0919aef1e915a21a24"} {"nl": {"description": "According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.You are given a jacket with n buttons. Determine if it is fastened in a right way.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of buttons on the jacket. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u20091). The number ai\u2009=\u20090 if the i-th button is not fastened. Otherwise ai\u2009=\u20091.", "output_spec": "In the only line print the word \"YES\" if the jacket is fastened in a right way. Otherwise print the word \"NO\".", "sample_inputs": ["3\n1 0 1", "3\n1 0 0"], "sample_outputs": ["YES", "NO"], "notes": null}, "positive_code": [{"source_code": "\nlet read_nums () = \n let s = read_line () in\n let n = int_of_string s in\n let s = read_line () in \n let nums = List.map int_of_string (Str.split (Str.regexp \" \") s) in\n (n, nums) \n\n;;\n\n\n\nlet rec sum nums acc = match nums with\n | [] -> acc\n | hd :: tl -> sum tl (acc + hd)\n \n;;\n\nlet get_ans () = \n \n let (n, nums) = read_nums () in\n let x = sum nums 0 in\n if (n = 1 && x = 1) then\n true\n else if (n > 1 && (n-1) = x) then\n true\n else\n false \n;;\n\n\nlet r = get_ans () in\nif r then\n print_string \"YES\\n\"\nelse\n print_string \"NO\\n\"\n \n\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let a = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n let s = Array.fold_left (+) 0 a in\n print_endline (if (n = 1 && s = 1) || (n > 1 && s = n - 1) then \"YES\" else \"NO\"))\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let cnt = ref 0 in\n for i = 1 to n do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tif k = 0\n\tthen incr cnt\n done;\n if (n > 1 && !cnt = 1) || (n = 1 && !cnt = 0)\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}], "negative_code": [{"source_code": "\nlet read_nums () = \n let s = read_line () in\n let n = int_of_string s in\n let s = read_line () in \n let nums = List.map int_of_string (Str.split (Str.regexp \" \") s) in\n (n, nums) \n\n;;\n\n\n\nlet rec sum nums acc = match nums with\n | [] -> acc\n | hd :: tl -> sum tl (acc + hd)\n \n\nlet get_ans () = \n \n let (n, nums) = read_nums () in\n let x = sum nums 0 in\n (n = 1 && x = 1) || ((n-1) = x)\n \n;;\n\n\nlet r = get_ans () in\nif r then\n print_string \"YES\\n\"\nelse\n print_string \"NO\\n\"\n \n\n"}], "src_uid": "7db0b870177e7d7b01da083e21ba35f5"} {"nl": {"description": "People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n\u2009\u00d7\u2009n is called k-special if the following three conditions are satisfied: every integer from 1 to n2 appears in the table exactly once; in each row numbers are situated in increasing order; the sum of numbers in the k-th column is maximum possible. Your goal is to help Alice and find at least one k-special table of size n\u2009\u00d7\u2009n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009500,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009n)\u00a0\u2014 the size of the table Alice is looking for and the column that should have maximum possible sum.", "output_spec": "First print the sum of the integers in the k-th column of the required table. Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on. If there are multiple suitable table, you are allowed to print any.", "sample_inputs": ["4 1", "5 3"], "sample_outputs": ["28\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16", "85\n5 6 17 18 19\n9 10 23 24 25\n7 8 20 21 22\n3 4 14 15 16\n1 2 11 12 13"], "notes": null}, "positive_code": [{"source_code": "(* started 8:23 *)\nopen Printf\nopen Scanf\n\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n \nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let k = k-1 in\n\n let m = Array.make_matrix n n 0 in\n\n let x = ref 1 in\n\n for i=0 to n-1 do \n for j=0 to k-1 do\n m.(i).(j) <- !x;\n x := !x + 1\n done\n done;\n\n x := n*n;\n\n for i=n-1 downto 0 do\n for j=n-1 downto k do \n m.(i).(j) <- !x;\n x := !x - 1 \n done\n done;\n\n let answer = sum 0 (n-1) (fun i -> m.(i).(k)) 0 in\n\n printf \"%d\\n\" answer;\n\n for i=0 to n-1 do\n for j=0 to n-1 do\n printf \"%d \" m.(i).(j)\n done;\n print_newline()\n done\n"}], "negative_code": [], "src_uid": "272f66f3c71c4997c5a1f0f009c9b99e"} {"nl": {"description": "By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1,\u2009a2,\u2009...,\u2009an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0\u2009=\u2009f1\u2009=\u20091 and at i\u2009\u2265\u20092: fi\u2009=\u2009fi\u2009-\u20091\u2009+\u2009fi\u2009-\u20092. For a group of three numbers li ri di you should increase value ax by di for all x (li\u2009\u2264\u2009x\u2009\u2264\u2009ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1\u2009\u2264\u2009ti\u2009\u2264\u20093) \u2014 the operation type: if ti\u2009=\u20091, then next follow two integers xi vi (1\u2009\u2264\u2009xi\u2009\u2264\u2009n,\u20090\u2009\u2264\u2009vi\u2009\u2264\u2009105); if ti\u2009=\u20092, then next follow two integers li ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n); if ti\u2009=\u20093, then next follow three integers li ri di (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n,\u20090\u2009\u2264\u2009di\u2009\u2264\u2009105). The input limits for scoring 30 points are (subproblem E1): It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): No extra limitations. ", "output_spec": "For each query print the calculated sum modulo 1000000000 (109).", "sample_inputs": ["5 5\n1 3 1 2 4\n2 1 4\n2 1 5\n2 2 4\n1 3 10\n2 1 5", "5 4\n1 3 1 2 4\n3 1 4 1\n2 2 4\n1 2 10\n2 1 5"], "sample_outputs": ["12\n32\n8\n50", "12\n45"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let mm = 1000000000 in\n let mmm = 1000000000l in\n let mmmm = 1000000000L in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let add x y =\n let r =\n Int32.to_int\n\t(Int32.rem\n\t (Int32.add\n\t (Int32.of_int x)\n\t (Int32.of_int y))\n\t mmm)\n in\n if r < 0\n then r + mm\n else r\n in\n let mul x y =\n let r =\n Int64.to_int\n\t(Int64.rem\n\t (Int64.mul\n\t (Int64.of_int x)\n\t (Int64.of_int y))\n\t mmmm)\n in\n if r < 0\n then r + mm\n else r\n in\n let o = 131072 * 2 in\n (*let o = 16 in*)\n let fib = Array.make (o + 1) 0 in\n let _ =\n fib.(1) <- 1;\n for i = 2 to o do\n fib.(i) <- add fib.(i - 1) fib.(i - 2)\n done\n in\n let d = Array.make (o + 1) 0 in\n let shift ofs v v' =\n let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) v') in\n (*Printf.printf \"shift %d %d %d %d -> %d\\n\" ofs v v' fib.(ofs + 1) res;*)\n res\n in\n let a = Array.make (2 * o) 0 in\n let a' = Array.make (2 * o) 0 in\n let rec update i x l r k =\n if l = r then (\n a.(k) <- x;\n a'.(k) <- 0;\n ) else (\n let m = (l + r) / 2 in\n\tif i <= m\n\tthen update i x l m (2 * k + 1)\n\telse update i x (m + 1) r (2 * k + 2);\n\tlet a1 = a.(2 * k + 1) in\n\tlet a2 = a.(2 * k + 2) in\n\tlet a1' = a'.(2 * k + 1) in\n\tlet a2' = a'.(2 * k + 2) in\n\t a.(k) <- add a1 (shift (m - l + 1) a2 a2');\n\t a'.(k) <- add a1' (shift (m - l + 0) a2 a2');\n )\n in\n let rec rmq x y l r k =\n if x <= l && r <= y\n then (\n shift (l - x) a.(k) a'.(k)\n ) else (\n let m = (l + r) / 2 in\n\tif m < x\n\tthen rmq x y (m + 1) r (2 * k + 2)\n\telse if m >= y\n\tthen rmq x y l m (2 * k + 1)\n\telse\n\t let a1 = rmq x y l m (2 * k + 1)\n\t and a2 = rmq x y (m + 1) r (2 * k + 2) in\n\t add a1 a2\n )\n in\n let () =\n for i = 1 to n do\n d.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n update i d.(i) 1 o 0\n done;\n in\n for k = 1 to m do\n(*for j = 0 to Array.length a - 1 do\n Printf.printf \"%d \" a.(j);\ndone;\nPrintf.printf \"\\n\";*)\n let op = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tmatch op with\n\t | 1 ->\n\t let i = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let v = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t\td.(i) <- v;\n\t\tupdate i v 1 o 0;\n\t | 2 ->\n\t let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let res = rmq l r 1 o 0 in\n\t\tPrintf.printf \"%d\\n\" res;\n\t | _ -> assert false\n done\n"}, {"source_code": "let _ =\n let mm = 1000000000 in\n let mmm = 1000000000l in\n let mmmm = 1000000000L in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let add x y =\n let r =\n Int32.to_int\n\t(Int32.rem\n\t (Int32.add\n\t (Int32.of_int x)\n\t (Int32.of_int y))\n\t mmm)\n in\n if r < 0\n then r + mm\n else r\n in\n let mul x y =\n let r =\n Int64.to_int\n\t(Int64.rem\n\t (Int64.mul\n\t (Int64.of_int x)\n\t (Int64.of_int y))\n\t mmmm)\n in\n if r < 0\n then r + mm\n else r\n in\n let o = 131072 * 2 in\n (*let o = 16 in*)\n let fib = Array.make (o + 1) 0 in\n let _ =\n fib.(1) <- 1;\n for i = 2 to o do\n fib.(i) <- add fib.(i - 1) fib.(i - 2)\n done\n in\n let d = Array.make (o + 1) 0 in\n let shift pos ofs v =\n let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) (add v (-d.(pos)))) in\n (*Printf.printf \"shift %d %d %d %d %d -> %d\\n\" pos ofs v d.(pos) fib.(ofs + 1) res;*)\n res\n in\n let a = Array.make (2 * o) 0 in\n let rec update i x l r k =\n if l = r then (\n a.(k) <- x;\n ) else (\n let m = (l + r) / 2 in\n\tif i <= m\n\tthen update i x l m (2 * k + 1)\n\telse update i x (m + 1) r (2 * k + 2);\n\tlet a1 = a.(2 * k + 1) in\n\tlet a2 = a.(2 * k + 2) in\n\t a.(k) <- add a1 (shift (m + 1) (m - l + 1) a2);\n )\n in\n let rec rmq x y l r k =\n if x <= l && r <= y\n then (\n a.(k)\n ) else (\n let m = (l + r) / 2 in\n\tif m < x\n\tthen rmq x y (m + 1) r (2 * k + 2)\n\telse if m >= y\n\tthen rmq x y l m (2 * k + 1)\n\telse\n\t let a1 = rmq x y l m (2 * k + 1)\n\t and a2 = rmq x y (m + 1) r (2 * k + 2) in\n\t add a1 (shift (m + 1) (m - x + 1) a2)\n )\n in\n let () =\n for i = 1 to n do\n d.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n update i d.(i) 1 o 0\n done;\n in\n for k = 1 to m do\n(*for j = 0 to Array.length a - 1 do\n Printf.printf \"%d \" a.(j);\ndone;\nPrintf.printf \"\\n\";*)\n let op = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tmatch op with\n\t | 1 ->\n\t let i = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let v = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t\td.(i) <- v;\n\t | 2 ->\n\t let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let res = ref 0 in\n\t\tfor i = l to r do\n\t\t res := add !res (mul fib.(i - l + 1) d.(i))\n\t\tdone;\n\t\tPrintf.printf \"%d\\n\" !res;\n\t | _ -> assert false\n done\n"}], "negative_code": [{"source_code": "let _ =\n let mm = 1000000000 in\n let mmm = 1000000000l in\n let mmmm = 1000000000L in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let add x y =\n let r =\n Int32.to_int\n\t(Int32.rem\n\t (Int32.add\n\t (Int32.of_int x)\n\t (Int32.of_int y))\n\t mmm)\n in\n if r < 0\n then r + mm\n else r\n in\n let mul x y =\n let r =\n Int64.to_int\n\t(Int64.rem\n\t (Int64.mul\n\t (Int64.of_int x)\n\t (Int64.of_int y))\n\t mmmm)\n in\n if r < 0\n then r + mm\n else r\n in\n let o = 131072 * 2 in\n (*let o = 8 in*)\n let fib = Array.make (o + 1) 0 in\n let _ =\n fib.(1) <- 1;\n for i = 2 to o do\n fib.(i) <- add fib.(i - 1) fib.(i - 2)\n done\n in\n let d = Array.make (o + 1) 0 in\n let shift pos ofs v =\n let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) (add v (-d.(pos)))) in\n (*Printf.printf \"shift %d %d %d %d %d -> %d\\n\" pos ofs v d.(pos) fib.(ofs + 1) res;*)\n res\n in\n let a = Array.make (2 * o) 0 in\n let rec update i x l r k =\n if l = r then (\n a.(k) <- x;\n ) else (\n let m = (l + r) / 2 in\n\tif i <= m\n\tthen update i x l m (2 * k + 1)\n\telse update i x (m + 1) r (2 * k + 2);\n\tlet a1 = a.(2 * k + 1) in\n\tlet a2 = a.(2 * k + 2) in\n\t a.(k) <- add a1 (shift (m + 1) (m - l + 1) a2);\n )\n in\n let rec rmq x y l r k =\n if x <= l && r <= y\n then (\n a.(k)\n ) else (\n let m = (l + r) / 2 in\n\tif m < x\n\tthen rmq x y (m + 1) r (2 * k + 2)\n\telse if m >= y\n\tthen rmq x y l m (2 * k + 1)\n\telse\n\t let a1 = rmq x y l m (2 * k + 1)\n\t and a2 = rmq x y (m + 1) r (2 * k + 2) in\n\t add a1 (shift (m + 1) (m - x + 1) a2)\n )\n in\n let () =\n for i = 1 to n do\n d.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n update i d.(i) 1 o 0\n done;\n in\n for k = 1 to m do\n(*for j = 0 to Array.length a - 1 do\n Printf.printf \"%d \" a.(j);\ndone;\nPrintf.printf \"\\n\";*)\n let op = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tmatch op with\n\t | 1 ->\n\t let i = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let v = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t\td.(i) <- v;\n\t\tupdate i v 1 o 0;\n\t | 2 ->\n\t let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let res = rmq l r 1 o 0 in\n\t\tPrintf.printf \"%d\\n\" res;\n\t | _ -> assert false\n done\n"}, {"source_code": "let _ =\n let mm = 1000000000 in\n let mmm = 1000000000l in\n let mmmm = 1000000000L in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let add x y =\n let r =\n Int32.to_int\n\t(Int32.rem\n\t (Int32.add\n\t (Int32.of_int x)\n\t (Int32.of_int y))\n\t mmm)\n in\n if r < 0\n then r + mm\n else r\n in\n let mul x y =\n let r =\n Int64.to_int\n\t(Int64.rem\n\t (Int64.mul\n\t (Int64.of_int x)\n\t (Int64.of_int y))\n\t mmmm)\n in\n if r < 0\n then r + mm\n else r\n in\n let o = 131072 * 2 in\n (*let o = 8 in*)\n let fib = Array.make (o + 1) 0 in\n let _ =\n fib.(1) <- 1;\n for i = 2 to o do\n fib.(i) <- add fib.(i - 1) fib.(i - 2)\n done\n in\n let d = Array.make (o + 1) 0 in\n let shift pos ofs v =\n let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) (v - d.(pos))) in\n (*Printf.printf \"shift %d %d %d %d %d -> %d\\n\" pos ofs v d.(pos) fib.(ofs + 1) res;*)\n res\n in\n let a = Array.make (2 * o) 0 in\n let rec update i x l r k =\n if l = r then (\n a.(k) <- x;\n ) else (\n let m = (l + r) / 2 in\n\tif i <= m\n\tthen update i x l m (2 * k + 1)\n\telse update i x (m + 1) r (2 * k + 2);\n\tlet a1 = a.(2 * k + 1) in\n\tlet a2 = a.(2 * k + 2) in\n\t a.(k) <- add a1 (shift (m + 1) (m - l + 1) a2);\n )\n in\n let rec rmq x y l r k =\n if x <= l && r <= y\n then (\n a.(k)\n ) else (\n let m = (l + r) / 2 in\n\tif m < x\n\tthen rmq x y (m + 1) r (2 * k + 2)\n\telse if m >= y\n\tthen rmq x y l m (2 * k + 1)\n\telse\n\t let a1 = rmq x y l m (2 * k + 1)\n\t and a2 = rmq x y (m + 1) r (2 * k + 2) in\n\t add a1 (shift (m + 1) (m - x + 1) a2)\n )\n in\n let () =\n for i = 1 to n do\n d.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n update i d.(i) 1 o 0\n done;\n in\n for k = 1 to m do\n(*for j = 0 to Array.length a - 1 do\n Printf.printf \"%d \" a.(j);\ndone;\nPrintf.printf \"\\n\";*)\n let op = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tmatch op with\n\t | 1 ->\n\t let i = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let v = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t\td.(i) <- v;\n\t\tupdate i v 1 o 0;\n\t | 2 ->\n\t let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let res = rmq l r 1 o 0 in\n\t\tPrintf.printf \"%d\\n\" res;\n\t | _ -> assert false\n done\n"}, {"source_code": "let _ =\n let mm = 1000000000 in\n let mmm = 1000000000l in\n let mmmm = 1000000000L in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let add x y =\n Int32.to_int\n (Int32.rem\n\t (Int32.add\n\t (Int32.of_int x)\n\t (Int32.of_int y))\n\t mmm)\n in\n let mul x y =\n Int64.to_int\n (Int64.rem\n\t (Int64.mul\n\t (Int64.of_int x)\n\t (Int64.of_int y))\n\t mmmm)\n in\n let o = 131072 * 2 in\n (*let o = 8 in*)\n let fib = Array.make (o + 1) 0 in\n let _ =\n fib.(1) <- 1;\n for i = 2 to o do\n fib.(i) <- add fib.(i - 1) fib.(i - 2)\n done\n in\n let d = Array.make (o + 1) 0 in\n let shift pos ofs v =\n let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) (v - d.(pos))) in\n (*Printf.printf \"shift %d %d %d %d %d -> %d\\n\" pos ofs v d.(pos) fib.(ofs + 1) res;*)\n res\n in\n let a = Array.make (2 * o) 0 in\n let rec update i x l r k =\n if l = r then (\n a.(k) <- x;\n ) else (\n let m = (l + r) / 2 in\n\tif i <= m\n\tthen update i x l m (2 * k + 1)\n\telse update i x (m + 1) r (2 * k + 2);\n\tlet a1 = a.(2 * k + 1) in\n\tlet a2 = a.(2 * k + 2) in\n\t a.(k) <- a1 + shift (m + 1) (m - l + 1) a2;\n )\n in\n let rec rmq x y l r k =\n if x <= l && r <= y\n then (\n a.(k)\n ) else (\n let m = (l + r) / 2 in\n\tif m < x\n\tthen rmq x y (m + 1) r (2 * k + 2)\n\telse if m >= y\n\tthen rmq x y l m (2 * k + 1)\n\telse\n\t let a1 = rmq x y l m (2 * k + 1)\n\t and a2 = rmq x y (m + 1) r (2 * k + 2) in\n\t a1 + shift (m + 1) (m - x + 1) a2\n )\n in\n let () =\n for i = 1 to n do\n d.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n update i d.(i) 1 o 0\n done;\n in\n for k = 1 to m do\n(*for j = 0 to Array.length a - 1 do\n Printf.printf \"%d \" a.(j);\ndone;\nPrintf.printf \"\\n\";*)\n let op = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tmatch op with\n\t | 1 ->\n\t let i = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let v = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t\td.(i) <- v;\n\t\tupdate i v 1 o 0;\n\t | 2 ->\n\t let l = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let r = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let res = rmq l r 1 o 0 in\n\t\tPrintf.printf \"%d\\n\" res;\n\t | _ -> assert false\n done\n"}], "src_uid": "165467dd842b47bc2d932b04e85ae8d7"} {"nl": {"description": "The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are, The chosen c prisoners has to form a contiguous segment of prisoners. Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. Find the number of ways you can choose the c prisoners.", "input_spec": "The first line of input will contain three space separated integers n\u00a0(1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105), t\u00a0(0\u2009\u2264\u2009t\u2009\u2264\u2009109) and c\u00a0(1\u2009\u2264\u2009c\u2009\u2264\u2009n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109. ", "output_spec": "Print a single integer \u2014 the number of ways you can choose the c prisoners.", "sample_inputs": ["4 3 3\n2 3 1 1", "1 1 1\n2", "11 4 2\n2 2 0 7 3 2 2 4 9 1 4"], "sample_outputs": ["2", "0", "6"], "notes": null}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet read_int () = scanf \" %d\" (fun x -> x)\n\nlet n = read_int ()\nlet t = read_int ()\nlet c = read_int ()\nlet a = Array.init n (fun i -> read_int())\n\nlet comp (l, r) x =\n if x > t then (0, r)\n else (l + 1, (if l + 1 >= c then r + 1 else r))\n\nlet () = printf \"%d\\n\" (snd (Array.fold_left comp (0, 0) a))\n"}], "negative_code": [], "src_uid": "7d1e8769a6b1d5c6680ab530d19e7fa4"} {"nl": {"description": "Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.", "input_spec": "The first line of the input contains two positive integers, n and m \u2014 the number of the cities and the number of roads in Berland (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000). Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi,\u2009yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, xi\u2009\u2260\u2009yi), where xi and yi are the numbers of the cities connected by the i-th road. It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of separated cities after the reform.", "sample_inputs": ["4 3\n2 1\n1 3\n4 3", "5 5\n2 1\n1 3\n2 3\n2 5\n4 3", "6 5\n1 2\n2 3\n4 5\n4 6\n5 6"], "sample_outputs": ["1", "0", "1"], "notes": "NoteIn the first sample the following road orientation is allowed: , , .The second sample: , , , , .The third sample: , , , , ."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\nlet n = scan_int() and m = scan_int();;\nlet rep = Array.init n (fun i -> i) and\n rnk = Array.make n 0 and czy = Array.make n false;;\n\nlet rec find x =\n if rep.(x) = x then x else begin\n rep.(x) <- find (rep.(x)); \n rep.(x);\n end;;\n\nlet rec union a b =\n let rA = find a and rB = find b in\n if rA = rB then czy.(rA) <- true\n else begin\n if rnk.(rA) > rnk.(rB) then union rB rA\n else begin\n rep.(rB) <- rA;\n rnk.(rA) <- max (rnk.(rA)) (rnk.(rB) + 1);\n czy.(rA) <- czy.(rA) || czy.(rB);\n end;\n end;;\n\nfor i = 1 to m do\n let a = scan_int() - 1 and b = scan_int() - 1 in\n union a b;\ndone;;\n\nlet cnt = ref 0 and odw = Array.make n false;;\nfor i = 0 to n - 1 do\n let ojciec = find i in\n if odw.(ojciec) = false then begin\n if czy.(ojciec) = false then incr cnt;\n odw.(ojciec) <- true;\n end;\ndone;;\n\nprint_int !cnt;;"}], "negative_code": [], "src_uid": "1817fbdc61541c09fb8f48df31f5049a"} {"nl": {"description": "Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:(1n\u2009+\u20092n\u2009+\u20093n\u2009+\u20094n)\u00a0mod\u00a05for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).", "input_spec": "The single line contains a single integer n (0\u2009\u2264\u2009n\u2009\u2264\u200910105). The number doesn't contain any leading zeroes.", "output_spec": "Print the value of the expression without leading zeros.", "sample_inputs": ["4", "124356983594583453458888889"], "sample_outputs": ["4", "0"], "notes": "NoteOperation x\u00a0mod\u00a0y means taking remainder after division x by y.Note to the first sample:"}, "positive_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nmodule Array = ArrayLabels ;;\nmodule List = struct\n include ListLabels ;;\n let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;\n let rec drop n a =\n if n = 0 then a\n else match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (n - 1) xs ;;\nend\nmodule H = Hashtbl ;;\n\nlet i n = Char.code n - Char.code '0' ;;\n\nlet () =\n sf \"%s \" (fun ss ->\n let l = String.length ss in\n let n = \n if l = 1 then i ss.[l - 1]\n else i ss.[l - 2] * 10 + i ss.[l - 1] in\n if n mod 4 = 0 then pf \"4\\n\"\n else pf \"0\\n\")\n;;\n"}], "negative_code": [], "src_uid": "74cbcbafbffc363137a02697952a8539"} {"nl": {"description": "Polycarp has $$$26$$$ tasks. Each task is designated by a capital letter of the Latin alphabet.The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.For example, if Polycarp solved tasks in the following order: \"DDBBCCCBBEZ\", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: \"BAB\", \"AABBCCDDEEBZZ\" and \"AAAAZAAAAA\".If Polycarp solved the tasks as follows: \"FFGZZZY\", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: \"BA\", \"AFFFCC\" and \"YYYYY\".Help Polycarp find out if his teacher might be suspicious.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$)\u00a0\u2014 the number of days during which Polycarp solved tasks. The second line contains a string of length $$$n$$$, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.", "output_spec": "For each test case output: \"YES\", if the teacher cannot be suspicious; \"NO\", otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).", "sample_inputs": ["5\n3\nABA\n11\nDDBBCCCBBEZ\n7\nFFGZZZY\n1\nZ\n2\nAB"], "sample_outputs": ["NO\nNO\nYES\nYES\nYES"], "notes": null}, "positive_code": [{"source_code": "(** https://codeforces.com/problemset/problem/1520/A *)\n\nlet has tbl elem =\n try\n let _ = Hashtbl.find tbl elem in\n true\n with\n | Not_found -> false\n\nlet is_distracted tasks =\n let len = String.length tasks and\n task_table = Hashtbl.create 26 in\n let rec helper i = \n if i = len\n then false\n else (\n let current_task = tasks.[i] and\n previous_task = tasks.[i-1] in\n if current_task <> previous_task\n then if has task_table current_task \n then true \n else (\n Hashtbl.add task_table current_task true;\n helper (i+1)\n ) \n else helper (i+1)\n ) in\n Hashtbl.add task_table tasks.[0] true;\n helper 1\n\nlet solve_n nb_cases =\n let rec helper i =\n if i > 0\n then (\n let _ = read_int () and\n tasks = read_line () in\n (if is_distracted tasks then \"NO\" else \"YES\")\n |> print_endline;\n helper (i-1)\n ) in\n helper nb_cases\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "negative_code": [], "src_uid": "3851854541b4bd168f5cb1e8492ed8ef"} {"nl": {"description": "There are $$$n$$$ logs, the $$$i$$$-th log has a length of $$$a_i$$$ meters. Since chopping logs is tiring work, errorgorn and maomao90 have decided to play a game.errorgorn and maomao90 will take turns chopping the logs with errorgorn chopping first. On his turn, the player will pick a log and chop it into $$$2$$$ pieces. If the length of the chosen log is $$$x$$$, and the lengths of the resulting pieces are $$$y$$$ and $$$z$$$, then $$$y$$$ and $$$z$$$ have to be positive integers, and $$$x=y+z$$$ must hold. For example, you can chop a log of length $$$3$$$ into logs of lengths $$$2$$$ and $$$1$$$, but not into logs of lengths $$$3$$$ and $$$0$$$, $$$2$$$ and $$$2$$$, or $$$1.5$$$ and $$$1.5$$$.The player who is unable to make a chop will be the loser. Assuming that both errorgorn and maomao90 play optimally, who will be the winner?", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 50$$$) \u00a0\u2014 the number of logs. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq 50$$$) \u00a0\u2014 the lengths of the logs. Note that there is no bound on the sum of $$$n$$$ over all test cases.", "output_spec": "For each test case, print \"errorgorn\" if errorgorn wins or \"maomao90\" if maomao90 wins. (Output without quotes).", "sample_inputs": ["2\n\n4\n\n2 4 2 1\n\n1\n\n1"], "sample_outputs": ["errorgorn\nmaomao90"], "notes": "NoteIn the first test case, errorgorn will be the winner. An optimal move is to chop the log of length $$$4$$$ into $$$2$$$ logs of length $$$2$$$. After this there will only be $$$4$$$ logs of length $$$2$$$ and $$$1$$$ log of length $$$1$$$.After this, the only move any player can do is to chop any log of length $$$2$$$ into $$$2$$$ logs of length $$$1$$$. After $$$4$$$ moves, it will be maomao90's turn and he will not be able to make a move. Therefore errorgorn will be the winner.In the second test case, errorgorn will not be able to make a move on his first turn and will immediately lose, making maomao90 the winner."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\nlet rec read_log_lengths = function\r\n | 0 -> []\r\n | n -> (read_int ())::(read_log_lengths (n-1))\r\n;;\r\n\r\nlet rec get_num_moves = function\r\n | 0 -> 0\r\n | n -> \r\n let log_length=read_int () in\r\n log_length-1 + get_num_moves (n-1)\r\n;;\r\n\r\n(* Moves | Length 0 | 1, 1 | 2, 2 | 3, 3 | 4 *)\r\nlet calculate_test_case = function\r\n | num_moves ->\r\n if (num_moves mod 2 == 0) then \"maomao90\"\r\n else \"errorgorn\"\r\n\r\n;;\r\n\r\nlet rec iterate_through_cases = function\r\n | 0 -> 0\r\n | n -> \r\n let num_logs = read_int () in\r\n let num_moves = get_num_moves num_logs in\r\n print_string (calculate_test_case num_moves);\r\n print_newline ();\r\n iterate_through_cases (n-1)\r\n;;\r\n\r\nlet num_cases = read_int () in\r\niterate_through_cases num_cases;;"}, {"source_code": "let parse len str = let rep = Array.make len (-1) in\r\n let temp = ref \"\" in\r\n let j = ref 0 in\r\n for i = 0 to String.length str -1 do\r\n if str.[i] = ' ' then \r\n (rep.(!j) <- (int_of_string !temp) ; incr j ; temp:=\"\" ) \r\n else \r\n (temp:= !temp ^ (String.make 1 str.[i]))\r\n done; rep.(!j) <- (int_of_string !temp) ;rep\r\n;; \r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len = int_of_string (input_line stdin) in\r\n let str = (input_line stdin) in\r\n let tab = parse len str in\r\n let rep = ref 0 in\r\n for j = 0 to len -1 do\r\n rep := !rep + tab.(j) -1\r\n done;\r\n if !rep mod 2 = 1 then \r\n print_endline \"errorgorn\"\r\n else \r\n print_endline \"maomao90\"\r\ndone;;"}], "negative_code": [], "src_uid": "fc75935b149cf9f4f2ddb9e2ac01d1c2"} {"nl": {"description": "Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening (\"(\") and closing (\")\") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as \"(())()\" and \"()\" are correct bracket sequences and such sequences as \")()\" and \"(()\" are not.In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one. You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled: Each bracket is either not colored any color, or is colored red, or is colored blue. For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored. No two neighboring colored brackets have the same color. Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo 1000000007 (109\u2009+\u20097).", "input_spec": "The first line contains the single string s (2\u2009\u2264\u2009|s|\u2009\u2264\u2009700) which represents a correct bracket sequence. ", "output_spec": "Print the only number \u2014 the number of ways to color the bracket sequence that meet the above given conditions modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["(())", "(()())", "()"], "sample_outputs": ["12", "40", "4"], "notes": "NoteLet's consider the first sample test. The bracket sequence from the sample can be colored, for example, as is shown on two figures below. The two ways of coloring shown below are incorrect. "}, "positive_code": [{"source_code": "(* codeforces 106. Danny Sleator *)\n(* This version is modified because apparently you can't make an\n array that is 5Million long on the codeforces server. *)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet m = 1000000007L\nlet ( ++ ) a b = Int64.rem (Int64.add a b) m\nlet ( ** ) a b = Int64.rem (Int64.mul a b) m\n\nlet () =\n let s = read_string() in\n let n = String.length s in\n\n let pair = Array.make n (-1) in (* if i is a left paren, pair.(i) is its matching right *)\n \n let rec scan i stack = if i=n then () else\n if s.[i] = '(' then scan (i+1) (i::stack) else (\n pair.(List.hd stack) <- i;\n scan (i+1) (List.tl stack)\n )\n in\n\n let () = scan 0 [] in\n\n let table = Array.make_matrix n (n * 3 * 3) None in\n let index j c1 c2 = c2 + 3*(c1 + 3*j) in\n let lookup i j c1 c2 = table.(i).(index j c1 c2) in\n let store i j c1 c2 x = table.(i).(index j c1 c2) <- x in\n\n let valid_pair c1 c2 = (c1=0 || c2=0) && (c1 <> c2) in\n let vn c1 c2 = c1=0 || c2=0 || c1 <> c2 in (* valid neighbors *)\n\n let color_list = [(0,0);(0,1);(0,2);(1,0);(1,1);(1,2);(2,0);(2,1);(2,2)] in\n\n let rec count i j c1 c2 = (* i is left, j is right, at the same level, and c1 and c2 are their colors *)\n match lookup i j c1 c2 with Some x -> x | None ->\n let answer = \n\tif pair.(i) = j then ( (* matching pair *)\n\t if not (valid_pair c1 c2) then 0L \n\t else if i+1=j then 1L\n\t else (\n\t List.fold_left \n\t (fun ac (d1,d2) -> \n\t\t if (vn c1 d1) && (vn d2 c2) then ac ++ count (i+1) (j-1) d1 d2 else ac\n\t ) 0L color_list\n\t )\n\t) else (\n\t List.fold_left\n\t (fun ac (d1,d2) ->\n\t if (valid_pair c1 d1) && (vn d1 d2)\n\t then ac ++ (count i pair.(i) c1 d1) ** (count (pair.(i)+1) j d2 c2)\n\t else ac\n\t ) 0L color_list\n\t)\n in\n\tstore i j c1 c2 (Some answer);\n\tanswer\n in\n\n let full_count = List.fold_left (fun ac (d1,d2) -> ac ++ count 0 (n-1) d1 d2) 0L color_list in\n Printf.printf \"%s\\n\" (Int64.to_string full_count)\n"}], "negative_code": [{"source_code": "(* codeforces 106. Danny Sleator *)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet m = 1000000007L\nlet ( ++ ) a b = Int64.rem (Int64.add a b) m\nlet ( ** ) a b = Int64.rem (Int64.mul a b) m\n\nlet () =\n let s = read_string() in\n let n = String.length s in\n\n let pair = Array.make n (-1) in (* if i is a left paren, pair.(i) is its matching right *)\n \n let rec scan i stack = if i=n then () else\n if s.[i] = '(' then scan (i+1) (i::stack) else (\n pair.(List.hd stack) <- i;\n scan (i+1) (List.tl stack)\n )\n in\n\n let () = scan 0 [] in\n\n let table = Array.make (n * n * 3 * 3) None in\n let index i j c1 c2 = c2 + 3*(c1 + 3*(j + n*i)) in\n let lookup i j c1 c2 = table.(index i j c1 c2) in\n let store i j c1 c2 x = table.(index i j c1 c2) <- x in\n\n let valid_pair c1 c2 = (c1=0 || c2=0) && (c1 <> c2) in\n let vn c1 c2 = c1=0 || c2=0 || c1 <> c2 in (* valid neighbors *)\n\n let color_list = [(0,0);(0,1);(0,2);(1,0);(1,1);(1,2);(2,0);(2,1);(2,2)] in\n\n let rec count i j c1 c2 = (* i is left, j is right, at the same level, and c1 and c2 are their colors *)\n match lookup i j c1 c2 with Some x -> x | None ->\n let answer = \n\tif pair.(i) = j then ( (* matching pair *)\n\t if not (valid_pair c1 c2) then 0L \n\t else if i+1=j then 1L\n\t else (\n\t List.fold_left \n\t (fun ac (d1,d2) -> \n\t\t if (vn c1 d1) && (vn d2 c2) then ac ++ count (i+1) (j-1) d1 d2 else ac\n\t ) 0L color_list\n\t )\n\t) else (\n\t List.fold_left\n\t (fun ac (d1,d2) ->\n\t if (valid_pair c1 d1) && (vn d1 d2)\n\t then ac ++ (count i pair.(i) c1 d1) ** (count (pair.(i)+1) j d2 c2)\n\t else ac\n\t ) 0L color_list\n\t)\n in\n\tstore i j c1 c2 (Some answer);\n\tanswer\n in\n\n let full_count = List.fold_left (fun ac (d1,d2) -> ac ++ count 0 (n-1) d1 d2) 0L color_list in\n Printf.printf \"%s\\n\" (Int64.to_string full_count)\n"}], "src_uid": "e05ef33935d04bd3714269268aceda41"} {"nl": {"description": "Alice and Bob play a game. Alice has $$$n$$$ cards, the $$$i$$$-th of them has the integer $$$a_i$$$ written on it. Bob has $$$m$$$ cards, the $$$j$$$-th of them has the integer $$$b_j$$$ written on it.On the first turn of the game, the first player chooses one of his/her cards and puts it on the table (plays it). On the second turn, the second player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the first turn, and plays it. On the third turn, the first player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the second turn, and plays it, and so on \u2014 the players take turns, and each player has to choose one of his/her cards with greater integer than the card played by the other player on the last turn.If some player cannot make a turn, he/she loses.For example, if Alice has $$$4$$$ cards with numbers $$$[10, 5, 3, 8]$$$, and Bob has $$$3$$$ cards with numbers $$$[6, 11, 6]$$$, the game may go as follows: Alice can choose any of her cards. She chooses the card with integer $$$5$$$ and plays it. Bob can choose any of his cards with number greater than $$$5$$$. He chooses a card with integer $$$6$$$ and plays it. Alice can choose any of her cards with number greater than $$$6$$$. She chooses the card with integer $$$10$$$ and plays it. Bob can choose any of his cards with number greater than $$$10$$$. He chooses a card with integer $$$11$$$ and plays it. Alice can choose any of her cards with number greater than $$$11$$$, but she has no such cards, so she loses. Both Alice and Bob play optimally (if a player is able to win the game no matter how the other player plays, the former player will definitely win the game).You have to answer two questions: who wins if Alice is the first player? who wins if Bob is the first player? ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Each test case consists of four lines. The first line of a test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the number of cards Alice has. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 50$$$) \u2014 the numbers written on the cards that Alice has. The third line contains one integer $$$m$$$ ($$$1 \\le m \\le 50$$$) \u2014 the number of Bob's cards. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \\dots, b_m$$$ ($$$1 \\le b_i \\le 50$$$) \u2014 the numbers on Bob's cards.", "output_spec": "For each test case, print two lines. The first line should be Alice if Alice wins when she is the first player; otherwise, the first line should be Bob. The second line should contain the name of the winner if Bob is the first player, in the same format.", "sample_inputs": ["4\n\n1\n\n6\n\n2\n\n6 8\n\n4\n\n1 3 3 7\n\n2\n\n4 2\n\n1\n\n50\n\n2\n\n25 50\n\n10\n\n1 2 3 4 5 6 7 8 9 10\n\n2\n\n5 15"], "sample_outputs": ["Bob\nBob\nAlice\nAlice\nAlice\nBob\nBob\nBob"], "notes": "NoteLet's consider the first test case of the example.Alice has one card with integer $$$6$$$, Bob has two cards with numbers $$$[6, 8]$$$.If Alice is the first player, she has to play the card with number $$$6$$$. Bob then has to play the card with number $$$8$$$. Alice has no cards left, so she loses.If Bob is the first player, then no matter which of his cards he chooses on the first turn, Alice won't be able to play her card on the second turn, so she will lose."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\nlet rec max_int_from_input max = function\r\n | 0 -> max\r\n | n -> \r\n let new_in = read_int () in \r\n if (max < new_in) then max_int_from_input new_in (n-1)\r\n else max_int_from_input max (n-1)\r\n;;\r\n\r\nlet rec run_test_case = function\r\n | 0 -> 0\r\n | n ->\r\n let num_alice = read_int () in\r\n let max_alice = max_int_from_input 0 num_alice in\r\n let num_bob = read_int () in\r\n let max_bob = max_int_from_input 0 num_bob in\r\n if (max_alice > max_bob) then begin\r\n print_string \"Alice\\n\";\r\n print_string \"Alice\\n\";\r\n run_test_case (n-1)\r\n end\r\n else if (max_alice == max_bob) then begin\r\n print_string \"Alice\\n\";\r\n print_string \"Bob\\n\";\r\n run_test_case (n-1)\r\n end\r\n else begin\r\n print_string \"Bob\\n\";\r\n print_string \"Bob\\n\";\r\n run_test_case (n-1)\r\n end\r\n;;\r\n\r\nlet num_cases = read_int () in\r\nrun_test_case num_cases;;"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () =\n\n let cases = read_int()in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n let m = read_int() in\n let b = Array.init m read_int in\n let maxa = maxf 0 (n-1) (fun i -> a.(i)) in\n let maxb = maxf 0 (m-1) (fun i -> b.(i)) in\n printf \"%s\\n\" (if maxa >= maxb then \"Alice\" else \"Bob\");\n printf \"%s\\n\" (if maxb >= maxa then \"Bob\" else \"Alice\"); \n done\n"}], "negative_code": [], "src_uid": "581c89736e549300c566e4700b741906"} {"nl": {"description": "Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters \"a\", \"b\" and \"c\". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.", "input_spec": "The input consists of a single string $$$s$$$\u00a0($$$2 \\leq |s| \\leq 10^6$$$). The string $$$s$$$ consists only of characters \"a\", \"b\", \"c\". It is guaranteed that no two consecutive characters are equal.", "output_spec": "Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \\geq \\lfloor \\frac{|s|}{2} \\rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string \"IMPOSSIBLE\" (quotes for clarity).", "sample_inputs": ["cacbac", "abc", "cbacacacbcbababacbcb"], "sample_outputs": ["aba", "a", "cbaaacbcaaabc"], "notes": "NoteIn the first example, other valid answers include \"cacac\", \"caac\", \"aca\" and \"ccc\". "}, "positive_code": [{"source_code": "let readString () = Scanf.scanf \" %s\" (fun s -> s)\n\nlet solve s =\n let open Bytes in\n let n = String.length s in\n let i = ref 0 in\n let j = ref (n-1) in\n let o = make n '\\x00' in\n let olen = ref 0 in\n let write c = (*Printf.eprintf \"%c %d\\n\" c !olen;*) set o !olen c; incr olen in\n while i <= j do\n (*Printf.eprintf \"%d %d\\n\" !i !j;*)\n if i = j then (write s.[!i]; incr i)\n else if s.[!i] = s.[!j] then (write s.[!i]; incr i; write s.[!j]; decr j)\n else if !i+1 = !j then (write s.[!i]; i := !i+2)\n else if s.[!i] = s.[!j-1] then decr j\n else incr i\n done;\n let olen = !olen in\n let o' = Bytes.make olen '\\x00' in\n for i=0 to olen/2-1 do\n let c = get o (2*i) in\n set o' i c;\n set o' (olen-1-i) c\n done;\n if olen mod 2 = 1 then get o (olen-1) |> set o' (olen/2);\n Bytes.to_string o'\n\nlet main () =\n let s = readString () in\n Printf.printf \"%s\\n\" (solve s)\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "3bebb50d1c2ef9f80e78715614f039d7"} {"nl": {"description": "Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n\u2009+\u20091 points with coordinates (1,\u2009y1), (2,\u2009y2), ..., (2n\u2009+\u20091,\u2009y2n\u2009+\u20091), with the i-th segment connecting the point (i,\u2009yi) and the point (i\u2009+\u20091,\u2009yi\u2009+\u20091). For any even i (2\u2009\u2264\u2009i\u2009\u2264\u20092n) the following condition holds: yi\u2009-\u20091\u2009<\u2009yi and yi\u2009>\u2009yi\u2009+\u20091. We shall call a vertex of a polyline with an even x coordinate a mountain peak. The figure to the left shows the initial picture, the figure to the right shows what the picture looks like after Bolek's actions. The affected peaks are marked red, k = 2. Bolek fancied a little mischief. He chose exactly k mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the y coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1,\u2009r1), (2,\u2009r2), ..., (2n\u2009+\u20091,\u2009r2n\u2009+\u20091).Given Bolek's final picture, restore the initial one.", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009100). The next line contains 2n\u2009+\u20091 space-separated integers r1,\u2009r2,\u2009...,\u2009r2n\u2009+\u20091 (0\u2009\u2264\u2009ri\u2009\u2264\u2009100) \u2014 the y coordinates of the polyline vertices on Bolek's picture. It is guaranteed that we can obtain the given picture after performing the described actions on some picture of mountain peaks.", "output_spec": "Print 2n\u2009+\u20091 integers y1,\u2009y2,\u2009...,\u2009y2n\u2009+\u20091 \u2014 the y coordinates of the vertices of the polyline on the initial picture. If there are multiple answers, output any one of them.", "sample_inputs": ["3 2\n0 5 3 5 1 5 2", "1 1\n0 2 0"], "sample_outputs": ["0 5 3 4 1 4 2", "0 1 0"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let k = ref (Scanf.scanf \" %d\" (fun x -> x)) in\n let a = Array.create (2*n+1) 0 in\n for i = 0 to 2 * n do\n a.(i) <- Scanf.scanf \" %d\" (fun x -> x)\n done;\n for i = 0 to n - 1 do\n let j = 2*i+1 in\n if !k > 0 && a.(j) > a.(j-1) + 1 && a.(j) > a.(j+1) + 1 then begin\n k := !k - 1;\n a.(j) <- a.(j) - 1\n end\n done;\n print_string (String.concat \" \" (List.map string_of_int (Array.to_list a)))\n;;\n"}, {"source_code": "open Scanf;;\nopen Printf;;\n\nlet rec head n ls =\n match (n, ls) with\n (0, _) -> []\n | (n, []) -> failwith \"\"\n | (n, x::xs) -> x :: (head (n - 1) xs)\n\nlet n, k = scanf \"%d %d \" (fun x y -> x, y);;\nlet arr = Array.make (2 * n + 1) 0;;\n\nfor i = 0 to 2 * n do\n arr.(i) <- (scanf \"%d \" (fun x -> x))\ndone;;\n\nlet main () = \n let rec loop i res =\n if i >= 2 * n then res\n else if arr.(i - 1) + 1 < arr.(i) && arr.(i) > arr.(i + 1) + 1 then\n loop (i + 2) (i :: res)\n else loop (i + 2) res in\n let res = head k (loop 1 []) in\n List.iter (fun i -> arr.(i) <- (arr.(i) - 1)) res;;\n\nmain ();;\n\nfor i = 0 to 2 * n do\n printf \"%d \" arr.(i)\ndone;;\nprintf \"\\n\"\n"}], "negative_code": [{"source_code": "open Scanf;;\nopen Printf;;\n\nlet rec head n ls =\n match (n, ls) with\n (0, _) -> []\n | (n, []) -> failwith \"\"\n | (n, x::xs) -> x :: (head (n - 1) xs)\n\nlet n, k = scanf \"%d %d \" (fun x y -> x, y);;\nlet arr = Array.make (2 * n + 1) 0;;\n\nfor i = 0 to 2 * n do\n arr.(i) <- (scanf \"%d \" (fun x -> x))\ndone;;\n\nlet main () = \n let rec loop i res =\n if i >= 2 * n then res\n else if arr.(i - 1) + 1 < arr.(i) && arr.(i) > arr.(i - 1) + 1 then\n loop (i + 2) (i :: res)\n else loop (i + 2) res in\n let res = head k (loop 1 []) in\n List.iter (fun i -> arr.(i) <- (arr.(i) - 1)) res;;\n\nmain ();;\n\nfor i = 0 to 2 * n do\n printf \"%d \" arr.(i)\ndone;;\nprintf \"\\n\"\n"}], "src_uid": "1adb4675dc88208f8a05a2db49bb44cb"} {"nl": {"description": "God's Blessing on This PermutationForces!A Random PebbleYou are given a permutation $$$p_1,p_2,\\ldots,p_n$$$ of length $$$n$$$ and a positive integer $$$k \\le n$$$. In one operation you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \\le i < j \\le n$$$) and swap $$$p_i$$$ with $$$p_j$$$.Find the minimum number of operations needed to make the sum $$$p_1 + p_2 + \\ldots + p_k$$$ as small as possible.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 100$$$). The second line of each test case contains $$$n$$$ integers $$$p_1,p_2,\\ldots,p_n$$$ ($$$1 \\le p_i \\le n$$$). It is guaranteed that the given numbers form a permutation of length $$$n$$$.", "output_spec": "For each test case print one integer\u00a0\u2014 the minimum number of operations needed to make the sum $$$p_1 + p_2 + \\ldots + p_k$$$ as small as possible.", "sample_inputs": ["4\n\n3 1\n\n2 3 1\n\n3 3\n\n1 2 3\n\n4 2\n\n3 4 1 2\n\n1 1\n\n1"], "sample_outputs": ["1\n0\n2\n0"], "notes": "NoteIn the first test case, the value of $$$p_1 + p_2 + \\ldots + p_k$$$ is initially equal to $$$2$$$, but the smallest possible value is $$$1$$$. You can achieve it by swapping $$$p_1$$$ with $$$p_3$$$, resulting in the permutation $$$[1, 3, 2]$$$.In the second test case, the sum is already as small as possible, so the answer is $$$0$$$."}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet () =\n let t = read_int () in\n\n for _ = 1 to t do\n let n = read_int () in\n let k = read_int () in\n let a = read_array read_int n in\n let ans = ref 0 in\n for i = 0 to k - 1 do\n if (a.(i) > k) then ans := !ans + 1;\n done;\n pf \"%d\\n\" !ans;\n done"}, {"source_code": "let get_num () =\n let rec f acc =\n try\n let c = input_byte stdin in\n if int_of_char '0' <= c && c <= int_of_char '9' then\n f ((acc * 10) + c - int_of_char '0')\n else if acc > 0 then Some acc\n else None\n with End_of_file -> if acc > 0 then Some acc else None\n in\n f 0\n\nlet solve_case () =\n match (get_num (), get_num ()) with\n | Some n, Some k ->\n let rec f i ans =\n let i = i + 1 in\n if i > n then print_int ans\n else\n match get_num () with\n | Some p ->\n let ans = if i <= k && p > k then ans + 1 else ans in\n f i ans\n | _ -> exit 1\n in\n f 0 0\n | _ -> ()\n\nlet () =\n match get_num () with\n | Some t ->\n let rec f i =\n if i = 0 then ()\n else\n let () = solve_case () in\n let () = print_newline () in\n f (i - 1)\n in\n f t\n | _ -> exit 1\n"}], "negative_code": [], "src_uid": "10927dcb59007fc3a31fdb6b5d13846f"} {"nl": {"description": "Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n\u2009=\u20095 the handkerchief pattern should look like that: \u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a01\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a01\u00a02\u00a01\u00a00\u00a0\u00a0\u00a0\u00a00\u00a01\u00a02\u00a03\u00a02\u00a01\u00a00\u00a0\u00a00\u00a01\u00a02\u00a03\u00a04\u00a03\u00a02\u00a01\u00a000\u00a01\u00a02\u00a03\u00a04\u00a05\u00a04\u00a03\u00a02\u00a01\u00a00\u00a0\u00a00\u00a01\u00a02\u00a03\u00a04\u00a03\u00a02\u00a01\u00a00\u00a0\u00a0\u00a0\u00a00\u00a01\u00a02\u00a03\u00a02\u00a01\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a01\u00a02\u00a01\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00\u00a01\u00a00\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a00Your task is to determine the way the handkerchief will look like by the given n.", "input_spec": "The first line contains the single integer n (2\u2009\u2264\u2009n\u2009\u2264\u20099).", "output_spec": "Print a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.", "sample_inputs": ["2", "3"], "sample_outputs": ["0\n 0 1 0\n0 1 2 1 0\n 0 1 0\n 0", "0\n 0 1 0\n 0 1 2 1 0\n0 1 2 3 2 1 0\n 0 1 2 1 0\n 0 1 0\n 0"], "notes": null}, "positive_code": [{"source_code": "let n = read_int();;\n\nfor i = n downto 0 do\n\tfor t = 1 to i do print_string \" \" done;\n\tfor t = i to n do print_int (t-i); if i <> t || i <> n then print_char ' ' done;\n\tfor t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;\n\tprint_string \"\\n\";\ndone;;\n\nfor i = 1 to n do\n for t = 1 to i do print_string \" \" done;\n for t = i to n do print_int (t-i); if i <> t || i <> n then print_char ' ' done;\n for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done; \n print_string \"\\n\";\ndone;;\n\n"}], "negative_code": [{"source_code": "let n = read_int();;\n\nfor i = n downto 0 do\n\tfor t = 1 to i do print_string \" \" done;\n\tfor t = i to n do print_int (t-i); if i <> t then print_char ' ' done;\n\tfor t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;\n\tprint_string \"\\n\";\ndone;;\n\nfor i = 1 to n do\n for t = 1 to i do print_string \" \" done;\n for t = i to n do print_int (t-i); if i <> t then print_char ' ' done;\n for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done; \n print_string \"\\n\";\ndone;;\n\n"}, {"source_code": "let n = read_int();;\n\nfor i = n downto 0 do\n\tfor t = 1 to i do print_string \" \" done;\n\tfor t = i to n do print_int (t-i); if t = i then print_char ' ' done;\n\tfor t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;\n\tprint_string \"\\n\";\ndone;;\n\nfor i = 1 to n do\n for t = 1 to i do print_string \" \" done;\n for t = i to n do print_int (t-i); if t = i then print_char ' ' done;\n for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done; \n print_string \"\\n\";\ndone;;\n\n"}, {"source_code": "let n = read_int();;\n\nfor i = n downto 0 do\n\tfor t = 1 to i do print_string \" \" done;\n\tfor t = i to n do print_int (t-i); print_char ' ' done;\n\tfor t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;\n\tprint_string \"\\n\";\ndone;;\n\nfor i = 1 to n do\n for t = 1 to i do print_string \" \" done;\n for t = i to n do print_int (t-i); print_char ' ' done;\n for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done; \n print_string \"\\n\";\ndone;;\n\n"}, {"source_code": "let n = read_int();;\n\nfor i = n downto 0 do\n\tfor t = 1 to i do print_string \" \" done;\n\tfor t = i to n do print_int (t-i); print_char ' ' done;\n\tfor t = n to n*2-i-1 do print_int (n*2-i-1-t); print_char ' ' done;\n\tprint_string \"\\n\";\ndone;;\n\nfor i = 1 to n do\n for t = 1 to i do print_string \" \" done;\n for t = i to n do print_int (t-i); print_char ' ' done;\n for t = n to n*2-i-1 do print_int (n*2-i-1-t); print_char ' ' done; \n print_string \"\\n\";\ndone;;\n\n"}, {"source_code": "let n = read_int();;\n\nfor i = n downto 0 do\n\tfor t = 1 to i do print_string \" \" done;\n\tfor t = i to n do print_int (t-i); print_char ' ' done;\n\tfor t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;\n\tprint_string \"\\n\";\ndone;;\n\nfor i = 1 to n do\n for t = 1 to i do print_string \" \" done;\n for t = i to n do print_int (t-i); print_char ' ' done;\n for t = n to n*2-i-1 do print_int (n*2-i-1-t); print_char ' ' done; \n print_string \"\\n\";\ndone;;\n\n"}], "src_uid": "7896740b6f35010af751d3261b5ef718"} {"nl": {"description": "You're given an integer $$$n$$$. For every integer $$$i$$$ from $$$2$$$ to $$$n$$$, assign a positive integer $$$a_i$$$ such that the following conditions hold: For any pair of integers $$$(i,j)$$$, if $$$i$$$ and $$$j$$$ are coprime, $$$a_i \\neq a_j$$$. The maximal value of all $$$a_i$$$ should be minimized (that is, as small as possible). A pair of integers is called coprime if their greatest common divisor is $$$1$$$.", "input_spec": "The only line contains the integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$).", "output_spec": "Print $$$n-1$$$ integers, $$$a_2$$$, $$$a_3$$$, $$$\\ldots$$$, $$$a_n$$$ ($$$1 \\leq a_i \\leq n$$$). If there are multiple solutions, print any of them.", "sample_inputs": ["4", "3"], "sample_outputs": ["1 2 1", "2 1"], "notes": "NoteIn the first example, notice that $$$3$$$ and $$$4$$$ are coprime, so $$$a_3 \\neq a_4$$$. Also, notice that $$$a=[1,2,3]$$$ satisfies the first condition, but it's not a correct answer because its maximal value is $$$3$$$."}, "positive_code": [{"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a = Array.make (n + 1) 0 in\n let x = ref 1 in\n for i = 2 to n do\n let idx = ref i in\n let p = ref false in\n while (!idx <= n) do\n if a.(!idx) = 0 then begin\n a.(!idx) <- !x;\n p := true;\n end;\n idx := !idx + i;\n done;\n if !p then incr x;\n done;\n for i = 2 to n do\n Printf.printf \"%d \" a.(i)\n done\n;;\n"}], "negative_code": [], "src_uid": "aa3c015c20cb0c1789661fdc78ae9bec"} {"nl": {"description": "The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i\u2009+\u20091. Reaching a certain rank i having not reached all the previous i\u2009-\u20091 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.", "input_spec": "The first input line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100). The second line contains n\u2009-\u20091 integers di (1\u2009\u2264\u2009di\u2009\u2264\u2009100). The third input line contains two integers a and b (1\u2009\u2264\u2009a\u2009<\u2009b\u2009\u2264\u2009n). The numbers on the lines are space-separated.", "output_spec": "Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.", "sample_inputs": ["3\n5 6\n1 2", "3\n5 6\n1 3"], "sample_outputs": ["5", "11"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 248C Football Robot Electronic *)\n\nopen Big_int;;\nopen List;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec sumab a b l = \n\tif a>1 then (sumab (a-1) (b-1) (List.tl l))\n\telse if b>1 then ((List.hd l) + (sumab 0 (b-1) (List.tl l)))\n\telse 0;;\n\nlet debug = false;;\n\nlet main () =\n\tlet n = gr() in\n\tlet d = readlist (n-1) [] in\n\tlet a = gr() in\n\tlet b = gr() in\n\tlet sab = sumab a b d in\n\tbegin\n\t\t(* printlisti d; *)\n\t\t(* print_string \"\\n now result\\n\"; *)\n\t print_int sab\n\tend;;\n\nmain();;\n"}, {"source_code": "open Scanf;;\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x);;\nlet aa = Array.make (n-1) 0;;\n\nfor i = 0 to n - 2 do\n let x = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun y->y) in\n aa.(i) <- x\ndone\n;;\n\nlet (a,b) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" (fun x y->(x,y) );;\nif b <= a then\n begin\n print_int 0; print_endline \"\";\n end\nelse\n let rslt=ref 0 in\n let () = \n for j = (a-1) to (b-2) do\n rslt := !rslt + aa.(j)\n done in print_int !rslt; print_endline \"\"\n;;\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "69850c2af99d60711bcff5870575e15e"} {"nl": {"description": "Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 amount of squares in the stripe. The second line contains n space-separated numbers \u2014 they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.", "output_spec": "Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.", "sample_inputs": ["9\n1 5 -6 7 9 -16 0 -2 2", "3\n1 1 1", "2\n0 0"], "sample_outputs": ["3", "0", "1"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let s = Array.fold_left (+) 0 a in\n let rec go c x i =\n if i >= n-1 then\n c\n else\n let x' = x+a.(i) in\n go (c + (if x'*2 == s then 1 else 0)) x' (i+1)\n in\n go 0 0 0 |> Printf.printf \"%d\\n\"\n"}], "negative_code": [], "src_uid": "5358fff5b798ac5e500d0f5deef765c7"} {"nl": {"description": "Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column.Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of segments drawn by Vika. Each of the next n lines contains four integers x1, y1, x2 and y2 (\u2009-\u2009109\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2\u2009\u2264\u2009109)\u00a0\u2014 the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.", "output_spec": "Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.", "sample_inputs": ["3\n0 1 2 1\n1 4 1 2\n0 3 2 3", "4\n-2 -1 2 -1\n2 1 -2 1\n-1 -2 -1 2\n1 2 1 -2"], "sample_outputs": ["8", "16"], "notes": "NoteIn the first sample Vika will paint squares (0,\u20091), (1,\u20091), (2,\u20091), (1,\u20092), (1,\u20093), (1,\u20094), (0,\u20093) and (2,\u20093)."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\n(* A segment tree that maintains a set of variables a0, a1, ... a(n-1),\n allowing you to assign to a variable, and also allowing you to sum\n a range of the variables ai+a(i+1)+...+aj.\n*)\n\nlet parent v = v/2\nlet lc v = 2*v\nlet rc v = 2*v+1\n\nlet superceil n =\n let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in\n 1 + (loop (n-1) 0)\n\nlet make_segtree n =\n let nn = superceil n in\n let a = Array.make (2*nn) 0 in\n (nn,a)\n\nlet assign (nn,a) v x =\n (* do a(v) <- x *)\n let x = x - a.(nn+v) in\n let rec loop j = if j > 0 then (\n a.(j) <- a.(j) + x;\n loop (parent j)\n ) in\n loop (nn+v)\n\nlet sum (nn,a) i j =\n let rec f v l r ql qr =\n let m = (l+r)/2 in\n if l=ql && r=qr then a.(v) else\n let t1 = if ql<=m then f (lc v) l m ql (min m qr) else 0 in\n let t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else 0 in\n t1 + t2\n in\n f 1 0 (nn-1) i j\n\n(*---------------------end segment tree----------------------*)\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_four () = bscanf Scanning.stdib \" %d %d %d %d \" (fun a b c d -> (a,b,c,d))\n\nlet () = \n let n = read_int() in\n let r = Array.init n (fun i -> read_four()) in\n\n let rec classify vert horiz i = if i=n then (vert,horiz) else\n let (x1,y1,x2,y2) = r.(i) in\n let (x1,x2) = (min x1 x2, max x1 x2) in\n let (y1,y2) = (min y1 y2, max y1 y2) in\n r.(i) <- (x1,x2,y1,y2);\n\n if x1 < x2 then classify vert ((y1,x1,x2)::horiz) (i+1)\n else classify ((x1,y1,y2)::vert) horiz (i+1)\n in\n\n let (vert,horiz) = classify [] [] 0 in\n\n let clean_up rect =\n let h = Hashtbl.create 100 in\n\n let add_to_h (y,x1,x2) = \n let c = try Hashtbl.find h y with Not_found -> [] in\n Hashtbl.replace h y ((x1,x2)::c)\n in\n List.iter add_to_h rect;\n\n let fix_bucket li =\n let li = List.sort compare li in\n let rec loop (cx1,cx2) li ac =\n\tmatch li with\n\t | [] -> (cx1,cx2)::ac\n\t | (x1,x2)::tail ->\n\t if x1 > cx2+1 then loop (x1,x2) tail ((cx1,cx2)::ac)\n\t else loop (cx1,max x2 cx2) tail ac\n in\n List.rev (loop (List.hd li) (List.tl li) [])\n in\n \n Hashtbl.fold (fun y li ac -> (y,(fix_bucket li))::ac) h []\n (* [(y1,[(x1,x2);(x3,x4)...]); (y2,[...]);...] *)\n in\n\n let vert = clean_up vert in\n let horiz = clean_up horiz in\n\n let compy = Hashtbl.create 100 in (* compress y table *)\n\n List.iter (fun (y,_) -> Hashtbl.replace compy y 0) horiz;\n\n List.iter (fun (_, li) ->\n List.iter (fun (y1,y2) ->\n Hashtbl.replace compy y1 0;\n Hashtbl.replace compy y2 0;\n ) li\n ) vert;\n\n let ys = Hashtbl.fold (fun y _ ac -> y::ac) compy [] in\n let ys = List.sort compare ys in\n List.iteri (fun i y -> Hashtbl.replace compy y i) ys;\n (* now Hashtbl.find compy y returns the mapped value of y *)\n let map y = Hashtbl.find compy y in\n let ny = Hashtbl.length compy in (* mapped ys are 0....ny-1 *)\n\n (* In the sweep-line algorithm there are three types of events\n (1) a horizontal segment enters\n (2) a vertical segment is processed\n (3) a horizontal segment leaves\n For each x coordinate we do the events in the this order.\n *)\n\n (* an event is (x, 1/2/3, (y1,y2)), where only y1 is used in cases\n (1) and (3)\n *)\n\n let rec build_horiz horiz ac =\n match horiz with\n | [] -> ac\n | (y, li)::tail ->\n\tlet y = map y in\n\tlet ac = List.fold_left (\n\t fun ac (x1,x2) -> (x1,1,(y,0))::((x2,3,(y,0))::ac)\n\t) ac li in\n\tbuild_horiz tail ac\n in\n\n let rec build_vert vert ac =\n match vert with\n | [] -> ac\n | (x, li)::tail ->\n\tlet ac = List.fold_left (\n\t fun ac (y1,y2) -> (x,2,(map y1, map y2))::ac\n\t) ac li in\n\tbuild_vert tail ac\n in\n\n let event_list = build_vert vert (build_horiz horiz []) in\n let event_list = List.sort compare event_list in\n\n let st = make_segtree ny in\n\n let overlap =\n List.fold_left (fun ac (_,t,(y1,y2)) ->\n match t with\n\t| 1 -> assign st y1 1; ac\n\t| 2 -> ac ++ long (sum st y1 y2)\n\t| 3 -> assign st y1 0; ac\n\t| _ -> failwith \"bad t\"\n ) 0L event_list\n in\n\n let total_length lili =\n List.fold_left (fun ac (_,li) ->\n List.fold_left (fun ac (x1,x2) -> ac ++ (long x2) -- (long x1) ++ 1L\n ) ac li\n ) 0L lili\n in\n\n let answer = (total_length horiz) ++ (total_length vert) -- overlap in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\n(* A segment tree that maintains a set of variables a0, a1, ... a(n-1),\n allowing you to assign to a variable, and also allowing you to sum\n a range of the variables ai+a(i+1)+...+aj.\n*)\n\nlet parent v = v/2\nlet lc v = 2*v\nlet rc v = 2*v+1\n\nlet superceil n =\n let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in\n 1 + (loop (n-1) 0)\n\nlet make_segtree n =\n let nn = superceil n in\n let a = Array.make (2*nn) 0 in\n (nn,a)\n\nlet assign (nn,a) v x =\n (* do a(v) <- x *)\n let x = x - a.(nn+v) in\n let rec loop j = if j > 0 then (\n a.(j) <- a.(j) + x;\n loop (parent j)\n ) in\n loop (nn+v)\n\nlet sum (nn,a) i j =\n let rec f v l r ql qr =\n let m = (l+r)/2 in\n if l=ql && r=qr then a.(v) else\n let t1 = if ql<=m then f (lc v) l m ql (min m qr) else 0 in\n let t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else 0 in\n t1 + t2\n in\n f 1 0 (nn-1) i j\n\n(*---------------------end segment tree----------------------*)\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_four () = bscanf Scanning.stdib \" %d %d %d %d \" (fun a b c d -> (a,b,c,d))\n\nlet () = \n let n = read_int() in\n let r = Array.init n (fun i -> read_four()) in\n\n let rec classify vert horiz i = if i=n then (vert,horiz) else\n let (x1,y1,x2,y2) = r.(i) in\n let (x1,x2) = (min x1 x2, max x1 x2) in\n let (y1,y2) = (min y1 y2, max y1 y2) in\n r.(i) <- (x1,x2,y1,y2);\n\n if x1 < x2 then classify vert ((y1,x1,x2)::horiz) (i+1)\n else classify ((x1,y1,y2)::vert) horiz (i+1)\n in\n\n let (vert,horiz) = classify [] [] 0 in\n\n let clean_up rect =\n let h = Hashtbl.create 100 in\n\n let add_to_h (y,x1,x2) = \n let c = try Hashtbl.find h y with Not_found -> [] in\n Hashtbl.replace h y ((x1,x2)::c)\n in\n List.iter add_to_h rect;\n\n let fix_bucket li =\n let li = List.sort compare li in\n let rec loop (cx1,cx2) li ac =\n\tmatch li with\n\t | [] -> (cx1,cx2)::ac\n\t | (x1,x2)::tail ->\n\t if x1 > cx2+1 then loop (x1,x2) tail ((cx1,cx2)::ac)\n\t else loop (cx1,x2) tail ac\n in\n List.rev (loop (List.hd li) (List.tl li) [])\n in\n \n Hashtbl.fold (fun y li ac -> (y,(fix_bucket li))::ac) h []\n (* [(y1,[(x1,x2);(x3,x4)...]); (y2,[...]);...] *)\n in\n\n let vert = clean_up vert in\n let horiz = clean_up horiz in\n\n let compy = Hashtbl.create 100 in (* compress y table *)\n\n List.iter (fun (y,_) -> Hashtbl.replace compy y 0) horiz;\n\n List.iter (fun (_, li) ->\n List.iter (fun (y1,y2) ->\n Hashtbl.replace compy y1 0;\n Hashtbl.replace compy y2 0;\n ) li\n ) vert;\n\n let ys = Hashtbl.fold (fun y _ ac -> y::ac) compy [] in\n let ys = List.sort compare ys in\n List.iteri (fun i y -> Hashtbl.replace compy y i) ys;\n (* now Hashtbl.find compy y returns the mapped value of y *)\n let map y = Hashtbl.find compy y in\n let ny = Hashtbl.length compy in (* mapped ys are 0....ny-1 *)\n\n (* In the sweep-line algorithm there are three types of events\n (1) a horizontal segment enters\n (2) a vertical segment is processed\n (3) a horizontal segment leaves\n For each x coordinate we do the events in the this order.\n *)\n\n (* an event is (x, 1/2/3, (y1,y2)), where only y1 is used in cases\n (1) and (3)\n *)\n\n let rec build_horiz horiz ac =\n match horiz with\n | [] -> ac\n | (y, li)::tail ->\n\tlet y = map y in\n\tlet ac = List.fold_left (\n\t fun ac (x1,x2) -> (x1,1,(y,0))::((x2,3,(y,0))::ac)\n\t) ac li in\n\tbuild_horiz tail ac\n in\n\n let rec build_vert vert ac =\n match vert with\n | [] -> ac\n | (x, li)::tail ->\n\tlet ac = List.fold_left (\n\t fun ac (y1,y2) -> (x,2,(map y1,map y2))::ac\n\t) ac li in\n\tbuild_vert tail ac\n in\n\n let event_list = build_vert vert (build_horiz horiz []) in\n let event_list = List.sort compare event_list in\n\n let st = make_segtree ny in\n\n let overlap =\n List.fold_left (fun ac (_,t,(y1,y2)) ->\n match t with\n\t| 1 -> assign st y1 1; ac\n\t| 2 -> ac ++ long (sum st y1 y2)\n\t| 3 -> assign st y1 0; ac\n\t| _ -> failwith \"bad t\"\n ) 0L event_list\n in\n\n let total_length lili =\n List.fold_left (fun ac (y,li) ->\n List.fold_left (fun ac (x1,x2) -> ac ++ (long x2) -- (long x1) ++ 1L\n ) ac li\n ) 0L lili\n in\n\n let answer = (total_length horiz) ++ (total_length vert) -- overlap in\n\n printf \"%Ld\\n\" answer\n"}], "src_uid": "6d7accf770d489f746648aa56c90d16d"} {"nl": {"description": "There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules: Problemset of each division should be non-empty. Each problem should be used in exactly one division (yes, it is unusual requirement). Each problem used in division 1 should be harder than any problem used in division 2. If two problems are similar, they should be used in different divisions. Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k.", "input_spec": "The first line of the input contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 0\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of problems prepared for the round and the number of pairs of similar problems, respectively. Each of the following m lines contains a pair of similar problems ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n,\u2009ui\u2009\u2260\u2009vi). It's guaranteed, that no pair of problems meets twice in the input.", "output_spec": "Print one integer\u00a0\u2014 the number of ways to split problems in two divisions.", "sample_inputs": ["5 2\n1 4\n5 2", "3 3\n1 2\n2 3\n1 3", "3 2\n3 1\n3 2"], "sample_outputs": ["2", "0", "1"], "notes": "NoteIn the first sample, problems 1 and 2 should be used in division 2, while problems 4 and 5 in division 1. Problem 3 may be used either in division 1 or in division 2.In the second sample, all pairs of problems are similar and there is no way to split problem between two divisions without breaking any rules.Third sample reminds you that the similarity relation is not transitive. Problem 3 is similar to both 1 and 2, but 1 is not similar to 2, so they may be used together."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in \n\n let maxleft = ref 0 in\n let minright = ref (n+1) in\n\n for i=0 to m-1 do\n let u = read_int () in\n let v = read_int () in\n let (u,v) = (min u v, max u v) in\n maxleft := max !maxleft u;\n minright := min !minright v\n done;\n\n let answer = max (!minright - !maxleft) 0 in\n let answer = if m=0 then (n-1) else answer in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "b54ced81e152a28c19e0068cf6a754f6"} {"nl": {"description": "We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $$$s$$$ can transform to another superhero with name $$$t$$$ if $$$s$$$ can be made equal to $$$t$$$ by changing any vowel in $$$s$$$ to any other vowel and any consonant in $$$s$$$ to any other consonant. Multiple changes can be made.In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.Given the names of two superheroes, determine if the superhero with name $$$s$$$ can be transformed to the Superhero with name $$$t$$$.", "input_spec": "The first line contains the string $$$s$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. The second line contains the string $$$t$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. Both strings $$$s$$$ and $$$t$$$ are guaranteed to be different and consist of lowercase English letters only.", "output_spec": "Output \"Yes\" (without quotes) if the superhero with name $$$s$$$ can be transformed to the superhero with name $$$t$$$ and \"No\" (without quotes) otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["a\nu", "abc\nukm", "akm\nua"], "sample_outputs": ["Yes", "Yes", "No"], "notes": "NoteIn the first sample, since both 'a' and 'u' are vowels, it is possible to convert string $$$s$$$ to $$$t$$$.In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string $$$s$$$ to $$$t$$$."}, "positive_code": [{"source_code": "Array.(Scanf.scanf \" %s %s\" @@ fun s t ->\n let f s =\n init (String.length s) (fun i -> s.[i])\n |> map (function\n | 'a' | 'i' | 'u' | 'e' | 'o' -> 1\n | _ -> 0) in\n print_endline @@ if f s = f t then \"Yes\" else \"No\")"}, {"source_code": "let is_vowel c = c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';;\n\nlet rec is_transformable a b i j na nb = na == nb && (if i < na && j < nb then (is_vowel (String.get a i)) == (is_vowel (String.get b j)) && (is_transformable a b (i + 1) (j + 1) na nb) else true);;\n\nlet a = read_line() in\nlet b = read_line() in\nprint_string (if is_transformable a b 0 0 (String.length a) (String.length b) then \"Yes\" else \"No\");;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_str _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let s = read_str() in\n let t = read_str() in\n\n let isvowel c =\n c='a' || c='e' || c='i' || c='o' || c='u' \n in\n \n let f s =\n let n = String.length s in\n Array.init n (fun i -> isvowel s.[i])\n in\n\n if (f s) = (f t) then printf \"Yes\\n\" else printf \"No\\n\""}], "negative_code": [{"source_code": "let is_vowel c = c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';;\n\nlet is_transformable a b i j na nb = na == nb && i < na && j < nb && (is_vowel (String.get a i)) == (is_vowel (String.get b j));;\n\nlet a = read_line() in\nlet b = read_line() in\nprint_string (if is_transformable a b 0 0 (String.length a) (String.length b) then \"Yes\" else \"No\");;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_str _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let s = read_str() in\n let t = read_str() in\n\n let isvowel c =\n c='a' || c='e' || c='i' || c='o' || c='u' \n in\n \n let f s =\n let n = String.length s in\n Array.init n (fun i -> isvowel s.[i])\n in\n\n let alldiff s t =\n let n = String.length s in\n let m = String.length t in\n m = n && (forall 0 (n-1) (fun i -> s.[i] <> t.[i]))\n in\n\n if (f s) = (f t) && (alldiff s t) then printf \"Yes\\n\" else printf \"No\\n\"\n"}], "src_uid": "2b346d5a578031de4d19edb4f8f2626c"} {"nl": {"description": "This is an interactive problem. Refer to the Interaction section below for better understanding.Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game.Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.", "input_spec": "The first line contains 3 integers n,\u2009m and c (, means rounded up)\u00a0\u2014 the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process.", "output_spec": null, "sample_inputs": ["2 4 4\n2\n1\n3"], "sample_outputs": ["1\n2\n2"], "notes": "NoteIn the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round.The input format for hacking: The first line contains 3 integers n,\u2009m and c; The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round. "}, "positive_code": [{"source_code": "open Printf\nopen String\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n \nlet split_string s = \n let s = trim s in\n \n let n = String.length s in\n let li = fold 0 (n-1) \n (fun i ac -> if s.[i] = ' ' then i::ac else ac) []\n in\n\n let rec chop prev li ac = \n match li with [] -> List.rev ac\n | i::tail -> \n\tchop i tail ((sub s (prev+1) (i-prev-1))::ac)\n in\n \n chop (-1) (List.rev (n::li)) []\n\nlet () =\n let line1 = split_string (read_line()) in\n let n = int_of_string(List.nth line1 0) in\n let m = int_of_string(List.nth line1 1) in\n let c = int_of_string(List.nth line1 2) in\n let c = ((c+1)/2) * 2 in (* next even number up *)\n \n let a = Array.make n 0 in\n\n let left_place p =\n let get i = if a.(i) = 0 then c+1 else a.(i) in\n let rec find i = if get i > p then i else find (i+1) in\n find 0\n in\n\n let right_place p =\n let rec find i = if a.(i) < p then i else find (i-1) in\n find (n-1)\n in\n\n let rec loop nblanks = if nblanks = 0 then () else (\n let p = int_of_string (read_line()) in\n let place = if p <= c/2 then left_place p else right_place p in\n Printf.printf \"%d\\n%!\" (place+1);\n let nblanks = nblanks - if a.(place) = 0 then 1 else 0 in\n a.(place) <- p;\n loop nblanks\n ) in\n\n loop n\n"}], "negative_code": [], "src_uid": "305159945f077d5fff514bfd398eb10e"} {"nl": {"description": "There are n cities and m two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads.The road minister decided to make a reform in Berland and to orient all roads in the country, i.e. to make each road one-way. The minister wants to maximize the number of cities, for which the number of roads that begins in the city equals to the number of roads that ends in it.", "input_spec": "The first line contains a positive integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009200)\u00a0\u2014 the number of testsets in the input. Each of the testsets is given in the following way. The first line contains two integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009200, 0\u2009\u2264\u2009m\u2009\u2264\u2009n\u00b7(n\u2009-\u20091)\u2009/\u20092)\u00a0\u2014 the number of cities and the number of roads in Berland. The next m lines contain the description of roads in Berland. Each line contains two integers u and v (1\u2009\u2264\u2009u,\u2009v\u2009\u2264\u2009n)\u00a0\u2014 the cities the corresponding road connects. It's guaranteed that there are no self-loops and multiple roads. It is possible that there is no way along roads between a pair of cities. It is guaranteed that the total number of cities in all testset of input data doesn't exceed 200. Pay attention that for hacks, you can only use tests consisting of one testset, so t should be equal to one.", "output_spec": "For each testset print the maximum number of such cities that the number of roads that begins in the city, is equal to the number of roads that ends in it. In the next m lines print oriented roads. First print the number of the city where the road begins and then the number of the city where the road ends. If there are several answers, print any of them. It is allowed to print roads in each test in arbitrary order. Each road should be printed exactly once. ", "sample_inputs": ["2\n5 5\n2 1\n4 5\n2 3\n1 3\n3 5\n7 2\n3 7\n4 2"], "sample_outputs": ["3\n1 3\n3 5\n5 4\n3 2\n2 1\n3\n2 4\n3 7"], "notes": null}, "positive_code": [{"source_code": "let zip xs ys =\n let rec h accu xs' ys' =\n match (xs', ys') with\n | [], _ | _, [] -> accu\n | x :: xr, y :: yr -> h ((x, y) :: accu) xr yr\n in\n h [] xs ys\n\n(* --- *)\nexception UnwrapNone\n\nlet unwrap v = match v with Some x -> x | _ -> raise UnwrapNone\n\n(* -- *)\nmodule RandomizedSet = struct\n type ('a, 'b) t =\n { hash: ('b, int) Hashtbl.t\n ; arr: 'a option array\n ; mutable size: int\n ; cap: int }\n\n let create cap =\n {hash= Hashtbl.create cap; arr= Array.make cap None; size= 0; cap}\n\n let is_empty set = set.size = 0\n\n let is_full set = set.size = set.cap\n\n let insert set v =\n let {hash; arr; cap} = set in\n match (Hashtbl.mem hash v, is_full set) with\n | true, _ -> false\n | _, true -> false\n | _ ->\n arr.(set.size) <- Some v ;\n Hashtbl.replace hash v set.size ;\n set.size <- set.size + 1 ;\n true\n\n let remove set v =\n let {hash; arr; cap} = set in\n if Hashtbl.mem hash v then (\n let i = Hashtbl.find hash v in\n let another = arr.(set.size - 1) in\n if i <> set.size - 1 then (\n arr.(i) <- another ;\n Hashtbl.replace hash (unwrap another) i ) ;\n set.size <- set.size - 1 ;\n Hashtbl.remove hash v ;\n true )\n else false\n\n let get_next set = if is_empty set then None else set.arr.(0)\nend\n\n(* --- *)\nlet concat_chars cs = String.concat \"\" (List.map (String.make 1) cs)\n\nlet explode str =\n let exploded = ref [] in\n for i = String.length str - 1 downto 0 do\n exploded := str.[i] :: !exploded\n done ;\n !exploded\n\nlet split_on_char c str =\n let exploded = explode str in\n let cs', pending' =\n List.fold_right\n (fun x (ls, pending) ->\n match (x = c, pending) with\n | false, _ -> (ls, x :: pending)\n | true, [] -> (ls, pending)\n | true, _ -> (pending :: ls, []) )\n exploded ([], [])\n in\n List.map concat_chars (if pending' = [] then cs' else pending' :: cs')\n\n(* --- *)\nexception InputError of string\n\nlet read_into_int_list () =\n read_line () |> String.trim |> split_on_char ' ' |> List.map int_of_string\n\n(* --- *)\ntype 'a edge = {from: 'a; to': 'a}\n\n(* --- *)\nlet do_case () =\n match read_into_int_list () with\n | [vertices_count; edges_count] ->\n let degs = Array.make (vertices_count + 1) 0 in\n let adj =\n Array.init (vertices_count + 1) (fun _ ->\n RandomizedSet.create vertices_count )\n in\n (* read in edges *)\n for i = 1 to edges_count do\n match read_into_int_list () with\n | [from; to'] ->\n degs.(from) <- degs.(from) + 1 ;\n degs.(to') <- degs.(to') + 1 ;\n RandomizedSet.insert adj.(from) {from; to'} ;\n RandomizedSet.insert adj.(to') {from; to'}\n | _ -> raise @@ InputError \"unexpected edge input\"\n done ;\n (* connect all odd vertices with an additional one *)\n let addv_i = 0 in\n let even_count = ref 0 in\n for i = 1 to vertices_count do\n if degs.(i) mod 2 <> 0 then (\n let e = {from= i; to'= addv_i} in\n RandomizedSet.insert adj.(i) e ;\n RandomizedSet.insert adj.(addv_i) e ;\n () )\n else even_count := !even_count + 1\n done ;\n Printf.printf \"%d\\n\" !even_count ;\n (* dfs *)\n let rec dfs v =\n while not @@ RandomizedSet.is_empty adj.(v) do\n match RandomizedSet.get_next adj.(v) with\n | Some e ->\n let next = if e.from = v then e.to' else e.from in\n RandomizedSet.remove adj.(v) e ;\n RandomizedSet.remove adj.(next) e ;\n if next <> addv_i && v <> addv_i then\n Printf.printf \"%d %d\\n\" v next ;\n dfs next\n | None -> ()\n done\n in\n for i = 0 to vertices_count do\n dfs i\n done\n | _ -> raise @@ InputError \"unexpected vertice_count and edges_count input\"\n\n(* --- *)\nlet test_case_count = read_line () |> int_of_string\n\n;;\nfor i = 1 to test_case_count do\n do_case ()\ndone\n"}, {"source_code": "(* --- *)\nexception UnwrapNone\n\nlet unwrap v = match v with Some x -> x | _ -> raise UnwrapNone\n\n(* -- *)\nmodule RandomizedSet = struct\n type ('a, 'b) t =\n { hash: ('b, int) Hashtbl.t\n ; arr: 'a option array\n ; mutable size: int\n ; cap: int }\n\n let create cap =\n {hash= Hashtbl.create cap; arr= Array.make cap None; size= 0; cap}\n\n let is_empty set = set.size = 0\n\n let is_full set = set.size = set.cap\n\n let insert set v =\n let {hash; arr; cap} = set in\n match (Hashtbl.mem hash v, is_full set) with\n | true, _ | _, true -> false\n | _ ->\n arr.(set.size) <- Some v ;\n Hashtbl.replace hash v set.size ;\n set.size <- set.size + 1 ;\n true\n\n let remove set v =\n let {hash; arr; cap} = set in\n if Hashtbl.mem hash v then (\n let i = Hashtbl.find hash v in\n let another = arr.(set.size - 1) in\n if i <> set.size - 1 then (\n arr.(i) <- another ;\n Hashtbl.replace hash (unwrap another) i ) ;\n set.size <- set.size - 1 ;\n Hashtbl.remove hash v ;\n true )\n else false\n\n let get_next set = if is_empty set then None else set.arr.(0)\nend\n\n(* --- *)\nlet concat_chars cs = String.concat \"\" (List.map (String.make 1) cs)\n\nlet explode str =\n let exploded = ref [] in\n for i = String.length str - 1 downto 0 do\n exploded := str.[i] :: !exploded\n done ;\n !exploded\n\nlet split_on_char c str =\n let exploded = explode str in\n let cs', pending' =\n List.fold_right\n (fun x (ls, pending) ->\n match (x = c, pending) with\n | false, _ -> (ls, x :: pending)\n | true, [] -> (ls, pending)\n | true, _ -> (pending :: ls, []) )\n exploded ([], [])\n in\n List.map concat_chars (if pending' = [] then cs' else pending' :: cs')\n\n(* --- *)\nexception InputError of string\n\nlet read_into_int_list () =\n read_line () |> String.trim |> split_on_char ' ' |> List.map int_of_string\n\n(* --- *)\nlet do_case () =\n match read_into_int_list () with\n | [vertices_count; edges_count] ->\n let degs = Array.make (vertices_count + 1) 0 in\n let adj =\n Array.init (vertices_count + 1) (fun _ ->\n RandomizedSet.create vertices_count )\n in\n (* read in edges *)\n for i = 1 to edges_count do\n match read_into_int_list () with\n | [one; another] ->\n degs.(one) <- degs.(one) + 1 ;\n degs.(another) <- degs.(another) + 1 ;\n RandomizedSet.insert adj.(one) (one, another) ;\n RandomizedSet.insert adj.(another) (one, another)\n | _ -> raise @@ InputError \"unexpected edge input\"\n done ;\n (* connect all odd vertices with an additional one *)\n let addv_i = 0 in\n let even_count = ref 0 in\n for i = 1 to vertices_count do\n if degs.(i) mod 2 <> 0 then (\n let e = (i, addv_i) in\n RandomizedSet.insert adj.(i) e ;\n RandomizedSet.insert adj.(addv_i) e ;\n () )\n else even_count := !even_count + 1\n done ;\n Printf.printf \"%d\\n\" !even_count ;\n (* dfs *)\n let rec dfs v =\n while not @@ RandomizedSet.is_empty adj.(v) do\n match RandomizedSet.get_next adj.(v) with\n | Some ((one, another) as e) ->\n let next = if one = v then another else one in\n RandomizedSet.remove adj.(v) e ;\n RandomizedSet.remove adj.(next) e ;\n if next <> addv_i && v <> addv_i then\n Printf.printf \"%d %d\\n\" v next ;\n dfs next\n | None -> ()\n done\n in\n for i = 0 to vertices_count do\n dfs i\n done\n | _ -> raise @@ InputError \"unexpected vertice_count and edges_count input\"\n\n(* --- *)\nlet test_case_count = read_line () |> int_of_string\n\n;;\nfor i = 1 to test_case_count do\n do_case ()\ndone\n"}, {"source_code": "\n(* --- *)\nexception UnwrapNone\n\nlet unwrap v = match v with Some x -> x | _ -> raise UnwrapNone\n\n(* -- *)\nmodule RandomizedSet = struct\n type ('a, 'b) t =\n { hash: ('b, int) Hashtbl.t\n ; arr: 'a option array\n ; mutable size: int\n ; cap: int }\n\n let create cap =\n {hash= Hashtbl.create cap; arr= Array.make cap None; size= 0; cap}\n\n let is_empty set = set.size = 0\n\n let is_full set = set.size = set.cap\n\n let insert set v =\n let {hash; arr; cap} = set in\n match (Hashtbl.mem hash v, is_full set) with\n | true, _ | _, true -> false\n | _ ->\n arr.(set.size) <- Some v ;\n Hashtbl.replace hash v set.size ;\n set.size <- set.size + 1 ;\n true\n\n let remove set v =\n let {hash; arr; cap} = set in\n if Hashtbl.mem hash v then (\n let i = Hashtbl.find hash v in\n let another = arr.(set.size - 1) in\n if i <> set.size - 1 then (\n arr.(i) <- another ;\n Hashtbl.replace hash (unwrap another) i ) ;\n set.size <- set.size - 1 ;\n Hashtbl.remove hash v ;\n true )\n else false\n\n let get_random set =\n if is_empty set then None else set.arr.(Random.int set.size)\nend\n\n(* --- *)\nlet concat_chars cs = String.concat \"\" (List.map (String.make 1) cs)\n\nlet explode str =\n let exploded = ref [] in\n for i = String.length str - 1 downto 0 do\n exploded := str.[i] :: !exploded\n done ;\n !exploded\n\nlet split_on_char c str =\n let exploded = explode str in\n let cs', pending' =\n List.fold_right\n (fun x (ls, pending) ->\n match (x = c, pending) with\n | false, _ -> (ls, x :: pending)\n | true, [] -> (ls, pending)\n | true, _ -> (pending :: ls, []) )\n exploded ([], [])\n in\n List.map concat_chars (if pending' = [] then cs' else pending' :: cs')\n\n(* --- *)\nexception InputError of string\n\nlet read_into_int_list () =\n read_line () |> String.trim |> split_on_char ' ' |> List.map int_of_string\n\n(* --- *)\nlet do_case () =\n match read_into_int_list () with\n | [vertices_count; edges_count] ->\n let degs = Array.make (vertices_count + 1) 0 in\n let adj =\n Array.init (vertices_count + 1) (fun _ ->\n RandomizedSet.create vertices_count )\n in\n (* read in edges *)\n for i = 1 to edges_count do\n match read_into_int_list () with\n | [one; another] ->\n degs.(one) <- degs.(one) + 1 ;\n degs.(another) <- degs.(another) + 1 ;\n RandomizedSet.insert adj.(one) (one, another) ;\n RandomizedSet.insert adj.(another) (one, another)\n | _ -> raise @@ InputError \"unexpected edge input\"\n done ;\n (* connect all odd vertices with an additional one *)\n let addv_i = 0 in\n let even_count = ref 0 in\n for i = 1 to vertices_count do\n if degs.(i) mod 2 <> 0 then (\n let e = (i, addv_i) in\n RandomizedSet.insert adj.(i) e ;\n RandomizedSet.insert adj.(addv_i) e ;\n () )\n else even_count := !even_count + 1\n done ;\n Printf.printf \"%d\\n\" !even_count ;\n (* dfs *)\n let rec dfs v =\n while not @@ RandomizedSet.is_empty adj.(v) do\n match RandomizedSet.get_random adj.(v) with\n | Some ((one, another) as e) ->\n let next = if one = v then another else one in\n RandomizedSet.remove adj.(v) e ;\n RandomizedSet.remove adj.(next) e ;\n if next <> addv_i && v <> addv_i then\n Printf.printf \"%d %d\\n\" v next ;\n dfs next\n | None -> ()\n done\n in\n for i = 0 to vertices_count do\n dfs i\n done\n | _ -> raise @@ InputError \"unexpected vertice_count and edges_count input\"\n\n(* --- *)\nlet test_case_count = read_line () |> int_of_string\n\n;;\nfor i = 1 to test_case_count do\n do_case ()\ndone\n"}, {"source_code": "\nlet zip xs ys =\n let rec h accu xs' ys' =\n match (xs', ys') with\n | [], _ | _, [] -> accu\n | x :: xr, y :: yr -> h ((x, y) :: accu) xr yr\n in\n h [] xs ys\n\n(* --- *)\nexception UnwrapNone\n\nlet unwrap v = match v with Some x -> x | _ -> raise UnwrapNone\n\n(* -- *)\nmodule RandomizedSet = struct\n type ('a, 'b) t =\n { hash: ('b, int) Hashtbl.t\n ; arr: 'a option array\n ; mutable size: int\n ; cap: int }\n\n let create cap =\n {hash= Hashtbl.create cap; arr= Array.make cap None; size= 0; cap}\n\n let is_empty set = set.size = 0\n\n let is_full set = set.size = set.cap\n\n let insert set v =\n let {hash; arr; cap} = set in\n match (Hashtbl.mem hash v, is_full set) with\n | true, _ -> false\n | _, true -> false\n | _ ->\n arr.(set.size) <- Some v ;\n Hashtbl.replace hash v set.size ;\n set.size <- set.size + 1 ;\n true\n\n let remove set v =\n let {hash; arr; cap} = set in\n if Hashtbl.mem hash v then (\n let i = Hashtbl.find hash v in\n let another = arr.(set.size - 1) in\n if i <> set.size - 1 then (\n arr.(i) <- another ;\n Hashtbl.replace hash (unwrap another) i ) ;\n set.size <- set.size - 1 ;\n Hashtbl.remove hash v ;\n true )\n else false\n\n let get_next set = if is_empty set then None else set.arr.(0)\nend\n\n(* --- *)\nlet concat_chars cs = String.concat \"\" (List.map (String.make 1) cs)\n\nlet explode str =\n let exploded = ref [] in\n for i = String.length str - 1 downto 0 do\n exploded := str.[i] :: !exploded\n done ;\n !exploded\n\nlet split_on_char c str =\n let exploded = explode str in\n let cs', pending' =\n List.fold_right\n (fun x (ls, pending) ->\n match (x = c, pending) with\n | false, _ -> (ls, x :: pending)\n | true, [] -> (ls, pending)\n | true, _ -> (pending :: ls, []) )\n exploded ([], [])\n in\n List.map concat_chars (if pending' = [] then cs' else pending' :: cs')\n\n(* --- *)\nexception InputError of string\n\nlet read_into_int_list () =\n read_line () |> String.trim |> split_on_char ' ' |> List.map int_of_string\n\n(* --- *)\ntype 'a edge = {from: 'a; to': 'a}\n\nlet identify {from; to'} =\n let f' = string_of_int from and t' = string_of_int to' in\n if from < to' then f' ^ \"-\" ^ t' else t' ^ \"-\" ^ f'\n\n(* --- *)\n\nlet do_case () =\n match read_into_int_list () with\n | [vertices_count; edges_count] ->\n let degs = Array.make (vertices_count + 1) 0 in\n let adj =\n Array.init (vertices_count + 1) (fun _ ->\n RandomizedSet.create vertices_count )\n in\n (* read in edges *)\n for i = 1 to edges_count do\n match read_into_int_list () with\n | [from; to'] ->\n degs.(from) <- degs.(from) + 1 ;\n degs.(to') <- degs.(to') + 1 ;\n RandomizedSet.insert adj.(from) {from; to'} ;\n RandomizedSet.insert adj.(to') {from; to'}\n | _ -> raise @@ InputError \"unexpected edge input\"\n done ;\n (* connect all odd vertices with an additional one *)\n let addv_i = 0 in\n let even_count = ref 0 in\n for i = 1 to vertices_count do\n if degs.(i) mod 2 <> 0 then (\n let e = {from= i; to'= addv_i} in\n RandomizedSet.insert adj.(i) e ;\n RandomizedSet.insert adj.(addv_i) e ;\n () )\n else even_count := !even_count + 1\n done ;\n Printf.printf \"%d\\n\" !even_count ;\n (* dfs *)\n let passed_vertices = ref [] in\n (* used to indicate that one vertex has been found in one component *)\n let is_vertex_visited = Array.make (vertices_count + 1) false in\n let rec dfs v =\n while not @@ RandomizedSet.is_empty adj.(v) do\n match RandomizedSet.get_next adj.(v) with\n | Some e ->\n let next = if e.from = v then e.to' else e.from in\n RandomizedSet.remove adj.(v) e ;\n RandomizedSet.remove adj.(next) e ;\n dfs next\n | None -> ()\n done ;\n is_vertex_visited.(v) <- true ;\n passed_vertices := v :: !passed_vertices\n in\n for i = 0 to vertices_count do\n if not is_vertex_visited.(i) then (\n (* reset passed_vertices when entering a new component *)\n passed_vertices := [] ;\n dfs i ;\n (* get path from passed_vertices within current component *)\n List.fold_left\n (fun es ((a, b) as e) ->\n if a = addv_i || b = addv_i then es else e :: es )\n []\n @@ zip !passed_vertices @@ List.tl !passed_vertices\n |> List.iter (fun (a, b) -> Printf.printf \"%d %d\\n\" a b) )\n done\n | _ -> raise @@ InputError \"unexpected vertice_count and edges_count input\"\n\n(* --- *)\nlet test_case_count = read_line () |> int_of_string\n\n;;\nfor i = 1 to test_case_count do\n do_case () ;\ndone\n"}], "negative_code": [], "src_uid": "4f2c2d67c1a84bf449959b06789bb3a7"} {"nl": {"description": "You are given two strings $$$s$$$ and $$$t$$$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $$$1$$$. You can't choose a string if it is empty.For example: by applying a move to the string \"where\", the result is the string \"here\", by applying a move to the string \"a\", the result is an empty string \"\". You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.Write a program that finds the minimum number of moves to make two given strings $$$s$$$ and $$$t$$$ equal.", "input_spec": "The first line of the input contains $$$s$$$. In the second line of the input contains $$$t$$$. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and $$$2\\cdot10^5$$$, inclusive.", "output_spec": "Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings.", "sample_inputs": ["test\nwest", "codeforces\nyes", "test\nyes", "b\nab"], "sample_outputs": ["2", "9", "7", "1"], "notes": "NoteIn the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to \"est\".In the second example, the move should be applied to the string \"codeforces\" $$$8$$$ times. As a result, the string becomes \"codeforces\" $$$\\to$$$ \"es\". The move should be applied to the string \"yes\" once. The result is the same string \"yes\" $$$\\to$$$ \"es\".In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.In the fourth example, the first character of the second string should be deleted."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet s = scanf \"%s\" (fun n -> n)\n\nlet s' = scanf \" %s\" (fun n -> n)\n\nlet compare s s' =\n let rec loop i i' =\n if i = -1 || i' = -1 then\n i, i'\n else if s.[i] = s'.[i'] then\n loop (i-1) (i'-1)\n else\n i, i'\n in loop (String.length s - 1) (String.length s' - 1)\n\nlet process s s' =\n let i, i' = compare s s' in\n i + i' + 2\n\nlet () =\n let out = process s s' in\n printf \"%d\\n\" out;\n ()\n"}, {"source_code": "open Printf\n\nlet char_list_of_string str = \n let rec f0 i a =\n if i<0 then a else f0 (i-1) (str.[i]::a)\n in f0 (String.length str - 1) []\n\nlet print_int_endline n = n |> string_of_int |> print_endline\n\nlet () =\n let rec f0 (lu,lv) = match lu,lv with\n | [],[] -> 0\n | [],rest | rest,[] -> List.length rest\n | p::tlu,q::tlv ->\n if p=q then f0 (tlu,tlv)\n else (List.length tlu + List.length tlv + 2)\n in\n Scanf.scanf \" %s %s\" (fun u v ->\n List.rev @@ char_list_of_string u,\n List.rev @@ char_list_of_string v)\n |> f0 |> printf \"%d\\n\"\n"}], "negative_code": [], "src_uid": "59d926bca19a6dcfe3eb3e3dc03fffd6"} {"nl": {"description": "You are given a simple undirected graph with $$$n$$$ vertices, $$$n$$$ is even. You are going to write a letter on each vertex. Each letter should be one of the first $$$k$$$ letters of the Latin alphabet.A path in the graph is called Hamiltonian if it visits each vertex exactly once. A string is called palindromic if it reads the same from left to right and from right to left. A path in the graph is called palindromic if the letters on the vertices in it spell a palindromic string without changing the order.A string of length $$$n$$$ is good if: each letter is one of the first $$$k$$$ lowercase Latin letters; if you write the $$$i$$$-th letter of the string on the $$$i$$$-th vertex of the graph, there will exist a palindromic Hamiltonian path in the graph. Note that the path doesn't necesserily go through the vertices in order $$$1, 2, \\dots, n$$$.Count the number of good strings.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \\le n \\le 12$$$; $$$n$$$ is even; $$$0 \\le m \\le \\frac{n \\cdot (n-1)}{2}$$$; $$$1 \\le k \\le 12$$$)\u00a0\u2014 the number of vertices in the graph, the number of edges in the graph and the number of first letters of the Latin alphabet that can be used. Each of the next $$$m$$$ lines contains two integers $$$v$$$ and $$$u$$$ ($$$1 \\le v, u \\le n$$$; $$$v \\neq u$$$)\u00a0\u2014 the edges of the graph. The graph doesn't contain multiple edges and self-loops.", "output_spec": "Print a single integer\u00a0\u2014 number of good strings.", "sample_inputs": ["4 3 3\n1 2\n2 3\n3 4", "4 6 3\n1 2\n1 3\n1 4\n2 3\n2 4\n3 4", "12 19 12\n1 3\n2 6\n3 6\n3 7\n4 8\n8 5\n8 7\n9 4\n5 9\n10 1\n10 4\n10 6\n9 10\n11 1\n5 11\n7 11\n12 2\n12 5\n12 11"], "sample_outputs": ["9", "21", "456165084"], "notes": null}, "positive_code": [{"source_code": "(* https://codeforces.com/problemset/problem/1569/F *)\n\n(* let _ = Gc.(set { (get()) with minor_heap_size = 5_000_000 }) *)\n\n(* let fnv_P = 0x01000193 *)\n(* let fnv_0 = 0x811c9dc5 *)\n\nmodule S = struct\n type 'a t = ('a -> unit) -> unit\n module Infix = struct\n let (>>=) s f i = s (fun x -> f x i)\n let (>>|) s f i = s (fun x -> i (f x))\n let (--) a b f = for i = a to b do f i done\n let (++) s1 s2 i = s1 i; s2 i\n end\n let return x i = i x\n let filter p s i = s (fun x -> if p x then i x)\n let map f s i = s (fun x -> i (f x))\n let of_list xs i = List.iter i xs\n let of_array xs i = Array.iter i xs\n let fold f a s =\n let acc = ref a in\n s (fun x -> acc := f !acc x);\n !acc\n let to_list s = fold (fun xs x -> x::xs) [] s |> List.rev\n let length s = fold (fun n _ -> n + 1) 0 s\n let null _ = ()\n (* let sum = fold (+) 0 *)\n let sum64 = fold Int64.add 0L\nend\n\nmodule Vset : sig\n type t\n val compare : t -> t -> int\n val equal : t -> t -> bool\n val empty : t\n val to_int : t -> int\n val of_int : int -> t\n (* val hash : int -> t -> int *)\n val sg : int -> t\n val add : int -> t -> t\n val mem : int -> t -> bool\n val union : t -> t -> t\n val iter : (int -> unit) -> t -> unit\n (* val pp : Format.formatter -> t -> unit *)\nend = struct (* vertex sets *)\n type t = int\n let compare (a: t) b = compare a b\n let equal (a: t) b = a == b\n let union t1 t2 = t1 lor t2\n let sg x =\n (* assert (0 <= x && x <= 30); *)\n 1 lsl x\n let add x t =\n (* assert (0 <= x && x <= 30); *)\n (1 lsl x) lor t\n let mem x t =\n (* assert (0 <= x && x <= 30); *)\n (1 lsl x) land t <> 0\n let empty = 0\n let to_int x = x\n let of_int x = x\n (* let hash h t = *)\n (* let b1 = t land 0xff *)\n (* and b2 = (t lsr 8) land 0xff in *)\n (* (((h * fnv_P) lxor b1) * fnv_P) lxor b2 *)\n let iter f t =\n let rec go f x = function\n | 0 -> ()\n | t -> if t land 1 = 1 then f x; go f (x + 1) (t lsr 1) in\n go f 0 t\n (* let pp ppf = Fmt.pf ppf \"@[<1>{%a}@]\" (Fmt.iter ~sep:Fmt.comma iter Fmt.int) *)\nend\n\n(* #install_printer Vset.pp *)\n\nlet init n f =\n let rec go i n f = if i < n then f i :: go (i + 1) n f else [] in\n go 0 n f\n\nlet rec lequal (l1: Vset.t list) l2 = match l1, l2 with\n| a1::l1, a2::l2 -> a1 == a2 && lequal l1 l2\n| [], [] -> true\n| _, _ -> false\n\nlet rec lequal (l1: Vset.t list) l2 =\n match l1, l2 with\n | a::l1, b::l2 ->\n let r1 = a == b in\n ( match l1, l2 with\n | a::l1, b::l2 ->\n let r2 = a == b in\n ( match l1, l2 with\n | a::l1, b::l2 ->\n let r3 = a == b in\n ( match l1, l2 with\n | a::l1, b::l2 ->\n let r4 = a == b in\n ( match l1, l2 with\n | a::l1, b::l2 ->\n let r5 = a == b in\n ( match l1, l2 with\n | a::l1, b::l2 ->\n let r6 = a == b in\n ( match l1, l2 with\n | _::_, _::_ -> assert false\n | [], [] -> r1 && r2 && r3 && r4 && r5 && r6\n | _ -> false )\n | [], [] -> r1 && r2 && r3 && r4 && r5\n | _ -> false )\n | [], [] -> r1 && r2 && r3 && r4\n | _ -> false )\n | [], [] -> r1 && r2 && r3 \n | _ -> false )\n | [], [] -> r1 && r2\n | _ -> false )\n | [], [] -> r1\n | _ -> false )\n | [], [] -> true\n | _ -> false\n\n(* let rec lequal (l1: Vset.t list) l2 = *)\n(* match l1, l2 with a::l1, b::l2 -> *)\n(* a == b && (match l1, l2 with a::l1, b::l2 -> *)\n(* a == b && (match l1, l2 with a::l1, b::l2 -> *)\n(* a == b && (match l1, l2 with a::l1, b::l2 -> *)\n(* a == b && (match l1, l2 with a::l1, b::l2 -> *)\n(* a == b && (match l1, l2 with a::l1, b::l2 -> *)\n(* a == b && (match l1, l2 with a::l1, b::l2 -> lequal l1 l2 | [], [] -> true | _ -> false) *)\n(* | [], [] -> true | _ -> false) *)\n(* | [], [] -> true | _ -> false) *)\n(* | [], [] -> true | _ -> false) *)\n(* | [], [] -> true | _ -> false) *)\n(* | [], [] -> true | _ -> false) *)\n(* | [], [] -> true | _ -> false *)\n\n\n(* let lhash xs = *)\n(* let rec go h = function x::xs -> go (Vset.hash h x) xs | _ -> h in *)\n(* go fnv_0 xs land 0x3fffffff *)\n\nlet lhash xs =\n let rec go h = function [] -> h\n | x::xs ->\n let h = Hashtbl.seeded_hash h x in match xs with [] -> h\n | x::xs ->\n let h = Hashtbl.seeded_hash h x in match xs with [] -> h\n | x::xs ->\n let h = Hashtbl.seeded_hash h x in match xs with [] -> h\n | x::xs ->\n let h = Hashtbl.seeded_hash h x in match xs with [] -> h\n | x::xs ->\n let h = Hashtbl.seeded_hash h x in match xs with [] -> h\n | x::xs ->\n let h = Hashtbl.seeded_hash h x in match xs with [] -> h\n | _ -> go h xs in\n (* let rec go h = function x::xs -> go (Hashtbl.seeded_hash h x) xs | _ -> h in *)\n go 0 xs\n\nlet aequal (l1: Vset.t array) l2 =\n let rec go i l1 l2 = i < 0 || l1.(i) == l2.(i) && go (i - 1) l1 l2 in\n let m = Array.length l1 and n = Array.length l2 in\n m = n && go (m - 1) l1 l2\n\nlet ahash a =\n let s = ref 0 in\n for i = 0 to Array.length a - 1 do s := Hashtbl.seeded_hash !s a.(i) done;\n !s\n\nmodule HSet = struct\n type t = { mutable tab : Vset.t list array; mutable n : int }\n let create b = { tab = Array.make (1 lsl b) []; n = 0 }\n let index0 v tab = (lhash v) land (Array.length tab - 1)\n let istep i tab = (i + 1) land (Array.length tab - 1)\n\n let rec repack ({ tab; _ } as t) =\n t.n <- 0;\n t.tab <- Array.make (Array.length t.tab lsl 1) [];\n for i = 0 to Array.length tab - 1 do\n let v = tab.(i) in if v != [] then scan v t |> ignore\n done\n\n and scan v t =\n let rec go v ({ tab; n } as t) i =\n let v0 = tab.(i) in\n if v0 == [] then begin\n tab.(i) <- v;\n let n = n + 1 in\n t.n <- n;\n if n lsl 2 > Array.length tab then repack t;\n false\n end else lequal v0 v || go v t (istep i tab) in\n go v t (index0 v t.tab)\n\n (* let find v t = *)\n (* let rec go v ({ tab; _ } as t) i c = *)\n (* if lequal v tab.(i) then c else go v t (istep i tab) (c + 1) in *)\n (* go v t (index0 v t.tab) 0 *)\n\n (* let stat t = *)\n (* let r = Array.make_matrix 10 6 0 in *)\n (* for i = 0 to Array.length t.tab - 1 do *)\n (* let v = t.tab.(i) in *)\n (* if v != [] then *)\n (* let d = find v t and l = List.length v in *)\n (* r.(min d 9).(l - 1) <- r.(min d 9).(l - 1) + 1 *)\n (* done; *)\n (* r *)\n\n(* let pp_stat ppf t = *)\n(* let cap = Array.length t.tab in *)\n(* Fmt.pf ppf \"@[cap: %d n: %d (load: %f)@ pos: @[\" *)\n(* cap t.n (float t.n /. float cap); *)\n(* let s = stat t in *)\n(* for d = 0 to Array.length s - 1 do *)\n(* let row = s.(d) in *)\n(* if Array.fold_left (+) 0 row > 0 then *)\n(* Fmt.pf ppf \"hop %d: @[%a@]@ \" d Fmt.(array ~sep:sp int) s.(d) *)\n(* done; *)\n(* Fmt.pf ppf \"@]@]\" *)\nend\n\n(* module Partition = struct *)\n(* type t = bytes *)\n(* let gets t i = Bytes.get_int16_ne t i |> Vset.of_int *)\n(* let sets t i s = Vset.to_int s |> Bytes.set_int16_ne t i *)\n(* let ins t s = *)\n(* let open Bytes in *)\n(* let rec go i = *)\n(* assert (i < length t - 1); *)\n(* let s1 = gets t i in *)\n(* if s1 == Vset.empty then sets t i s *)\n(* else match Vset.compare s s1 with *)\n(* | 0 -> () *)\n(* | 1 -> go (i + 2) *)\n(* | _ -> *)\n(* blit t i t (i + 2) (length t - i - 2); *)\n(* set_int16_ne t i (Vset.to_int s) in *)\n(* go 0 *)\n(* let create n k = *)\n(* let b = Bytes.make (n * 2) '\\x00' in *)\n(* k (ins b); *)\n(* b *)\n(* let join t i j = *)\n(* let open Bytes in *)\n(* let n = length t in *)\n(* let i = min i j * 2 and j = max i j * 2 in *)\n(* let s = Vset.union (gets t i) (gets t j) in *)\n(* let t1 = make (n - 2) '\\x00' in *)\n(* blit t 0 t1 0 i; *)\n(* blit t (i + 2) t1 i (j - i - 2); *)\n(* blit t (j + 2) t1 (j - 2) (n - j - 2); *)\n(* ins t1 s; *)\n(* t1 *)\n(* let card t = Bytes.length t / 2 *)\n(* end *)\n\n(* #install_printer Vset.pp *)\n\nmodule Pmem = struct\n module Vsmap = Map.Make(Vset)\n type t = { mutable m : t Vsmap.t } (* no partition is a prefix of another *)\n let create () = { m = Vsmap.empty }\n let mem t ss =\n let rec go t = function s::ss -> go (Vsmap.find s t.m) ss | [] -> true in\n try go t ss with Not_found -> false\n let rec add t = function\n | [] -> ()\n | s::ss -> match Vsmap.find s t.m with\n | t -> add t ss\n | exception Not_found ->\n let t1 = create () in\n t.m <- Vsmap.add s t1 t.m; add t1 ss\nend\n\nmodule I64 = struct\n include Int64\n let ( + ) = add and ( - ) = sub and ( * ) = mul and ( / ) = div and v = of_int\nend\n\nlet fac n =\n let rec go a = function 0 -> a | n -> go I64.(a * v n) (n - 1) in\n go 1L n\n\nlet prod n k =\n let rec go a n = function 0 -> a | k -> go I64.(a * v n) (n - 1) (k - 1) in\n go 1L n k\n\nlet rec choose k n =\n assert (k <= n);\n if k > n / 2 then choose (n - k) n else I64.(prod n k / fac k)\n\nlet stop (type a) f =\n let module M = struct exception Stop of a end in\n try f (fun x -> raise (M.Stop x)) with M.Stop x -> x\n\nlet seen (type a) ~eq ~hash () =\n let module H = Hashtbl.Make(struct type t = a let hash, equal = hash, eq end) in\n let ht = H.create 100_003 in\n (* let cnt = ref 0 in *)\n (* at_exit (fun () -> *)\n (* let open Hashtbl in *)\n (* let stat = H.stats ht in *)\n (* Fmt.pr \"@[stats:@ queries: %d@ len: %d@ bkts: %d@ histo: %a@]@.\" *)\n (* !cnt stat.num_bindings stat.num_buckets *)\n (* Fmt.(Dump.array int) stat.bucket_histogram); *)\n (* fun x -> if H.mem ht x then (incr cnt; true) else (H.add ht x (); false) *)\n fun x -> H.mem ht x || (H.add ht x (); false)\n\nlet seen2 (type a) ~cmp () =\n let module S = Set.Make(struct type t = a let compare = cmp end) in\n let r = ref S.empty in\n fun x -> let s = !r in S.mem x s || (r := S.add x s; false)\n\nlet seen3 () =\n let m = Pmem.create () in\n fun x -> Pmem.mem m x || (Pmem.add m x; false)\n\nlet seen4 () =\n let h = HSet.create 10 in\n (* at_exit (fun () -> Fmt.pr \"stat: @[%a@]@.\" HSet.pp_stat h); *)\n fun x -> HSet.scan x h\n\nlet rec lines ic i = match input_line ic with\n| exception End_of_file -> ()\n| line -> i line; lines ic i\n\nopen S.Infix\n\nlet partitions_of n =\n assert (n land 1 = 0);\n let rec go acc = function\n | x::y::xs -> go (x::acc) (y::xs) ++ go acc (x + y::xs)\n | r -> S.return (r @ acc) in\n go [] (init (n / 2) (fun _ -> 2))\n\nlet assignments n k = (* upper bound for a complete graph *)\n let rec go acc n = function\n | [] -> acc\n | x::xs -> go I64.(acc * choose x n) (n - x) xs in\n partitions_of n\n |> S.map (fun p -> List.length p, p)\n |> S.filter (fun (x, _) -> x <= k)\n |> S.map I64.(fun (x, p) -> go 1L n p * choose x k)\n |> S.sum64\n\n(* module Vmap = Map.Make(struct type t = int let compare (a: int) b = compare a b end) *)\n\nlet graph vs = (* from edges *)\n let a = Array.make 12 [] in\n vs (fun (v1, v2) ->\n let v1 = v1 - 1 and v2 = v2 - 1 in\n a.(v1) <- v2 :: a.(v1); a.(v2) <- v1 :: a.(v2));\n let a = Array.map (fun vs -> List.sort compare vs |> Array.of_list) a in\n fun v -> a.(v)\n\nlet hams (n, succ) it =\n let ham = Array.make n (-42) in\n let rec go seen v i =\n ham.(i) <- v;\n if i < n - 1 then\n let vxn = succ v in\n for vi = 0 to Array.length vxn - 1 do\n let v1 = vxn.(vi) in\n if not (Vset.mem v1 seen) then go Vset.(add v1 seen) v1 (i + 1)\n done\n else if ham.(0) <= v then it ham in\n for v0 = 0 to n - 1 do go Vset.(sg v0) v0 0 done\n\n(* let join p it = *)\n(* let n = Array.length p in *)\n(* for i = 0 to n - 2 do *)\n(* for j = i + 1 to n - 1 do *)\n(* let p1 = Array.init (n - 1) @@ fun k -> *)\n(* if k = i then Vset.union p.(i) p.(j) else *)\n(* if k >= j then p.(k + 1) else p.(k) in *)\n(* Array.sort Vset.compare p1; *)\n(* it p1 *)\n(* done *)\n(* done *)\n\n(* let coarser k seen ham = *)\n(* let rec go p0 = *)\n(* if not (seen p0) then *)\n(* match Array.length p0 with *)\n(* | c when c <= 1 -> S.return p0 *)\n(* | c when c <= k -> S.return p0 ++ (join p0 >>= go) *)\n(* | c -> join p0 >>= go *)\n(* else S.null in *)\n(* let n = Array.length ham in *)\n(* let p0 = Array.init (n / 2) @@ fun i -> Vset.(sg ham.(i) |> add ham.(n - i - 1)) in *)\n(* Array.sort Vset.compare p0; *)\n(* go p0 *)\n\n(* let partitions k hams = *)\n(* let memo = seen ~eq:aequal ~hash:ahash () in *)\n(* hams >>= coarser k memo *)\n\n\nlet rec ins v0 = function\n| [] -> [v0]\n| v::vs as ss ->\n match Vset.compare v0 v with -1 -> v0 :: ss | 1 -> v :: ins v0 vs | _ -> ss\n\nlet rec sel acc xs it = match xs with\n| [] -> ()\n| x::xs -> it (acc, x, xs); sel (x::acc) xs it\n\nlet join p it =\n sel [] p @@ fun (xs, s1, ys) ->\n sel xs ys @@ fun (xs, s2, ys) ->\n ins (Vset.union s1 s2) List.(rev_append xs ys) |> it\n\nlet partition ham =\n let n = Array.length ham in\n let rec go acc = function\n | 0 -> acc\n | i -> go (ins Vset.(sg ham.(i - 1) |> add ham.(n - i)) acc) (i - 1) in\n go [] (n / 2)\n\nlet coarser k seen1 seen2 p it = (* coarser partitions *)\n let rec go c p =\n if not (seen2 p) then begin\n if c <= 1 then it p else\n if c <= k then (it p; join p (go (c - 1))) else\n join p (go (c - 1))\n end in\n if not (seen1 p) then go (List.length p) p\n\nlet partitions k hams =\n (* let eq = lequal and hash = lhash in *)\n (* let memo1 = seen ~eq ~hash () and memo2 = seen ~eq ~hash () in *)\n (* let memo = seen2 ~cmp:(List.compare Vset.compare) () in *)\n (* let memo = seen3 () in *)\n (* let memo1 = seen4 () and memo2 = seen4 () in *)\n (* let memo1 = seen4 () and memo2 = seen ~eq ~hash () in *)\n let memo1 = seen4 () and memo2 = seen3 () in\n hams >>= fun ham -> coarser k memo1 memo2 (partition ham)\n\n\n(* let join p it = *)\n(* let n = Partition.card p in *)\n(* for i = 0 to n - 2 do *)\n(* for j = i + 1 to n - 1 do *)\n(* it (Partition.join p i j) *)\n(* done *)\n(* done *)\n\n(* let partition ham = *)\n(* let n = Array.length ham in *)\n(* Partition.create (n / 2) @@ fun add -> *)\n(* for i = 0 to n / 2 - 1 do *)\n(* add Vset.(sg ham.(i) |> add ham.(n - i - 1)) *)\n(* done *)\n\n(* let coarser k seen p = *)\n(* let rec go p = *)\n(* if not (seen p) then *)\n(* match Partition.card p with *)\n(* | c when c <= 1 -> S.return p *)\n(* | c when c <= k -> S.return p ++ (join p >>= go) *)\n(* | c -> join p >>= go *)\n(* else S.null in *)\n(* go p *)\n\n(* let partitions k hams = *)\n(* let memo = seen ~eq:Bytes.equal ~hash:Hashtbl.hash () in *)\n(* hams >>= fun ham -> coarser k memo (partition ham) *)\n\n\nlet count g k = (* legal letter assignments *)\n (* let ns = hams g |> partitions k |> S.map (fun s -> prod k (Array.length s)) in *)\n let ns = hams g |> partitions k |> S.map (fun s -> prod k (List.length s)) in\n (* let ns = hams g |> partitions k |> S.map (fun s -> prod k (Partition.card s)) in *)\n let max = assignments (fst g) k in\n stop @@ fun exit ->\n let f a b =\n let a = I64.(a + b) in\n if a = max then exit max else a in\n S.fold f 0L ns\n\nlet input ic =\n Scanf.sscanf (input_line ic) \"%d %d %d\" @@ fun vx lx k ->\n let vxn = lines ic |> S.map @@ fun s -> Scanf.sscanf s \"%d %d\" (fun a b -> a, b) in\n (vx, graph vxn), k\n\nlet _ =\n let g, k = input stdin in\n Format.printf \"%Ld@.\" (count g k)\n\n\nlet g1 = 4, graph (S.of_list [(1,2); (2,3); (3,4)])\nlet g2 = 4, graph (S.of_list [(1,2); (1,3); (1,4); (2,3); (2,4); (3,4)])\nlet g3 = 12, graph (S.of_list [\n (1,3); (2,6); (3,6); (3,7); (4,8); (8,5); (8,7); (9,4); (5,9); (10,1);\n (10,4); (10,6); (9,10); (11,1); (5,11); (7,11); (12,2); (12,5); (12,11) ])\nlet g20 = 12, graph (S.of_list [\n (3,4); (4,9); (12,8); (12,11); (12,1); (8,11); (1,7); (1,3); (2,6); (10,12);\n (3,12); (3,8); (3,5); (8,5); (11,4); (2,5); (1,6); (4,12); (9,8); (12,7);\n (5,9); (9,12); (10,9); (7,5); (2,8); (7,2); (2,11); (7,3); (4,6); (1,5);\n (5,10); (2,10); (9,6); (8,10); (12,5); (4,5); (1,2); (5,11); (4,7); (7,10);\n (6,5); (11,6); (9,2); (11,10); (2,12); (2,4); (10,4); (3,2); (6,3); (9,3);\n (8,4); (3,11); (9,11); (1,10); (1,8); (12,6); (11,1); (6,8); (9,1); (11,7);\n (9,7); (4,1); (8,7); (10,3); (10,6); (6,7) ])\n\nlet complete n =\n let a =\n Array.init n @@ fun i ->\n Array.init (n - 1) @@ fun j ->\n if j < i then j else j + 1 in\n n, fun v -> a.(v)\n\nlet check name g k res =\n let x = count g k in\n Format.printf \"%s -> %Ld (of %Ld)@.\" name x (assignments (fst g) k);\n assert (x = res)\n\n(* let _ = *)\n(* check \"g1\" g1 3 9L; *)\n(* check \"g2\" g2 3 21L; *)\n(* check \"g3\" g3 12 456165084L; *)\n(* check \"g20\" g20 2 2048L; *)\n(* () *)\n\n(* (1* let check_complete n k = *1) *)\n(* (1* let c = count (complete n) k *1) *)\n(* (1* and l = assignments n k in *1) *)\n(* (1* Format.printf \"count: %d, limit: %d@.\" c l; *1) *)\n(* (1* assert (c = l) *1) *)\n\n(* (1* let _ = *1) *)\n(* (1* for n = 1 to 5 do *1) *)\n(* (1* let n = n * 2 in *1) *)\n(* (1* Format.printf \"@[n = %d@ \" n; *1) *)\n(* (1* for k = 1 to 12 do *1) *)\n(* (1* let c = count (complete n) k *1) *)\n(* (1* and l = assignments n k in *1) *)\n(* (1* Format.printf \"k = %d -> %d (limit %d)@ \" k c l; *1) *)\n(* (1* assert (c = l) *1) *)\n(* (1* done; *1) *)\n(* (1* Format.printf \"@]@.\" *1) *)\n(* (1* done *1) *)\n\n\n\n(* (1* let _ = Format.printf \"%d@.\" (hams g20 |> S.length) *1) *)\n\n(* (1* let _ = Format.printf \"%d@.\" (count g20 2) *1) *)\n\n(* (1* (2* let _ = Format.printf \"%d@.\" (count (g4 10) 12) *2) *1) *)\n(* (1* (2* let _ = Format.printf \"%d@.\" (g4 10 |> hams |> S.length) *2) *1) *)\n\n(* (1* (2* let s = Vset.[|empty |> add 1 |> add 2; empty |> add 3 |> add 4; empty |> add 5 |> add 6|] *2) *1) *)\n(* (1* (2* let _ = reducex s |> S.to_list *2) *1) *)\n\n(* (1* (2* let ham_g1 = hams g1 |> S.to_list |> List.hd *2) *1) *)\n(* (1* (2* let ham_g2 = hams g2 |> S.to_list |> List.hd *2) *1) *)\n(* (1* (2* let ham_g3 = hams g3 |> S.to_list |> List.hd *2) *1) *)\n(* (1* (2* let hamm = [|1; 2; 3; 4; 5; 6|] *2) *1) *)\n\n(* (1* (2* let h0 = hams g3 |> S.to_list |> List.hd *2) *1) *)\n(* (1* (2* let pp0 = p0x h0 *2) *1) *)\n(* (1* (2* let xxx i = *2) *1) *)\n(* (1* (2* let a = h0.(i) and b = h0.(12 - i - 1) in *2) *1) *)\n(* (1* (2* Vset.(empty |> add a |> add b), (a, b) *2) *1) *)\n(* (1* (2* let l2 = reducex pp0 |> S.to_list *2) *1) *)\n\n(* (1* (2* let xs = (hams g2 >>= partitions1x 3) |> S.to_list |> List.sort_uniq compare *2) *1) *)\n(* (1* (2* List.iter (Array.sort compare) xs *2) *1) *)\n(* (1* (2* xs *2) *1) *)\n\n"}], "negative_code": [{"source_code": "(* https://codeforces.com/problemset/problem/1569/F *)\n\nmodule S = struct\n type 'a t = ('a -> unit) -> unit\n module Infix = struct\n let (>>=) s f i = s (fun x -> f x i)\n let (>>|) s f i = s (fun x -> i (f x))\n let (--) a b f = for i = a to b do f i done\n let (++) s1 s2 i = s1 i; s2 i\n end\n let return x i = i x\n let filter p s i = s (fun x -> if p x then i x)\n let map f s i = s (fun x -> i (f x))\n let of_list xs i = List.iter i xs\n let of_array xs i = Array.iter i xs\n let fold f a s =\n let acc = ref a in\n s (fun x -> acc := f !acc x);\n !acc\n let to_list s = fold (fun xs x -> x::xs) [] s |> List.rev\n let length s = fold (fun n _ -> n + 1) 0 s\n let null _ = ()\n let sum = fold (+) 0\nend\n\nmodule Vset : sig\n type t\n val compare : t -> t -> int\n val equal : t -> t -> bool\n val empty : t\n val sg : int -> t\n val add : int -> t -> t\n val mem : int -> t -> bool\n val union : t -> t -> t\n val iter : (int -> unit) -> t -> unit\n (* val pp : Format.formatter -> t -> unit *)\nend = struct (* vertex sets *)\n type t = int\n let compare (a: t) b = compare a b\n let equal (a: t) b = a == b\n let union t1 t2 = t1 lor t2\n let sg x =\n (* assert (0 <= x && x <= 62); *)\n 1 lsl x\n let add x t =\n (* assert (0 <= x && x <= 62); *)\n (1 lsl x) lor t\n let mem x t =\n (* assert (0 <= x && x <= 62); *)\n (1 lsl x) land t <> 0\n let empty = 0\n let iter f t =\n let rec go f x = function\n | 0 -> ()\n | t -> if t land 1 = 1 then f x; go f (x + 1) (t lsr 1) in\n go f 0 t\n (* let pp ppf = Fmt.pf ppf \"@[<1>{%a}@]\" (Fmt.iter ~sep:Fmt.comma iter Fmt.int) *)\nend\n\n(* #install_printer Vset.pp *)\n\nlet fac n =\n let rec go acc = function 0 -> acc | n -> go (acc * n) (n - 1) in\n go 1 n\n\nlet prod n k =\n let rec go acc n = function 0 -> acc | k -> go (acc * n) (n - 1) (k - 1) in\n go 1 n k\n\nlet rec choose k n =\n assert (k <= n);\n if k > n / 2 then choose (n - k) n else prod n k / fac k\n\nlet stop (type a) f =\n let module M = struct exception Stop of a end in\n try f (fun x -> raise (M.Stop x)) with M.Stop x -> x\n\nlet seen (type a) ~eq ~hash () =\n let module H = Hashtbl.Make(struct type t = a let hash, equal = hash, eq end) in\n let ht = H.create 4096 in\n (* at_exit (fun () -> Format.printf \"ht pop: %d@.\" (H.length ht)); *)\n fun x -> if H.mem ht x then true else ( H.add ht x (); false )\n\nlet init n f =\n let rec go i n f = if i < n then f i :: go (i + 1) n f else [] in\n go 0 n f\n\nlet rec lequal eq l1 l2 = match l1, l2 with\n| a1::l1, a2::l2 -> eq a1 a2 && lequal eq l1 l2\n| [], [] -> true\n| _, _ -> false\n\nlet rec lhash seed = function\n| a::xs -> lhash Hashtbl.(seeded_hash seed a) xs\n| [] -> seed\n\nlet rec lines ic i = match input_line ic with\n| exception End_of_file -> ()\n| line -> i line; lines ic i\n\nopen S.Infix\n\nlet partitions_of n =\n assert (n land 1 = 0);\n let rec go acc = function\n | x::y::xs -> go (x::acc) (y::xs) ++ go acc (x + y::xs)\n | r -> S.return (r @ acc) in\n go [] (init (n / 2) (fun _ -> 2))\n\nlet assignments n k = (* upper bound for a complete graph *)\n let rec go acc n = function\n | [] -> acc\n | x::xs -> go (acc * choose x n) (n - x) xs in\n partitions_of n\n |> S.map (fun p -> List.length p, p)\n |> S.filter (fun (x, _) -> x <= k)\n |> S.map (fun (x, p) -> go 1 n p * choose x k)\n |> S.sum\n\nmodule Vmap = Map.Make(struct type t = int let compare (a: int) b = compare a b end)\n\nlet graph vs = (* graph from edges *)\n let ext v1 v2 m =\n let xs = match Vmap.find v1 m with xs -> xs | exception Not_found -> [] in\n Vmap.add v1 (v2::xs) m in\n let m = S.fold (fun m (v1, v2) -> ext v1 v2 m |> ext v2 v1) Vmap.empty vs in\n let a = Array.init 12 @@ fun i ->\n try Vmap.find (i + 1) m |> List.sort compare |> Array.of_list\n with Not_found -> [||] in\n fun v -> a.(v - 1)\n\nlet hams (n, succ) it =\n let ham = Array.make n 0 in\n let rec go seen v i =\n ham.(i) <- v;\n if i < n - 1 then\n succ v |> Array.iter (fun v1 ->\n if not (Vset.mem v1 seen) then go Vset.(add v1 seen) v1 (i + 1))\n else if ham.(0) <= v then it ham in\n for v0 = 1 to n do go Vset.(sg v0) v0 0 done\n\nlet select xs =\n let rec go acc = function\n | [] -> S.null\n | x::xs -> S.return (acc, x, xs) ++ go (x::acc) xs in\n go [] xs\n\nlet coarser p =\n select p >>= fun (xs, s1, ys) ->\n select ys >>| fun (ys, s2, zs) ->\n Vset.union s1 s2 :: xs @ ys @ zs\n\nlet partitions1 k seen ham = (* partitions induced by a hamiltonian *)\n let rec go s0 =\n let s0 = List.sort Vset.compare s0 in\n if seen s0 then S.null else\n match List.length s0 with\n | c when c <= 1 -> S.return s0\n | c when c <= k -> S.return s0 ++ (coarser s0 >>= go)\n | c -> coarser s0 >>= go in\n let n = Array.length ham in\n let p0 = init (n/2) @@ fun i ->\n Vset.(empty |> add ham.(i) |> add ham.(n - i - 1)) in\n go p0\n\nlet p_memo () = seen ~eq:(lequal Vset.equal) ~hash:(lhash 0) ()\n\nlet partitions k hams = S.(hams >>= partitions1 k (p_memo ()))\n\n\nlet count g k = (* legal letter assignments *)\n let ns = hams g |> partitions k |> S.map (fun s -> prod k (List.length s)) in\n let max = assignments (fst g) k in\n stop @@ fun exit ->\n S.fold (fun a x -> let ax = a + x in if ax = max then exit max else ax) 0 ns\n\nlet input ic =\n Scanf.sscanf (input_line ic) \"%d %d %d\" @@ fun vx lx k ->\n let vxn = lines ic |> S.map @@ fun s -> Scanf.sscanf s \"%d %d\" (fun a b -> a, b) in\n (vx, graph vxn), k\n\nlet _ =\n let g, k = input stdin in\n Format.printf \"%d@.\" (count g k)\n\n\n\n(* let g1 = 4, graph (S.of_list [(1,2); (2,3); (3,4)]) *)\n(* let g2 = 4, graph (S.of_list [(1,2); (1,3); (1,4); (2,3); (2,4); (3,4)]) *)\n(* let g3 = 12, graph (S.of_list [ *)\n(* (1,3); (2,6); (3,6); (3,7); (4,8); (8,5); (8,7); (9,4); (5,9); (10,1); *)\n(* (10,4); (10,6); (9,10); (11,1); (5,11); (7,11); (12,2); (12,5); (12,11) ]) *)\n(* let g20 = 12, graph (S.of_list [ *)\n(* (3,4); (4,9); (12,8); (12,11); (12,1); (8,11); (1,7); (1,3); (2,6); (10,12); *)\n(* (3,12); (3,8); (3,5); (8,5); (11,4); (2,5); (1,6); (4,12); (9,8); (12,7); *)\n(* (5,9); (9,12); (10,9); (7,5); (2,8); (7,2); (2,11); (7,3); (4,6); (1,5); *)\n(* (5,10); (2,10); (9,6); (8,10); (12,5); (4,5); (1,2); (5,11); (4,7); (7,10); *)\n(* (6,5); (11,6); (9,2); (11,10); (2,12); (2,4); (10,4); (3,2); (6,3); (9,3); *)\n(* (8,4); (3,11); (9,11); (1,10); (1,8); (12,6); (11,1); (6,8); (9,1); (11,7); *)\n(* (9,7); (4,1); (8,7); (10,3); (10,6); (6,7) ]) *)\n\n(* let complete n = *)\n(* let a = *)\n(* Array.init n @@ fun i -> *)\n(* Array.init (n - 1) @@ fun j -> *)\n(* if j < i then j + 1 else j + 2 in *)\n(* n, fun v -> a.(v - 1) *)\n\n(* let check name g k res = *)\n(* let x = count g k in *)\n(* Format.printf \"%s -> %d (of %d)@.\" name x (assignments (fst g) k); *)\n(* assert (x = res) *)\n\n(* let _ = *)\n(* check \"g1\" g1 3 9; *)\n(* check \"g2\" g2 3 21; *)\n(* check \"g3\" g3 12 456165084 *)\n\n(* (1* let check_complete n k = *1) *)\n(* (1* let c = count (complete n) k *1) *)\n(* (1* and l = assignments n k in *1) *)\n(* (1* Format.printf \"count: %d, limit: %d@.\" c l; *1) *)\n(* (1* assert (c = l) *1) *)\n\n(* (1* let _ = *1) *)\n(* (1* for n = 1 to 5 do *1) *)\n(* (1* let n = n * 2 in *1) *)\n(* (1* Format.printf \"@[n = %d@ \" n; *1) *)\n(* (1* for k = 1 to 12 do *1) *)\n(* (1* let c = count (complete n) k *1) *)\n(* (1* and l = assignments n k in *1) *)\n(* (1* Format.printf \"k = %d -> %d (limit %d)@ \" k c l; *1) *)\n(* (1* assert (c = l) *1) *)\n(* (1* done; *1) *)\n(* (1* Format.printf \"@]@.\" *1) *)\n(* (1* done *1) *)\n\n(* (1* let _ = Format.printf \"%d@.\" (hams g20 |> S.length) *1) *)\n\n(* (1* let _ = Format.printf \"%d@.\" (count g20 2) *1) *)\n\n(* (1* (2* let _ = Format.printf \"%d@.\" (count (g4 10) 12) *2) *1) *)\n(* (1* (2* let _ = Format.printf \"%d@.\" (g4 10 |> hams |> S.length) *2) *1) *)\n\n(* (1* (2* let s = Vset.[|empty |> add 1 |> add 2; empty |> add 3 |> add 4; empty |> add 5 |> add 6|] *2) *1) *)\n(* (1* (2* let _ = reducex s |> S.to_list *2) *1) *)\n\n(* (1* (2* let ham_g1 = hams g1 |> S.to_list |> List.hd *2) *1) *)\n(* (1* (2* let ham_g2 = hams g2 |> S.to_list |> List.hd *2) *1) *)\n(* (1* (2* let ham_g3 = hams g3 |> S.to_list |> List.hd *2) *1) *)\n(* (1* (2* let hamm = [|1; 2; 3; 4; 5; 6|] *2) *1) *)\n\n(* (1* (2* let h0 = hams g3 |> S.to_list |> List.hd *2) *1) *)\n(* (1* (2* let pp0 = p0x h0 *2) *1) *)\n(* (1* (2* let xxx i = *2) *1) *)\n(* (1* (2* let a = h0.(i) and b = h0.(12 - i - 1) in *2) *1) *)\n(* (1* (2* Vset.(empty |> add a |> add b), (a, b) *2) *1) *)\n(* (1* (2* let l2 = reducex pp0 |> S.to_list *2) *1) *)\n\n(* (1* (2* let xs = (hams g2 >>= partitions1x 3) |> S.to_list |> List.sort_uniq compare *2) *1) *)\n(* (1* (2* List.iter (Array.sort compare) xs *2) *1) *)\n(* (1* (2* xs *2) *1) *)\n\n\n"}, {"source_code": "let _ = Format.printf \"compiler test.@.\"\n"}], "src_uid": "97f96e83c8e893d2a12dd5ca2b401323"} {"nl": {"description": " Frodo was caught by Saruman. He tore a pouch from Frodo's neck, shook out its contents\u00a0\u2014there was a pile of different rings: gold and silver...\"How am I to tell which is the One?!\" the mage howled.\"Throw them one by one into the Cracks of Doom and watch when Mordor falls!\" Somewhere in a parallel Middle-earth, when Saruman caught Frodo, he only found $$$n$$$ rings. And the $$$i$$$-th ring was either gold or silver. For convenience Saruman wrote down a binary string $$$s$$$ of $$$n$$$ characters, where the $$$i$$$-th character was 0 if the $$$i$$$-th ring was gold, and 1 if it was silver.Saruman has a magic function $$$f$$$, which takes a binary string and returns a number obtained by converting the string into a binary number and then converting the binary number into a decimal number. For example, $$$f(001010) = 10, f(111) = 7, f(11011101) = 221$$$.Saruman, however, thinks that the order of the rings plays some important role. He wants to find $$$2$$$ pairs of integers $$$(l_1, r_1), (l_2, r_2)$$$, such that: $$$1 \\le l_1 \\le n$$$, $$$1 \\le r_1 \\le n$$$, $$$r_1-l_1+1\\ge \\lfloor \\frac{n}{2} \\rfloor$$$ $$$1 \\le l_2 \\le n$$$, $$$1 \\le r_2 \\le n$$$, $$$r_2-l_2+1\\ge \\lfloor \\frac{n}{2} \\rfloor$$$ Pairs $$$(l_1, r_1)$$$ and $$$(l_2, r_2)$$$ are distinct. That is, at least one of $$$l_1 \\neq l_2$$$ and $$$r_1 \\neq r_2$$$ must hold. Let $$$t$$$ be the substring $$$s[l_1:r_1]$$$ of $$$s$$$, and $$$w$$$ be the substring $$$s[l_2:r_2]$$$ of $$$s$$$. Then there exists non-negative integer $$$k$$$, such that $$$f(t) = f(w) \\cdot k$$$.Here substring $$$s[l:r]$$$ denotes $$$s_ls_{l+1}\\ldots s_{r-1}s_r$$$, and $$$\\lfloor x \\rfloor$$$ denotes rounding the number down to the nearest integer.Help Saruman solve this problem! It is guaranteed that under the constraints of the problem at least one solution exists.", "input_spec": "Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^4$$$)\u00a0\u2014 length of the string. The second line of each test case contains a non-empty binary string of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For every test case print four integers $$$l_1$$$, $$$r_1$$$, $$$l_2$$$, $$$r_2$$$, which denote the beginning of the first substring, the end of the first substring, the beginning of the second substring, and the end of the second substring, respectively. If there are multiple solutions, print any.", "sample_inputs": ["7\n6\n101111\n9\n111000111\n8\n10000000\n5\n11011\n6\n001111\n3\n101\n30\n100000000000000100000000000000"], "sample_outputs": ["3 6 1 3\n1 9 4 9\n5 8 1 4\n1 5 3 5\n1 6 2 4\n1 2 2 3\n1 15 16 30"], "notes": "NoteIn the first testcase $$$f(t) = f(1111) = 15$$$, $$$f(w) = f(101) = 5$$$.In the second testcase $$$f(t) = f(111000111) = 455$$$, $$$f(w) = f(000111) = 7$$$.In the third testcase $$$f(t) = f(0000) = 0$$$, $$$f(w) = f(1000) = 8$$$.In the fourth testcase $$$f(t) = f(11011) = 27$$$, $$$f(w) = f(011) = 3$$$.In the fifth testcase $$$f(t) = f(001111) = 15$$$, $$$f(w) = f(011) = 3$$$."}, "positive_code": [{"source_code": "open Printf\r\nopen Scanf\r\n\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_int_char _ = bscanf Scanning.stdin \" %c \" (fun x -> int_of_char x - 48)\r\n\r\nlet rec find lst x =\r\n match lst with\r\n | [] -> -100000000\r\n | h :: t -> if x = h then 0 else 1 + find t x\r\n\r\nlet find_last lst x =\r\n if find lst x < 0 then -1\r\n else List.length lst - 1 - find (List.rev lst) x\r\n\r\nlet () = \r\n let cases = read_int () in\r\n for case = 1 to cases do\r\n let n = read_int () in\r\n let n2 = (n+1)/2 in\r\n let a = Array.init n (fun _ -> read_int_char ()) in\r\n let l = Array.to_list a in\r\n let last = find_last l 0 in\r\n if last >= n2 then printf \"%d %d %d %d\\n\" 1 (last+1) 1 last\r\n else if List.nth l (n2-1) = 0 then\r\n printf \"%d %d %d %d\\n\" n2 n (n2+1) n\r\n else \r\n printf \"%d %d %d %d\\n\" n2 (n-1) (n2+1) n\r\n done\r\n"}], "negative_code": [{"source_code": "open Printf\r\nopen Scanf\r\n\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_int_char _ = bscanf Scanning.stdin \" %c \" (fun x -> int_of_char x - 48)\r\n\r\nlet rec find lst x =\r\n match lst with\r\n | [] -> -100000000\r\n | h :: t -> if x = h then 0 else 1 + find t x\r\n\r\nlet find_last lst x =\r\n if find lst x < 0 then -1\r\n else List.length lst - 1 - find (List.rev lst) x\r\n\r\nlet () = \r\n let cases = read_int () in\r\n for case = 1 to cases do\r\n let n = read_int () in\r\n let n2 = (n+1)/2 in\r\n let a = Array.init n (fun _ -> read_int_char ()) in\r\n let l = Array.to_list a in\r\n let last = find_last l 0 in\r\n if last > n2 then printf \"%d %d %d %d\\n\" 1 last 1 (last-1)\r\n else if List.nth l (n2-1) = 0 then\r\n printf \"%d %d %d %d\\n\" n2 n (n2+1) n\r\n else \r\n printf \"%d %d %d %d\\n\" n2 (n-1) (n2+1) n\r\n done\r\n"}], "src_uid": "eadc7f5e1043ac431984ec921c62892d"} {"nl": {"description": "You have two strings $$$s_1$$$ and $$$s_2$$$ of length $$$n$$$, consisting of lowercase English letters. You can perform the following operation any (possibly zero) number of times: Choose a positive integer $$$1 \\leq k \\leq n$$$. Swap the prefix of the string $$$s_1$$$ and the suffix of the string $$$s_2$$$ of length $$$k$$$. Is it possible to make these two strings equal by doing described operations?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u2014 the length of the strings $$$s_1$$$ and $$$s_2$$$. The second line contains the string $$$s_1$$$ of length $$$n$$$, consisting of lowercase English letters. The third line contains the string $$$s_2$$$ of length $$$n$$$, consisting of lowercase English letters. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print \"YES\" if it is possible to make the strings equal, and \"NO\" otherwise.", "sample_inputs": ["7\n\n3\n\ncbc\n\naba\n\n5\n\nabcaa\n\ncbabb\n\n5\n\nabcaa\n\ncbabz\n\n1\n\na\n\na\n\n1\n\na\n\nb\n\n6\n\nabadaa\n\nadaaba\n\n8\n\nabcabdaa\n\nadabcaba"], "sample_outputs": ["YES\nYES\nNO\nYES\nNO\nNO\nYES"], "notes": "NoteIn the first test case: Initially $$$s_1 = \\mathtt{cbc}$$$, $$$s_2 = \\mathtt{aba}$$$. Operation with $$$k = 1$$$, after the operation $$$s_1 = \\mathtt{abc}$$$, $$$s_2 = \\mathtt{abc}$$$. In the second test case: Initially $$$s_1 = \\mathtt{abcaa}$$$, $$$s_2 = \\mathtt{cbabb}$$$. Operation with $$$k = 2$$$, after the operation $$$s_1 = \\mathtt{bbcaa}$$$, $$$s_2 = \\mathtt{cbaab}$$$. Operation with $$$k = 3$$$, after the operation $$$s_1 = \\mathtt{aabaa}$$$, $$$s_2 = \\mathtt{cbbbc}$$$. Operation with $$$k = 1$$$, after the operation $$$s_1 = \\mathtt{cabaa}$$$, $$$s_2 = \\mathtt{cbbba}$$$. Operation with $$$k = 2$$$, after the operation $$$s_1 = \\mathtt{babaa}$$$, $$$s_2 = \\mathtt{cbbca}$$$. Operation with $$$k = 1$$$, after the operation $$$s_1 = \\mathtt{aabaa}$$$, $$$s_2 = \\mathtt{cbbcb}$$$. Operation with $$$k = 2$$$, after the operation $$$s_1 = \\mathtt{cbbaa}$$$, $$$s_2 = \\mathtt{cbbaa}$$$. In the third test case, it's impossible to make strings equal."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet l2n c = (int_of_char c) - (int_of_char 'a') \n \nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let st_to_array s = Array.init n (fun i -> l2n s.[i]) in\n let s = st_to_array (read_string ()) in\n let t = st_to_array (read_string ()) in\n let pairs = Array.make_matrix 26 26 0 in\n let inc (x,y) =\n let (x,y) = min (x,y) (y,x) in\n pairs.(x).(y) <- 1 + pairs.(x).(y)\n in\n\n for i=0 to n-1 do\n let j = n-1-i in\n inc (s.(i),t.(j))\n done;\n\n let distinct_pairs_ok = \n forall 0 24 (fun i -> forall (i+1) 25 (fun j ->\n\tpairs.(i).(j) land 1 = 0\n )) \n in\n\n let n_odd_identital_pairs =\n sum 0 25 (fun i -> pairs.(i).(i) land 1)\n in\n\n if distinct_pairs_ok && (n_odd_identital_pairs = n land 1)\n then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}], "negative_code": [], "src_uid": "2d011ba7eaa16642d77dade98966b54a"} {"nl": {"description": "There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \\ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.", "input_spec": "First line contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \\leq x_i,y_i \\leq 10^9$$$).", "output_spec": "Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.", "sample_inputs": ["3\n1 1\n1 2\n2 1", "4\n1 1\n1 2\n2 1\n2 2"], "sample_outputs": ["3", "4"], "notes": "NoteIllustration for the first example: Illustration for the second example: "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\n\n\nlet () =\n\tlet n = get_i64 0 in\n\trepm 1L n 0L (fun m _ ->\n\t\tlet x,y = get_2_i64 9 in `Ok (max m (x+y))\n\t)\n\t|> printf \"%Ld\\n\"\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "7c41fb6212992d1b3b3f89694b579fea"} {"nl": {"description": "There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007\u00a0(109\u2009+\u20097).", "input_spec": "The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1\u2009\u2264\u2009n\u2009\u2264\u20091000,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on.", "output_spec": "In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007\u00a0(109\u2009+\u20097).", "sample_inputs": ["3 1\n1", "4 2\n1 4", "11 2\n4 8"], "sample_outputs": ["1", "2", "6720"], "notes": null}, "positive_code": [{"source_code": "open Int64\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet mmod = 1000000007\n\nlet sum a b =\n\tInt64.to_int(Int64.rem (Int64.add (Int64.of_int a) (Int64.of_int b)) (Int64.of_int mmod))\n;;\n\nlet pdt a b =\n\tInt64.to_int(Int64.rem (Int64.mul (Int64.of_int a) (Int64.of_int b)) (Int64.of_int mmod))\n;;\n\nlet rec pow a n =\n\tif n=0 then 1 else\n\tlet b = pow a (n/2) in\n\tif (n mod 2) = 0 then pdt b b else pdt a (pdt b b)\n ;;\n \n let rec comb n m =\n\tif m = 0 or n = m then 1\n\telse sum (comb(n-1) (m-1)) (comb(n-1) m)\n;;\n\nlet init_binomial n m = \n let b = Array.make_matrix (n+1) (m+1) 0 in\n for i=0 to n do for j=0 to min i m do \n b.(i).(j) <- if j=0 then 1 else sum b.(i-1).(j-1) b.(i-1).(j)\n done done;\n b\n;;\n\nlet n = read_int 0 in\nlet k = read_int 0 in\nlet a = Array.init k read_int in\nlet b = Array.make (n+2) 0 in\nlet s = Array.make 5 0 in\nlet bb = init_binomial n n in\n\nfor i = 0 to k-1 do\t\n\tb.(a.(i)) <- 1\ndone;\n\nb.(n+1) <- 1;\ns.(1) <- n - k;\ns.(2) <- 1;\n\n\nfor i = 1 to n+1 do\n\tif b.(i) = 0 then s.(0) <- s.(0) + 1\n\telse begin\t\t\t\n\t\tif s.(3) = 1 then begin \t\t\n\t\t\tif s.(4) > 0 then s.(2) <- pdt (s.(2)) (pow 2 (s.(4) - 1));\t\t\n\t\t\ts.(4) <- s.(0);\n\t\tend;\n\t\t\n\t\ts.(3) <- 1; \n\t\t\n\t\ts.(2) <- pdt (s.(2)) (bb.(s.(1)).(s.(0)));\n\t\ts.(1) <- s.(1) - s.(0);\n\t\ts.(0) <- 0;\n\tend;\ndone;\n\n\nPrintf.printf \"%d\\n\" s.(2)"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet mval = 1_000_000_007L\n\nlet ( ** ) a b = (Int64.rem (Int64.mul a b) mval)\nlet ( ++ ) a b = (Int64.rem (Int64.add a b) mval)\n(* let ( -- ) a b = Int64.sub a b\n let ( // ) a b = Int64.div a b *)\n\n(*------------create binomial--------------*)\nlet init_binomial n m = \n (* compute an array b so that b.(p).(q) = (p choose q), \n where 0 <= p <= n and 0 <= q <= m. *)\n let b = Array.make_matrix (n+1) (m+1) 0L in\n for i=0 to n do for j=0 to min i m do \n b.(i).(j) <- if j=0 then 1L else b.(i-1).(j-1) ++ b.(i-1).(j)\n done done;\n b\n\nlet init_powers n = \n let p = Array.make (n+1) 1L in\n for i=1 to n do\n p.(i) <- p.(i-1) ++ p.(i-1)\n done;\n p\n\nlet () =\n let n = read_int() in\n let m = read_int() in\n let on = Array.make (m+2) 0 in\n let () = for i=1 to m do\n on.(i) <- read_int();\n done in\n\n let () = on.(m+1) <- n+1 in\n\n let () = Array.sort compare on in\n\n let bi = init_binomial n n in\n let po = init_powers n in\n\n let rec find_gaps i stop ac = if i=stop then ac else\n (* consider gap from on.(i-1) to on.(i) *)\n if on.(i-1) + 1 = on.(i) then find_gaps (i+1) stop ac else\n find_gaps (i+1) stop ((on.(i) - on.(i-1) - 1) :: ac)\n in\n\n let gaps = find_gaps 1 (m+2) [] in\n let gaps = Array.of_list gaps in\n let g = Array.length gaps in\n\n let rec bloop i s ac = if i=g then ac else\n let s = s+gaps.(i) in\n let ac = ac ** bi.(s).(gaps.(i)) in\n bloop (i+1) s ac\n in\n\n let mix_count = bloop 0 0 1L in\n\n let pgaps = find_gaps 2 (m+1) [] in\n\n let rec ploop gl ac = match gl with [] -> ac\n | g::gl -> ploop gl (po.(g-1) ** ac)\n in\n let pow_count = ploop pgaps 1L in\n\n Printf.printf \"%Ld\\n\" (pow_count ** mix_count);\n"}], "negative_code": [{"source_code": "open Int64\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet mmod = 1000000007\n\nlet sum a b =\n\t(a + b) mod mmod\n;;\n\nlet pdt a b =\n\tInt64.to_int(Int64.rem (Int64.mul (Int64.of_int a) (Int64.of_int b)) (Int64.of_int mmod))\n;;\n \nlet rec pow a n =\n\tif n=0 then 1 else\n\tlet b = pow a (n/2) in\n\tif (n mod 2) = 0 then pdt b b else pdt a (pdt b b)\n ;;\n \n let rec comb n m =\n\tif m = 0 or n = m then 1\n\telse sum (comb(n-1) (m-1)) (comb(n-1) m)\n;;\n\n\nlet n = read_int 0 in\nlet k = read_int 0 in\nlet a = Array.init k read_int in\nlet b = Array.make (n+2) 0 in\nlet s = Array.make 5 0 in\n\nfor i = 0 to k-1 do\t\n\tb.(a.(i)) <- 1\ndone;\n\nb.(n+1) <- 1;\n\ns.(1) <- n - k;\ns.(2) <- 1;\n\nfor i = 1 to n+1 do\n\tif b.(i) = 0 then s.(0) <- s.(0) + 1\n\telse begin\t\t\t\n\t\tif s.(3) = 1 then s.(2) <- pdt (s.(2)) ((pow 2 s.(4)) - 1);\n\t\tif (s.(0) > 0) then begin s.(3) <- 1; s.(4) <- s.(0); end;\n\t\ts.(2) <- pdt (s.(2)) (comb s.(1) s.(0));\n\t\ts.(1) <- s.(1) - s.(0);\n\t\ts.(0) <- 0;\n\tend;\ndone;\n\n\n\nPrintf.printf \"%d\\n\" s.(2)\n\n(*\n(pdt (pow k (k-1)) (pow (n-k) (n-k)))\n*)"}, {"source_code": "open Int64\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet mmod = 1000000007\n\nlet sum a b =\n\t(a + b) mod mmod\n;;\n\nlet pdt a b =\n\tInt64.to_int(Int64.rem (Int64.mul (Int64.of_int a) (Int64.of_int b)) (Int64.of_int mmod))\n;;\n \nlet rec pow a n =\n\tif n=0 then 1 else\n\tlet b = pow a (n/2) in\n\tif (n mod 2) = 0 then pdt b b else pdt a (pdt b b)\n ;;\n \n let rec comb n m =\n\tif m = 0 or n = m then 1\n\telse sum (comb(n-1) (m-1)) (comb(n-1) m)\n;;\n\n\nlet n = read_int 0 in\nlet k = read_int 0 in\nlet a = Array.init k read_int in\nlet b = Array.make (n+2) 0 in\nlet s = Array.make 5 0 in\n\nfor i = 0 to k-1 do\t\n\tb.(a.(i)) <- 1\ndone;\n\nb.(n+1) <- 1;\ns.(1) <- n - k;\ns.(2) <- 1;\n\nfor i = 1 to n+1 do\n\tif b.(i) = 0 then s.(0) <- s.(0) + 1\n\telse begin\t\t\t\n\t\tif s.(3) = 1 && s.(4) > 0 then s.(2) <- pdt (s.(2)) ((pow 2 s.(4)) - 1);\t\t\n\t\ts.(3) <- 1; s.(4) <- s.(0);\t\t\t\t\t\t\t\t\t\n\t\ts.(2) <- pdt (s.(2)) (comb s.(1) s.(0));\n\t\ts.(1) <- s.(1) - s.(0);\n\t\ts.(0) <- 0;\n\tend;\ndone;\n\n\nPrintf.printf \"%d\\n\" s.(2)\n\n(*\n(pdt (pow k (k-1)) (pow (n-k) (n-k)))\n*)"}, {"source_code": "open Int64\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet mmod = 1000000007\n\nlet sum a b =\n\t(a + b) mod mmod\n;;\n\nlet pdt a b =\n\tInt64.to_int(Int64.rem (Int64.mul (Int64.of_int a) (Int64.of_int b)) (Int64.of_int mmod))\n;;\n \nlet rec pow a n =\n\tif n=0 then 1 else\n\tlet b = pow a (n/2) in\n\tif (n mod 2) = 0 then pdt b b else pdt a (pdt b b)\n ;;\n \n let rec comb n m =\n\tif m = 0 or n = m then 1\n\telse sum (comb(n-1) (m-1)) (comb(n-1) m)\n;;\n\n\nlet n = read_int 0 in\nlet k = read_int 0 in\nlet a = Array.init k read_int in\nlet b = Array.make (n+2) 0 in\nlet s = Array.make 5 0 in\n\nfor i = 0 to k-1 do\t\n\tb.(a.(i)) <- 1\ndone;\n\nb.(n) <- 1;\n\n\ns.(1) <- n - k;\ns.(2) <- 1;\n\n\nfor i = 1 to n+1 do\n\tif b.(i) = 0 then s.(0) <- s.(0) + 1\n\telse begin\t\t\t\n\t\tif s.(3) = 1 then s.(2) <- pdt (s.(2)) ((pow 2 s.(4)) - 1);\n\t\ts.(3) <- 1; \n\t\ts.(4) <- s.(0);\n\t\ts.(2) <- pdt (s.(2)) (comb s.(1) s.(0));\n\t\ts.(1) <- s.(1) - s.(0);\n\t\ts.(0) <- 0;\n\tend;\ndone;\n\n\n\nPrintf.printf \"%d\\n\" s.(2)\n\n(*\n(pdt (pow k (k-1)) (pow (n-k) (n-k)))\n*)"}, {"source_code": "open Int64\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet mmod = 1000000007\n\nlet sum a b =\n\t(a + b) mod mmod\n;;\n\nlet pdt a b =\n\tInt64.to_int(Int64.rem (Int64.mul (Int64.of_int a) (Int64.of_int b)) (Int64.of_int mmod))\n;;\n \nlet rec pow a n =\n\tif n=0 then 1 else\n\tlet b = pow a (n/2) in\n\tif (n mod 2) = 0 then pdt b b else pdt a (pdt b b)\n ;;\n \n let rec comb n m =\n\tif m = 0 or n = m then 1\n\telse sum (comb(n-1) (m-1)) (comb(n-1) m)\n;;\n\n\nlet n = read_int 0 in\nlet k = read_int 0 in\nlet a = Array.init k read_int in\nlet b = Array.make (n+2) 0 in\nlet s = Array.make 5 0 in\n\nfor i = 0 to k-1 do\t\n\tb.(a.(i)) <- 1\ndone;\n\nb.(n+1) <- 1;\ns.(1) <- n - k;\ns.(2) <- 1;\n\nfor i = 1 to n+1 do\n\tif b.(i) = 0 then s.(0) <- s.(0) + 1\n\telse begin\t\t\t\n\t\tif (s.(3) = 1) && (s.(4) > 0) then begin \n\t\t\ts.(2) <- pdt (s.(2)) (pow 2 (s.(4) - 1));\t\t\n\t\t\ts.(4) <- s.(0);\n\t\tend;\n\t\t\n\t\ts.(3) <- 1; \n\t\t\n\t\ts.(2) <- pdt (s.(2)) (comb s.(1) s.(0));\n\t\ts.(1) <- s.(1) - s.(0);\n\t\ts.(0) <- 0;\n\tend;\ndone;\n\n\nPrintf.printf \"%d\\n\" s.(2)\n\n(*\n(pdt (pow k (k-1)) (pow (n-k) (n-k)))\n*)"}, {"source_code": "open Int64\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet mmod = 1000000007\n\nlet sum a b =\n\t(a + b) mod mmod\n;;\n\nlet pdt a b =\n\tInt64.to_int(Int64.rem (Int64.mul (Int64.of_int a) (Int64.of_int b)) (Int64.of_int mmod))\n;;\n\nlet rec pow a n =\n\tif n=0 then 1 else\n\tlet b = pow a (n/2) in\n\tif (n mod 2) = 0 then pdt b b else pdt a (pdt b b)\n ;;\n \n let rec comb n m =\n\tif m = 0 or n = m then 1\n\telse sum (comb(n-1) (m-1)) (comb(n-1) m)\n;;\n\nlet init_binomial n m = \n let b = Array.make_matrix (n+1) (m+1) 0 in\n for i=0 to n do for j=0 to min i m do \n b.(i).(j) <- if j=0 then 1 else sum b.(i-1).(j-1) b.(i-1).(j)\n done done;\n b\n;;\n\nlet n = read_int 0 in\nlet k = read_int 0 in\nlet a = Array.init k read_int in\nlet b = Array.make (n+2) 0 in\nlet s = Array.make 5 0 in\nlet bb = init_binomial n n in\n\nfor i = 0 to k-1 do\t\n\tb.(a.(i)) <- 1\ndone;\n\nb.(n+1) <- 1;\ns.(1) <- n - k;\ns.(2) <- 1;\n\n\nfor i = 1 to n+1 do\n\tif b.(i) = 0 then s.(0) <- s.(0) + 1\n\telse begin\t\t\t\n\t\tif s.(3) = 1 then begin \t\t\n\t\t\tif s.(4) > 0 then s.(2) <- pdt (s.(2)) (pow 2 (s.(4) - 1));\t\t\n\t\t\ts.(4) <- s.(0);\n\t\tend;\n\t\t\n\t\ts.(3) <- 1; \n\t\t\n\t\ts.(2) <- pdt (s.(2)) (bb.(s.(1)).(s.(0)));\n\t\ts.(1) <- s.(1) - s.(0);\n\t\ts.(0) <- 0;\n\tend;\ndone;\n\n\nPrintf.printf \"%d\\n\" s.(2)"}, {"source_code": "open Int64\n\nlet read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet mmod = 1000000007\n\nlet sum a b =\n\t(a + b) mod mmod\n;;\n\nlet pdt a b =\n\tInt64.to_int(Int64.rem (Int64.mul (Int64.of_int a) (Int64.of_int b)) (Int64.of_int mmod))\n;;\n \nlet rec pow a n =\n\tif n=0 then 1 else\n\tlet b = pow a (n/2) in\n\tif (n mod 2) = 0 then pdt b b else pdt a (pdt b b)\n ;;\n \n let rec comb n m =\n\tif m = 0 or n = m then 1\n\telse sum (comb(n-1) (m-1)) (comb(n-1) m)\n;;\n\n\nlet n = read_int 0 in\nlet k = read_int 0 in\nlet a = Array.init k read_int in\nlet b = Array.make (n+2) 0 in\nlet s = Array.make 5 0 in\n\nfor i = 0 to k-1 do\t\n\tb.(a.(i)) <- 1\ndone;\n\nb.(n+1) <- 1;\ns.(1) <- n - k;\ns.(2) <- 1;\n\nfor i = 1 to n+1 do\n\tif b.(i) = 0 then s.(0) <- s.(0) + 1\n\telse begin\t\t\t\n\t\tif s.(3) = 1 && s.(4) > 0 then s.(2) <- pdt (s.(2)) (pow 2 (s.(4) - 1));\t\t\n\t\ts.(3) <- 1; s.(4) <- s.(0);\t\t\t\t\t\t\t\t\t\n\t\ts.(2) <- pdt (s.(2)) (comb s.(1) s.(0));\n\t\ts.(1) <- s.(1) - s.(0);\n\t\ts.(0) <- 0;\n\tend;\ndone;\n\n\nPrintf.printf \"%d\\n\" s.(2)\n\n(*\n(pdt (pow k (k-1)) (pow (n-k) (n-k)))\n*)"}], "src_uid": "14da0cdf2939c796704ec548f49efb87"} {"nl": {"description": "You are given $$$n$$$ numbers $$$a_1, a_2, \\ldots, a_n$$$. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?For example, for the array $$$[1, 4, 5, 6, 7, 8]$$$, the arrangement on the left is valid, while arrangement on the right is not, as $$$5\\ge 4 + 1$$$ and $$$8> 1 + 6$$$. ", "input_spec": "The first line contains a single integer $$$n$$$ ($$$3\\le n \\le 10^5$$$)\u00a0\u2014 the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\le 10^9$$$)\u00a0\u2014 the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).", "output_spec": "If there is no solution, output \"NO\" in the first line. If there is a solution, output \"YES\" in the first line. In the second line output $$$n$$$ numbers\u00a0\u2014 elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.", "sample_inputs": ["3\n2 4 3", "5\n1 2 3 4 4", "3\n13 8 5", "4\n1 10 100 1000"], "sample_outputs": ["YES\n4 2 3", "YES\n4 4 2 1 3", "NO", "NO"], "notes": "NoteOne of the possible arrangements is shown in the first example: $$$4< 2 + 3$$$;$$$2 < 4 + 3$$$;$$$3< 4 + 2$$$.One of the possible arrangements is shown in the second example.No matter how we arrange $$$13, 8, 5$$$ in a circle in the third example, $$$13$$$ will have $$$8$$$ and $$$5$$$ as neighbors, but $$$13\\ge 8 + 5$$$. There is no solution in the fourth example."}, "positive_code": [{"source_code": "let () =\n let split s =\n let rec loop i cur flag acc =\n if i = String.length s then (\n if flag then cur :: acc else acc\n ) else (\n match flag, s.[i] with\n | true, ' ' -> loop (i + 1) 0 false (cur :: acc)\n | false, ' ' -> loop (i + 1) 0 false acc\n | true, v -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc\n | false, v -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc\n )\n in\n List.rev (loop 0 0 false [])\n in\n let main () =\n let n = int_of_string (read_line ()) in\n let a = Array.of_list (split (read_line ())) in\n Array.sort (fun a b -> compare b a) a;\n if a.(0) >= a.(1) + a.(2) then print_endline \"NO\" else (\n print_endline \"YES\";\n for i = 0 to n - 1 do\n let k = i * 2 in\n let k = if k < n then k else 2 * n - 1 - k in\n Printf.printf \"%d \" a.(k)\n done;\n print_newline ()\n )\n\n in\n main ()\n"}], "negative_code": [], "src_uid": "a5ee97e99ecfe4b72c0642546746842a"} {"nl": {"description": "Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c \u2014 Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.For instance, let's say the garland is represented by \"kooomo\", and Brother Koyomi's favourite colour is \"o\". Among all subsegments containing pieces of \"o\" only, \"ooo\" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.", "input_spec": "The first line of input contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091\u2009500) \u2014 the length of the garland. The second line contains n lowercase English letters s1s2... sn as a string \u2014 the initial colours of paper pieces on the garland. The third line contains a positive integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009200\u2009000) \u2014 the number of plans Nadeko has. The next q lines describe one plan each: the i-th among them contains an integer mi (1\u2009\u2264\u2009mi\u2009\u2264\u2009n) \u2014 the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci \u2014 Koyomi's possible favourite colour.", "output_spec": "Output q lines: for each work plan, output one line containing an integer \u2014 the largest Koyomity achievable after repainting the garland according to it.", "sample_inputs": ["6\nkoyomi\n3\n1 o\n4 o\n4 m", "15\nyamatonadeshiko\n10\n1 a\n2 a\n3 a\n4 a\n5 a\n1 b\n2 b\n3 b\n4 b\n5 b", "10\naaaaaaaaaa\n2\n10 b\n10 z"], "sample_outputs": ["3\n6\n5", "3\n4\n5\n7\n8\n1\n2\n3\n4\n5", "10\n10"], "notes": "NoteIn the first sample, there are three plans: In the first plan, at most 1 piece can be repainted. Repainting the \"y\" piece to become \"o\" results in \"kooomi\", whose Koyomity of 3 is the best achievable; In the second plan, at most 4 pieces can be repainted, and \"oooooo\" results in a Koyomity of 6; In the third plan, at most 4 pieces can be repainted, and \"mmmmmi\" and \"kmmmmm\" both result in a Koyomity of 5. "}, "positive_code": [{"source_code": "(* started codeing 11:39 *)\n(* done coding 11:54 *)\n(* submit: 12:06 (wrong answer) *)\n\nopen Printf\nopen Scanf\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let s = read_string () in\n let s = Array.init n (fun i -> l2n s.[i]) in\n let q = read_int () in\n let query = Array.init q (fun _ ->\n let m = read_int() in\n let c = l2n ((read_string()).[0]) in\n (m,c)\n ) in\n\n let pre = Array.make_matrix (n+1) 26 0 in\n (* pre.(i).(c) = the number of c's in s.(0)...s.(i-1) *)\n\n for c = 0 to 25 do\n for i=1 to n do\n pre.(i).(c) <- pre.(i-1).(c) + (if s.(i-1) = c then 1 else 0)\n done\n done;\n\n let range_count i j c = pre.(j+1).(c) - pre.(i).(c) in\n (* the number of c's in the range s.(i) ... s.(j) *)\n\n let ans = Array.make_matrix (n+1) 26 0 in\n\n for i=0 to n-1 do\n for j=i to n-1 do\n for c=0 to 25 do\n\tlet len = j-i+1 in\n\tlet count = len - (range_count i j c) in\n\tans.(count).(c) <- max ans.(count).(c) len\n done\n done\n done;\n\n for c=0 to 25 do\n for count = 1 to n do\n ans.(count).(c) <- max ans.(count-1).(c) ans.(count).(c)\n done\n done;\n\n for qx = 0 to q-1 do\n let (m,c) = query.(qx) in\n printf \"%d\\n\" ans.(m).(c)\n done;\n"}], "negative_code": [{"source_code": "(* started codeing 11:39 *)\n(* done coding 11:54 *)\n(* submit: *)\n\nopen Printf\nopen Scanf\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let s = read_string () in\n let s = Array.init n (fun i -> l2n s.[i]) in\n let q = read_int () in\n let query = Array.init q (fun _ ->\n let m = read_int() in\n let c = l2n ((read_string()).[0]) in\n (m,c)\n ) in\n\n let pre = Array.make_matrix (n+1) 26 0 in\n (* pre.(i).(c) = the number of c's in s.(0)...s.(i-1) *)\n\n for c = 0 to 25 do\n for i=1 to n do\n pre.(i).(c) <- pre.(i-1).(c) + (if s.(i-1) = c then 1 else 0)\n done\n done;\n\n let range_count i j c = pre.(j+1).(c) - pre.(i).(c) in\n (* the number of c's in the range s.(i) ... s.(j) *)\n\n let ans = Array.make_matrix (n+1) 26 0 in\n\n for i=0 to n-1 do\n for j=i to n-1 do\n for c=0 to 25 do\n\tlet len = j-i+1 in\n\tlet count = len - (range_count i j c) in\n\tans.(count).(c) <- max ans.(count).(c) len\n done\n done\n done;\n\n for qx = 0 to q-1 do\n let (m,c) = query.(qx) in\n printf \"%d\\n\" ans.(m).(c)\n done;\n"}], "src_uid": "0646a23b550eefea7347cef831d1c69d"} {"nl": {"description": "You are given a permutation $$$p_1, p_2, \\dots, p_n$$$. Then, an undirected graph is constructed in the following way: add an edge between vertices $$$i$$$, $$$j$$$ such that $$$i < j$$$ if and only if $$$p_i > p_j$$$. Your task is to count the number of connected components in this graph.Two vertices $$$u$$$ and $$$v$$$ belong to the same connected component if and only if there is at least one path along edges connecting $$$u$$$ and $$$v$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$)\u00a0\u2014 the elements of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print one integer $$$k$$$\u00a0\u2014 the number of connected components.", "sample_inputs": ["6\n3\n1 2 3\n5\n2 1 4 3 5\n6\n6 1 4 2 5 3\n1\n1\n6\n3 2 1 6 5 4\n5\n3 1 5 2 4"], "sample_outputs": ["3\n3\n1\n1\n2\n1"], "notes": "NoteEach separate test case is depicted in the image below. The colored squares represent the elements of the permutation. For one permutation, each color represents some connected component. The number of distinct colors is the answer. "}, "positive_code": [{"source_code": "(* Codeforces 1638 C Inversion Graph train *)\r\n \r\n(* you can use either gr or rdln but not both *)\r\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\r\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\r\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet rdln() = input_line stdin;;\r\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\r\nlet debug = false;;\r\n \r\n(* reading list *)\r\nlet rec readlist n acc = match n with\r\n\t| 0 -> List.rev acc\r\n\t| _ -> readlist (n -1) (gr() :: acc);;\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\r\n\r\nlet rec count_comps i cnt max lp comps = match lp with\r\n | [] -> comps\r\n | hp :: t ->\r\n let ncnt = if hp <= i+1 then cnt+1 else cnt in\r\n let nmax = if hp > max then hp else max in\r\n let ni = i+1 in \r\n let ncomps = if nmax == (i+1) then comps+1 else comps in\r\n (* let _ = Printf.printf \"ncnt nmax ni ncomps = %d %d %d %d\\n\" ncnt nmax ni ncomps in *)\r\n count_comps ni ncnt nmax t ncomps;; \r\n\r\nlet do_one () = \r\n let n = gr () in\r\n let p = readlist n [] in\r\n let cnt = count_comps 0 0 0 p 0 in\r\n\t(print_int cnt; print_string \"\\n\");;\r\n \r\nlet do_all () = \r\n let t = gr () in\r\n for i = 1 to t do\r\n do_one ()\r\n done;;\r\n \r\nlet main() =\r\n\tdo_all ();;\r\n \r\nmain();;"}], "negative_code": [], "src_uid": "b371d47ea08091917ab632e559ee75c6"} {"nl": {"description": "You are given a set of all integers from $$$l$$$ to $$$r$$$ inclusive, $$$l < r$$$, $$$(r - l + 1) \\le 3 \\cdot 10^5$$$ and $$$(r - l)$$$ is always odd.You want to split these numbers into exactly $$$\\frac{r - l + 1}{2}$$$ pairs in such a way that for each pair $$$(i, j)$$$ the greatest common divisor of $$$i$$$ and $$$j$$$ is equal to $$$1$$$. Each number should appear in exactly one of the pairs.Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.", "input_spec": "The only line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l < r \\le 10^{18}$$$, $$$r - l + 1 \\le 3 \\cdot 10^5$$$, $$$(r - l)$$$ is odd).", "output_spec": "If any solution exists, print \"YES\" in the first line. Each of the next $$$\\frac{r - l + 1}{2}$$$ lines should contain some pair of integers. GCD of numbers in each pair should be equal to $$$1$$$. All $$$(r - l + 1)$$$ numbers should be pairwise distinct and should have values from $$$l$$$ to $$$r$$$ inclusive. If there are multiple solutions, print any of them. If there exists no solution, print \"NO\".", "sample_inputs": ["1 8"], "sample_outputs": ["YES\n2 7\n4 1\n3 8\n6 5"], "notes": null}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\n\nlet () =\n\tlet l,r = get_2_i64 0 in\n\tlet p = ref l in\n\tprintf \"YES\\n\";\n\twhile !p <= r do\n\t\tprintf \"%Ld %Ld\\n\" !p (!p+1L);\n\t\tp += 2L;\n\tdone;"}], "negative_code": [], "src_uid": "6432a543eeee9833c6d849222ad6b93d"} {"nl": {"description": "Vasya has decided to build a zip-line on trees of a nearby forest. He wants the line to be as long as possible but he doesn't remember exactly the heights of all trees in the forest. He is sure that he remembers correct heights of all trees except, possibly, one of them.It is known that the forest consists of n trees staying in a row numbered from left to right with integers from 1 to n. According to Vasya, the height of the i-th tree is equal to hi. The zip-line of length k should hang over k (1\u2009\u2264\u2009k\u2009\u2264\u2009n) trees i1,\u2009i2,\u2009...,\u2009ik (i1\u2009<\u2009i2\u2009<\u2009...\u2009<\u2009ik) such that their heights form an increasing sequence, that is hi1\u2009<\u2009hi2\u2009<\u2009...\u2009<\u2009hik.Petya had been in this forest together with Vasya, and he now has q assumptions about the mistake in Vasya's sequence h. His i-th assumption consists of two integers ai and bi indicating that, according to Petya, the height of the tree numbered ai is actually equal to bi. Note that Petya's assumptions are independent from each other.Your task is to find the maximum length of a zip-line that can be built over the trees under each of the q assumptions.In this problem the length of a zip line is considered equal to the number of trees that form this zip-line.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009400\u2009000)\u00a0\u2014 the number of the trees in the forest and the number of Petya's assumptions, respectively. The following line contains n integers hi (1\u2009\u2264\u2009hi\u2009\u2264\u2009109)\u00a0\u2014 the heights of trees according to Vasya. Each of the following m lines contains two integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009n, 1\u2009\u2264\u2009bi\u2009\u2264\u2009109).", "output_spec": "For each of the Petya's assumptions output one integer, indicating the maximum length of a zip-line that can be built under this assumption.", "sample_inputs": ["4 4\n1 2 3 4\n1 1\n1 4\n4 3\n4 5", "4 2\n1 3 2 6\n3 5\n2 4"], "sample_outputs": ["4\n3\n3\n4", "4\n3"], "notes": "NoteConsider the first sample. The first assumption actually coincides with the height remembered by Vasya. In the second assumption the heights of the trees are (4,\u20092,\u20093,\u20094), in the third one they are (1,\u20092,\u20093,\u20093) and in the fourth one they are (1,\u20092,\u20093,\u20095)."}, "positive_code": [{"source_code": "let hmax = 1_000_000_001;;\nlet rec readlist n f = match n with\n | 0 -> []\n | _ -> f() :: readlist (n-1) f ;;\nlet (n, m) = Scanf.scanf \"%d %d\" (fun x y -> (x,y)) ;;\nlet ans = Array.make m 0 ;;\nlet q = Array.make n [] ;;\nlet h = Array.make n 0 ;;\nfor i = 0 to n-1 do\n h.(i) <- Scanf.scanf \" %d\" (fun x -> x)\ndone ;;\nfor i = 0 to m-1 do\n let (a,b) = Scanf.scanf \" %d %d\" (fun x y -> (x-1, y)) in\n q.(a) <- (i, b) :: q.(a)\ndone ;;\n\nmodule M = Map.Make(struct type t = int let compare = compare end)\n\nlet calcpre () = \n let zpre = Array.make n 0 and\n minWithSize = Array.make (n+1) (hmax+1) in\n let rec calcpre_ i m =\n if i < n then\n let score h = 1 + ( snd @@ M.max_binding @@ (fun (x1,_,_) -> x1) @@ M.split h m ) in (\n List.iter (fun (id, hnew) -> ans.(id) <- score hnew ) q.(i);\n let zhere = score h.(i) in\n zpre.(i) <- zhere;\n calcpre_ (i+1) (if h.(i) < minWithSize.(zhere)\n then let oldh = minWithSize.(zhere) in\n (minWithSize.(zhere) <- h.(i) ; \n m |> M.remove oldh |> M.add h.(i) zhere)\n else m)\n )\n in calcpre_ 0 (M.singleton 0 0) ; zpre\n;;\nlet zpre = calcpre () ;;\n\nlet calcpost () =\n let maxWithSize = Array.make (n+1) (-1) in\n let rec calcpost i m = if i >= 0\n then let score h = snd @@ M.min_binding @@ (fun (_,_,x3) -> x3) @@ M.split h m in (\n List.iter (fun (id, hnew) -> ans.(id) <- ans.(id) + score hnew) q.(i) ;\n let zhere = 1 + score h.(i) in\n calcpost (i-1) (if h.(i) > maxWithSize.(zhere)\n then let oldh = maxWithSize.(zhere) in\n (maxWithSize.(zhere) <- h.(i) ; \n m |> M.remove oldh |> M.add h.(i) zhere )\n else m)\n ) else snd @@ M.min_binding m\n in calcpost (n-1) (M.singleton hmax 0)\n;;\nlet zmax = calcpost () ;;\n\nlet critical = Array.make zmax true ;;\nlet iused = Array.make n false;;\nlet maxWithSize = Array.make (zmax+1) 0 in (\n maxWithSize.(zmax) <- hmax;\n for i = n-1 downto 0 do\n let zhere = zpre.(i) in\n if h.(i) < maxWithSize.(zhere) then (\n iused.(i) <- true ;\n if maxWithSize.(zhere - 1) != 0 then critical.(zhere - 1) <- false ;\n maxWithSize.(zhere - 1) <- max maxWithSize.(zhere - 1) h.(i)\n )\n done \n) ;;\n\nArray.iteri (fun i qq -> List.iter (fun (id, hnew) -> ans.(id) <- max ans.(id) (if iused.(i) && critical.(zpre.(i) - 1) then zmax-1 else zmax) ) qq) q ;;\nArray.iter (Printf.printf \"%d\\n\") ans ;;\n\n\n\n(*\n\n9 9\n3 4 3 4 3 4 3 4 3\n1 3\n2 3\n3 3\n4 3\n5 3\n6 3\n7 3 \n8 3\n9 3\n\n*)\n\n\n"}], "negative_code": [], "src_uid": "91c90ca2749ce123b8606da36482093d"} {"nl": {"description": "Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.Public transport is not free. There are 4 types of tickets: A ticket for one ride on some bus or trolley. It costs c1 burles; A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles; A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles; A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.", "input_spec": "The first line contains four integers c1,\u2009c2,\u2009c3,\u2009c4 (1\u2009\u2264\u2009c1,\u2009c2,\u2009c3,\u2009c4\u2009\u2264\u20091000) \u2014 the costs of the tickets. The second line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20091000) \u2014 the number of buses and trolleys Vasya is going to use. The third line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 the number of times Vasya is going to use the bus number i. The fourth line contains m integers bi (0\u2009\u2264\u2009bi\u2009\u2264\u20091000) \u2014 the number of times Vasya is going to use the trolley number i.", "output_spec": "Print a single number \u2014 the minimum sum of burles Vasya will have to spend on the tickets.", "sample_inputs": ["1 3 7 19\n2 3\n2 5\n4 4 4", "4 3 2 1\n1 3\n798\n1 2 3", "100 100 8 100\n3 5\n7 94 12\n100 1 47 0 42"], "sample_outputs": ["12", "1", "16"], "notes": "NoteIn the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2\u00b71)\u2009+\u20093\u2009+\u20097\u2009=\u200912 burles.In the second sample the profitable strategy is to buy one ticket of the fourth type.In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys."}, "positive_code": [{"source_code": "let (@@) f x = f x ;;\nlet (|>) x f = f x ;;\nlet ident x = x ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n let acc = ref init in\n let cur = ref min in\n while !cur < max do\n acc := f !acc !cur;\n cur := !cur + skip;\n done;\n !acc\n;;\n\nlet iter_for ?(skip=1) min max ~f =\n let cur = ref min in\n while !cur < max do\n f !cur;\n cur := !cur + skip;\n done\n;;\n\nlet solve k d =\n if d <> 0 then begin\n let s = String.create k in\n s.[0] <- char_of_int (d + int_of_char '0');\n String.fill s 1 (k - 1) '0';\n print_endline s\n end else if k = 1 then begin\n print_endline \"0\"\n end else begin\n print_endline \"No solution\";\n end\n;;\n\nlet input () =\n let cs = Scanf.scanf \"%d %d %d %d \" (fun c1 c2 c3 c4 -> c1, c2, c3, c4) in\n let m, n = Scanf.scanf \"%d %d \" (fun m n -> m, n) in\n let rec iter i =\n if i = 0 then []\n else (Scanf.scanf \"%d \" ident) :: iter (i - 1) in\n let buses = iter m in\n let trolleys = iter n in\n (cs, m, n, buses, trolleys)\n;;\n\nlet solve c1 c2 c3 c4 buses trolleys =\n let min_buses = List.map buses ~f:(fun i -> min (c1 * i) c2) in\n let min_trolleys = List.map trolleys ~f:(fun i -> min (c1 * i) c2) in\n let sum_buses = min (List.fold_left ~init:0 min_buses ~f:(+)) c3 in\n let sum_trolleys = min (List.fold_left ~init:0 min_trolleys ~f:(+)) c3 in\n min (sum_buses + sum_trolleys) c4\n;;\n\nlet () =\n let ((c1, c2, c3, c4), _, _, buses, trolleys) = input () in\n let res = solve c1 c2 c3 c4 buses trolleys in\n Printf.printf \"%d\\n\" res\n;;\n"}], "negative_code": [], "src_uid": "11fabde93815c1805369bbbc5a40e2d8"} {"nl": {"description": "Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle. As you spend lots of time \"glued to the screen\", your vision is impaired. So you have to write a program that will pass the check for you.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of mannequins. Next n lines contain two space-separated integers each: xi,\u2009yi (|xi|,\u2009|yi|\u2009\u2264\u20091000) \u2014 the coordinates of the i-th mannequin. It is guaranteed that the origin of the coordinates has no mannequin. It is guaranteed that no two mannequins are located in the same point on the plane.", "output_spec": "Print a single real number \u2014 the value of the sought angle in degrees. The answer will be considered valid if the relative or absolute error doesn't exceed 10\u2009-\u20096. ", "sample_inputs": ["2\n2 0\n0 2", "3\n2 0\n0 2\n-2 2", "4\n2 0\n0 2\n-2 0\n0 -2", "2\n2 1\n1 2"], "sample_outputs": ["90.0000000000", "135.0000000000", "270.0000000000", "36.8698976458"], "notes": "NoteSolution for the first sample test is shown below: Solution for the second sample test is shown below: Solution for the third sample test is shown below: Solution for the fourth sample test is shown below: "}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet pi = 4.0 *. (atan2 1.0 1.0)\n\nlet () = \n let n = read_int() in\n let p = Array.init n (fun _ -> \n\t\t\t let (x,y) = read_pair() in\n\t\t\t let (x,y) = (float(x), float(y)) in\n\t\t\t atan2 x y\n\t\t ) in\n \n\n if n=1 then Printf.printf \"0.0\\n\" else \n let () = Array.sort compare p in\n let a1 = maxf 0 (n-2) (fun i -> p.(i+1) -. p.(i)) in\n let a2 = (pi -. p.(n-1)) +. (p.(0) -. (-. pi)) in\n let answer = max a1 a2 in\n\tPrintf.printf \"%5.10f\\n\" (180.0 *. ((2.0*.pi -. answer) /. pi))\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet pi = 4.0 *. (atan2 1.0 1.0)\n\nlet () = \n let n = read_int() in\n let p = Array.init n (fun _ -> \n\t\t\t let (x,y) = read_pair() in\n\t\t\t let (x,y) = (float(x), float(y)) in\n\t\t\t atan2 x y\n\t\t ) in\n \n\n if n=1 then Printf.printf \"360.0\\n\" else \n let () = Array.sort compare p in\n let a1 = maxf 0 (n-2) (fun i -> p.(i+1) -. p.(i)) in\n let a2 = (pi -. p.(n-1)) +. (p.(0) -. (-. pi)) in\n let answer = max a1 a2 in\n\tPrintf.printf \"%5.10f\\n\" (180.0 *. ((2.0*.pi -. answer) /. pi))\n"}], "src_uid": "a67cdb7501e99766b20a2e905468c29c"} {"nl": {"description": "Little X used to play a card game called \"24 Game\", but recently he has found it too easy. So he invented a new game.Initially you have a sequence of n integers: 1,\u20092,\u2009...,\u2009n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a\u2009+\u2009b, or a\u2009-\u2009b, or a\u2009\u00d7\u2009b.After n\u2009-\u20091 steps there is only one number left. Can you make this number equal to 24?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "If it's possible, print \"YES\" in the first line. Otherwise, print \"NO\" (without the quotes). If there is a way to obtain 24 as the result number, in the following n\u2009-\u20091 lines print the required operations an operation per line. Each operation should be in form: \"a op b = c\". Where a and b are the numbers you've picked at this operation; op is either \"+\", or \"-\", or \"*\"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces. If there are multiple valid answers, you may print any of them.", "sample_inputs": ["1", "8"], "sample_outputs": ["NO", "YES\n8 * 7 = 56\n6 * 5 = 30\n3 - 4 = -1\n1 - 2 = -1\n30 - -1 = 31\n56 - 31 = 25\n25 + -1 = 24"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n\n let rec solve n ac = \n if n=4 then (\n let ac = \"3 * 4 = 12\" :: ac in\n let ac = \"2 * 12 = 24\" :: ac in\n let ac = \"1 * 24 = 24\" :: ac in\n ac\n ) else if n=5 then (\n let ac = \"4 + 5 = 9\" :: ac in\n let ac = \"3 + 9 = 12\" :: ac in\n let ac = \"2 * 12 = 24\" :: ac in\n let ac = \"1 * 24 = 24\" :: ac in\n ac\n ) else (\n let ac = ((sprintf \"%d - %d = %d\") n (n-1) 1) :: ac in\n let ac = ((sprintf \"%d * %d = %d\") 1 (n-2) (n-2)) :: ac in\n solve (n-2) ac\n )\n in\n\n if n<4 then printf \"NO\\n\" \n else (\n printf \"YES\\n\";\n List.iter (fun e -> printf \"%s\\n\" e) (List.rev (solve n []))\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n\n let rec solve n ac = \n if n=4 then (\n let ac = \"3 * 4 = 12\" :: ac in\n let ac = \"2 * 12 = 24\" :: ac in\n let ac = \"1 * 24 = 24\" :: ac in\n ac\n ) else if n=5 then (\n let ac = \"4 + 5 = 9\" :: ac in\n let ac = \"3 + 9 = 12\" :: ac in\n let ac = \"2 * 12 = 24\" :: ac in\n let ac = \"1 * 24 = 24\" :: ac in\n ac\n ) else (\n let ac = ((sprintf \"%d - %d = %d\") n (n-1) 1) :: ac in\n let ac = ((sprintf \"%d * %d = %d\") 1 (n-2) (n-2)) :: ac in\n solve (n-2) ac\n )\n in\n\n if n<4 then printf \"NO\\n\" \n else List.iter (fun e -> printf \"%s\\n\" e) (List.rev (solve n []))\n"}], "src_uid": "1bd1a7fd2a07e3f8633d5bc83d837769"} {"nl": {"description": "At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.Fortunately, Picks remembers something about his set S: its elements were distinct integers from 1 to limit; the value of was equal to sum; here lowbit(x) equals 2k where k is the position of the first one in the binary representation of x. For example, lowbit(100102)\u2009=\u2009102,\u2009lowbit(100012)\u2009=\u200912,\u2009lowbit(100002)\u2009=\u2009100002 (binary representation). Can you help Picks and find any set S, that satisfies all the above conditions?", "input_spec": "The first line contains two integers: sum,\u2009limit (1\u2009\u2264\u2009sum,\u2009limit\u2009\u2264\u2009105).", "output_spec": "In the first line print an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them. If it's impossible to find a suitable set, print -1.", "sample_inputs": ["5 5", "4 3", "5 1"], "sample_outputs": ["2\n4 5", "3\n2 3 1", "-1"], "notes": "NoteIn sample test 1: lowbit(4)\u2009=\u20094,\u2009lowbit(5)\u2009=\u20091,\u20094\u2009+\u20091\u2009=\u20095.In sample test 2: lowbit(1)\u2009=\u20091,\u2009lowbit(2)\u2009=\u20092,\u2009lowbit(3)\u2009=\u20091,\u20091\u2009+\u20092\u2009+\u20091\u2009=\u20094."}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet sum=read_int();;\nlet limit=Scanf.scanf \"%d\" (fun x->x);;\n\nlet rec lowbit n i=\n if (n mod 2)=0 then lowbit (n/2) (i+1) else i;;\n \nlet tab=Array.make 30 [];;\nlet nb=Array.make 30 0;;\n\nlet rec remplir n i=\n if (n mod 2)=0 then (nb.(i)<-0;remplir (n/2) (i+1))\n else (nb.(i)<-1;if n<>1 then remplir (n/2) (i+1));;\n \nremplir sum 1;;\n\nfor i=1 to limit do\n let a=lowbit i 1 in tab.(a)<-i::tab.(a)\ndone;;\n\nlet sol=Array.make 30 0;;\n\nlet rec add x=\n if sol.(x)=0 then sol.(x)<-1 else (sol.(x)<-0;add (x+1));;\n\nlet b=ref true;;\n\nlet tete=function\n|[]->0\n|h::t->h;;\n\nlet queue=function\n|[]->[]\n|h::t->t;;\n\nlet y=ref 0;;\n\nlet liste=ref [];;\n\nlet rec prem i=\n if i=0 then (0,0)\n else if tab.(i)<>[] then (y:=tete tab.(i);tab.(i)<-queue tab.(i); (!y,i))\n else prem (i-1);;\n \nfor i=29 downto 1 do\n while (nb.(i)=1)&&(sol.(i)=0)&&(!b) do\n let (x,z)=prem i in\n if x=0 then b:=false else\n begin\n liste:=x::(!liste);\n add z\n end\n done\ndone;;\n\nlet rec taille=function\n|[]->0\n|h::t->1+taille t;;\n\nlet rec print_list=function\n|[]->print_newline()\n|h::t->Printf.printf \"%d \" h;print_list t;;\n\nif !b=false then print_int (-1) else\n begin\n let x=taille !liste in\n Printf.printf \"%d\\n\" x;\n print_list !liste\n end;;"}], "negative_code": [], "src_uid": "1e4b638810ea9fa83c60a934ad49bf5e"} {"nl": {"description": "Arkady has a playlist that initially consists of $$$n$$$ songs, numerated from $$$1$$$ to $$$n$$$ in the order they appear in the playlist. Arkady starts listening to the songs in the playlist one by one, starting from song $$$1$$$. The playlist is cycled, i.\u00a0e. after listening to the last song, Arkady will continue listening from the beginning.Each song has a genre $$$a_i$$$, which is a positive integer. Let Arkady finish listening to a song with genre $$$y$$$, and the genre of the next-to-last listened song be $$$x$$$. If $$$\\operatorname{gcd}(x, y) = 1$$$, he deletes the last listened song (with genre $$$y$$$) from the playlist. After that he continues listening normally, skipping the deleted songs, and forgetting about songs he listened to before. In other words, after he deletes a song, he can't delete the next song immediately.Here $$$\\operatorname{gcd}(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.For example, if the initial songs' genres were $$$[5, 9, 2, 10, 15]$$$, then the playlist is converted as follows: [5, 9, 2, 10, 15] $$$\\to$$$ [5, 9, 2, 10, 15] $$$\\to$$$ [5, 2, 10, 15] (because $$$\\operatorname{gcd}(5, 9) = 1$$$) $$$\\to$$$ [5, 2, 10, 15] $$$\\to$$$ [5, 2, 10, 15] $$$\\to$$$ [5, 2, 10, 15] $$$\\to$$$ [5, 2, 10, 15] $$$\\to$$$ [5, 2, 10, 15] $$$\\to$$$ [5, 10, 15] (because $$$\\operatorname{gcd}(5, 2) = 1$$$) $$$\\to$$$ [5, 10, 15] $$$\\to$$$ [5, 10, 15] $$$\\to$$$ ... The bold numbers represent the two last played songs. Note that after a song is deleted, Arkady forgets that he listened to that and the previous songs.Given the initial playlist, please determine which songs are eventually deleted and the order these songs are deleted.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of songs. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the genres of the songs. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single line. First, print a single integer $$$k$$$\u00a0\u2014 the number of deleted songs. After that print $$$k$$$ distinct integers: deleted songs in the order of their deletion.", "sample_inputs": ["5\n5\n5 9 2 10 15\n6\n1 2 4 2 4 2\n2\n1 2\n1\n1\n1\n2"], "sample_outputs": ["2 2 3 \n2 2 1 \n2 2 1 \n1 1 \n0"], "notes": "NoteExplanation of the first test case is given in the statement.In the second test case, the playlist is converted as follows: [1, 2, 4, 2, 4, 2] $$$\\to$$$ [1, 2, 4, 2, 4, 2] $$$\\to$$$ [1, 4, 2, 4, 2] (because $$$\\operatorname{gcd}(1, 2) = 1$$$) $$$\\to$$$ [1, 4, 2, 4, 2] $$$\\to$$$ [1, 4, 2, 4, 2] $$$\\to$$$ [1, 4, 2, 4, 2] $$$\\to$$$ [1, 4, 2, 4, 2] $$$\\to$$$ [1, 4, 2, 4, 2] $$$\\to$$$ [4, 2, 4, 2] (because $$$\\operatorname{gcd}(2, 1) = 1$$$) $$$\\to$$$ [4, 2, 4, 2] $$$\\to$$$ ...In the third test case, the playlist is converted as follows: [1, 2] $$$\\to$$$ [1, 2] $$$\\to$$$ [1] (because $$$\\operatorname{gcd}(1, 2) = 1$$$) $$$\\to$$$ [1] $$$\\to$$$ [1] (Arkady listened to the same song twice in a row) $$$\\to$$$ [] (because $$$\\operatorname{gcd}(1, 1) = 1$$$).The fourth test case is same as the third after deletion of the second song.In the fifth test case, the same song is listened to over and over again, but since $$$\\operatorname{gcd}(2, 2) \\ne 1$$$, it is not deleted."}, "positive_code": [{"source_code": "let rec gcd a b = if a=0 then b else gcd (b mod a) a\n\nmodule Iset = Set.Make (struct type t = int let compare = compare end)\n\nopen Iset\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet pred x s = \n let (l,_,_) = split x s in\n max_elt (if is_empty l then s else l)\n\nlet succ x s = \n let (_,_,r) = split x s in\n min_elt (if is_empty r then s else r)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet solve n a = \n let gcd_test i j = gcd a.(i) a.(j) = 1 in\n\n let delete i j present active =\n (* i is active and present. j and its successor, have GCD = 1.\n Remove j, and return (present', active') *)\n if not (gcd_test i j) then failwith \"inconsistent 3\";\n let present = remove j present in\n let active = remove j active in\n if is_empty active then (present, active) else\n let k = succ i present in\n (present, if gcd_test i k then active else remove i active)\n in\n\n let rec loop i present active ac =\n (* i = current place, i must be active\n present = the set of idices that still exist\n active = the indices where that and the successor index in present\n have gcd = 1. *)\n let j = succ i present in\n let (present, active) = delete i j present active in\n let ac = j::ac in\n if is_empty active then ac else\n loop (succ i active) present active ac\n in\n\n let active = fold 0 (n-1) (fun i ac ->\n let j = (i+1) mod n in\n if gcd a.(i) a.(j) = 1 then add i ac else ac\n ) empty in\n\n let present = fold 0 (n-1) (fun i ac -> add i ac) empty in\n\n if is_empty active then [] else\n let i = succ (n-1) active in\n List.rev (loop i present active [])\n\nlet () =\n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let a = Array.init n read_int in\n let answer = solve n a in\n printf \"%d \" (List.length answer);\n List.iter (fun i -> printf \"%d \" (i+1)) answer;\n print_newline()\n done\n"}], "negative_code": [], "src_uid": "5d3d68a5b7a6e1357f4d4318805976ee"} {"nl": {"description": "A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle.A simple cycle in a undirected graph is a sequence of distinct vertices v1,\u2009v2,\u2009...,\u2009vt (t\u2009>\u20092), such that for any i (1\u2009\u2264\u2009i\u2009<\u2009t) exists an edge between vertices vi and vi\u2009+\u20091, and also exists an edge between vertices v1 and vt.A simple path in a undirected graph is a sequence of not necessarily distinct vertices v1,\u2009v2,\u2009...,\u2009vt (t\u2009>\u20090), such that for any i (1\u2009\u2264\u2009i\u2009<\u2009t) exists an edge between vertices vi and vi\u2009+\u20091 and furthermore each edge occurs no more than once. We'll say that a simple path v1,\u2009v2,\u2009...,\u2009vt starts at vertex v1 and ends at vertex vt.You've got a graph consisting of n vertices and m edges, that is a vertex cactus. Also, you've got a list of k pairs of interesting vertices xi,\u2009yi, for which you want to know the following information \u2014 the number of distinct simple paths that start at vertex xi and end at vertex yi. We will consider two simple paths distinct if the sets of edges of the paths are distinct.For each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo 1000000007 (109\u2009+\u20097). ", "input_spec": "The first line contains two space-separated integers n,\u2009m (2\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009m\u2009\u2264\u2009105) \u2014 the number of vertices and edges in the graph, correspondingly. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n) \u2014 the indexes of the vertices connected by the i-th edge. The next line contains a single integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009105) \u2014 the number of pairs of interesting vertices. Next k lines contain the list of pairs of interesting vertices: the i-th line contains two space-separated numbers xi, yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n;\u00a0xi\u2009\u2260\u2009yi) \u2014 the indexes of interesting vertices in the i-th pair. It is guaranteed that the given graph is a vertex cactus. It is guaranteed that the graph contains no loops or multiple edges. Consider the graph vertices are numbered from 1 to n.", "output_spec": "Print k lines: in the i-th line print a single integer \u2014 the number of distinct simple ways, starting at xi and ending at yi, modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["10 11\n1 2\n2 3\n3 4\n1 4\n3 5\n5 6\n8 6\n8 7\n7 6\n7 9\n9 10\n6\n1 2\n3 5\n6 9\n9 2\n9 3\n9 10"], "sample_outputs": ["2\n2\n2\n4\n4\n1"], "notes": null}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet wypelnij p2 n =\n for i=1 to max 20 (n-1) do\n p2.(i) <- (p2.(i-1) * 2) mod (1000*1000*1000+7)\n done;;\n\nlet rec dfs from x tab g vis cykle =\n(* Printf.printf \"dfs %d %d\\n\" from x;*)\n vis.(x) <- true;\n let cykl = ref 0 in\n let rec loop l =\n match l with\n | [] -> ()\n | h::t -> (*Printf.printf \"lista %d, \\n\" h;*)\n if h <> from && vis.(h) && !cykl = 0 then begin (*Printf.printf \"zacykla %d \\n\" h ; *)cykl := h end\n else if h <> from && not vis.(h)\n then let z = dfs x h tab g vis cykle in\n if z <> 0 && !cykl = 0 then cykl := z else ()\n else () ;\n loop t; in\n loop g.(x);\n if !cykl <> 0 then begin tab.(x) <- !cykl ;(* Printf.printf \"na cyklu %d %d\\n\" x !cykl;*)cykle.(x) <- true end;\n(* Printf.printf \"wyjdz z %d\\n\" x;\n*) if !cykl = x || !cykl = 0 then 0\n else !cykl;;\n\nlet rec dfs2 from x tab g dyn ojc gleb vis cykle =\n(* Printf.printf \"dfs2 %d %d\\n\" x tab.(x);\n*) ojc.(0).(x) <- from;\n gleb.(x) <- gleb.(from) + 1;\n if dyn.( tab.(x) ) = 0 then dyn.( tab.(x) ) <- dyn.( tab.(from) );\n if cykle.( tab.(x) ) && not vis.( tab.(x) ) then begin\n vis.( tab.(x) ) <- true;\n dyn.( tab.(x) ) <- dyn.( tab.(x) ) + 1 end;\n List.iter ( fun y -> if y <> 1 && ojc.(0).(y) = 0 then dfs2 x y tab g dyn ojc gleb vis cykle ) g.(x);;\n\nlet przodek p2 ojc x l =\n(* Printf.printf \"przodek %d %d\\n\" x l;\n*) let a = ref x\n and k = ref l in\n for i = 19 downto 0 do\n if p2.(i) <= !k then begin\n(* Printf.printf \"przesun %d %d\\n\" i !a;\n *) a := ojc.(i).(!a);\n k := !k - p2.(i)\n end\n done; !a;;\n\nlet rec lca p2 ojc gleb x y =\n(* Printf.printf \"lca %d %d\\n\" x y;*)\n if gleb.(x) < gleb.(y) then lca p2 ojc gleb y x\n else\n let a = ref ( przodek p2 ojc x (gleb.(x)-gleb.(y)) )\n and b = ref y in\n for i = 19 downto 0 do\n if ojc.(i).(!a) <> ojc.(i).(!b) then begin\n a := ojc.(i).(!a);\n b := ojc.(i).(!b)\n end\n done;\n(* Printf.printf \"lca %d %d %d\\n\" !a !b ojc.(0).(!b);*)\n if !a <> !b then ojc.(0).(!b)\n else !a;;\n \n\nlet _ = \n let (n, m) = read2() in\n let p2 = Array.make ( max 21 n ) 1 in\n wypelnij p2 n;\n let g = Array.make (n+1) [] in\n for i=1 to m do\n let (a,b) = read2 () in\n g.(a) <- b::g.(a);\n g.(b) <- a::g.(b);\n done;\n let tab = Array.init (n+1) ( fun x -> x )\n and vis = Array.make (n+1) false \n and cykl = Array.make (n+1) false in\n dfs 0 1 tab g vis cykl;\n Array.iteri ( fun i _ -> vis.(i) <- false ) vis; (* czyszczenie vis *)\n let dyn = Array.make (n+1) 0\n and ojc = Array.make_matrix 20 (n+1) 0\n and gleb = Array.make (n+1) 0 in\n dfs2 0 1 tab g dyn ojc gleb vis cykl;\n for i=1 to 19 do\n for j=1 to n do\n(* Printf.printf \"%d %d -- %d %d\\n\" i j ojc.(i-1).(j) ojc.(i-1).( ojc.(i-1).(j)); \n*) ojc.(i).(j) <- ojc.(i-1).( ojc.(i-1).(j) )\n done; done;\n let q = read1() in\n for i=1 to q do\n let (a,b) = read2() in\n let c = tab.( lca p2 ojc gleb tab.(a) tab.(b) ) in\n(* Printf.printf \"tab %d %d dyn %d %d\\n\" tab.(a) tab.(b) dyn.( tab.(a) ) dyn.( tab.(b) ); *)\n let wyn = dyn.( tab.(a) ) + dyn.( tab.(b) ) - 2*dyn.( tab.(c) )\n and ww = \n (if cykl.( tab.(c) ) then 1 else 0) in\n(* Printf.printf \"%d %d \" wyn ww; *)\n Printf.printf \"%d\\n\" p2.(wyn + ww)\n done;;\n\n\n"}], "negative_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet wypelnij p2 n =\n for i=1 to max 20 (n-1) do\n p2.(i) <- (p2.(i-1) * 2) mod (1000*1000*1000+7)\n done;;\n\nlet rec dfs from x tab g vis cykle =\n(* Printf.printf \"dfs %d %d\\n\" from x;*)\n vis.(x) <- true;\n let cykl = ref 0 in\n let rec loop l =\n match l with\n | [] -> ()\n | h::t -> (*Printf.printf \"lista %d, \\n\" h;*)\n if h <> from && vis.(h) && !cykl = 0 then begin(* Printf.printf \"zacykla %d \\n\" h ;*) cykl := h end\n else if h <> from && not vis.(h)\n then let z = dfs x h tab g vis cykle in\n if z <> 0 && !cykl = 0 then cykl := z else ()\n else () ;\n loop t; in\n loop g.(x);\n if !cykl <> 0 then begin tab.(x) <- !cykl ; (*Printf.printf \"na cyklu %d %d\\n\" x !cykl;*)cykle.(x) <- true end;\n(* Printf.printf \"wyjdz z %d\\n\" x;\n*) if !cykl = x || !cykl = 0 then 0\n else !cykl;;\n\nlet rec dfs2 from x tab g dyn ojc gleb vis =\n(* Printf.printf \"dfs2 %d %d\\n\" x tab.(x);\n*) ojc.(0).(x) <- from;\n gleb.(x) <- gleb.(from) + 1;\n if dyn.( tab.(x) ) = 0 then dyn.( tab.(x) ) <- dyn.( tab.(from) );\n if tab.(x) <> x && not vis.( tab.(x) ) then begin\n vis.( tab.(x) ) <- true;\n dyn.( tab.(x) ) <- dyn.( tab.(x) ) + 1 end;\n List.iter ( fun y -> if y <> 1 && ojc.(0).(y) = 0 then dfs2 x y tab g dyn ojc gleb vis ) g.(x);;\n\nlet przodek p2 ojc x l =\n(* Printf.printf \"przodek %d %d\\n\" x l;\n*) let a = ref x\n and k = ref l in\n for i = 19 downto 0 do\n if p2.(i) <= !k then begin\n(* Printf.printf \"przesun %d %d\\n\" i !a;\n *) a := ojc.(i).(!a);\n k := !k - p2.(i)\n end\n done; !a;;\n\nlet rec lca p2 ojc gleb x y =\n(* Printf.printf \"lca %d %d\\n\" x y;\n*) if gleb.(x) < gleb.(y) then lca p2 ojc gleb y x\n else\n let a = ref ( przodek p2 ojc x (gleb.(x)-gleb.(y)) )\n and b = ref y in\n for i = 19 downto 0 do\n if ojc.(i).(!a) <> ojc.(i).(!b) then begin\n a := ojc.(i).(!a);\n b := ojc.(i).(!b)\n end\n done;\n(* Printf.printf \"lca %d %d %d\\n\" !a !b ojc.(0).(!b);\n*) if !a <> !b then ojc.(0).(!b)\n else !a;;\n \n\nlet _ = \n let (n, m) = read2() in\n let p2 = Array.make ( max 21 n ) 1 in\n wypelnij p2 n;\n let g = Array.make (n+1) [] in\n for i=1 to m do\n let (a,b) = read2 () in\n g.(a) <- b::g.(a);\n g.(b) <- a::g.(b);\n done;\n let tab = Array.init (n+1) ( fun x -> x )\n and vis = Array.make (n+1) false \n and cykl = Array.make (n+1) false in\n dfs 0 1 tab g vis cykl;\n Array.iteri ( fun i _ -> vis.(i) <- false ) vis; (* czyszczenie vis *)\n let dyn = Array.make (n+1) 0\n and ojc = Array.make_matrix 20 (n+1) 0\n and gleb = Array.make (n+1) 0 in\n dfs2 0 1 tab g dyn ojc gleb vis;\n for i=1 to 19 do\n for j=1 to n do\n(* Printf.printf \"%d %d -- %d %d\\n\" i j ojc.(i-1).(j) ojc.(i-1).( ojc.(i-1).(j)); \n*) ojc.(i).(j) <- ojc.(i-1).( ojc.(i-1).(j) )\n done; done;\n let q = read1() in\n for i=1 to q do\n let (a,b) = read2() in\n let c = tab.( lca p2 ojc gleb tab.(a) tab.(b) )in\n let wyn = dyn.( tab.(a) ) + dyn.( tab.(b) ) - 2*dyn.( tab.( tab.(c) ) )\n and ww = \n (if cykl.(c) then 1 else 0) in\n Printf.printf \"%d\\n\" p2.(wyn + ww)\n done;;\n\n\n"}], "src_uid": "01deb2b3ff08c8c065d2993421c7c43d"} {"nl": {"description": "We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people. After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too. Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009500\u2009000,\u20090\u2009\u2264\u2009k\u2009\u2264\u2009109)\u00a0\u2014 the number of citizens in Kekoland and the number of days left till Robin Hood's retirement. The second line contains n integers, the i-th of them is ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009109)\u00a0\u2014 initial wealth of the i-th person.", "output_spec": "Print a single line containing the difference between richest and poorest peoples wealth.", "sample_inputs": ["4 1\n1 1 4 2", "3 1\n2 2 2"], "sample_outputs": ["2", "0"], "notes": "NoteLets look at how wealth changes through day in the first sample. [1,\u20091,\u20094,\u20092] [2,\u20091,\u20093,\u20092] or [1,\u20092,\u20093,\u20092] So the answer is 3\u2009-\u20091\u2009=\u20092In second sample wealth will remain the same for each person."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n \nlet long x = Int64.of_int x\nlet float = Int64.to_float\nlet abs = Int64.abs\n\nlet rec gcd a b = if a=0L then b else gcd (b %% a) a\n\nlet normalize (a,b) = \n if a=0L then (0L,1L) else \n let g = gcd (abs a) (abs b) in \n if b<0L then (0L--a//g, 0L--b//g) else (a//g, b//g)\nlet ( -/ ) (a,b) (c,d) = normalize (a**d -- b**c, b**d)\nlet ( 0L\n \nlet rat_floor (a,b) = a//b\nlet rat_ceil (a,b) = (a++b--1L)//b\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let moves = long (read_int()) in\n let c = Array.init n (fun i -> long (read_int())) in\n\n Array.sort (fun a b -> compare b a) c;\n for i=0 to n-1 do\n c.(i) <- c.(i) -- c.(n-1)\n done;\n\n if c.(0) = c.(n-1) then printf \"0\\n\"\n else if moves = 0L then printf \"%Ld\\n\" c.(0)\n else \n let make_height_vol_list n c flip =\n let get i = if flip then c.(n-i-1) else c.(i) in\n let rec scan i v ac = if i=n then ac\n\telse\n\t let d = abs ((get (i-1)) -- (get i)) in\n\t if d = 0L then scan (i+1) v ac\n\t else\n\t let v = v ++ d ** (long i) in\n\t let ac = (v, get i) :: ac in\n\t scan (i+1) v ac\n in\n \n Array.of_list (List.rev (scan 1 0L [(0L, get 0)]))\n in\n \n let givefunct = make_height_vol_list n c false in\n let ng = Array.length givefunct in\n\n let takefunct = make_height_vol_list n c true in\n let nt = Array.length takefunct in\n\n let eval funct n x =\n let rec bsearch lo hi =\n\t(* x is in the interval [funct.(lo), funct.(hi)] *)\n\tif lo+1 = hi then (lo, hi)\n\telse\n\t let m = (lo+hi)/2 in\n\t if x <= fst funct.(m) then bsearch lo m else bsearch m hi\n in\n if x > fst funct.(n-1) then failwith \"bad eval\"\n else\n\tlet (lo,hi) = bsearch 0 (n-1) in\n\tlet (x1,y1) = funct.(lo) in\n\tlet (x2,y2) = funct.(hi) in\n\tlet a = x -- x1 in\n\tlet b = x2 -- x in\n\tnormalize (y1 ** b ++ y2 ** a, a ++ b)\n in\n\n let saturated =\n moves > fst givefunct.(ng-1)\n || moves > fst takefunct.(nt-1)\n || (eval givefunct ng moves) takefunct(lo) && givefunct(hi) <= takefunct(hi) *)\n\tif lo ++ 1L = hi then hi\n\telse\n\t let m = (lo ++ hi) // 2L in\n\t let y1 = eval givefunct ng m in\n\t let y2 = eval takefunct nt m in\n\t if y2 \n List.rev acc\n in go []\n\nlet () =\n let xs = read 0 in\n let m = List.fold_left (fun m a -> max m (String.length a)) 0 xs in\n let banner = String.make (m+2) '*' in\n print_endline banner;\n List.fold_left (fun c a ->\n let pad = m - String.length a in\n if pad mod 2 = 0 then (\n Printf.printf \"*%*s%s%*s*\\n\" (pad/2) \"\" a (pad/2) \"\";\n c\n ) else if c then (\n Printf.printf \"*%*s%s%*s*\\n\" (pad/2+1) \"\" a (pad/2) \"\";\n false\n ) else (\n Printf.printf \"*%*s%s%*s*\\n\" (pad/2) \"\" a (pad/2+1) \"\";\n true\n )\n ) false xs;\n print_endline banner\n"}], "negative_code": [], "src_uid": "a017393743ae70a4d8a9d9dc40410653"} {"nl": {"description": "Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change. ", "input_spec": "The first line contains two space-separated integers n,\u2009s (1\u2009\u2264\u2009n,\u2009s\u2009\u2264\u2009100). The i-th of the next n lines contains two integers xi, yi (1\u2009\u2264\u2009xi\u2009\u2264\u2009100;\u00a00\u2009\u2264\u2009yi\u2009<\u2009100), where xi represents the number of dollars and yi the number of cents needed in order to buy the i-th type of sugar.", "output_spec": "Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.", "sample_inputs": ["5 10\n3 90\n12 0\n9 70\n5 50\n7 0", "5 5\n10 10\n20 20\n30 30\n40 40\n50 50"], "sample_outputs": ["50", "-1"], "notes": "NoteIn the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change."}, "positive_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\n\nmodule Array = struct\n include ArrayLabels\n let fold_lefti ~f ~init arr =\n let acc = ref init in\n for i = 0 to Array.length arr - 1 do\n acc := f i !acc arr.(i)\n done;\n !acc\n ;;\nend\nmodule String = StringLabels ;;\nmodule List = struct\n include ListLabels ;;\n let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;\n let rec drop n a =\n if n = 0 then a\n else match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (n - 1) xs ;;\n\n let init ~f n =\n let res = ref [] in\n for i = 0 to n - 1 do\n res := f i :: !res\n done;\n List.rev !res\n ;;\nend ;;\nmodule H = Hashtbl ;;\n\nmodule SI = Set.Make (struct\n type t = int \n let compare = compare\nend)\n\nlet solve n s ss =\n let max = Array.fold_left ~init:(-1) ss ~f:(fun acc (d, c) ->\n let cng = (if c = 0 then 0 else (100 - c)) in\n if s * 100 >= d * 100 + c && acc < cng then cng else acc) in\n pf \"%d\\n\" max\n;;\n \nlet () =\n sf \"%d %d \" (fun n s ->\n let ss = Array.init n ~f:(fun i -> sf \"%d %d \" (fun x y -> x, y)) in\n solve n s ss)\n;;\n"}], "negative_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\n\nmodule Array = struct\n include ArrayLabels\n let fold_lefti ~f ~init arr =\n let acc = ref init in\n for i = 0 to Array.length arr - 1 do\n acc := f i !acc arr.(i)\n done;\n !acc\n ;;\nend\nmodule String = StringLabels ;;\nmodule List = struct\n include ListLabels ;;\n let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;\n let rec drop n a =\n if n = 0 then a\n else match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (n - 1) xs ;;\n\n let init ~f n =\n let res = ref [] in\n for i = 0 to n - 1 do\n res := f i :: !res\n done;\n List.rev !res\n ;;\nend ;;\nmodule H = Hashtbl ;;\n\nmodule SI = Set.Make (struct\n type t = int \n let compare = compare\nend)\n\nlet solve n s ss =\n let max = Array.fold_left ~init:(-1) ss ~f:(fun acc (d, c) ->\n if s * 100 > d * 100 + c && acc < (if c = 0 then 0 else (100 - c)) then 100 - c else acc) in\n pf \"%d\\n\" max\n;;\n \nlet () =\n sf \"%d %d \" (fun n s ->\n let ss = Array.init n ~f:(fun i -> sf \"%d %d \" (fun x y -> x, y)) in\n solve n s ss)\n;;\n"}], "src_uid": "91be5db48b44a44adff4c809ffbb8e3e"} {"nl": {"description": "First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the \"root\" of the word \u2014 some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction \u2014 it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word \"suffix\" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: , where the root of the word is overlined, and suffixes are marked by \"corners\". Thus, the set of possible suffixes for this word is {aca,\u2009ba,\u2009ca}. ", "input_spec": "The only line contains a string s (5\u2009\u2264\u2009|s|\u2009\u2264\u2009104) consisting of lowercase English letters.", "output_spec": "On the first line print integer k \u2014 a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. ", "sample_inputs": ["abacabaca", "abaca"], "sample_outputs": ["3\naca\nba\nca", "0"], "notes": "NoteThe first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let s = read_string() in\n let n = String.length s in\n\n let valid2 = Array.make (n+1) false in\n let valid3 = Array.make (n+1) false in\n (* valid3.(k) means a block starting at k of length 3 is valid *)\n\n valid2.(n-2) <- true;\n valid3.(n-3) <- true;\n\n for k = n-4 downto 5 do\n let sk2x = String.sub s k 2 in\n let sk2y = String.sub s (k+2) 2 in\n let sk3x = String.sub s k 3 in\n let sk3y = if k+6 <= n then String.sub s (k+3) 3 else sk3x in \n let ans = sk2x <> sk2y && valid2.(k+2) in\n let ans = ans || valid3.(k+2) in\n valid2.(k) <- ans;\n let ans = sk3x <> sk3y && valid3.(k+3) in\n let ans = ans || valid2.(k+3) in\n valid3.(k) <- ans\n done;\n\n let stringlist = fold 5 (n-2) (\n fun i ac ->\n fold (i+2) (min n (i+3)) (\n\tfun j ac ->\n\t let sx = String.sub s i (j-i) in\n\t if j-i = 2 then (\n\t if valid2.(i) then sx::ac else ac\n\t ) else (\n\t if valid3.(i) then sx::ac else ac\n\t )\n ) ac\n ) [] in\n\n let stringlist = List.sort_uniq compare stringlist in\n\n printf \"%d\\n\" (List.length stringlist);\n List.iter (printf \"%s\\n\") stringlist\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let s = read_string() in\n let n = String.length s in\n\n let stringlist = fold 5 (n-2) (\n fun i ac ->\n fold (i+2) (min n (i+3)) (\n\tfun j ac ->\n\t if j = n || j <= n-2 then (String.sub s i (j-i))::ac else ac\n ) ac\n ) [] in\n\n let stringlist = List.sort_uniq compare stringlist in\n\n printf \"%d\\n\" (List.length stringlist);\n List.iter (printf \"%s\\n\") stringlist\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let s = read_string() in\n let n = String.length s in\n\n let valid2 = Array.make (n+1) false in\n let valid3 = Array.make (n+1) false in\n (* valid3.(k) means a block starting at k of length 3 is valid *)\n\n valid2.(n-2) <- true;\n valid3.(n-3) <- true;\n\n for k = n-4 downto 5 do\n let sk2x = String.sub s k 2 in\n let sk2y = String.sub s (k+2) 2 in\n let sk3x = String.sub s k 3 in\n let sk3y = if k+5 <= n then String.sub s (k+3) 2 else \"\" in \n let ans = sk2x <> sk2y && valid2.(k+2) in\n let ans = ans || valid3.(k+2) in\n valid2.(k) <- ans;\n let ans = sk3x <> sk3y && valid3.(k+3) in\n let ans = ans || valid2.(k+3) in\n valid3.(k) <- ans\n done;\n\n let stringlist = fold 5 (n-2) (\n fun i ac ->\n fold (i+2) (min n (i+3)) (\n\tfun j ac ->\n\t let sx = String.sub s i (j-i) in\n\t if j-i = 2 then (\n\t if valid2.(i) then sx::ac else ac\n\t ) else (\n\t if valid3.(i) then sx::ac else ac\n\t )\n ) ac\n ) [] in\n\n let stringlist = List.sort_uniq compare stringlist in\n\n printf \"%d\\n\" (List.length stringlist);\n List.iter (printf \"%s\\n\") stringlist\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let s = read_string() in\n let n = String.length s in\n\n let valid2 = Array.make (n+1) false in\n let valid3 = Array.make (n+1) false in\n (* valid3.(k) means a block starting at k of length 3 is valid *)\n\n valid2.(n-2) <- true;\n valid3.(n-3) <- true;\n\n for k = n-4 downto 5 do\n let sk2x = String.sub s k 2 in\n let sk2y = String.sub s (k+2) 2 in\n let sk3x = String.sub s k 3 in\n let sk3y = if k+5 <= n then String.sub s (k+3) 2 else sk3x in \n let ans = sk2x <> sk2y && valid2.(k+2) in\n let ans = ans || valid3.(k+2) in\n valid2.(k) <- ans;\n let ans = sk3x <> sk3y && valid3.(k+3) in\n let ans = ans || valid2.(k+3) in\n valid3.(k) <- ans\n done;\n\n let stringlist = fold 5 (n-2) (\n fun i ac ->\n fold (i+2) (min n (i+3)) (\n\tfun j ac ->\n\t let sx = String.sub s i (j-i) in\n\t if j-i = 2 then (\n\t if valid2.(i) then sx::ac else ac\n\t ) else (\n\t if valid3.(i) then sx::ac else ac\n\t )\n ) ac\n ) [] in\n\n let stringlist = List.sort_uniq compare stringlist in\n\n printf \"%d\\n\" (List.length stringlist);\n List.iter (printf \"%s\\n\") stringlist\n"}], "src_uid": "dd7ccfee8c2a19bf47d65d5a62ac0071"} {"nl": {"description": "A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.", "input_spec": "The first line of the input data contains numbers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950), n \u2014 amount of lines, and m \u2014 amount of columns on Bob's sheet. The following n lines contain m characters each. Character \u00ab.\u00bb stands for a non-shaded square on the sheet, and \u00ab*\u00bb \u2014 for a shaded square. It is guaranteed that Bob has shaded at least one square.", "output_spec": "Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better.", "sample_inputs": ["6 7\n.......\n..***..\n..*....\n..***..\n..*....\n..***..", "3 3\n***\n*.*\n***"], "sample_outputs": ["***\n*..\n***\n*..\n***", "***\n*.*\n***"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let a = Array.init n read_str in\n let u = ref n and b = ref 0 and l = ref m and r = ref 0 in\n for i = 0 to n-1 do\n for j = 0 to m-1 do\n if a.(i).[j]='*' then (\n u := min !u i;\n b := max !b i;\n l := min !l j;\n r := max !r j\n )\n done\n done;\n for i = !u to !b do\n for j = !l to !r do\n print_char a.(i).[j]\n done;\n print_char '\\n'\n done\n"}], "negative_code": [], "src_uid": "d715095ff068f4d081b58fbfe103a02c"} {"nl": {"description": "Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $$$a$$$ coins, Barbara has $$$b$$$ coins and Cerene has $$$c$$$ coins. Recently Polycarp has returned from the trip around the world and brought $$$n$$$ coins.He wants to distribute all these $$$n$$$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $$$A$$$ coins to Alice, $$$B$$$ coins to Barbara and $$$C$$$ coins to Cerene ($$$A+B+C=n$$$), then $$$a + A = b + B = c + C$$$.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all $$$n$$$ coins between sisters in a way described above.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a new line and consists of four space-separated integers $$$a, b, c$$$ and $$$n$$$ ($$$1 \\le a, b, c, n \\le 10^8$$$) \u2014 the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.", "output_spec": "For each test case, print \"YES\" if Polycarp can distribute all $$$n$$$ coins between his sisters and \"NO\" otherwise.", "sample_inputs": ["5\n5 3 2 8\n100 101 102 105\n3 2 1 100000000\n10 20 15 14\n101 101 101 3"], "sample_outputs": ["YES\nYES\nNO\nNO\nYES"], "notes": null}, "positive_code": [{"source_code": "open! Printf;;\n\nmodule String = struct\n\tinclude String\n\tlet split c str =\n\t\tlet str = String.concat \"\" [str; String.make 1 c] in\n\t\tlet cur = ref [] in\n\t\tlet res = ref [] in\n\t\tString.iter (fun a ->\n\t\t\tmatch a = c with\n\t\t\t| false -> cur := (String.make 1 a) :: !cur\n\t\t\t| true -> \n\t\t\t\tlet char_list = List.rev (!cur) in\n\t\t\t\tres := (String.concat \"\" char_list) :: !res;\n\t\t\t\tcur := []) str ;\n\t\t\tList.rev !res \n\t;;\n\t\t\n\nend;;\n\nlet test_num = read_int () in\nfor _i = 1 to test_num do\n\tlet input = read_line () |> String.split ' ' |> List.map int_of_string in\n\tmatch input with \n\t| [a; b; c; n] -> \n\t\tlet max = List.fold_left max a [a; b; c] in\n\t\tlet rest = n - 3*max + a + b + c in\n\t\t(match rest >= 0, rest mod 3 = 0 with\n\t\t| false, _ \n\t\t| true, false -> print_endline \"NO\"\n\t\t| true, true -> print_endline \"YES\")\n\t| _ -> assert false\ndone\n"}], "negative_code": [{"source_code": "module String = struct\n\tinclude String\n\tlet split c str =\n\t\tlet str = String.concat \"\" [str; String.make 1 c] in\n\t\tlet cur = ref [] in\n\t\tlet res = ref [] in\n\t\tString.iter (fun a ->\n\t\t\tmatch a = c with\n\t\t\t| false -> cur := (String.make 1 a) :: !cur\n\t\t\t| true -> \n\t\t\t\tlet char_list = List.rev (!cur) in\n\t\t\t\tres := (String.concat \"\" char_list) :: !res;\n\t\t\t\tcur := []) str ;\n\t\t\t!res \n\t;;\n\t\t\n\nend;;\n\nlet test_num = read_int () in\nfor _i = 1 to test_num do\n\tlet input = read_line () |> String.split ' ' |> List.map int_of_string in\n\tmatch input with \n\t| [a; b; c; n] -> \n\t\tlet max = List.fold_left max a [a; b; c] in\n\t\tlet rest = n - 3*max + a + b + c in\n\t\t(match rest >= 0, rest mod 3 = 0 with\n\t\t| false, _ \n\t\t| true, false -> print_endline \"NO\"\n\t\t| true, true -> print_endline \"YES\")\n\t| _ -> assert false\ndone\n"}], "src_uid": "bc5fb5d6882b86d83e5c86f21d806a52"} {"nl": {"description": "You have integer $$$n$$$. Calculate how many ways are there to fully cover belt-like area of $$$4n-2$$$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $$$2$$$ coverings are different if some $$$2$$$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding. On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for $$$n = 1, 2, 3, 4$$$. You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^{4}$$$)\u00a0\u2014 the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^{9}$$$).", "output_spec": "For each test case, print the number of ways to fully cover belt-like area of $$$4n-2$$$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $$$10^{18}$$$.", "sample_inputs": ["2\n2\n1"], "sample_outputs": ["2\n1"], "notes": "NoteIn the first test case, there are the following $$$2$$$ ways to fill the area: In the second test case, there is a unique way to fill the area: "}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet show_int n = Printf.printf \"%d\\n\" n;;\n\nlet t = scan_int ();;\nfor x = 1 to t do\n\tlet n = scan_int () in\n\tshow_int n\ndone;;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n printf \"%d\\n\" n\n done\n"}], "negative_code": [], "src_uid": "740c05c036b646d8fb6b391af115d7f0"} {"nl": {"description": "Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.Two matrices $$$A$$$ and $$$B$$$ are given, each of them has size $$$n \\times m$$$. Nastya can perform the following operation to matrix $$$A$$$ unlimited number of times: take any square square submatrix of $$$A$$$ and transpose it (i.e. the element of the submatrix which was in the $$$i$$$-th row and $$$j$$$-th column of the submatrix will be in the $$$j$$$-th row and $$$i$$$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $$$A$$$). Nastya's task is to check whether it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$. Example of the operation As it may require a lot of operations, you are asked to answer this question for Nastya.A square submatrix of matrix $$$M$$$ is a matrix which consist of all elements which comes from one of the rows with indeces $$$x, x+1, \\dots, x+k-1$$$ of matrix $$$M$$$ and comes from one of the columns with indeces $$$y, y+1, \\dots, y+k-1$$$ of matrix $$$M$$$. $$$k$$$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ separated by space ($$$1 \\leq n, m \\leq 500$$$)\u00a0\u2014 the numbers of rows and columns in $$$A$$$ and $$$B$$$ respectively. Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$1 \\leq A_{ij} \\leq 10^{9}$$$). Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$1 \\leq B_{ij} \\leq 10^{9}$$$).", "output_spec": "Print \"YES\" (without quotes) if it is possible to transform $$$A$$$ to $$$B$$$ and \"NO\" (without quotes) otherwise. You can print each letter in any case (upper or lower).", "sample_inputs": ["2 2\n1 1\n6 1\n1 6\n1 1", "2 2\n4 4\n4 5\n5 4\n4 4", "3 3\n1 2 3\n4 5 6\n7 8 9\n1 4 7\n2 5 6\n3 8 9"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteConsider the third example. The matrix $$$A$$$ initially looks as follows.$$$$$$ \\begin{bmatrix} 1 & 2 & 3\\\\ 4 & 5 & 6\\\\ 7 & 8 & 9 \\end{bmatrix} $$$$$$Then we choose the whole matrix as transposed submatrix and it becomes$$$$$$ \\begin{bmatrix} 1 & 4 & 7\\\\ 2 & 5 & 8\\\\ 3 & 6 & 9 \\end{bmatrix} $$$$$$Then we transpose the submatrix with corners in cells $$$(2, 2)$$$ and $$$(3, 3)$$$. $$$$$$ \\begin{bmatrix} 1 & 4 & 7\\\\ 2 & \\textbf{5} & \\textbf{8}\\\\ 3 & \\textbf{6} & \\textbf{9} \\end{bmatrix} $$$$$$So matrix becomes$$$$$$ \\begin{bmatrix} 1 & 4 & 7\\\\ 2 & 5 & 6\\\\ 3 & 8 & 9 \\end{bmatrix} $$$$$$and it is $$$B$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet rec iterate i n f =\n if i > n\n then []\n else (f i) :: iterate (i+1) n f\n\nlet diagonal_sort a n m =\n let rec f i k =\n if i > k\n then []\n else if i < n && k - i < m\n then a.(i).(k-i) :: f (i+1) k\n else f (i+1) k in\n iterate 0 (n+m-2) (fun k -> List.fast_sort (fun x y -> x - y) @@ f 0 k)\n\nlet () =\n let n = read_int () in\n let m = read_int () in\n let a = Array.(init n (fun _ -> init m read_int)) in\n let b = Array.(init n (fun _ -> init m read_int)) in\n let ans =\n if diagonal_sort a n m = diagonal_sort b n m\n then \"YES\"\n else \"NO\" in\n printf \"%s\\n\" ans\n"}], "negative_code": [], "src_uid": "77e2ddc4684fccd1856c93c2fc6e1ce2"} {"nl": {"description": "In the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares.Bertown has n squares, numbered from 1 to n, they are numbered in the order of increasing distance between them and the city center. That is, square number 1 is central, and square number n is the farthest from the center. Naturally, the opposition wants to hold a meeting as close to the city center as possible (that is, they want an square with the minimum number).There are exactly k (k\u2009<\u2009n) days left before the demonstration. Now all squares are free. But the Bertown city administration never sleeps, and the approval of an application for the demonstration threatens to become a very complex process. The process of approval lasts several days, but every day the following procedure takes place: The opposition shall apply to hold a demonstration at a free square (the one which isn't used by the administration). The administration tries to move the demonstration to the worst free square left. To do this, the administration organizes some long-term activities on the square, which is specified in the application of opposition. In other words, the administration starts using the square and it is no longer free. Then the administration proposes to move the opposition demonstration to the worst free square. If the opposition has applied for the worst free square then request is accepted and administration doesn't spend money. If the administration does not have enough money to organize an event on the square in question, the opposition's application is accepted. If administration doesn't have enough money to organize activity, then rest of administration's money spends and application is accepted If the application is not accepted, then the opposition can agree to the administration's proposal (that is, take the worst free square), or withdraw the current application and submit another one the next day. If there are no more days left before the meeting, the opposition has no choice but to agree to the proposal of City Hall. If application is accepted opposition can reject it. It means than opposition still can submit more applications later, but square remains free. In order to organize an event on the square i, the administration needs to spend ai bourles. Because of the crisis the administration has only b bourles to confront the opposition. What is the best square that the opposition can take, if the administration will keep trying to occupy the square in question each time? Note that the administration's actions always depend only on the actions of the opposition.", "input_spec": "The first line contains two integers n and k \u2014 the number of squares and days left before the meeting, correspondingly (1\u2009\u2264\u2009k\u2009<\u2009n\u2009\u2264\u2009105). The second line contains a single integer b \u2014 the number of bourles the administration has (1\u2009\u2264\u2009b\u2009\u2264\u20091018). The third line contains n space-separated integers ai \u2014 the sum of money, needed to organise an event on square i (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print a single number \u2014 the minimum number of the square where the opposition can organize the demonstration.", "sample_inputs": ["5 2\n8\n2 4 5 3 1", "5 2\n8\n3 2 4 1 5", "5 4\n1000000000000000\n5 4 3 2 1"], "sample_outputs": ["2", "5", "5"], "notes": "NoteIn the first sample the opposition can act like this. On day one it applies for square 3. The administration has to organize an event there and end up with 3 bourles. If on the second day the opposition applies for square 2, the administration won't have the money to intervene.In the second sample the opposition has only the chance for the last square. If its first move occupies one of the first four squares, the administration is left with at least 4 bourles, which means that next day it can use its next move to move the opposition from any square to the last one.In the third sample administration has a lot of money, so opposition can occupy only last square."}, "positive_code": [{"source_code": "module IntPairSet = Set.Make(\n struct\n type t = int * int\n (*let compare ((x, x') : int * int) (y, y') =\n if x < y\n then -1\n else if x > y\n then 1\n else 0*)\n let compare = compare\n end\n)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let a = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- k\n done;\n in\n let res = ref (n - 1) in\n let ss = ref IntPairSet.empty in\n let s = ref 0L in\n let c = ref 0 in\n for i = n - 2 downto 0 do\n if Int64.add !s (Int64.of_int a.(i)) > b\n then res := i;\n ss := IntPairSet.add (a.(i), i) !ss;\n s := Int64.add !s (Int64.of_int a.(i));\n incr c;\n if !c > k - 1 then (\n\tlet e = IntPairSet.min_elt !ss in\n\tlet v = fst e in\n\t ss := IntPairSet.remove e !ss;\n\t s := Int64.sub !s (Int64.of_int v);\n\t decr c;\n )\n done;\n Printf.printf \"%d\\n\" (!res + 1);\n"}], "negative_code": [{"source_code": "module IntPairSet = Set.Make(\n struct\n type t = int * int\n let compare ((x, x') : int * int) (y, y') =\n if x < y\n then -1\n else if x > y\n then 1\n else 0\n end\n)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let a = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- k\n done;\n in\n let res = ref (n - 1) in\n let ss = ref IntPairSet.empty in\n let s = ref 0L in\n let c = ref 0 in\n for i = n - 1 downto 0 do\n if Int64.add !s (Int64.of_int a.(i)) > b\n then res := i;\n ss := IntPairSet.add (a.(i), i) !ss;\n s := Int64.add !s (Int64.of_int a.(i));\n incr c;\n if !c > k - 1 then (\n\tlet e = IntPairSet.min_elt !ss in\n\tlet v = fst e in\n\t ss := IntPairSet.remove e !ss;\n\t s := Int64.sub !s (Int64.of_int v);\n\t decr c;\n )\n done;\n Printf.printf \"%d\\n\" (!res + 1);\n"}, {"source_code": "module IntPairSet = Set.Make(\n struct\n type t = int * int\n let compare ((x, x') : int * int) (y, y') =\n if x < y\n then -1\n else if x > y\n then 1\n else 0\n end\n)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let a = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- k\n done;\n in\n let res = ref (n - 1) in\n let ss = ref IntPairSet.empty in\n let s = ref 0L in\n let c = ref 0 in\n for i = n - 2 downto 0 do\n if Int64.add !s (Int64.of_int a.(i)) > b\n then res := i;\n ss := IntPairSet.add (a.(i), i) !ss;\n s := Int64.add !s (Int64.of_int a.(i));\n incr c;\n if !c > k - 1 then (\n\tlet e = IntPairSet.min_elt !ss in\n\tlet v = fst e in\n\t ss := IntPairSet.remove e !ss;\n\t s := Int64.sub !s (Int64.of_int v);\n\t decr c;\n )\n done;\n Printf.printf \"%d\\n\" (!res + 1);\n"}], "src_uid": "8cc0271266966b3d0545c48ab82292df"} {"nl": {"description": "Having read half of the book called \"Storm and Calm\" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Innocentius suggested the algorithm of solving equations of the fifth degree in the general case, Ms. Watkins had no other choice but to give him a new task.The teacher asked to write consecutively (without spaces) all words from the \"Storm and Calm\" in one long string s. She thought that a string is good if the number of vowels in the string is no more than twice more than the number of consonants. That is, the string with v vowels and c consonants is good if and only if v\u2009\u2264\u20092c.The task Innocentius had to solve turned out to be rather simple: he should find the number of the longest good substrings of the string s.", "input_spec": "The only input line contains a non-empty string s consisting of no more than 2\u00b7105 uppercase and lowercase Latin letters. We shall regard letters \"a\", \"e\", \"i\", \"o\", \"u\" and their uppercase variants as vowels.", "output_spec": "Print on a single line two numbers without a space: the maximum length of a good substring and the number of good substrings with this length. If no good substring exists, print \"No solution\" without the quotes. Two substrings are considered different if their positions of occurrence are different. So if some string occurs more than once, then it should be counted more than once.", "sample_inputs": ["Abo", "OEIS", "auBAAbeelii", "AaaBRAaaCAaaDAaaBRAaa", "EA"], "sample_outputs": ["3 1", "3 1", "9 3", "18 4", "No solution"], "notes": "NoteIn the first sample there is only one longest good substring: \"Abo\" itself. The other good substrings are \"b\", \"Ab\", \"bo\", but these substrings have shorter length.In the second sample there is only one longest good substring: \"EIS\". The other good substrings are: \"S\", \"IS\"."}, "positive_code": [{"source_code": "\n\nlet getint () = Scanf.scanf \" %d\" (fun i->i)\nlet getstr () = Scanf.bscanf Scanf.Scanning.stdin \"%s\" (fun s -> s)\nlet getval c= \n match c with\n | 'a' | 'e' | 'i' | 'o' | 'u' -> -1\n | _ -> 2\n\nlet _ =\n let s = String.lowercase (getstr ()) in\n let n = String.length s in\n let mn = ref 0 in\n let res = ref ~-1 in\n let mxSub = Array.make 200200 0 in\n let prefix = Array.make 200200 0 in\n let getsum i j = prefix.(j) - (if i=0 then 0 else prefix.(i-1)) in\n for i = 0 to n-1 do\n prefix.(i) <- getval s.[i] + (if i=0 then 0 else prefix.(i-1));\n done;\n for i = 0 to n-1 do\n mxSub.(i) <- prefix.(i) - !mn;\n mn := min !mn prefix.(i);\n let lo = ref 0 and hi = ref i and ans = ref ~-1 in\n while !lo <= !hi do\n let mid = (!lo + !hi) / 2 in\n let right = getsum mid i\n and left = max 0 (if mid=0 then 0 else mxSub.(mid-1)) in\n if left+right>=0 then (ans:= mid; hi := mid-1)\n else lo := mid+1\n done;\n if !ans <> -1 then res := max !res (i - !ans + 1)\n done;\n if !res= -1 then Printf.printf \"No solution\\n\"\n else\n begin\n let cnt = ref 0 in\n for i = 0 to n - !res do\n if getsum i (i + !res - 1) >=0 \n then cnt := !cnt + 1\n done;\n Printf.printf \"%d %d\\n\" !res !cnt\n end"}, {"source_code": "\n\nlet getint () = Scanf.scanf \" %d\" (fun i->i)\nlet getstr () = Scanf.bscanf Scanf.Scanning.stdin \"%s\" (fun s -> s)\nlet getval c= \n\tmatch c with\n\t\t| 'a' | 'e' | 'i' | 'o' | 'u' -> -1\n\t\t| _ -> 2\n\nlet _ =\n let s = String.lowercase (getstr ()) in\n let n = String.length s in\n let mn = ref 0 in\n let res = ref ~-1 in\n let mxSub = Array.make 200200 0 in\n let prefix = Array.make 200200 0 in\n let getsum i j = prefix.(j) - (if i=0 then 0 else prefix.(i-1)) in\n \tfor i = 0 to n-1 do\n \t\tprefix.(i) <- getval s.[i] + (if i=0 then 0 else prefix.(i-1));\n \tdone;\n \tfor i = 0 to n-1 do\n \t\tmxSub.(i) <- prefix.(i) - !mn;\n \t\tmn := min !mn prefix.(i);\n \t\tlet lo = ref 0 and hi = ref i and ans = ref ~-1 in\n \t\t\twhile !lo <= !hi do\n \t\t\t\tlet mid = (!lo + !hi) / 2 in\n\t \t\t\t\tlet right = getsum mid i\n\t \t\t\t\tand left = max 0 (if mid=0 then 0 else mxSub.(mid-1)) in\n\t \t\t\t\t\tif left+right>=0 then (ans:= mid; hi := mid-1)\n\t \t\t\t\t\telse lo := mid+1\n \t\t\tdone;\n \t\t\tif !ans <> -1 then res := max !res (i - !ans + 1)\n \tdone;\n \tif !res= -1 then Printf.printf \"No solution\\n\"\n \telse\n \t\tbegin\n \t\t\tlet cnt = ref 0 in\n\t \t\t\tfor i = 0 to n - !res do\n\t \t\t\t\tif getsum i (i + !res - 1) >=0 \n\t \t\t\t\tthen cnt := !cnt + 1\n\t \t\t\tdone;\n\t \t\t\tPrintf.printf \"%d %d\\n\" !res !cnt\n \t\tend"}, {"source_code": "let main() =\n let f = function\n 'a' | 'e' | 'i' | 'o' | 'u' -> -1\n | _ -> 2\n in\n let s = Scanf.scanf \"%s\" String.lowercase in\n let n = String.length s in\n let a = Array.init n (fun i -> (f s.[i])) in\n let b = Array.create (n+1) 0 in\n Array.iteri (fun i x -> b.(i+1) <- b.(i) + x) a;\n let c = Array.mapi (fun i x -> x, i) b in\n Array.stable_sort (fun x y -> compare (fst x) (fst y)) c;\n let rec g k j maxl tot =\n if k < 0 then maxl, tot\n else\n let i = snd c.(k) in\n if i > j then g (k-1) i maxl tot\n else (\n let l = j - i in\n if l < maxl then g (k-1) j maxl tot\n else g (k-1) j l (if l == maxl then (tot+1) else 1)\n )\n in\n let r,v = g n 0 0 0 in\n if r > 0 then Printf.printf \"%d %d\\n\" r v else Printf.printf \"No solution\\n\"\n ;;\nmain()"}, {"source_code": "let min (x : int) y = if x < y then x else y\n\nlet fr n = n + (n land (-n))\nlet fl n = n land (n - 1)\n\nlet fenwick_new n =\n Array.make (n + 1) 1000000000\n\nlet fenwick_modify ft n x =\n let i = ref n in\n while !i < Array.length ft do\n ft.(!i) <- min ft.(!i) x;\n i := fr !i;\n done\n\nlet fenwick_min ft n =\n let i = ref n in\n let res = ref 1000000000 in\n while !i > 0 do\n res := min !res ft.(!i);\n i := fl !i;\n done;\n !res\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let ft = fenwick_new 800000 in\n let sum = ref 300000 in\n let res = ref (-1) in\n let a = Array.make (n + 1) !sum in\n fenwick_modify ft !sum 0;\n for i = 0 to n - 1 do\n let c = s.[i] in\n\t(match c with\n\t | 'a' | 'e' | 'i' | 'o' | 'u'\n\t | 'A' | 'E' | 'I' | 'O' | 'U' ->\n\t decr sum;\n\t | _ ->\n\t sum := !sum + 2\n\t);\n\tlet l = fenwick_min ft !sum in\n\t (*Printf.printf \"asd %d %d %d\\n\" i !sum l;*)\n\t if l < 1000000000 && i + 1 - l > !res then (\n\t res := i + 1 - l\n\t );\n\t fenwick_modify ft !sum (i + 1);\n\t a.(i + 1) <- !sum\n done;\n if !res < 0\n then Printf.printf \"No solution\\n\"\n else (\n let c = ref 0 in\n\tfor i = !res to n do\n\t if a.(i) - a.(i - !res) >= 0\n\t then incr c\n\tdone;\n\tPrintf.printf \"%d %d\\n\" !res !c;\n )\n"}, {"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet s = String.lowercase (read_string ())\nlet n = String.length s\n\nlet start = n\n\nlet leftmost = Array.init (3*n+1) (fun i -> if i>=start then 0 else max_int/2)\n\nlet is_vowel c = match c with 'a' | 'e' | 'i' | 'o' | 'u' -> true | _ -> false\n\n(* we've processed chars 0,1,2...i-1, and have the height and best for that *)\nlet rec fill_leftmost i height best = if i=n then (height,best) else\n if is_vowel s.[i] then (\n leftmost.(height-1) <- min leftmost.(height-1) (i+1);\n fill_leftmost (i+1) (height-1) (max best (i+1-leftmost.(height-1)))\n ) else (\n leftmost.(height+1) <- min leftmost.(height+1) i;\n leftmost.(height+2) <- min leftmost.(height+2) (i+1);\n fill_leftmost (i+1) (height+2) (max best (i+1-leftmost.(height+2)))\n )\n\nlet (height,best) = fill_leftmost 0 start 0\n\nlet rec complete h b = if h<0 then b else\n complete (h-1) (max b (n - leftmost.(h)))\n\nlet best = complete height best\n\nlet cvowel i = if is_vowel s.[i] then 1 else 0\n\n(* vow for the range i....i+best-1, count for the previous one *)\nlet rec count_strings i count vow =\n let count = count + (if vow<=2*(best-vow) then 1 else 0) in\n if i+best-1 = n-1 then count else\n let vow = vow - (cvowel i) + (cvowel (i+best)) in\n count_strings (i+1) count vow\n\nlet rec count_vow i count = \n if i=best then count else count_vow (i+1) (count + (cvowel i))\n\nlet () = \n if best = 0\n then Printf.printf \"No solution\\n\"\n else Printf.printf \"%d %d\\n\" best (count_strings 0 0 (count_vow 0 0))\n"}, {"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet s = String.lowercase (read_string ())\nlet n = String.length s\n\nlet start = n\n\nlet leftmost = Array.init (3*n+1) (fun i -> if i>=start then 0 else max_int/2)\n\nlet is_vowel c = match c with 'a' | 'e' | 'i' | 'o' | 'u' -> true | _ -> false\n\n(* we've processed chars 0,1,2...i-1, and have the height and best for that *)\nlet rec fill_leftmost i height bc = if i=n then bc else\n let best_count (b,c) nb = if nb < b then (b,c) else if nb = b then (b,c+1) else (nb, 1) in\n if is_vowel s.[i] then (\n leftmost.(height-1) <- min leftmost.(height-1) (i+1);\n fill_leftmost (i+1) (height-1) (best_count bc (i+1-leftmost.(height-1)))\n ) else (\n leftmost.(height+1) <- min leftmost.(height+1) i;\n leftmost.(height+2) <- min leftmost.(height+2) (i+1);\n fill_leftmost (i+1) (height+2) (best_count bc (i+1-leftmost.(height+2)))\n )\n\nlet (best,count) = fill_leftmost 0 start (0,1)\n\nlet () = \n if best = 0\n then Printf.printf \"No solution\\n\"\n else Printf.printf \"%d %d\\n\" best count\n"}], "negative_code": [{"source_code": "let main() =\n let f = function\n 'a' | 'e' | 'i' | 'o' | 'u' | 'y' -> -1\n | _ -> 2\n in\n let s = Scanf.scanf \"%s\" String.lowercase in\n let n = String.length s in\n let a = Array.init n (fun i -> (f s.[i])) in\n let b = Array.create (n+1) 0 in\n Array.iteri (fun i x -> b.(i+1) <- b.(i) + x) a;\n let c = Array.mapi (fun i x -> x, i) b in\n Array.stable_sort (fun x y -> compare (fst x) (fst y)) c;\n let rec g k j maxl tot =\n if k < 0 then maxl, tot\n else\n let i = snd c.(k) in\n if i > j then g (k-1) i maxl tot\n else (\n let l = j - i in\n if l < maxl then g (k-1) j maxl tot\n else g (k-1) j l (if l == maxl then (tot+1) else 1)\n )\n in\n let r,v = g n 0 0 0 in\n if r > 0 then Printf.printf \"%d %d\\n\" r v else Printf.printf \"No solution\\n\"\n ;;\nmain()"}, {"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet s = String.lowercase (read_string ())\nlet n = String.length s\n\nlet start = n\n\nlet leftmost = Array.init (3*n+1) (fun i -> if i>=start then 0 else max_int/2)\n\nlet is_vowel c = match c with 'a' | 'e' | 'i' | 'o' | 'u' -> true | _ -> false\n\n(* we've processed chars 0,1,2...i-1, and have the height and best for that *)\nlet rec fill_leftmost i height best = if i=n then (height,best) else\n if is_vowel s.[i] then (\n leftmost.(height-1) <- min leftmost.(height-1) (i+1);\n fill_leftmost (i+1) (height-1) (max best (i+1-leftmost.(height-1)))\n ) else (\n leftmost.(height+1) <- min leftmost.(height+1) i;\n leftmost.(height+2) <- min leftmost.(height+2) (i+1);\n fill_leftmost (i+1) (height+2) (max best (i+1-leftmost.(height+2)))\n )\n\nlet (height,best) = fill_leftmost 0 start 0\n\nlet rec complete h b = if h<0 then b else\n complete (h-1) (max b (n - leftmost.(h)))\n\nlet best = complete height best\n\nlet cvowel i = if is_vowel s.[i] then 1 else 0\n\n(* vow for the range i....i+best-1, count for the previous one *)\nlet rec count_strings i count vow =\n let count = count + (if vow<=2*(best-vow) then 1 else 0) in\n if i+best-1 = n-1 then count else\n let vow = vow - (cvowel i) + (cvowel (i+best)) in\n count_strings (i+1) count vow\n\nlet rec count_vow i count = \n if i=best then count else count_vow (i+1) (count + (cvowel i))\n\n;;\n\nPrintf.printf \"%d %d\\n\" best (count_strings 0 0 (count_vow 0 0))\n"}], "src_uid": "763aa950a9a8e5c975a6028e014de20f"} {"nl": {"description": "You are playing another computer game, and now you have to slay $$$n$$$ monsters. These monsters are standing in a circle, numbered clockwise from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th monster has $$$a_i$$$ health.You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by $$$1$$$ (deals $$$1$$$ damage to it). Furthermore, when the health of some monster $$$i$$$ becomes $$$0$$$ or less than $$$0$$$, it dies and explodes, dealing $$$b_i$$$ damage to the next monster (monster $$$i + 1$$$, if $$$i < n$$$, or monster $$$1$$$, if $$$i = n$$$). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.You have to calculate the minimum number of bullets you have to fire to kill all $$$n$$$ monsters in the circle.", "input_spec": "The first line contains one integer $$$T$$$ ($$$1 \\le T \\le 150000$$$) \u2014 the number of test cases. Then the test cases follow, each test case begins with a line containing one integer $$$n$$$ ($$$2 \\le n \\le 300000$$$) \u2014 the number of monsters. Then $$$n$$$ lines follow, each containing two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le a_i, b_i \\le 10^{12}$$$) \u2014 the parameters of the $$$i$$$-th monster in the circle. It is guaranteed that the total number of monsters in all test cases does not exceed $$$300000$$$.", "output_spec": "For each test case, print one integer \u2014 the minimum number of bullets you have to fire to kill all of the monsters.", "sample_inputs": ["1\n3\n7 15\n2 14\n5 3"], "sample_outputs": ["6"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x)\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let n = read_int () in\n let a = Array.make n 0L in\n let b = Array.make n 0L in\n let need = Array.make n 0L in\n for i=0 to n-1 do\n a.(i) <- read_long();\n b.(i) <- read_long()\n done;\n\n let needtot = ref 0L in\n for i=0 to n-1 do\n need.(i) <- max 0L (a.(i) -- b.((i+n-1) mod n));\n needtot := !needtot ++ need.(i)\n done;\n\n let starter = max 1L (minf 0 (n-1) (fun i -> a.(i) -- need.(i))) in\n\n printf \"%Ld\\n\" (starter ++ !needtot)\n done\n"}], "negative_code": [], "src_uid": "414d1f0cef26fbbf4ede8eac32a1dd48"} {"nl": {"description": "A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q\u2009=\u2009[4,\u20095,\u20091,\u20092,\u20093] is a permutation. For the permutation q the square of permutation is the permutation p that p[i]\u2009=\u2009q[q[i]] for each i\u2009=\u20091... n. For example, the square of q\u2009=\u2009[4,\u20095,\u20091,\u20092,\u20093] is p\u2009=\u2009q2\u2009=\u2009[2,\u20093,\u20094,\u20095,\u20091].This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2\u2009=\u2009p. If there are several such q find any of them.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of elements in permutation p. The second line contains n distinct integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) \u2014 the elements of permutation p.", "output_spec": "If there is no permutation q such that q2\u2009=\u2009p print the number \"-1\". If the answer exists print it. The only line should contain n different integers qi (1\u2009\u2264\u2009qi\u2009\u2264\u2009n) \u2014 the elements of the permutation q. If there are several solutions print any of them.", "sample_inputs": ["4\n2 1 4 3", "4\n2 1 3 4", "5\n2 3 4 5 1"], "sample_outputs": ["3 4 2 1", "-1", "4 5 1 2 3"], "notes": null}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet length = Array.length\nlet print_array l = Array.iter (fun a -> printf \"%d \" (a+1)) l\nlet print_array2 l = Array.iter (fun a -> print_array a; print_newline ()) l\nlet square p =\n let n = Array.length p in\n Array.init n (fun a -> p.(p.(a)))\n\nlet read_int _ = scanf \" %d\" (fun x -> x)\nlet read_perm _ = scanf \" %d\" (fun x -> (x-1))\nlet read_array num =\n Array.init num read_perm\n\nlet add x l =\n l := (x :: !l)\n\ntype permutation = int array\n\nlet split_cycles ar =\n let n = Array.length ar in\n let visited = Array.make n false\n and out = ref [] in\n for i = 0 to n-1 do\n if not visited.(i) then\n begin\n let per = ref [] and x = ref i in\n while not visited.(!x) do\n add (!x) per;\n visited.(!x) <- true;\n x := ar.(!x)\n done;\n let x = Array.of_list (List.rev !per)\n in add x out\n end\n done;\n Array.of_list !out\n\nlet cmp a b =\n Array.length a - Array.length b\n\nlet root_odd ar =\n let n = Array.length ar in\n let m = (n+1)/2 in\n assert (n mod 2 = 1);\n Array.init n (fun x -> if x mod 2 = 0 then ar.(x/2) else ar.(m + x/2))\n\nlet root_even a b =\n assert (Array.length a = Array.length b);\n assert (Array.length a mod 2 = 0);\n let n = Array.length a in\n Array.init (2*n) (fun x -> if x mod 2 = 0 then a.(x/2) else b.(x/2))\n\nlet get_answer ar = (* assume sorted *)\n let n = Array.length ar\n and i = ref 0\n and out = ref []\n and error = ref false in\n while !i < n do\n let l = Array.length ar.(!i) in\n if l mod 2 = 0 then\n begin\n if !i = n - 1 then (incr i; error := true)\n else if Array.length ar.(!i + 1) <> l then (i := n; error := true)\n else (add (root_even ar.(!i) ar.(!i + 1)) out; i := !i + 2)\n end\n else\n begin\n add (root_odd ar.(!i)) out;\n incr i\n end\n done;\n if !error then [||]\n else Array.of_list !out\n\nlet convert n ar =\n let out = Array.make n 0\n and k = Array.length ar in\n for i = 0 to k - 1 do\n let a = ar.(i) in\n let l = Array.length a in\n for j = 0 to l - 1 do\n if j = l - 1 then out.(a.(j)) <- a.(0)\n else out.(a.(j)) <- a.(j+1)\n done\n done;\n out\n\n\nlet n = read_int ()\nlet ar = read_array n\nlet cycles = split_cycles ar\nlet () = Array.sort cmp cycles\n(*let () = print_array2 cycles; print_endline \"====================\"*)\nlet ans = get_answer cycles\nlet () =\n if ans = [||] then printf \"-1\\n\"\n else\n let out = convert n ans in\n print_array out (*; print_string \"\\nSquare:\\n\"; print_array (square out) *)\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1\n done;\n let u = Array.make n false in\n let cs = ref [] in\n let _ =\n for i = 0 to n - 1 do\n\tif not u.(i) then (\n\t let pos = ref i in\n\t let c = ref [] in\n\t while not u.(!pos) do\n\t u.(!pos) <- true;\n\t c := !pos :: !c;\n\t pos := a.(!pos);\n\t done;\n\t let c = Array.of_list (List.rev !c) in\n\t cs := (Array.length c, c) :: !cs\n\t)\n done;\n in\n let cs = Array.of_list !cs in\n let res = Array.make n 0 in\n let skip = ref false in\n Array.sort compare cs;\n for i = 0 to Array.length cs - 1 do\n\tif not !skip then (\n\tlet (k, p) = cs.(i) in\n(*Printf.printf \"qwe %d\\n\" k;*)\n\t if k mod 2 <> 0 then (\n\t for j = 0 to k - 1 do\n\t res.(p.(j)) <- p.((j + k / 2 + 1) mod k)\n\t done;\n\t ) else (\n\t if i + 1 < Array.length cs && fst (cs.(i + 1)) = k then (\n\t let (_, p') = cs.(i + 1) in\n\t\tfor j = 0 to k - 1 do\n(*Printf.printf \"asd %d %d %d %d\\n\" i k p.(j) p'.(j);*)\n\t\t res.(p.(j)) <- p'.(j);\n\t\t res.(p'.(j)) <- p.((j + 1) mod k)\n\t\tdone;\n\t\tskip := true;\n\t ) else (\n\t Printf.printf \"-1\\n\";\n\t exit 0;\n\t )\n\t )\n\t) else skip := false\n done;\n for i = 0 to n - 1 do\n\tPrintf.printf \"%d \" (res.(i) + 1);\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "open Scanf\nopen Printf\n\nlet length = Array.length\nlet print_array l = Array.iter (fun a -> printf \"%d \" a) l\nlet print_array2 l = Array.iter (fun a -> print_array a; print_newline ()) l\nlet square p =\n let n = Array.length p in\n Array.init n (fun a -> p.(p.(a)-1))\n\nlet read_int _ = scanf \" %d\" (fun x -> x)\nlet read_array num =\n Array.init num read_int\n\nlet add x l =\n l := (x :: !l)\n\ntype permutation = int array\n\nlet split_cycles ar =\n let n = Array.length ar in\n let visited = Array.make n false\n and out = ref [] in\n for i = 0 to n-1 do\n if not visited.(i) then\n let per = ref [] and x = ref i in\n while not visited.(!x) do\n add (!x + 1) per;\n visited.(!x) <- true;\n x := ar.(!x) - 1\n done;\n let x = Array.of_list (List.rev !per)\n in add x out\n done;\n Array.of_list !out\n\nlet cmp a b =\n Array.length a - Array.length b\n\nlet root_odd ar =\n let n = Array.length ar in\n assert (n mod 2 = 1);\n Array.init n (fun a -> ar.(2*a mod n))\n\nlet root_even a b =\n assert (Array.length a = Array.length b);\n assert (Array.length a mod 2 = 0);\n let n = Array.length a in\n Array.init (2*n) (fun x -> if x mod 2 = 0 then a.(x/2) else b.(x/2))\n\nlet get_answer ar = (* assume sorted *)\n let n = Array.length ar\n and i = ref 0\n and out = ref []\n and error = ref false in\n while !i < n do\n let l = Array.length ar.(!i) in\n if l mod 2 = 0 then\n begin\n if !i = n - 1 then (incr i; error := true)\n else if Array.length ar.(!i + 1) <> l then (i := n; error := true)\n else (add (root_even ar.(!i) ar.(!i + 1)) out; i := !i + 2)\n end\n else\n begin\n add (root_odd ar.(!i)) out;\n incr i\n end\n done;\n if !error then [||]\n else Array.of_list !out\n\nlet convert n ar =\n let out = Array.make n 0\n and k = Array.length ar in\n for i = 0 to k - 1 do\n let a = ar.(i) in\n let l = Array.length a in\n for j = 0 to l - 1 do\n if j = l - 1 then out.(a.(j)-1) <- a.(0)\n else out.(a.(j)-1) <- a.(j+1)\n done\n done;\n out\n\n\nlet n = read_int ()\nlet ar = read_array n\nlet cycles = split_cycles ar\nlet () = Array.sort cmp cycles\n(*let () = print_array2 cycles; print_endline \"====================\"*)\nlet ans = get_answer cycles\nlet () =\n if ans = [||] then printf \"-1\\n\"\n else\n let out = convert n ans in\n print_array out (*; print_string \"\\nSquare:\\n\"; print_array (square out) *)\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet length = Array.length\nlet print_array l = Array.iter (fun a -> printf \"%d \" a) l\nlet print_array2 l = Array.iter (fun a -> print_array a; print_newline ()) l\n\nlet read_int _ = scanf \" %d\" (fun x -> x)\nlet read_array num =\n Array.init num read_int\n\nlet add x l =\n l := (x :: !l)\n\ntype permutation = int array\n\nlet split_cycles ar =\n let n = Array.length ar in\n let visited = Array.make n false\n and out = ref [] in\n for i = 0 to n-1 do\n if not visited.(i) then\n let per = ref [] and x = ref i in\n while not visited.(!x) do\n add (!x + 1) per;\n visited.(!x) <- true;\n x := ar.(!x) - 1\n done;\n let x = Array.of_list !per\n in add x out\n done;\n Array.of_list !out\n\nlet cmp a b =\n Array.length a - Array.length b\n\nlet root_odd ar =\n let n = Array.length ar in\n assert (n mod 2 = 1);\n Array.init n (fun a -> ar.(2*a mod n))\n\nlet root_even a b =\n assert (Array.length a = Array.length b);\n assert (Array.length a mod 2 = 0);\n let n = Array.length a in\n Array.init (2*n) (fun x -> if x mod 2 = 0 then a.(x/2) else b.(x/2))\n\nlet get_answer ar = (* assume sorted *)\n let n = Array.length ar\n and i = ref 0\n and out = ref []\n and error = ref false in\n while !i < n do\n let l = Array.length ar.(!i) in\n if l mod 2 = 0 then\n begin\n if !i = n - 1 then (incr i; error := true)\n else if Array.length ar.(!i + 1) <> l then (i := n; error := true)\n else (add (root_even ar.(!i) ar.(!i + 1)) out; i := !i + 2)\n end\n else\n begin\n add (root_odd ar.(!i)) out;\n incr i\n end\n done;\n if !error then [||]\n else Array.of_list !out\n\nlet convert n ar =\n let out = Array.make n 0\n and k = Array.length ar in\n for i = 0 to k - 1 do\n let a = ar.(i) in\n let l = Array.length a in\n for j = 0 to l - 1 do\n if j = l - 1 then out.(a.(j)-1) <- a.(0)\n else out.(a.(j)-1) <- a.(j+1)\n done\n done;\n out\n\n\nlet n = read_int ()\nlet ar = read_array n\nlet cycles = split_cycles ar\nlet _ = Array.sort cmp cycles\nlet ans = get_answer cycles\nlet () =\n if ans = [||] then printf \"-1\\n\"\n else\n let out = convert n ans in\n print_array out\n"}], "src_uid": "f52a4f8c4d84733a8e78a5825b63bdbc"} {"nl": {"description": "The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.", "input_spec": "The first line contains an integer n, which is the number of people in the crew (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Then follow n lines. The i-th of those lines contains two words \u2014 the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.", "output_spec": "Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.", "sample_inputs": ["6\nJack captain\nAlice woman\nCharlie man\nTeddy rat\nBob child\nJulia woman"], "sample_outputs": ["Teddy\nAlice\nBob\nJulia\nCharlie\nJack"], "notes": null}, "positive_code": [{"source_code": "module Person = struct\n\ttype t = \n\t\tRat of string | \n\t\tWoman of string | \n\t\tChild of string | \n\t\tMan of string | \n\t\tCaptain of string \n\t;;\n\tlet priority = function\n\t\t| Rat _ -> 3\n\t\t| (Woman _|Child _) -> 2\n\t\t| Man _ -> 1\n\t\t| Captain _ -> 0\n\t;;\n\tlet compare a b =\n\t\tpriority b - priority a\n\t;;\n\tlet of_string n t =\n\t\tmatch t with\n\t\t| \"rat\" -> Rat n\n\t\t| \"woman\" -> Woman n\n\t\t| \"child\" -> Child n\n\t\t| \"man\" -> Man n\n\t\t| \"captain\" -> Captain n\t\n\t\t| _ -> invalid_arg \"Undefined rank\"\t\n\t;;\n\tlet to_string = function\n\t\t| Rat s -> s\n\t\t| Woman s -> s\n\t\t| Child s -> s\n\t\t| Man s -> s\n\t\t| Captain s -> s\n\t;;\nend;;\n\nlet () = \n\tlet n = read_int () in\n\tlet persons = Array.init n (fun _ ->\n\t\tScanf.scanf \" %s %s\" Person.of_string\n\t) in\n\tlet _ = Array.stable_sort Person.compare persons in\n\t\tArray.iter (fun p ->\n\t\t\tPrintf.printf \"%s\\n\" (Person.to_string p)\n\t\t) persons\n;;\n"}], "negative_code": [], "src_uid": "753113fa5130a67423f2e205c97f8017"} {"nl": {"description": "Permutation $$$p$$$ is a sequence of integers $$$p=[p_1, p_2, \\dots, p_n]$$$, consisting of $$$n$$$ distinct (unique) positive integers between $$$1$$$ and $$$n$$$, inclusive. For example, the following sequences are permutations: $$$[3, 4, 1, 2]$$$, $$$[1]$$$, $$$[1, 2]$$$. The following sequences are not permutations: $$$[0]$$$, $$$[1, 2, 1]$$$, $$$[2, 3]$$$, $$$[0, 1, 2]$$$.The important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation $$$p$$$ of length $$$n$$$. You don't know this permutation, you only know the array $$$q$$$ of prefix maximums of this permutation. Formally: $$$q_1=p_1$$$, $$$q_2=\\max(p_1, p_2)$$$, $$$q_3=\\max(p_1, p_2,p_3)$$$, ... $$$q_n=\\max(p_1, p_2,\\dots,p_n)$$$. You want to construct any possible suitable permutation (i.e. any such permutation, that calculated $$$q$$$ for this permutation is equal to the given array).", "input_spec": "The first line contains integer number $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains one integer $$$n$$$ $$$(1 \\le n \\le 10^{5})$$$\u00a0\u2014 the number of elements in the secret code permutation $$$p$$$. The second line of a test case contains $$$n$$$ integers $$$q_1, q_2, \\dots, q_n$$$ $$$(1 \\le q_i \\le n)$$$\u00a0\u2014 elements of the array $$$q$$$ for secret permutation. It is guaranteed that $$$q_i \\le q_{i+1}$$$ for all $$$i$$$ ($$$1 \\le i < n$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.", "output_spec": "For each test case, print: If it's impossible to find such a permutation $$$p$$$, print \"-1\" (without quotes). Otherwise, print $$$n$$$ distinct integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$). If there are multiple possible answers, you can print any of them. ", "sample_inputs": ["4\n5\n1 3 4 5 5\n4\n1 1 3 4\n2\n2 2\n1\n1"], "sample_outputs": ["1 3 4 5 2 \n-1\n2 1 \n1"], "notes": "NoteIn the first test case of the example answer $$$[1,3,4,5,2]$$$ is the only possible answer: $$$q_{1} = p_{1} = 1$$$; $$$q_{2} = \\max(p_{1}, p_{2}) = 3$$$; $$$q_{3} = \\max(p_{1}, p_{2}, p_{3}) = 4$$$; $$$q_{4} = \\max(p_{1}, p_{2}, p_{3}, p_{4}) = 5$$$; $$$q_{5} = \\max(p_{1}, p_{2}, p_{3}, p_{4}, p_{5}) = 5$$$. It can be proved that there are no answers for the second test case of the example."}, "positive_code": [{"source_code": "module IS = Set.Make(struct type t = int let compare = compare end)\n\nlet rec to_set m =\n if m = 0 then\n []\n else\n m::(to_set (m-1))\n\nlet previous = ref (-1)\nlet rec remove x l =\n match l with\n | [] -> assert false\n | y::l -> if x = y then l\n else\n y::(remove x l)\n\nlet rec find_perm l p cand s =\n match l with\n | [] -> p\n | x::l ->\n let cand',y =\n if x = !previous && !previous <> -1 then\n let rec find = function\n | [] -> failwith \"Oops\"\n | y::l ->\n if y <= x then\n if IS.mem y s then find l else l,y\n else\n failwith \"Oops\"\n in find cand\n else\n cand,x\n in\n previous := x;\n find_perm l (y::p) cand' (IS.add y s)\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n previous := -1;\n let m = int_of_string (input_line stdin) in\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n let set = List.rev @@ to_set m in\n let rec pp fmt = function\n | [] -> Format.fprintf fmt \"\"\n | [x] -> Format.fprintf fmt \"%d\" x\n | x::l -> Format.fprintf fmt \"%d %a\" x pp l\n in\n try\n let l' = List.rev @@ find_perm l [] set IS.empty in\n Format.printf \"%a@.\" pp l'\n with _ -> Format.printf \"-1@.\"\n done\n"}], "negative_code": [{"source_code": "module IS = Set.Make(struct type t = int let compare = compare end)\n\nlet rec to_set m =\n if m = 0 then\n IS.empty\n else\n IS.add m (to_set (m-1))\n\nlet previous = ref (-1)\n\nlet rec find_perm l p s =\n match l with\n | [] -> p\n | x::l ->\n let y = if x = !previous && !previous <> -1 then\n IS.choose (IS.filter (fun y -> y <= x) s)\n else\n x\n in\n previous := x;\n let s' = IS.remove y s in\n find_perm l (y::p) s'\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let m = int_of_string (input_line stdin) in\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n let set = to_set m in\n let rec pp fmt = function\n | [] -> Format.fprintf fmt \"\"\n | [x] -> Format.fprintf fmt \"%d\" x\n | x::l -> Format.fprintf fmt \"%d %a\" x pp l\n in\n try\n let l' = List.rev @@ find_perm l [] set in\n Format.printf \"%a@.\" pp l'\n with _ -> Format.printf \"-1@.\"\n done\n"}, {"source_code": "module IS = Set.Make(struct type t = int let compare = compare end)\n\nlet rec to_set m =\n if m = 0 then\n []\n else\n m::(to_set (m-1))\n\nlet previous = ref (-1)\nlet rec remove x l =\n match l with\n | [] -> assert false\n | y::l -> if x = y then l\n else\n y::(remove x l)\n\nlet rec find_perm l p s =\n match l with\n | [] -> p\n | x::l ->\n let y = if x = !previous && !previous <> -1 then\n match s with\n | [] -> failwith \"Oops\"\n | y::_ -> if y <= x then y else failwith \"oops\"\n else\n x\n in\n previous := x;\n let s' = remove y s in\n find_perm l (y::p) s'\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n previous := -1;\n let m = int_of_string (input_line stdin) in\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n let set = to_set m in\n let rec pp fmt = function\n | [] -> Format.fprintf fmt \"\"\n | [x] -> Format.fprintf fmt \"%d\" x\n | x::l -> Format.fprintf fmt \"%d %a\" x pp l\n in\n try\n let l' = List.rev @@ find_perm l [] set in\n Format.printf \"%a@.\" pp l'\n with _ -> Format.printf \"-1@.\"\n done\n"}, {"source_code": "module IS = Set.Make(struct type t = int let compare = compare end)\n\nlet rec to_set m =\n if m = 0 then\n IS.empty\n else\n IS.add m (to_set (m-1))\n\n\nlet rec find_perm l p s =\n match l with\n | [] -> p\n | x::l ->\n let y = IS.choose (IS.filter (fun y -> y <= x) s) in\n let s' = IS.remove y s in\n find_perm l (y::p) s'\n\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let m = int_of_string (input_line stdin) in\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n let set = to_set m in\n let rec pp fmt = function\n | [] -> Format.fprintf fmt \"\"\n | [x] -> Format.fprintf fmt \"%d\" x\n | x::l -> Format.fprintf fmt \"%d %a\" x pp l\n in\n try\n let l' = List.rev @@ find_perm l [] set in\n Format.printf \"%a@.\" pp l'\n with _ -> Format.printf \"-1@.\"\n done\n"}, {"source_code": "module IS = Set.Make(struct type t = int let compare = compare end)\n\nlet rec to_set m =\n if m = 0 then\n []\n else\n m::(to_set (m-1))\n\nlet previous = ref (-1)\nlet rec remove x l =\n match l with\n | [] -> assert false\n | y::l -> if x = y then l\n else\n y::(remove x l)\n\nlet rec find_perm l p s =\n match l with\n | [] -> p\n | x::l ->\n let y = if x = !previous && !previous <> -1 then\n match s with\n | [] -> failwith \"Oops\"\n | x::_ -> x\n else\n x\n in\n previous := x;\n let s' = remove y s in\n find_perm l (y::p) s'\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n previous := -1;\n let m = int_of_string (input_line stdin) in\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n let set = to_set m in\n let rec pp fmt = function\n | [] -> Format.fprintf fmt \"\"\n | [x] -> Format.fprintf fmt \"%d\" x\n | x::l -> Format.fprintf fmt \"%d %a\" x pp l\n in\n try\n let l' = List.rev @@ find_perm l [] set in\n Format.printf \"%a@.\" pp l'\n with _ -> Format.printf \"-1@.\"\n done\n"}, {"source_code": "module IS = Set.Make(struct type t = int let compare = compare end)\n\nlet rec to_set m =\n if m = 0 then\n IS.empty\n else\n IS.add m (to_set (m-1))\n\nlet previous = ref (-1)\n\nlet rec find_perm l p s =\n match l with\n | [] -> p\n | x::l ->\n let y = if x = !previous then\n IS.choose (IS.filter (fun y -> y <= x) s)\n else\n x\n in\n previous := x;\n let s' = IS.remove y s in\n find_perm l (y::p) s'\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let m = int_of_string (input_line stdin) in\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n let set = to_set m in\n let rec pp fmt = function\n | [] -> Format.fprintf fmt \"\"\n | [x] -> Format.fprintf fmt \"%d\" x\n | x::l -> Format.fprintf fmt \"%d %a\" x pp l\n in\n try\n let l' = List.rev @@ find_perm l [] set in\n Format.printf \"%a@.\" pp l'\n with _ -> Format.printf \"-1@.\"\n done\n"}], "src_uid": "81912dccb339d675e09df40919f9f6fe"} {"nl": {"description": "In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1,\u2009t2,\u2009...,\u2009tp (p\u2009\u2265\u20091) such that: t1\u2009=\u2009c1 tp\u2009=\u2009c2 for any i (1\u2009\u2264\u2009i\u2009<\u2009p), cities ti and ti\u2009+\u20091 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di\u2009\u2265\u20090) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.", "input_spec": "The first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire. The following m lines contain pairs of integers ai, bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n,\u2009ai\u2009\u2260\u2009bi), separated by a space \u2014 the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire. The next line contains a single integer k \u2014 the number of merchants in the empire. The following k lines contain pairs of integers si, li (1\u2009\u2264\u2009si,\u2009li\u2009\u2264\u2009n), separated by a space, \u2014 si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located. The input limitations for getting 20 points are: 1\u2009\u2264\u2009n\u2009\u2264\u2009200 1\u2009\u2264\u2009m\u2009\u2264\u2009200 1\u2009\u2264\u2009k\u2009\u2264\u2009200 The input limitations for getting 50 points are: 1\u2009\u2264\u2009n\u2009\u2264\u20092000 1\u2009\u2264\u2009m\u2009\u2264\u20092000 1\u2009\u2264\u2009k\u2009\u2264\u20092000 The input limitations for getting 100 points are: 1\u2009\u2264\u2009n\u2009\u2264\u2009105 1\u2009\u2264\u2009m\u2009\u2264\u2009105 1\u2009\u2264\u2009k\u2009\u2264\u2009105 ", "output_spec": "Print exactly k lines, the i-th line should contain a single integer di \u2014 the number of dinars that the i-th merchant paid.", "sample_inputs": ["7 8\n1 2\n2 3\n3 4\n4 5\n5 6\n5 7\n3 5\n4 7\n4\n1 5\n2 4\n2 6\n4 7"], "sample_outputs": ["2\n1\n2\n0"], "notes": "NoteThe given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1,\u20092) or (2,\u20093) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let () =\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let is_bridge = ref false in\n\tes.(u) <- (v, is_bridge) :: es.(u);\n\tes.(v) <- (u, is_bridge) :: es.(v);\n done\n in\n let es = Array.map Array.of_list es in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Array.make k 0 in\n let l = Array.make k 0 in\n let () =\n for i = 0 to k - 1 do\n s.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1;\n l.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1;\n done\n in\n let min (x : int) y = if x < y then x else y in\n let used = Array.make n false in\n let t = ref 0 in\n let e = Array.make n 0 in\n let up = Array.make n 0 in\n let rec dfs u prev =\n used.(u) <- true;\n e.(u) <- !t;\n up.(u) <- !t;\n incr t;\n for i = 0 to Array.length es.(u) - 1 do\n let (v, is_bridge) = es.(u).(i) in\n\tif v <> prev then (\n\t if not used.(v) then (\n\t dfs v u;\n\t up.(u) <- min up.(u) up.(v);\n\t if up.(v) > e.(u) then (\n\t is_bridge := true;\n\t (*Printf.printf \"bridge %d %d\\n\" u v*)\n\t )\n\t ) else (\n\t up.(u) <- min up.(u) e.(v);\n\t )\n\t)\n done;\n in\n let res = ref 0 in\n let rec dfs2 u dest dist =\n used.(u) <- true;\n if u = dest then (\n res := dist\n );\n for i = 0 to Array.length es.(u) - 1 do\n let (v, is_bridge) = es.(u).(i) in\n\tif not used.(v) then (\n\t let dist =\n\t if !is_bridge\n\t then dist + 1\n\t else dist\n\t in\n\t dfs2 v dest dist;\n\t)\n done;\n in\n for i = 0 to n - 1 do\n if not used.(i)\n then dfs i (-1)\n done;\n for i = 0 to k - 1 do\n for j = 0 to n - 1 do\n\tused.(j) <- false\n done;\n dfs2 s.(i) l.(i) 0;\n Printf.printf \"%d\\n\" !res;\n done\n"}, {"source_code": "module type ExtremumType =\nsig\n type t\n val extremum : t -> t -> bool\nend\n\nmodule type RMQ =\nsig\n type t\n type elt\n val of_array : elt array -> t\n val rmq : t -> int -> int -> int\nend\n\nmodule type RMQMake =\nsig\n module Make(Ext : ExtremumType) : RMQ with type elt = Ext.t\nend\n\nmodule RMQST =\nstruct\n module Make(Ext : ExtremumType) : RMQ with type elt = Ext.t =\n struct\n type elt = Ext.t\n type t = {a : elt array;\n\t m : int array array}\n let ext = Ext.extremum\n let of_array a =\n let n = Array.length a in\n let k = ref 0\n and d = ref 1 in\n\twhile !d <= n do\n\t d := 2 * !d;\n\t incr k\n\tdone;\n\tlet k = !k in\n\tlet m = Array.make_matrix k n 0 in\n\t for i = 0 to n - 1 do\n\t m.(0).(i) <- i;\n\t done;\n\t for j = 1 to k - 1 do\n\t for i = 0 to n - (1 lsl j) do\n\t let i2 = i + (1 lsl (j - 1)) in\n\t\tm.(j).(i) <-\n\t\t if ext a.(m.(j - 1).(i)) a.(m.(j - 1).(i2))\n\t\t then m.(j - 1).(i)\n\t\t else m.(j - 1).(i2)\n\t done\n\t done;\n\t {a = a;\n\t m = m}\n let rmq data x y =\n let a = data.a\n and m = data.m in\n let l = y - x + 1 in\n let k = ref 0\n and d = ref 1 in\n\twhile !d <= l do\n\t d := 2 * !d;\n\t incr k\n\tdone;\n\tlet k = !k - 1 in\n\tlet i2 = y - (1 lsl k) + 1 in\n\t if ext a.(m.(k).(x)) a.(m.(k).(i2))\n\t then m.(k).(x)\n\t else m.(k).(i2)\n end\nend\n\nmodule RMQSTmin =\n RMQST.Make(\n struct\n type t = int\n let extremum (x : t) (y : t) = x < y\n end\n )\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let () =\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let is_bridge = ref false in\n\tes.(u) <- (v, is_bridge) :: es.(u);\n\tes.(v) <- (u, is_bridge) :: es.(v);\n done\n in\n let es = Array.map Array.of_list es in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Array.make k 0 in\n let l = Array.make k 0 in\n let () =\n for i = 0 to k - 1 do\n s.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1;\n l.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1;\n done\n in\n let min (x : int) y = if x < y then x else y in\n let used = Array.make n false in\n let t = ref 0 in\n let e = Array.make n 0 in\n let up = Array.make n 0 in\n let rec dfs u prev =\n used.(u) <- true;\n e.(u) <- !t;\n up.(u) <- !t;\n incr t;\n for i = 0 to Array.length es.(u) - 1 do\n let (v, is_bridge) = es.(u).(i) in\n\tif v <> prev then (\n\t if not used.(v) then (\n\t dfs v u;\n\t up.(u) <- min up.(u) up.(v);\n\t if up.(v) > e.(u) then (\n\t is_bridge := true;\n\t (*Printf.printf \"bridge %d %d\\n\" u v*)\n\t )\n\t ) else (\n\t up.(u) <- min up.(u) e.(v);\n\t )\n\t)\n done;\n in\n let stack = Array.make (2 * n) (fun _ -> ()) in\n let stack_pos = ref 0 in\n let rec execute () =\n if !stack_pos > 0 then (\n decr stack_pos;\n let f = stack.(!stack_pos) in\n\tf ();\n\texecute ()\n )\n in\n let rec dfs u prev =\n used.(u) <- true;\n e.(u) <- !t;\n up.(u) <- !t;\n incr t;\n let rec aux i =\n if i < Array.length es.(u) then (\n\tstack.(!stack_pos) <- (fun () -> aux (i + 1));\n\tincr stack_pos;\n\tlet (v, is_bridge) = es.(u).(i) in\n\t if v <> prev then (\n\t if not used.(v) then (\n\t let f () =\n\t\tup.(u) <- min up.(u) up.(v);\n\t\tif up.(v) > e.(u) then (\n\t\t is_bridge := true;\n\t\t (*Printf.printf \"bridge %d %d\\n\" u v*)\n\t\t)\n\t in\n\t\tstack.(!stack_pos) <- f;\n\t\tincr stack_pos;\n\t\tstack.(!stack_pos) <- (fun () -> dfs v u);\n\t\tincr stack_pos;\n\t ) else (\n\t up.(u) <- min up.(u) e.(v);\n\t )\n\t );\n )\n in\n aux 0\n in\n let color = Array.make n (-1) in\n let c = ref 0 in\n let rec dfs2 u =\n used.(u) <- true;\n color.(u) <- !c;\n for i = 0 to Array.length es.(u) - 1 do\n let (v, is_bridge) = es.(u).(i) in\n\tif not used.(v) && not !is_bridge then (\n\t dfs2 v\n\t)\n done\n in\n let rec dfs2 u =\n used.(u) <- true;\n color.(u) <- !c;\n let rec aux i =\n if i < Array.length es.(u) then (\n\tstack.(!stack_pos) <- (fun () -> aux (i + 1));\n\tincr stack_pos;\n\tlet (v, is_bridge) = es.(u).(i) in\n\t if not used.(v) && not !is_bridge then (\n\t stack.(!stack_pos) <- (fun () -> dfs2 v);\n\t incr stack_pos;\n\t )\n )\n in\n aux 0\n in\n for i = 0 to n - 1 do\n if not used.(i) then (\n\tstack_pos := 0;\n\tdfs i (-1);\n\texecute ()\n )\n done;\n for j = 0 to n - 1 do\n used.(j) <- false\n done;\n for i = 0 to n - 1 do\n if not used.(i) then (\n\tstack_pos := 0;\n\tdfs2 i;\n\texecute ();\n\tincr c\n )\n done;\n let c = !c in\n let es2 = Array.make c [] in\n let () =\n for i = 0 to n - 1 do\n\tfor j = 0 to Array.length es.(i) - 1 do\n\t let (v, is_bridge) = es.(i).(j) in\n\t if !is_bridge then (\n\t let u = color.(i)\n\t and v = color.(v) in\n\t\tes2.(u) <- v :: es2.(u);\n\t\tes2.(v) <- u :: es2.(v);\n\t )\n\tdone\n done\n in\n let es = Array.map Array.of_list es2 in\n let used = Array.make c false in\n let d = Array.make (2 * c) 0 in\n let de = Array.make (2 * c) 0 in\n let g1 = Array.make c 0 in\n let g2 = Array.make c 0 in\n let pos = ref 0 in\n let rec dfs3 u depth =\n used.(u) <- true;\n g1.(u) <- !pos;\n d.(!pos) <- depth;\n de.(!pos) <- u;\n incr pos;\n for i = 0 to Array.length es.(u) - 1 do\n\tlet v = es.(u).(i) in\n\t if not used.(v) then (\n\t dfs3 v (depth + 1);\n\t g2.(u) <- !pos;\n\t d.(!pos) <- depth;\n\t de.(!pos) <- u;\n\t incr pos;\n\t )\n done\n in\n let rec dfs3 u depth =\n used.(u) <- true;\n g1.(u) <- !pos;\n d.(!pos) <- depth;\n de.(!pos) <- u;\n incr pos;\n let rec aux i =\n\tif i < Array.length es.(u) then (\n\t stack.(!stack_pos) <- (fun () -> aux (i + 1));\n\t incr stack_pos;\n\t let v = es.(u).(i) in\n\t if not used.(v) then (\n\t let f () =\n\t\tg2.(u) <- !pos;\n\t\td.(!pos) <- depth;\n\t\tde.(!pos) <- u;\n\t\tincr pos;\n\t in\n\t\tstack.(!stack_pos) <- f;\n\t\tincr stack_pos;\n\t\tstack.(!stack_pos) <- (fun () -> dfs3 v (depth + 1));\n\t\tincr stack_pos;\n\t )\n\t)\n in\n\taux 0\n in\n stack_pos := 0;\n dfs3 0 0;\n execute ();\n let rmq = RMQSTmin.of_array d in\n\tfor i = 0 to k - 1 do\n\t let u = color.(s.(i))\n\t and v = color.(l.(i)) in\n\t let w =\n\t if g1.(u) < g1.(v)\n\t then RMQSTmin.rmq rmq g1.(u) g1.(v)\n\t else RMQSTmin.rmq rmq g1.(v) g1.(u)\n\t in\n\t let depth = d.(w) in\n\t let res = d.(g1.(u)) - depth + d.(g1.(v)) - depth in\n\t Printf.printf \"%d\\n\" res;\n\tdone\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let () =\n for i = 1 to m do\n let u = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let v = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let is_bridge = ref false in\n\tes.(u) <- (v, is_bridge) :: es.(u);\n\tes.(v) <- (u, is_bridge) :: es.(v);\n done\n in\n let es = Array.map Array.of_list es in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Array.make k 0 in\n let l = Array.make k 0 in\n let () =\n for i = 0 to k - 1 do\n s.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1;\n l.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1;\n done\n in\n let min (x : int) y = if x < y then x else y in\n let used = Array.make n false in\n let t = ref 0 in\n let e = Array.make n 0 in\n let up = Array.make n 0 in\n let rec dfs u prev =\n used.(u) <- true;\n e.(u) <- !t;\n up.(u) <- !t;\n incr t;\n for i = 0 to Array.length es.(u) - 1 do\n let (v, is_bridge) = es.(u).(i) in\n\tif v <> prev then (\n\t if not used.(v) then (\n\t dfs v u;\n\t up.(u) <- min up.(u) up.(v);\n\t if up.(v) > e.(u) then (\n\t is_bridge := true;\n\t (*Printf.printf \"bridge %d %d\\n\" u v*)\n\t )\n\t ) else (\n\t up.(u) <- min up.(u) e.(v);\n\t )\n\t)\n done;\n in\n let res = ref 0 in\n let rec dfs2 u dest dist =\n used.(u) <- true;\n if u = dest then (\n res := dist\n );\n for i = 0 to Array.length es.(u) - 1 do\n let (v, is_bridge) = es.(u).(i) in\n\tif not used.(v) then (\n\t let dist =\n\t if !is_bridge\n\t then dist + 1\n\t else dist\n\t in\n\t dfs2 v dest dist;\n\t)\n done;\n in\n for i = 0 to n - 1 do\n if not used.(i)\n then dfs i (-1)\n done;\n for i = 0 to k - 1 do\n for j = 0 to n - 1 do\n\tused.(j) <- false\n done;\n dfs2 s.(i) l.(i) 0;\n Printf.printf \"%d\\n\" !res;\n done\n"}], "negative_code": [], "src_uid": "184314d3aa83d48b71a95ae4b48de457"} {"nl": {"description": "You are given two integers $$$a$$$ and $$$b$$$. You may perform any number of operations on them (possibly zero).During each operation you should choose any positive integer $$$x$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$ or $$$a := a - 2x$$$, $$$b := b - x$$$. Note that you may choose different values of $$$x$$$ in different operations.Is it possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously?Your program should answer $$$t$$$ independent test cases.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then the test cases follow, each test case is represented by one line containing two integers $$$a$$$ and $$$b$$$ for this test case ($$$0 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case print the answer to it \u2014 YES if it is possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).", "sample_inputs": ["3\n6 9\n1 1\n1 2"], "sample_outputs": ["YES\nNO\nYES"], "notes": "NoteIn the first test case of the example two operations can be used to make both $$$a$$$ and $$$b$$$ equal to zero: choose $$$x = 4$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$. Then $$$a = 6 - 4 = 2$$$, $$$b = 9 - 8 = 1$$$; choose $$$x = 1$$$ and set $$$a := a - 2x$$$, $$$b := b - x$$$. Then $$$a = 2 - 2 = 0$$$, $$$b = 1 - 1 = 0$$$. "}, "positive_code": [{"source_code": "let () =\n let n = read_int () in\n let rec iter i =\n if i < n then (\n let (a,b) = Scanf.scanf \"%d %d \" (fun x y -> (x,y)) in\n print_endline (if (a mod 3 + b) mod 3 = 0 && a - b <= b && b - a <= a then \"YES\" else \"NO\");\n iter (i+1)\n ) in iter 0;\n"}], "negative_code": [{"source_code": "let () =\n let n = read_int () in\n let rec iter i =\n if i < n then (\n let (a,b) = Scanf.scanf \" %d %d \" (fun x y -> (x,y)) in\n print_endline (if (a mod 3 + b mod 3) mod 3 = 0 && a <= 2*b && b <= 2*a then \"YES\" else \"NO\");\n iter (i+1)\n ) in iter 0;\n"}, {"source_code": "let () =\n let n = read_int () in\n let rec iter i =\n if i < n then (\n let (a,b) = Scanf.scanf \" %d %d \" (fun x y -> (x,y)) in\n print_endline (if (a+b) mod 3 = 0 && a <= 2*b && b <= 2*a then \"YES\" else \"NO\");\n iter (i+1)\n ) in iter 0;\n"}, {"source_code": "let () =\n let n = read_int () in\n let rec iter i =\n if i < n then (\n let (a,b) = Scanf.scanf \" %d %d \" (fun x y -> (x,y)) in\n print_endline (if (a mod 3 + b) mod 3 = 0 && a <= 2*b && b <= 2*a then \"YES\" else \"NO\");\n iter (i+1)\n ) in iter 0;\n"}], "src_uid": "0a720a0b06314fde783866b47f35af81"} {"nl": {"description": "You are given a tree, consisting of $$$n$$$ vertices. Each edge has an integer value written on it.Let $$$f(v, u)$$$ be the number of values that appear exactly once on the edges of a simple path between vertices $$$v$$$ and $$$u$$$.Calculate the sum of $$$f(v, u)$$$ over all pairs of vertices $$$v$$$ and $$$u$$$ such that $$$1 \\le v < u \\le n$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 5 \\cdot 10^5$$$)\u00a0\u2014 the number of vertices in the tree. Each of the next $$$n-1$$$ lines contains three integers $$$v, u$$$ and $$$x$$$ ($$$1 \\le v, u, x \\le n$$$)\u00a0\u2014 the description of an edge: the vertices it connects and the value written on it. The given edges form a tree.", "output_spec": "Print a single integer\u00a0\u2014 the sum of $$$f(v, u)$$$ over all pairs of vertices $$$v$$$ and $$$u$$$ such that $$$v < u$$$.", "sample_inputs": ["3\n1 2 1\n1 3 2", "3\n1 2 2\n1 3 2", "5\n1 4 4\n1 2 3\n3 4 4\n4 5 5", "2\n2 1 1", "10\n10 2 3\n3 8 8\n4 8 9\n5 8 5\n3 10 7\n7 8 2\n5 6 6\n9 3 4\n1 6 3"], "sample_outputs": ["4", "2", "14", "1", "120"], "notes": null}, "positive_code": [{"source_code": "(* An implementation of link-cut trees in ocaml *)\n\n(* In this version the weight of a node is one plus the total number of nodes\n in its dotted children. The size of a node is its weight plus\n the sizes of its left and right children. Thus, the size of the root\n of the real tree is the number of nodes in it. *)\n\ntype node = {\n mutable id:int; (* For this aplication we don't need ids *)\n mutable l:node;\n mutable r:node;\n mutable p:node;\n mutable size:int;\n mutable weight:int\n}\n\nlet rec null = {id=0; l=null; r=null; p=null; size=0; weight=0}\n\nlet isroot n = n.p == null || (n.p.l != n && n.p.r != n)\nlet update p = if p == null then failwith \"update called on null\"\n else (p.size <- p.l.size + p.weight + p.r.size)\nlet discharge p = ()\n\nlet rot_right p =\n let q = p.p in\n let r = q.p in\n q.l <- p.r;\n if q.l != null then q.l.p <- q;\n p.r <- q;\n q.p <- p;\n p.p <- r;\n if r != null then (\n if r.l == q then r.l <- p \n else if r.r == q then r.r <- p\n );\n update q\n\nlet rot_left p =\n let q = p.p in\n let r = q.p in\n q.r <- p.l;\n if q.r != null then q.r.p <- q;\n p.l <- q;\n q.p <- p;\n p.p <- r;\n if r != null then (\n if r.r == q then r.r <- p \n else if r.l == q then r.l <- p\n );\n update q\n\nlet splay p =\n let rec loop p = if not (isroot p) then\n let q = p.p in\n if isroot q then (\n\tdischarge q;\n\tdischarge p;\n\tif q.l == p then rot_right p else rot_left p\n ) else (\n\tlet r = q.p in\n\tdischarge r;\n\tdischarge q;\n\tdischarge p;\n\tif r.l == q then (\n\t if q.l == p then (rot_right q; rot_right p)\n\t else (rot_left p; rot_right p)\n\t) else (\n\t if q.r == p then (rot_left q; rot_left p)\n\t else (rot_right p; rot_left p)\n\t)\n );\n loop p\n in\n loop p;\n discharge p; (* useful only if p was already the root *)\n update p (* only useful if p was not already a root *)\n\nlet expose q =\n let rec loop r p = if p != null then (\n splay p;\n p.weight <- p.weight + p.l.size - r.size;\n p.l <- r;\n update p;\n loop p p.p\n ) in\n \n loop null q;\n splay q\n\nlet link p q =\n expose p;\n if p.r != null then failwith \"p's right child should be null\";\n expose q; (* this expose was missing, but it is needed for this application. *)\n p.p <- q;\n q.weight <- q.weight + p.size;\n update q\n \n(* let lca a b =\n ignore(expose a);\n expose(b) *)\n\nlet cut a =\n expose a;\n if a.r != null then (\n a.r.p <- null;\n a.r <- null;\n update a\n )\n\nlet findroot p =\n expose p;\n let rec loop p = if p.r == null then p else loop p.r in\n let p = loop p in\n splay p;\n p\n\nlet getsize p = (findroot p).size\n\nlet st n =\n if n == null then \"null\" else Printf.sprintf \"%d\" n.id\n \nlet printnode n =\n Printf.printf \"node %s: l=%s r=%s p=%s size=%d weight=%d\\n\"\n (st n) (st n.l) (st n.r) (st n.p) n.size n.weight\n \n(*--------------------------------------------------------------------------*)\n\nopen Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n let treenode = Array.init n (fun i -> {null with id=i; size=1; weight=1}) in\n\n let tree = Array.make n [] in\n\n let edgelist = Array.make n [] in\n (* the list of edges of a given label. edgelist.(l) = [(v1,u1)...]\n where v1 is a child of u1 and the edge has label l. *)\n\n let add_edge u v x =\n tree.(u) <- (v,x)::tree.(u);\n tree.(v) <- (u,x)::tree.(v)\n in\n\n for i=1 to n-1 do\n let u = read_int() in\n let v = read_int() in\n let x = read_int() in\n add_edge (u-1) (v-1) (x-1);\n done;\n\n let rec dfs u p =\n List.iter (fun (v,x) ->\n if v <> p then (\n\tedgelist.(x) <- (treenode.(v),treenode.(u))::edgelist.(x);\n\tdfs v u\n )\n ) tree.(u)\n in\n dfs 0 (-1);\n\n for x = 0 to n-1 do\n List.iter (fun (v,u) -> link v u) edgelist.(x)\n done;\n\n (* we've built the tree *)\n\n let answer = sum 0 (n-1) (fun x ->\n List.iter (fun (v,u) -> cut v) edgelist.(x);\n let summand = List.fold_left (fun ac (v,u) ->\n ac ++ (long (getsize v)) ** (long (getsize u))\n ) 0L edgelist.(x)\n in\n List.iter (fun (v,u) -> link v u) edgelist.(x);\n summand\n ) in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "96fe0cd25dc0f6a76ebeb43834bae8de"} {"nl": {"description": "Vasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer k\u00a0\u2014 the number of digits in n. Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substring of n (a substring of n is a sequence of consecutive digits of the number n).Vasya knows that there may be more than one way to restore the number n. Your task is to find the smallest possible initial integer n. Note that decimal representation of number n contained no leading zeroes, except the case the integer n was equal to zero itself (in this case a single digit 0 was used).", "input_spec": "The first line of the input contains the string received by Kate. The number of digits in this string does not exceed 1\u2009000\u2009000. The second line contains the substring of n which Vasya remembers. This string can contain leading zeroes. It is guaranteed that the input data is correct, and the answer always exists.", "output_spec": "Print the smalles integer n which Vasya could pass to Kate.", "sample_inputs": ["003512\n021", "199966633300\n63"], "sample_outputs": ["30021", "3036366999"], "notes": null}, "positive_code": [{"source_code": "(* my rank would have been 271 if it had been a real contest *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n \nlet rec log10 x = if x=0 then 0 else 1 + log10 (x/10)\n\nlet l2n c = (int_of_char c) - (int_of_char '0')\nlet n2l n = char_of_int ((int_of_char '0') + n)\n \nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let r = read_string() in\n let sub = read_string() in\n\n let lr = String.length r in\n\n let length_of_n =\n let x1 = log10 lr in\n if x1 = log10 (lr - x1) then lr-x1 else lr-x1+1\n in\n\n let hist = Array.make 10 0 in\n\n let add_to_hist str d = \n for i=0 to (String.length str) -1 do\n let j = l2n str.[i] in\n hist.(j) <- hist.(j) + d\n done;\n in\n\n add_to_hist r 1;\n add_to_hist (sprintf \"%d\" length_of_n) (-1);\n add_to_hist sub (-1);\n\n let rec non_zero i = if i=10 then -1\n else if hist.(i) > 0 then i else non_zero (i+1)\n in\n\n if non_zero 0 = -1 then printf \"%s\\n\" sub else\n \n let make_low_string d =\n let first_digit = non_zero d in\n let len = sum 0 9 (fun i -> hist.(i)) 0 in\n if first_digit < 0 then\n String.init len (fun i -> '0')\n else \n let pa = Array.make len 0 in\n pa.(0) <- first_digit;\n hist.(first_digit) <- hist.(first_digit) - 1;\n let p = ref 1 in\n for i=0 to 9 do\n\tfor j=0 to hist.(i)-1 do\n\t pa.(!p) <- i;\n\t p := !p+1\n\tdone\n done;\n hist.(first_digit) <- hist.(first_digit) + 1; \n String.init len (fun i -> n2l pa.(i))\n in\n\n let low_string = make_low_string 1 in\n\n (* printf \"low_string = %s\\n\" low_string; *)\n\n let lsn = String.length low_string in\n\n let st = if sub.[0] = '0' then 1 else 0 in\n let en = if low_string.[0] = '0' then 0 else lsn in\n \n let try_places = fold st en (\n fun i ac ->\n if i=0 || i=1 || i=lsn || (low_string.[i-1] <> low_string.[i])\n then i::ac else ac\n ) [] in\n\n (*\n printf \"try_places = \";\n List.iter (fun i -> printf \"%d \" i) try_places;\n print_newline();\n *)\n \n let min_string = List.fold_left (fun best i ->\n let front = String.sub low_string 0 i in\n let back = String.sub low_string i (lsn-i) in\n let s = String.concat \"\" [front; sub; back] in\n if best = \"\" || s < best then s else best\n ) \"\" try_places in\n\n let min_string =\n if sub.[0] = '0' then min_string\n else \n let alternate = String.concat \"\" [sub; make_low_string 0] in\n min alternate min_string\n in\n \n printf \"%s\\n\" min_string\n"}], "negative_code": [{"source_code": "(* my rank would have been 271 if it had been a real contest *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n \nlet rec log10 x = if x=0 then 0 else 1 + log10 (x/10)\n\nlet l2n c = (int_of_char c) - (int_of_char '0')\nlet n2l n = char_of_int ((int_of_char '0') + n)\n \nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let r = read_string() in\n let sub = read_string() in\n\n let lr = String.length r in\n\n let length_of_n =\n let x1 = log10 lr in\n if x1 = log10 (lr - x1) then lr-x1 else lr-x1+1\n in\n\n let hist = Array.make 10 0 in\n\n let add_to_hist str d = \n for i=0 to (String.length str) -1 do\n let j = l2n str.[i] in\n hist.(j) <- hist.(j) + d\n done;\n in\n\n add_to_hist r 1;\n add_to_hist (sprintf \"%d\" length_of_n) (-1);\n add_to_hist sub (-1);\n\n let rec non_zero i = if i=10 then -1\n else if hist.(i) > 0 then i else non_zero (i+1)\n in\n\n if non_zero 0 = -1 then printf \"%s\\n\" sub else\n \n let low_string =\n let first_digit = non_zero 1 in\n let len = sum 0 9 (fun i -> hist.(i)) 0 in\n if first_digit < 0 then\n String.init len (fun i -> '0')\n else \n let pa = Array.make len 0 in\n pa.(0) <- first_digit;\n hist.(first_digit) <- hist.(first_digit) - 1;\n let p = ref 1 in\n for i=0 to 9 do\n\tfor j=0 to hist.(i)-1 do\n\t pa.(!p) <- i;\n\t p := !p+1\n\tdone\n done;\n String.init len (fun i -> n2l pa.(i))\n in\n\n (* printf \"low_string = %s\\n\" low_string; *)\n\n let lsn = String.length low_string in\n\n let st = if sub.[0] = '0' then 1 else 0 in\n let en = if low_string.[0] = '0' then 0 else lsn in\n \n let try_places = fold st en (\n fun i ac ->\n if i=0 || i=1 || i=lsn || (low_string.[i-1] <> low_string.[i])\n then i::ac else ac\n ) [] in\n\n (*\n printf \"try_places = \";\n List.iter (fun i -> printf \"%d \" i) try_places;\n print_newline();\n *)\n \n let min_string = List.fold_left (fun best i ->\n let front = String.sub low_string 0 i in\n let back = String.sub low_string i (lsn-i) in\n let s = String.concat \"\" [front; sub; back] in\n if best = \"\" || s < best then s else best\n ) \"\" try_places in\n\n printf \"%s\\n\" min_string\n"}, {"source_code": "(* my rank would have been 271 if it had been a real contest *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n \nlet rec log10 x = if x=0 then 0 else 1 + log10 (x/10)\n\nlet l2n c = (int_of_char c) - (int_of_char '0')\nlet n2l n = char_of_int ((int_of_char '0') + n)\n \nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let r = read_string() in\n let sub = read_string() in\n\n let lr = String.length r in\n\n let length_of_n =\n let x1 = log10 lr in\n if x1 = log10 (lr - x1) then lr-x1 else lr-x1+1\n in\n\n let hist = Array.make 10 0 in\n\n let add_to_hist str d = \n for i=0 to (String.length str) -1 do\n let j = l2n str.[i] in\n hist.(j) <- hist.(j) + d\n done;\n in\n\n add_to_hist r 1;\n add_to_hist (sprintf \"%d\" length_of_n) (-1);\n add_to_hist sub (-1);\n\n let rec non_zero i = if i=10 then -1\n else if hist.(i) > 0 then i else non_zero (i+1)\n in\n\n if non_zero 0 = -1 then printf \"%s\\n\" sub else\n \n let low_string =\n let first_digit = non_zero 1 in\n let len = sum 0 9 (fun i -> hist.(i)) 0 in\n if first_digit < 0 then\n String.init len (fun i -> '0')\n else \n let pa = Array.make len 0 in\n pa.(0) <- first_digit;\n hist.(first_digit) <- hist.(first_digit) - 1;\n let p = ref 1 in\n for i=0 to 9 do\n\tfor j=0 to hist.(i)-1 do\n\t pa.(!p) <- i;\n\t p := !p+1\n\tdone\n done;\n String.init len (fun i -> n2l pa.(i))\n in\n\n (* printf \"low_string = %s\\n\" low_string; *)\n\n let lsn = String.length low_string in\n\n let st = if sub.[0] = '0' then 1 else 0 in\n \n let try_places = fold st lsn (\n fun i ac ->\n if i=0 || i=lsn || (low_string.[i-1] <> low_string.[i])\n then i::ac else ac\n ) [] in\n\n (*\n printf \"try_places = \";\n List.iter (fun i -> printf \"%d \" i) try_places;\n print_newline();\n *)\n \n let min_string = List.fold_left (fun best i ->\n let front = String.sub low_string 0 i in\n let back = String.sub low_string i (lsn-i) in\n let s = String.concat \"\" [front; sub; back] in\n if best = \"\" || s < best then s else best\n ) \"\" try_places in\n\n printf \"%s\\n\" min_string\n"}, {"source_code": "(* my rank would have been 271 if it had been a real contest *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n \nlet rec log10 x = if x=0 then 0 else 1 + log10 (x/10)\n\nlet l2n c = (int_of_char c) - (int_of_char '0')\nlet n2l n = char_of_int ((int_of_char '0') + n)\n \nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let r = read_string() in\n let sub = read_string() in\n\n let lr = String.length r in\n\n let length_of_n =\n let x1 = log10 lr in\n if x1 = log10 (lr - x1) then lr-x1 else lr-x1+1\n in\n\n printf \"length_of_n = %d\\n\" length_of_n;\n\n let hist = Array.make 10 0 in\n\n let add_to_hist str d = \n for i=0 to (String.length str) -1 do\n let j = l2n str.[i] in\n hist.(j) <- hist.(j) + d\n done;\n in\n\n add_to_hist r 1;\n add_to_hist (sprintf \"%d\" length_of_n) (-1);\n add_to_hist sub (-1);\n\n let low_string =\n let rec non_zero i = if i=10 then failwith \"no-non-zero\"\n else if hist.(i) > 0 then i else non_zero (i+1)\n in\n let first_digit = non_zero 1 in\n let len = sum 0 9 (fun i -> hist.(i)) 0 in\n let pa = Array.make len 0 in\n pa.(0) <- first_digit;\n hist.(first_digit) <- hist.(first_digit) - 1;\n let p = ref 1 in\n for i=0 to 9 do\n for j=0 to hist.(i)-1 do\n\tpa.(!p) <- i;\n\tp := !p+1\n done\n done;\n String.init len (fun i -> n2l pa.(i))\n in\n\n let lsn = String.length low_string in\n\n let st = if sub.[0] = '0' then 1 else 0 in\n \n let try_places = fold st lsn (\n fun i ac ->\n if (i>0 && low_string.[i-1] = sub.[0]) || (i\n let front = String.sub low_string 0 i in\n let back = String.sub low_string i (lsn-i) in\n String.concat \"\" [front; sub; back]\n ) try_places in\n\n let min_string = List.fold_left (\n fun best s -> if best = \"\" || s < best then s else best\n ) \"\" try_strings in\n\n printf \"%s\\n\" min_string\n"}, {"source_code": "(* my rank would have been 271 if it had been a real contest *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n \nlet rec log10 x = if x=0 then 0 else 1 + log10 (x/10)\n\nlet l2n c = (int_of_char c) - (int_of_char '0')\nlet n2l n = char_of_int ((int_of_char '0') + n)\n \nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let r = read_string() in\n let sub = read_string() in\n\n let lr = String.length r in\n\n let length_of_n =\n let x1 = log10 lr in\n if x1 = log10 (lr - x1) then lr-x1 else lr-x1+1\n in\n\n let hist = Array.make 10 0 in\n\n let add_to_hist str d = \n for i=0 to (String.length str) -1 do\n let j = l2n str.[i] in\n hist.(j) <- hist.(j) + d\n done;\n in\n\n add_to_hist r 1;\n add_to_hist (sprintf \"%d\" length_of_n) (-1);\n add_to_hist sub (-1);\n\n let rec non_zero i = if i=10 then -1\n else if hist.(i) > 0 then i else non_zero (i+1)\n in\n\n if non_zero 0 = -1 then printf \"%s\\n\" sub else\n \n let low_string =\n let first_digit = non_zero 1 in\n let len = sum 0 9 (fun i -> hist.(i)) 0 in\n if first_digit < 0 then\n String.init len (fun i -> '0')\n else \n let pa = Array.make len 0 in\n pa.(0) <- first_digit;\n hist.(first_digit) <- hist.(first_digit) - 1;\n let p = ref 1 in\n for i=0 to 9 do\n\tfor j=0 to hist.(i)-1 do\n\t pa.(!p) <- i;\n\t p := !p+1\n\tdone\n done;\n String.init len (fun i -> n2l pa.(i))\n in\n\n (* printf \"low_string = %s\\n\" low_string; *)\n\n let lsn = String.length low_string in\n\n let st = if sub.[0] = '0' then 1 else 0 in\n \n let try_places = fold st lsn (\n fun i ac ->\n if (i>0 && low_string.[i-1] = sub.[0]) <> (i\n let front = String.sub low_string 0 i in\n let back = String.sub low_string i (lsn-i) in\n let s = String.concat \"\" [front; sub; back] in\n if best = \"\" || s < best then s else best\n ) \"\" try_places in\n\n printf \"%s\\n\" min_string\n"}, {"source_code": "(* my rank would have been 271 if it had been a real contest *)\n\nopen Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n \nlet rec log10 x = if x=0 then 0 else 1 + log10 (x/10)\n\nlet l2n c = (int_of_char c) - (int_of_char '0')\nlet n2l n = char_of_int ((int_of_char '0') + n)\n \nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let r = read_string() in\n let sub = read_string() in\n\n let lr = String.length r in\n\n let length_of_n =\n let x1 = log10 lr in\n if x1 = log10 (lr - x1) then lr-x1 else lr-x1+1\n in\n\n let hist = Array.make 10 0 in\n\n let add_to_hist str d = \n for i=0 to (String.length str) -1 do\n let j = l2n str.[i] in\n hist.(j) <- hist.(j) + d\n done;\n in\n\n add_to_hist r 1;\n add_to_hist (sprintf \"%d\" length_of_n) (-1);\n add_to_hist sub (-1);\n\n let rec non_zero i = if i=10 then -1\n else if hist.(i) > 0 then i else non_zero (i+1)\n in\n\n if non_zero 0 = -1 then printf \"%s\\n\" sub else\n \n let low_string =\n let first_digit = non_zero 1 in\n let len = sum 0 9 (fun i -> hist.(i)) 0 in\n if first_digit < 0 then\n String.init len (fun i -> '0')\n else \n let pa = Array.make len 0 in\n pa.(0) <- first_digit;\n hist.(first_digit) <- hist.(first_digit) - 1;\n let p = ref 1 in\n for i=0 to 9 do\n\tfor j=0 to hist.(i)-1 do\n\t pa.(!p) <- i;\n\t p := !p+1\n\tdone\n done;\n String.init len (fun i -> n2l pa.(i))\n in\n\n (* printf \"low_string = %s\\n\" low_string; *)\n\n let lsn = String.length low_string in\n\n let st = if sub.[0] = '0' then 1 else 0 in\n let en = if low_string.[0] = '0' then 0 else lsn in\n \n let try_places = fold st en (\n fun i ac ->\n if i=0 || i=lsn || (low_string.[i-1] <> low_string.[i])\n then i::ac else ac\n ) [] in\n\n (*\n printf \"try_places = \";\n List.iter (fun i -> printf \"%d \" i) try_places;\n print_newline();\n *)\n \n let min_string = List.fold_left (fun best i ->\n let front = String.sub low_string 0 i in\n let back = String.sub low_string i (lsn-i) in\n let s = String.concat \"\" [front; sub; back] in\n if best = \"\" || s < best then s else best\n ) \"\" try_places in\n\n printf \"%s\\n\" min_string\n"}], "src_uid": "5c3cec98676675355bb870d818704be6"} {"nl": {"description": "After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game \u00abCall of Soldiers 3\u00bb.The game has (m\u2009+\u20091) players and n types of soldiers in total. Players \u00abCall of Soldiers 3\u00bb are numbered form 1 to (m\u2009+\u20091). Types of soldiers are numbered from 0 to n\u2009-\u20091. Each player has an army. Army of the i-th player can be described by non-negative integer xi. Consider binary representation of xi: if the j-th bit of number xi equal to one, then the army of the i-th player has soldiers of the j-th type. Fedor is the (m\u2009+\u20091)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.", "input_spec": "The first line contains three integers n, m, k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u200920;\u00a01\u2009\u2264\u2009m\u2009\u2264\u20091000). The i-th of the next (m\u2009+\u20091) lines contains a single integer xi (1\u2009\u2264\u2009xi\u2009\u2264\u20092n\u2009-\u20091), that describes the i-th player's army. We remind you that Fedor is the (m\u2009+\u20091)-th player.", "output_spec": "Print a single integer \u2014 the number of Fedor's potential friends.", "sample_inputs": ["7 3 1\n8\n5\n111\n17", "3 3 3\n1\n2\n3\n4"], "sample_outputs": ["0", "3"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet make_list n = \n let rec loop i list =\n if i < n + 1\n then\n let temp = read () in\n loop (i + 1) (temp :: list)\n else\n list\n in loop 0 []\n\nlet bin_of_int number types = \n let rec loop i number list =\n match i < types with\n | false -> List.rev list\n | true -> loop (i + 1) (number / 2) (number mod 2 :: list)\n in loop 0 number []\n\nlet compare contender target =\n let rec loop l ll count =\n match l, ll with\n | (hd :: tl), (hhd :: ttl) -> \n if hd != hhd \n then \n loop tl ttl (count + 1)\n else\n loop tl ttl count\n | [], [] -> count\n | _, [] | [], _ -> failwith \"Lists are not conformant\"\n in loop contender target 0\n\nlet counter max_error total count = \n if count <= max_error\n then\n total + 1\n else\n total\n\nlet input () = \n let types = read () in\n let commanders = read () in\n let max_error = read () in\n match make_list commanders with\n | (head :: tail) -> \n let army = tail in\n let target = bin_of_int head types in\n (types, max_error, army, target)\n\nlet solve (types, max_error, army, target) =\n let rec loop army total =\n match army with\n | (head :: tail) -> \n let bin_contender = bin_of_int head types in\n let count = compare bin_contender target in\n let total_upd = counter max_error total count in\n loop tail total_upd\n | [] -> total\n in loop army 0\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}], "negative_code": [], "src_uid": "5ebb0ee239d68ea33d9dac2d0bdd5f4e"} {"nl": {"description": "Let's consider a k\u2009\u00d7\u2009k square, divided into unit squares. Please note that k\u2009\u2265\u20093 and is odd. We'll paint squares starting from the upper left square in the following order: first we move to the right, then down, then to the left, then up, then to the right again and so on. We finish moving in some direction in one of two cases: either we've reached the square's border or the square following after the next square is already painted. We finish painting at the moment when we cannot move in any direction and paint a square. The figure that consists of the painted squares is a spiral. The figure shows examples of spirals for k\u2009=\u20093,\u20095,\u20097,\u20099. You have an n\u2009\u00d7\u2009m table, each of its cells contains a number. Let's consider all possible spirals, formed by the table cells. It means that we consider all spirals of any size that don't go beyond the borders of the table. Let's find the sum of the numbers of the cells that form the spiral. You have to find the maximum of those values among all spirals.", "input_spec": "The first line contains two integers n and m (3\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500) \u2014 the sizes of the table. Each of the next n lines contains m space-separated integers: the j-th number in the i-th line aij (\u2009-\u20091000\u2009\u2264\u2009aij\u2009\u2264\u20091000) is the number recorded in the j-th cell of the i-th row of the table.", "output_spec": "Print a single number \u2014 the maximum sum of numbers among all spirals.", "sample_inputs": ["6 5\n0 0 0 0 0\n1 1 1 1 1\n0 0 0 0 1\n1 1 1 0 1\n1 0 0 0 1\n1 1 1 1 1", "3 3\n1 1 1\n1 0 0\n1 1 1", "6 6\n-3 2 0 1 5 -1\n4 -1 2 -3 0 1\n-5 1 2 4 1 -2\n0 -2 1 3 -1 2\n3 1 4 -3 -2 0\n-1 2 -1 3 1 2"], "sample_outputs": ["17", "6", "13"], "notes": "NoteIn the first sample the spiral with maximum sum will cover all 1's of the table.In the second sample the spiral may cover only six 1's."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m 0 in\n let () =\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tlet k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t a.(i).(j) <- k\n done\n done\n in\n let max (x : int) y = if x > y then x else y in\n let res = ref (-1000000000) in\n let v = Array.make_matrix (n + 1) m 0 in\n let h = Array.make_matrix n (m + 1) 0 in\n for i = 0 to n - 1 do\n for j = 1 to m do\n\th.(i).(j) <- h.(i).(j - 1) + a.(i).(j - 1)\n done\n done;\n for i = 1 to n do\n for j = 0 to m - 1 do\n\tv.(i).(j) <- v.(i - 1).(j) + a.(i - 1).(j)\n done\n done;\n for y = 0 to n - 3 do\n for x = 0 to m - 3 do\n\tlet s = ref (a.(y).(x) + \n\t\t a.(y).(x + 1) + \n\t\t a.(y).(x + 2) + \n\t\t a.(y + 1).(x + 2) + \n\t\t a.(y + 2).(x) + \n\t\t a.(y + 2).(x + 1) + \n\t\t a.(y + 2).(x + 2))\n\tin\n\tlet () = res := max !res !s in\n\tlet d = ref 1 in\n\t while x - 2 * !d >= 0 && x + 2 + 2 * !d < m &&\n\t y - 2 * !d >= 0 && y + 2 + 2 * !d < n do\n\t let x' = x - 2 * !d in\n\t let y' = y - 2 * !d in\n\t\ts := !s + h.(y').(x' + 3 + 4 * !d) - h.(y').(x');\n\t\ts := !s +\n\t\t v.(y' + 2 + 4 * !d).(x' + 2 + 4 * !d) -\n\t\t v.(y' + 1).(x' + 2 + 4 * !d);\n\t\ts := !s +\n\t\t h.(y' + 2 + 4 * !d).(x' + 3 + 4 * !d) -\n\t\t h.(y' + 2 + 4 * !d).(x');\n\t\ts := !s +\n\t\t v.(y' + 2 + 4 * !d).(x') -\n\t\t v.(y' + 2).(x');\n\t\ts := !s + a.(y' + 2).(x' + 1);\n\t\tres := max !res !s;\n\t\tincr d;\n\t done\n done\n done;\n for y = 0 to n - 5 do\n for x = 0 to m - 5 do\n\tlet s = ref 0 in\n\tlet () =\n\t for i = 0 to 4 do\n\t s := !s + a.(y).(x + i);\n\t done;\n\t for i = 1 to 3 do\n\t s := !s + a.(y + i).(x + 4);\n\t done;\n\t for i = 0 to 4 do\n\t s := !s + a.(y + 4).(x + i);\n\t done;\n\t for i = 2 to 3 do\n\t s := !s + a.(y + i).(x);\n\t done;\n\t s := !s + a.(y + 2).(x + 1) + a.(y + 2).(x + 2);\n\tin\n\tlet () = res := max !res !s in\n\tlet d = ref 1 in\n\t while x - 2 * !d >= 0 && x + 4 + 2 * !d < m &&\n\t y - 2 * !d >= 0 && y + 4 + 2 * !d < n do\n\t let x' = x - 2 * !d in\n\t let y' = y - 2 * !d in\n\t\ts := !s + h.(y').(x' + 5 + 4 * !d) - h.(y').(x');\n\t\ts := !s +\n\t\t v.(y' + 4 + 4 * !d).(x' + 4 + 4 * !d) -\n\t\t v.(y' + 1).(x' + 4 + 4 * !d);\n\t\ts := !s +\n\t\t h.(y' + 4 + 4 * !d).(x' + 5 + 4 * !d) -\n\t\t h.(y' + 4 + 4 * !d).(x');\n\t\ts := !s +\n\t\t v.(y' + 4 + 4 * !d).(x') -\n\t\t v.(y' + 2).(x');\n\t\ts := !s + a.(y' + 2).(x' + 1);\n\t\tres := max !res !s;\n\t\tincr d;\n\t done\n done\n done;\n Printf.printf \"%d\\n\" !res;\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m 0 in\n let () =\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tlet k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t a.(i).(j) <- k\n done\n done\n in\n let max (x : int) y = if x > y then x else y in\n let res = ref (-1000000000) in\n let v = Array.make_matrix (n + 1) m 0 in\n let h = Array.make_matrix n (m + 1) 0 in\n for i = 0 to n - 1 do\n for j = 1 to m do\n\th.(i).(j) <- h.(i).(j - 1) + a.(i).(j - 1)\n done\n done;\n for i = 1 to n do\n for j = 0 to m - 1 do\n\tv.(i).(j) <- v.(i - 1).(j) + a.(i - 1).(j)\n done\n done;\n for y = 0 to n - 3 do\n for x = 0 to m - 3 do\n\tlet s = ref (a.(y).(x) + \n\t\t a.(y).(x + 1) + \n\t\t a.(y).(x + 2) + \n\t\t a.(y + 1).(x + 2) + \n\t\t a.(y + 2).(x) + \n\t\t a.(y + 2).(x + 1) + \n\t\t a.(y + 2).(x + 2))\n\tin\n\tlet () = res := max !res !s in\n\tlet d = ref 1 in\n\t while x - 2 * !d >= 0 && x + 2 + 2 * !d < m &&\n\t y - 2 * !d >= 0 && y + 2 + 2 * !d < n do\n\t let x' = x - 2 * !d in\n\t let y' = y - 2 * !d in\n\t\ts := !s + h.(y').(x' + 3 + 4 * !d) - h.(y').(x');\n\t\ts := !s +\n\t\t v.(y' + 2 + 4 * !d).(x' + 2 + 4 * !d) -\n\t\t v.(y' + 1).(x' + 2 + 4 * !d);\n\t\ts := !s +\n\t\t h.(y' + 2 + 4 * !d).(x' + 3 + 4 * !d) -\n\t\t h.(y' + 2 + 4 * !d).(x');\n\t\ts := !s +\n\t\t v.(y' + 2 + 4 * !d).(x') -\n\t\t v.(y' + 2).(x');\n\t\ts := !s + a.(y' + 2).(x' + 1);\n\t\tres := max !res !s;\n\t\tincr d;\n\t done\n done\n done;\n for y = 0 to n - 5 do\n for x = 0 to m - 5 do\n\tlet s = ref 0 in\n\tlet () =\n\t for i = 0 to 4 do\n\t s := !s + a.(y).(x + i);\n\t done;\n\t for i = 1 to 3 do\n\t s := !s + a.(y + i).(x + 4);\n\t done;\n\t for i = 0 to 4 do\n\t s := !s + a.(y + 4).(x + i);\n\t done;\n\t for i = 2 to 3 do\n\t s := !s + a.(y + i).(x);\n\t done;\n\t s := !s + a.(y + 2).(x + 1) + a.(y + 2).(x + 2);\n\tin\n\tlet () = res := max !res !s in\n\tlet d = ref 1 in\n\t while x - 2 * !d >= 0 && x + 2 + 2 * !d < m &&\n\t y - 2 * !d >= 0 && y + 2 + 2 * !d < n do\n\t let x' = x - 2 * !d in\n\t let y' = y - 2 * !d in\n\t\ts := !s + h.(y').(x' + 3 + 4 * !d) - h.(y').(x');\n\t\ts := !s +\n\t\t v.(y' + 2 + 4 * !d).(x' + 2 + 4 * !d) -\n\t\t v.(y' + 1).(x' + 2 + 4 * !d);\n\t\ts := !s +\n\t\t h.(y' + 2 + 4 * !d).(x' + 3 + 4 * !d) -\n\t\t h.(y' + 2 + 4 * !d).(x');\n\t\ts := !s +\n\t\t v.(y' + 2 + 4 * !d).(x') -\n\t\t v.(y' + 2).(x');\n\t\ts := !s + a.(y' + 2).(x' + 1);\n\t\tres := max !res !s;\n\t\tincr d;\n\t done\n done\n done;\n Printf.printf \"%d\\n\" !res;\n"}], "src_uid": "d33d7dc7082a449b35f99ef1c72c866e"} {"nl": {"description": "Polycarp found a rectangular table consisting of $$$n$$$ rows and $$$m$$$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm \"by columns\": cells are numbered starting from one; cells are numbered from left to right by columns, and inside each column from top to bottom; number of each cell is an integer one greater than in the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, the table will be numbered as follows:$$$$$$ \\begin{matrix} 1 & 4 & 7 & 10 & 13 \\\\ 2 & 5 & 8 & 11 & 14 \\\\ 3 & 6 & 9 & 12 & 15 \\\\ \\end{matrix} $$$$$$However, Polycarp considers such numbering inconvenient. He likes the numbering \"by rows\": cells are numbered starting from one; cells are numbered from top to bottom by rows, and inside each row from left to right; number of each cell is an integer one greater than the number of the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, then Polycarp likes the following table numbering: $$$$$$ \\begin{matrix} 1 & 2 & 3 & 4 & 5 \\\\ 6 & 7 & 8 & 9 & 10 \\\\ 11 & 12 & 13 & 14 & 15 \\\\ \\end{matrix} $$$$$$Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering \"by rows\", if in the numbering \"by columns\" the cell has the number $$$x$$$?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single line containing three integers $$$n$$$, $$$m$$$, $$$x$$$ ($$$1 \\le n, m \\le 10^6$$$, $$$1 \\le x \\le n \\cdot m$$$), where $$$n$$$ and $$$m$$$ are the number of rows and columns in the table, and $$$x$$$ is the cell number. Note that the numbers in some test cases do not fit into the $$$32$$$-bit integer type, so you must use at least the $$$64$$$-bit integer type of your programming language.", "output_spec": "For each test case, output the cell number in the numbering \"by rows\".", "sample_inputs": ["5\n1 1 1\n2 2 3\n3 5 11\n100 100 7312\n1000000 1000000 1000000000000"], "sample_outputs": ["1\n2\n9\n1174\n1000000000000"], "notes": null}, "positive_code": [{"source_code": "(* https://codeforces.com/contest/1506/problem/0 *)\n\nlet (--) = Int64.sub and\n(++) = Int64.add and\n(//) = Int64.div and\n(%%) = Int64.rem and\n( ** ) = Int64.mul\n\nlet xy_of_columnsi i rows columns =\n ((i--1L) // rows, (i--1L) %% rows)\n\nlet i_of_rowsxy (x, y) rows columns =\n x ++ y ** columns ++ 1L\n\nlet solve_n n =\n let rec helper i =\n if i <> 0\n then (\n let [rows; columns; index] =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map Int64.of_string in\n let (x, y) = xy_of_columnsi index rows columns in\n let index2 = i_of_rowsxy (x, y) rows columns in\n Printf.printf \"%Ld\\n\" index2;\n helper (i-1)\n ) in\n helper n\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "negative_code": [], "src_uid": "e519e4495c9acef4c4a614aef73cb322"} {"nl": {"description": "Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x\u2009=\u20090 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.What is the maximum number of apples he can collect?", "input_spec": "The first line contains one number n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), the number of apple trees in Lala Land. The following n lines contains two integers each xi, ai (\u2009-\u2009105\u2009\u2264\u2009xi\u2009\u2264\u2009105, xi\u2009\u2260\u20090, 1\u2009\u2264\u2009ai\u2009\u2264\u2009105), representing the position of the i-th tree and number of apples on it. It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0.", "output_spec": "Output the maximum number of apples Amr can collect.", "sample_inputs": ["2\n-1 5\n1 5", "3\n-2 2\n1 4\n-1 3", "3\n1 9\n3 5\n7 10"], "sample_outputs": ["10", "9", "9"], "notes": "NoteIn the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples.In the second sample test the optimal solution is to go left to x\u2009=\u2009\u2009-\u20091, collect apples from there, then the direction will be reversed, Amr has to go to x\u2009=\u20091, collect apples from there, then the direction will be reversed and Amr goes to the final tree x\u2009=\u2009\u2009-\u20092.In the third sample test the optimal solution is to go right to x\u2009=\u20091, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let d = Array.init n (fun _ -> read_pair()) in\n\n let rec make_lists l r i = if i=n then (l,r) else\n let (x,a) = d.(i) in\n if x < 0 then make_lists ((-x,a)::l) r (i+1)\n else make_lists l ((x,a)::r) (i+1)\n in\n\n let (l,r) = make_lists [] [] 0 in\n\n let l = List.sort compare l in\n let r = List.sort compare r in\n\n let (nl, nr) = (List.length l, List.length r) in\n\n let (l,r) = if nl < nr then (r,l) else (l,r) in\n let (nl,nr) = (max nl nr, min nl nr) in\n\n let sum_r = List.fold_left (fun t (_,a) -> t+a) 0 r in\n\n let (sum_l,_) = List.fold_left (fun (t,i) (_,a) -> if (i>=nr+1) then (t,i+1) else (t+a,i+1)) (0,0) l in\n\n printf \"%d\\n\" (sum_l + sum_r)\n"}, {"source_code": "open List\nlet read_int _ = Scanf.scanf \" %d\" (fun x -> x);;\n\nlet min x y = if x < y then x else y;; \n\nlet rec read_list l n = \n if n = 0 then l \n else let x = read_int() and y = read_int() in \n read_list (l @ [(x, y)]) (n-1);;\n\nlet rec answer l r n = match (l, r) with\n | ([], []) -> n\n | ((x, y) :: l, []) -> n + y \n | ([], (x, y)::l) -> n + y \n | ((x1, y1) :: l', (x2, y2) :: r') -> answer l' r' (n + y1 + y2);;\n\nlet mysort (x1, y1) (x2, y2) = x1 - x2;;\n\nlet () = \n let n = read_int () in\n let xa = read_list [] n in \n let left = filter (fun (x, y) -> (x < 0)) xa and right = filter (fun (x, y) -> (x > 0)) xa in\n let left = sort mysort left and right = sort mysort right in\n let ans = answer (rev left) right 0 in\n Printf.printf \"%d\\n\" ans \n;;\n"}], "negative_code": [], "src_uid": "bf573af345509b2364ada6e613b6f998"} {"nl": {"description": "You are given two positive integers $$$n$$$ and $$$s$$$. Find the maximum possible median of an array of $$$n$$$ non-negative integers (not necessarily distinct), such that the sum of its elements is equal to $$$s$$$.A median of an array of integers of length $$$m$$$ is the number standing on the $$$\\lceil {\\frac{m}{2}} \\rceil$$$-th (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting from $$$1$$$. For example, a median of the array $$$[20,40,20,50,50,30]$$$ is the $$$\\lceil \\frac{m}{2} \\rceil$$$-th element of $$$[20,20,30,40,50,50]$$$, so it is $$$30$$$. There exist other definitions of the median, but in this problem we use the described definition.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. Each test case contains a single line with two integers $$$n$$$ and $$$s$$$ ($$$1 \\le n, s \\le 10^9$$$)\u00a0\u2014 the length of the array and the required sum of the elements.", "output_spec": "For each test case print a single integer\u00a0\u2014 the maximum possible median.", "sample_inputs": ["8\n1 5\n2 5\n3 5\n2 1\n7 17\n4 14\n1 1000000000\n1000000000 1"], "sample_outputs": ["5\n2\n2\n0\n4\n4\n1000000000\n0"], "notes": "NotePossible arrays for the first three test cases (in each array the median is underlined): In the first test case $$$[\\underline{5}]$$$ In the second test case $$$[\\underline{2}, 3]$$$ In the third test case $$$[1, \\underline{2}, 2]$$$ "}, "positive_code": [{"source_code": "let w = read_int () in\r\nlet rec aux z = (if z > 0 then\r\n (\r\n let y = read_line () in\r\n let len = String.length y in\r\n let resolution y =\r\n let rec breaker = (function\r\n (a,b) when y.[b] = ' ' -> (int_of_string(String.sub y 0 b), int_of_string(String.sub y (b+1) (len-(b+1))))\r\n |(a,b) -> breaker(a,b+1)) in\r\n let a = breaker (y,0) in let (x,y) = a in\r\n print_int (match x with\r\n 1 -> y\r\n |x when x mod 2 = 0 -> y/(x-((x-1)/2))\r\n |x -> y/(x-(x/2))); print_newline ()\r\n in \r\n (resolution y; aux(z-1) )\r\n )) in aux (w);;"}, {"source_code": "let solve n s =\n let elts = n/2 + 1 in\n s/elts;;\n\n\nlet divide s =\n let l = String.length s in\n let rec aux i =\n if s.[i] = ' ' then i else aux (i+1) in\n let space = aux 0 in\n let a = String.sub s 0 space and b = String.sub s (space+1) (l-space-1) in\n (int_of_string a, int_of_string b);;\n \n \n\nlet read_test i =\n let test = read_line () in divide test;;\n \n\nlet t = read_int ();;\n\n\n\nlet process x =\n let (n, s) = read_test () in print_int(solve n s); print_newline ();;\n\n\nlet rec execute i =\n if i < t then\n begin\n process i; execute (i+1)\n end;;\n\nlet () = execute 0;;\n"}], "negative_code": [], "src_uid": "0a05b11307fbb2536f868acf4e81c1e2"} {"nl": {"description": "Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers l and r such that r\u2009-\u2009l\u2009+\u20091 is even. After that animals that occupy positions between l and r inclusively are rearranged as follows: the animal at position l swaps places with the animal at position l\u2009+\u20091, the animal l\u2009+\u20092 swaps with the animal l\u2009+\u20093, ..., finally, the animal at position r\u2009-\u20091 swaps with the animal r.Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20\u2009000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 number of animals in the robber girl's zoo. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the height of the animal occupying the i-th place.", "output_spec": "Print the sequence of operations that will rearrange the animals by non-decreasing height. The output should contain several lines, i-th of the lines should contain two space-separated integers li and ri (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009n)\u00a0\u2014 descriptions of segments the robber girl should name. The segments should be described in the order the operations are performed. The number of operations should not exceed 20\u2009000. If the animals are arranged correctly from the start, you are allowed to output nothing.", "sample_inputs": ["4\n2 1 4 3", "7\n36 28 57 39 66 69 68", "5\n1 2 1 2 1"], "sample_outputs": ["1 4", "1 4\n6 7", "2 5\n3 4\n1 4\n1 4"], "notes": "NoteNote that you don't have to minimize the number of operations. Any solution that performs at most 20\u2009000 operations is allowed."}, "positive_code": [{"source_code": "let n = read_int ()\nlet a = read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string |> Array.of_list\n\nlet () =\n for i = 0 to n - 2 do\n let min = ref i in\n for j = i + 1 to n - 1 do\n if a.(j) < a.(!min) then\n min := j\n done;\n\n for j = !min - 1 downto i do\n Printf.printf \"%d %d\\n\" (j+1) (j+2);\n let tmp = a.(j) in\n a.(j) <- a.(j+1);\n a.(j+1) <- tmp\n done\n done\n"}, {"source_code": "let _ =\n let n = Scanf.scanf \"%d\" (fun i -> i) in\n let tab = Array.init n (fun _ -> Scanf.scanf \" %d\" (fun j -> j)) in\n let perm i j =\n let z = tab.(i) in\n tab.(i) <- tab.(j);\n tab.(j) <- z\n in\n let a = ref (-1) in\n while !a < n-1 do\n if !a < 0\n then incr a\n else if tab.(!a) > tab.(1 + !a)\n then begin\n perm !a (1 + !a);\n Printf.printf \"%d %d\\n\" (1 + !a) (2 + !a);\n decr a\n end\n else incr a;\n done\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n for i=1 to n-1 do\n for j=i downto 1 do\n if a.(j-1) > a.(j) then (\n\tprintf \"%d %d\\n\" (j) (j+1);\n\tlet (x,y) = (a.(j-1), a.(j)) in\n\ta.(j-1) <- y;\n\ta.(j) <- x\n )\n done\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n for i=0 to n-2 do\n for j=i to n-2 do\n if a.(j) > a.(j+1) then (\n\tprintf \"%d %d\\n\" (j+1) (j+2);\n\tlet (x,y) = (a.(j), a.(j+1)) in\n\ta.(j) <- y;\n\ta.(j+1) <- x\n )\n done\n done\n\n"}], "src_uid": "233c2806db31916609421fbd126133d0"} {"nl": {"description": "This is simplified version of the problem used on the original contest. The original problem seems to have too difiicult solution. The constraints for input data have been reduced.Polycarp likes to play computer role-playing game \u00abLizards and Basements\u00bb. At the moment he is playing it as a magician. At one of the last levels he has to fight the line of archers. The only spell with which he can damage them is a fire ball. If Polycarp hits the i-th archer with his fire ball (they are numbered from left to right), the archer loses a health points. At the same time the spell damages the archers adjacent to the i-th (if any) \u2014 they lose b (1\u2009\u2264\u2009b\u2009<\u2009a\u2009\u2264\u200910) health points each.As the extreme archers (i.e. archers numbered 1 and n) are very far, the fire ball cannot reach them. Polycarp can hit any other archer with his fire ball.The amount of health points for each archer is known. An archer will be killed when this amount is less than 0. What is the minimum amount of spells Polycarp can use to kill all the enemies?Polycarp can throw his fire ball into an archer if the latter is already killed.", "input_spec": "The first line of the input contains three integers n,\u2009a,\u2009b (3\u2009\u2264\u2009n\u2009\u2264\u200910; 1\u2009\u2264\u2009b\u2009<\u2009a\u2009\u2264\u200910). The second line contains a sequence of n integers \u2014 h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u200915), where hi is the amount of health points the i-th archer has.", "output_spec": "In the first line print t \u2014 the required minimum amount of fire balls. In the second line print t numbers \u2014 indexes of the archers that Polycarp should hit to kill all the archers in t shots. All these numbers should be between 2 and n\u2009-\u20091. Separate numbers with spaces. If there are several solutions, output any of them. Print numbers in any order.", "sample_inputs": ["3 2 1\n2 2 2", "4 3 1\n1 4 1 1"], "sample_outputs": ["3\n2 2 2", "4\n2 2 3 3"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let a = read_int 0 in\n let b = read_int 0 in\n let h = Array.init n read_int in\n let dp = Array.init (n-1) (fun _ -> Array.make_matrix 17 17 200) in\n let pr = Array.init (n-1) (fun _ -> Array.make_matrix 17 17 (-1)) in\n dp.(0).(0).(0) <- 0;\n for i = 1 to n-2 do\n for j = 0 to 16 do\n for k = 0 to 16 do\n let t = dp.(i-1).(j).(k) in\n if t < 200 then\n for l = 0 to 16 do\n if (j+l)*b+k*a > h.(i-1) && t+l < dp.(i).(k).(l) then (\n if i=2 && k=0 && l=2 then\n Printf.printf \"+++ %d %d %d\\n\" i j k;\n dp.(i).(k).(l) <- t+l;\n pr.(i).(k).(l) <- j\n )\n done\n done\n done\n done;\n\n let ans = ref 200 and ansj = ref (-1) and ansk = ref (-1) in\n for j = 0 to 16 do\n for k = 0 to 16 do\n if j*b+k*a > h.(n-2) && k*b > h.(n-1) && dp.(n-2).(j).(k) < !ans then (\n ans := dp.(n-2).(j).(k);\n ansj := j;\n ansk := k\n )\n done\n done;\n\n Printf.printf \"%d\\n\" !ans;\n let rec plan i j k =\n if i > 0 then\n plan (i-1) pr.(i).(j).(k) j;\n for g = 1 to k do\n Printf.printf \"%d \" (i+1)\n done\n in\n plan (n-2) !ansj !ansk\n"}], "negative_code": [], "src_uid": "a9bad412597726f8cdc0cfa2da891bc4"} {"nl": {"description": "Dreamoon likes coloring cells very much.There is a row of $$$n$$$ cells. Initially, all cells are empty (don't contain any color). Cells are numbered from $$$1$$$ to $$$n$$$.You are given an integer $$$m$$$ and $$$m$$$ integers $$$l_1, l_2, \\ldots, l_m$$$ ($$$1 \\le l_i \\le n$$$)Dreamoon will perform $$$m$$$ operations.In $$$i$$$-th operation, Dreamoon will choose a number $$$p_i$$$ from range $$$[1, n-l_i+1]$$$ (inclusive) and will paint all cells from $$$p_i$$$ to $$$p_i+l_i-1$$$ (inclusive) in $$$i$$$-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.Dreamoon hopes that after these $$$m$$$ operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose $$$p_i$$$ in each operation to satisfy all constraints.", "input_spec": "The first line contains two integers $$$n,m$$$ ($$$1 \\leq m \\leq n \\leq 100\\,000$$$). The second line contains $$$m$$$ integers $$$l_1, l_2, \\ldots, l_m$$$ ($$$1 \\leq l_i \\leq n$$$).", "output_spec": "If it's impossible to perform $$$m$$$ operations to satisfy all constraints, print \"'-1\" (without quotes). Otherwise, print $$$m$$$ integers $$$p_1, p_2, \\ldots, p_m$$$ ($$$1 \\leq p_i \\leq n - l_i + 1$$$), after these $$$m$$$ operations, all colors should appear at least once and all cells should be colored. If there are several possible solutions, you can print any.", "sample_inputs": ["5 3\n3 2 2", "10 1\n1"], "sample_outputs": ["2 4 1", "-1"], "notes": null}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_int_pair () = let x = scan_int() in let y = scan_int() in (x,y);;\nlet scan_int_array_of_size n = Array.init n (fun _ -> scan_int());;\nlet show_int n = Printf.printf \"%d\\n\" n;;\nlet show_int_array t = Array.iter (fun v -> Printf.printf \"%d \" v) t; print_newline ();;\n\nlet valide tab n =\n\tlet test = ref true and count = ref 0L and n = Int64.of_int n in\n\tfor i = 0 to (Array.length tab)-1 do\n\t\tcount := Int64.add !count (Int64.of_int tab.(i));\n\t\ttest := !test && (Int64.sub n (Int64.of_int tab.(i)) >= (Int64.of_int i))\n\tdone;\n\t!test && (!count >= n);;\n\nlet suffixe_sum tab =\n\tlet n = Array.length tab in\n\tlet sum = Array.make n 0L in\n\tlet somme = ref 0L in\n\tfor i = n-1 downto 0 do\n\t\tsomme := Int64.add !somme (Int64.of_int tab.(i));\n\t\tsum.(i) <- !somme\n\tdone;\n\tsum;;\n\nlet creation_sol l n m =\n\tlet sol = Array.make m 0 in\n\tlet n = Int64.of_int n in\n\tlet sum = suffixe_sum l in\n\tfor i = 0 to m-1 do sol.(i) <- Int64.to_int (Int64.add (max (Int64.of_int i) (Int64.sub n sum.(i))) 1L) done;\n\tsol;;\n\nlet n,m = scan_int_pair () in\nlet l = scan_int_array_of_size m in\nif not (valide l n)\n\tthen show_int (-1)\n\telse (let sol = creation_sol l n m in show_int_array sol)\n"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_int_pair () = let x = scan_int() in let y = scan_int() in (x,y);;\nlet scan_int_array_of_size n = Array.init n (fun _ -> scan_int());;\nlet show_int n = Printf.printf \"%d\\n\" n;;\nlet show_int_array t = Array.iter (fun v -> Printf.printf \"%d \" v) t; print_newline ();;\n\nlet valide tab n =\n\tlet test = ref true and count = ref 0 in\n\tfor i = 0 to (Array.length tab)-1 do\n\t\tcount := !count + tab.(i);\n\t\ttest := !test && (n - tab.(i) >= i)\n\tdone;\n\t!test && (!count >= n);;\n\nlet suffixe_sum tab =\n\tlet n = Array.length tab in\n\tlet sum = Array.make n 0L in\n\tlet somme = ref 0L in\n\tfor i = n-1 downto 0 do\n\t\tsomme := Int64.add !somme (Int64.of_int tab.(i));\n\t\tsum.(i) <- !somme\n\tdone;\n\tsum;;\n\nlet creation_sol l n m =\n\tlet sol = Array.make m 0 in\n\tlet n = Int64.of_int n in\n\tlet sum = suffixe_sum l in\n\tfor i = 0 to m-1 do sol.(i) <- Int64.to_int (Int64.add (max (Int64.of_int i) (Int64.sub n sum.(i))) 1L) done;\n\tsol;;\n\nlet n,m = scan_int_pair () in\nlet l = scan_int_array_of_size m in\nif not (valide l n)\n\tthen show_int (-1)\n\telse (let sol = creation_sol l n m in show_int_array sol)"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_int_pair () = let x = scan_int() in let y = scan_int() in (x,y);;\nlet scan_int_array_of_size n = Array.init n (fun _ -> scan_int());;\nlet show_int n = Printf.printf \"%d\\n\" n;;\nlet show_int_array t = Array.iter (fun v -> Printf.printf \"%d \" v) t;;\n\n\nlet valide tab n =\n\tlet test = ref true and count = ref 0 in\n\tfor i = 0 to (Array.length tab)-1 do\n\t\tcount := !count + tab.(i);\n\t\ttest := !test && (n - tab.(i) > i)\n\tdone;\n\t!test && (!count >= n);;\n\nlet suffixe_sum tab =\n\tlet n = Array.length tab in\n\tlet sum = Array.make n 0 in\n\tlet somme = ref 0 in\n\tfor i = n-1 downto 0 do\n\t\tsomme := !somme + tab.(i);\n\t\tsum.(i) <- !somme\n\tdone;\n\tsum;;\n\n\nlet creation_sol l n m =\n\tlet sol = Array.make m 0 in\n\tlet sum = suffixe_sum l in\n\tfor i = 0 to m-1 do sol.(i) <- (max i (n-sum.(i)))+1 done;\n\tsol;;\n\n\n\nlet n,m = scan_int_pair () in\nlet l = scan_int_array_of_size m in\nif not (valide l n)\n\tthen show_int (-1)\n\telse (let sol = creation_sol l n m in show_int_array sol)\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_int_pair () = let x = scan_int() in let y = scan_int() in (x,y);;\nlet scan_int_array_of_size n = Array.init n (fun _ -> scan_int());;\nlet show_int n = Printf.printf \"%d\\n\" n;;\nlet show_int_array t = Array.iter (fun v -> Printf.printf \"%d \" v) t;;\n\n\nlet valide tab n =\n\tlet test = ref true and count = ref 0 in\n\tfor i = 0 to (Array.length tab)-1 do\n\t\tcount := !count + tab.(i);\n\t\ttest := !test && (n - tab.(i) >= i)\n\tdone;\n\t!test && (!count >= n);;\n\nlet suffixe_sum tab =\n\tlet n = Array.length tab in\n\tlet sum = Array.make n 0 in\n\tlet somme = ref 0 in\n\tfor i = n-1 downto 0 do\n\t\tsomme := !somme + tab.(i);\n\t\tsum.(i) <- !somme\n\tdone;\n\tsum;;\n\n\nlet creation_sol l n m =\n\tlet sol = Array.make m 0 in\n\tlet sum = suffixe_sum l in\n\tfor i = 0 to m-1 do sol.(i) <- (max i (n-sum.(i)))+1 done;\n\tsol;;\n\n\n\nlet n,m = scan_int_pair () in\nlet l = scan_int_array_of_size m in\nif not (valide l n)\n\tthen show_int (-1)\n\telse (let sol = creation_sol l n m in show_int_array sol)"}], "src_uid": "90be8c6cf8f2cd626d41d2b0be2dfed3"} {"nl": {"description": "As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x,\u2009y,\u2009z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xa\u00b7yb\u00b7zc.To test the metric of mushroom scientists, the usual scientists offered them a task: find such x,\u2009y,\u2009z (0\u2009\u2264\u2009x,\u2009y,\u2009z;\u00a0x\u2009+\u2009y\u2009+\u2009z\u2009\u2264\u2009S), that the distance between the center of the Universe and the point (x,\u2009y,\u2009z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.Note that in this problem, it is considered that 00\u2009=\u20091.", "input_spec": "The first line contains a single integer S (1\u2009\u2264\u2009S\u2009\u2264\u2009103) \u2014 the maximum sum of coordinates of the sought point. The second line contains three space-separated integers a, b, c (0\u2009\u2264\u2009a,\u2009b,\u2009c\u2009\u2264\u2009103) \u2014 the numbers that describe the metric of mushroom scientists.", "output_spec": "Print three real numbers \u2014 the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations. A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10\u2009-\u20096. We think that ln(0)\u2009=\u2009\u2009-\u2009\u221e.", "sample_inputs": ["3\n1 1 1", "3\n2 0 0"], "sample_outputs": ["1.0 1.0 1.0", "3.0 0.0 0.0"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = float_of_int s in\n let a = float_of_int a in\n let b = float_of_int b in\n let c = float_of_int c in\n if false then (\n let l = ref 0.0 in\n let r = ref s in\n let calc x y z =\n let xa = if a = 0.0 then 0.0 else a *. log x in\n let yb = if b = 0.0 then 0.0 else b *. log y in\n let zc = if c = 0.0 then 0.0 else c *. log z in\n xa +. yb +. zc\n in\n for i = 1 to 400 do\n let x1 = (2.0 *. !l +. !r) /. 3.0 in\n let y1 = b *. (s -. x1) /. (b +. c) in\n let y1 = if y1 >= 0.0 && y1 <= s then y1 else if y1 > s then s else 0.0 in\n let z1 = s -. x1 -. y1 in\n let x2 = (!l +. 2.0 *. !r) /. 3.0 in\n let y2 = b *. (s -. x2) /. (b +. c) in\n let y2 = if y2 >= 0.0 && y2 <= s then y2 else if y2 > s then s else 0.0 in\n let z2 = s -. x2 -. y2 in\n\tif calc x1 y1 z1 > calc x2 y2 z2\n\tthen r := x2\n\telse l := x1\n done;\n let x = (!l +. !r) /. 2.0 in\n let y = b *. (s -. x) /. (b +. c) in\n let y = if y >= 0.0 && y <= s then y else if y > s then s else 0.0 in\n let z = s -. x -. y in\n Printf.printf \"asd %f\\n\" (x ** a *. y ** b *. z ** c);\n Printf.printf \"%.8f %.8f %.8f\\n\" x y z;\n );\n if a +. b +. c > 0.0 then (\n let x = s *. a /. (a +. b +. c) in\n let y = s *. b /. (a +. b +. c) in\n let z = s *. c /. (a +. b +. c) in\n let z = s -. x -. y in\n let z = max z 0.0 in\n let d = 1e10 in\n let x = floor (x *. d) /. d in\n let y = floor (y *. d) /. d in\n let z = floor (z *. d) /. d in\n\tPrintf.printf \"%.10f %.10f %.10f\\n\" x y z\n ) else\n Printf.printf \"%.8f %.8f %.8f\\n\" s 0.0 0.0\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = float_of_int s in\n let a = float_of_int a in\n let b = float_of_int b in\n let c = float_of_int c in\n let l = ref 0.0 in\n let r = ref s in\n let calc x y z =\n let xa = if a = 0.0 then 0.0 else a *. log x in\n let yb = if b = 0.0 then 0.0 else b *. log y in\n let zc = if c = 0.0 then 0.0 else c *. log z in\n xa +. yb +. zc\n in\n for i = 1 to 400 do\n let x1 = (2.0 *. !l +. !r) /. 3.0 in\n let y1 = b *. (s -. x1) /. (b +. c) in\n let y1 = if y1 >= 0.0 && y1 <= s then y1 else if y1 > s then s else 0.0 in\n let z1 = s -. x1 -. y1 in\n let x2 = (!l +. 2.0 *. !r) /. 3.0 in\n let y2 = b *. (s -. x2) /. (b +. c) in\n let y2 = if y2 >= 0.0 && y2 <= s then y2 else if y2 > s then s else 0.0 in\n let z2 = s -. x2 -. y2 in\n\tif calc x1 y1 z1 > calc x2 y2 z2\n\tthen r := x2\n\telse l := x1\n done;\n let x = (!l +. !r) /. 2.0 in\n let y = b *. (s -. x) /. (b +. c) in\n let y = if y >= 0.0 && y <= s then y else if y > s then s else 0.0 in\n let z = s -. x -. y in\n Printf.printf \"%.8f %.8f %.8f\\n\" x y z\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = float_of_int s in\n let a = float_of_int a in\n let b = float_of_int b in\n let c = float_of_int c in\n (*let l = ref 0.0 in\n let r = ref s in\n let calc x y z =\n let xa = if a = 0.0 then 0.0 else a *. log x in\n let yb = if b = 0.0 then 0.0 else b *. log y in\n let zc = if c = 0.0 then 0.0 else c *. log z in\n xa +. yb +. zc\n in\n for i = 1 to 400 do\n let x1 = (2.0 *. !l +. !r) /. 3.0 in\n let y1 = b *. (s -. x1) /. (b +. c) in\n let y1 = if y1 >= 0.0 && y1 <= s then y1 else if y1 > s then s else 0.0 in\n let z1 = s -. x1 -. y1 in\n let x2 = (!l +. 2.0 *. !r) /. 3.0 in\n let y2 = b *. (s -. x2) /. (b +. c) in\n let y2 = if y2 >= 0.0 && y2 <= s then y2 else if y2 > s then s else 0.0 in\n let z2 = s -. x2 -. y2 in\n\tif calc x1 y1 z1 > calc x2 y2 z2\n\tthen r := x2\n\telse l := x1\n done;\n let x = (!l +. !r) /. 2.0 in\n let y = b *. (s -. x) /. (b +. c) in\n let y = if y >= 0.0 && y <= s then y else if y > s then s else 0.0 in\n let z = s -. x -. y in\n Printf.printf \"asd %f\\n\" (x ** a *. y ** b *. z ** c);\n Printf.printf \"%.8f %.8f %.8f\\n\" x y z;*)\n let x = s *. a /. (a +. b +. c) in\n let y = s *. b /. (a +. b +. c) in\n let z = s *. c /. (a +. b +. c) in\n\tPrintf.printf \"%.8f %.8f %.8f\\n\" x y z;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = float_of_int s in\n let a = float_of_int a in\n let b = float_of_int b in\n let c = float_of_int c in\n (*let l = ref 0.0 in\n let r = ref s in\n let calc x y z =\n let xa = if a = 0.0 then 0.0 else a *. log x in\n let yb = if b = 0.0 then 0.0 else b *. log y in\n let zc = if c = 0.0 then 0.0 else c *. log z in\n xa +. yb +. zc\n in\n for i = 1 to 400 do\n let x1 = (2.0 *. !l +. !r) /. 3.0 in\n let y1 = b *. (s -. x1) /. (b +. c) in\n let y1 = if y1 >= 0.0 && y1 <= s then y1 else if y1 > s then s else 0.0 in\n let z1 = s -. x1 -. y1 in\n let x2 = (!l +. 2.0 *. !r) /. 3.0 in\n let y2 = b *. (s -. x2) /. (b +. c) in\n let y2 = if y2 >= 0.0 && y2 <= s then y2 else if y2 > s then s else 0.0 in\n let z2 = s -. x2 -. y2 in\n\tif calc x1 y1 z1 > calc x2 y2 z2\n\tthen r := x2\n\telse l := x1\n done;\n let x = (!l +. !r) /. 2.0 in\n let y = b *. (s -. x) /. (b +. c) in\n let y = if y >= 0.0 && y <= s then y else if y > s then s else 0.0 in\n let z = s -. x -. y in\n Printf.printf \"asd %f\\n\" (x ** a *. y ** b *. z ** c);\n Printf.printf \"%.8f %.8f %.8f\\n\" x y z;*)\n if a +. b +. c > 0.0 then (\n let x = s *. a /. (a +. b +. c) in\n let y = s *. b /. (a +. b +. c) in\n let z = s *. c /. (a +. b +. c) in\n\tPrintf.printf \"%.8f %.8f %.8f\\n\" x y z\n ) else\n Printf.printf \"%.8f %.8f %.8f\\n\" s 0.0 0.0\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let c = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = float_of_int s in\n let a = float_of_int a in\n let b = float_of_int b in\n let c = float_of_int c in\n let l = ref 0.0 in\n let r = ref s in\n let calc x y z =\n a *. log x +. b *. log y +. c *. log z\n in\n for i = 1 to 100 do\n let x1 = (2.0 *. !l +. !r) /. 3.0 in\n let y1 = b *. (s -. x1) /. (b +. c) in\n let y1 = if y1 >= 0.0 && y1 <= s then y1 else if y1 > s then s else 0.0 in\n let z1 = s -. x1 -. y1 in\n let x2 = (!l +. 2.0 *. !r) /. 3.0 in\n let y2 = b *. (s -. x2) /. (b +. c) in\n let y2 = if y2 >= 0.0 && y2 <= s then y2 else if y2 > s then s else 0.0 in\n let z2 = s -. x2 -. y2 in\n\tif calc x1 y1 z1 > calc x2 y2 z2\n\tthen r := x2\n\telse l := x1\n done;\n let x = (!l +. !r) /. 2.0 in\n let y = b *. (s -. x) /. (b +. c) in\n let y = if y >= 0.0 && y <= s then y else if y > s then s else 0.0 in\n let z = s -. x -. y in\n Printf.printf \"%.8f %.8f %.8f\\n\" x y z\n"}], "src_uid": "0a9cabb857949e818453ffe411f08f95"} {"nl": {"description": "Gerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such tickets and moved on to a more general question. Now he explores k-lucky tickets.Pollard sais that a ticket is k-lucky if we can add arithmetic operation signs between its digits to the left or right of them (i.e., \"+\", \"-\", \"\u2009\u00d7\u2009\") and brackets so as to obtain the correct arithmetic expression whose value would equal k. For example, ticket \"224201016\" is 1000-lucky as (\u2009-\u20092\u2009-\u2009(2\u2009+\u20094))\u2009\u00d7\u2009(2\u2009+\u20090)\u2009+\u20091016\u2009=\u20091000.Pollard was so carried away by the lucky tickets that he signed up for a seminar on lucky tickets and, as far as Gerald knows, Pollard will attend it daily at 7 pm in some famous institute and will commute to it in the same tram for m days. In this tram tickets have eight digits. And Gerald wants to make a surprise for Pollard: each day Pollard will receive a tram k-lucky ticket. The conductor has already agreed to give Pollard certain tickets during all these m days and he only wants Gerald to tell him what kind of tickets to give out. In this regard, help Gerald pick exactly m distinct k-lucky tickets.", "input_spec": "The single line contains two integers k and m (0\u2009\u2264\u2009k\u2009\u2264\u2009104, 1\u2009\u2264\u2009m\u2009\u2264\u20093\u00b7105).", "output_spec": "Print m lines. Each line must contain exactly 8 digits \u2014 the k-winning ticket. The tickets may begin with 0, all tickets must be distinct. If there are more than m distinct k-lucky tickets, print any m of them. It is guaranteed that at least m distinct k-lucky tickets exist. The tickets can be printed in any order.", "sample_inputs": ["0 3", "7 4"], "sample_outputs": ["00000000\n00000001\n00000002", "00000007\n00000016\n00000017\n00000018"], "notes": null}, "positive_code": [{"source_code": "module IntSet = Set.Make( \n struct\n let compare = Pervasives.compare\n type t = int\n end );;\n\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\n\nlet (k, m) = (read_int(), read_int());;\n\nlet ans = ref IntSet.empty;;\n\nlet counter = ref 0;;\n\nlet rec build cval rest pos orig = \n let append v = (\n if (IntSet.mem v !ans) or (!counter == k) then ()\n else (counter := !counter + 1; ans := IntSet.add v !ans)\n )\n in\n if pos = 4 then\n let delta = abs ((abs cval) - m) in\n if (delta < 10000) then (\n append (delta * 10000 + orig);\n append (orig * 10000 + delta);\n )\n else () \n else\n let (dig, rest') = (rest mod 10, rest / 10) in (\n build (cval + dig) rest' (pos + 1) orig;\n build (cval - dig) rest' (pos + 1) orig;\n build (cval * dig) rest' (pos + 1) orig\n )\n ;;\n\nfor i = 0 to 9999 do\n build (i mod 10) (i / 10) 1 i\ndone;;\n\nlet print a t = Printf.printf \"%08d\\n\" a in IntSet.fold print !ans ();;\n\n"}], "negative_code": [{"source_code": "module IntSet = Set.Make( \n struct\n let compare = Pervasives.compare\n type t = int\n end );;\n\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\n\nlet (k, m) = (read_int(), read_int());;\n\nPrintf.printf \"%d %d\\n\" m k;;\n\nlet ans = ref IntSet.empty;;\n\nlet rec build set cval rest pos orig = \n let append s v = \n if (IntSet.cardinal s < k) then (IntSet.add v s) else s\n in\n if pos = 4 then\n let delta = abs ((abs cval) - m) in\n if (delta < 10000) then\n append (append set (delta * 10000 + orig)) (orig * 10000 + delta)\n else set \n else\n let (dig, rest') = (rest mod 10, rest / 10) in\n let s0 = build set (cval + dig) rest' (pos + 1) orig in\n let s1 = build s0 (cval - dig) rest' (pos + 1) orig in\n let s2 = build s1 (cval * dig) rest' (pos + 1) orig\n in s2\n ;;\n\nfor i = 0 to 9999 do\n ans := build !ans (i mod 10) (i / 10) 1 i\ndone;;\n\nlet print a t = Printf.printf \"%08d\\n\" a in IntSet.fold print !ans ();;\n\n"}], "src_uid": "4720ca1d2f4b7a0e553a3ea07a76943c"} {"nl": {"description": "We are sum for we are manySome NumberThis version of the problem differs from the previous one only in the constraint on $$$t$$$. You can make hacks only if both versions of the problem are solved.You are given two positive integers $$$l$$$ and $$$r$$$.Count the number of distinct triplets of integers $$$(i, j, k)$$$ such that $$$l \\le i < j < k \\le r$$$ and $$$\\operatorname{lcm}(i,j,k) \\ge i + j + k$$$.Here $$$\\operatorname{lcm}(i, j, k)$$$ denotes the least common multiple (LCM) of integers $$$i$$$, $$$j$$$, and $$$k$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$\\bf{1 \\le t \\le 10^5}$$$). Description of the test cases follows. The only line for each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \\le l \\le r \\le 2 \\cdot 10^5$$$, $$$l + 2 \\le r$$$).", "output_spec": "For each test case print one integer\u00a0\u2014 the number of suitable triplets.", "sample_inputs": ["5\n\n1 4\n\n3 5\n\n8 86\n\n68 86\n\n6 86868"], "sample_outputs": ["3\n1\n78975\n969\n109229059713337"], "notes": "NoteIn the first test case, there are $$$3$$$ suitable triplets: $$$(1,2,3)$$$, $$$(1,3,4)$$$, $$$(2,3,4)$$$. In the second test case, there is $$$1$$$ suitable triplet: $$$(3,4,5)$$$. "}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet max_n = 200000\n\nmodule SegTree = struct\n type t = int64 array\n\n let init n = A.make n I.zero\n\n let add t i x =\n let v = ref i in\n let n = A.length t in\n while !v < n do\n t.(!v) <- I.add t.(!v) x;\n v := !v lor (!v + 1);\n done\n\n let pref_sum t i =\n let r = ref i in\n let res = ref I.zero in\n while !r >= 0 do\n res := I.add !res t.(!r);\n r := (!r land (!r + 1)) - 1;\n done;\n !res\n\n let sum t l r = I.sub (pref_sum t r) (pref_sum t (l - 1))\nend\n\nmodule L_ = struct\n let filter_map f =\n let rec aux accu = function\n | [] -> L.rev accu\n | x :: l ->\n match f x with\n | None -> aux accu l\n | Some v -> aux (v :: accu) l\n in\n aux []\nend\n\ntype query = {\n l: int;\n q_index: int;\n}\n\nlet find_first_div n =\n let i = ref 2 in\n let found = ref (-1) in\n while !i * !i <= n && !found = -1 do\n if (n mod !i = 0) then found := !i;\n i := !i + 1;\n done;\n if (!found = -1) then n\n else !found\n\nlet () =\n let q = read_int () in\n let original_queries: (int * int) array = Array.make q (0, 0) in\n let ans = Array.make q I.zero in\n let (events: query list array) = Array.init (max_n + 1) (fun _ -> []) in\n for i = 0 to q - 1 do\n let l = read_int () in\n let r = read_int () in\n original_queries.(i) <- (l, r);\n events.(r) <- {l; q_index = i;} :: events.(r);\n done;\n\n let (divisors: int list array) = Array.make (max_n + 1) [] in\n let pw2 = Array.make (max_n + 1) 0 in\n divisors.(1) <- [1];\n\n let inc_tree = SegTree.init (max_n + 1) in\n for k = 2 to max_n do\n let fd = find_first_div k in\n let divs_prev = divisors.(k / fd) in\n divisors.(k) <- L.sort_uniq compare (divs_prev @ List.map (fun x -> x * fd) divs_prev);\n if (k mod 2 = 0) then pw2.(k) <- pw2.(k / 2) + 1;\n\n let divs = divisors.(k) in\n let divs_num = L.length divs in\n L.iteri (fun idx i ->\n if (i <> k) then\n SegTree.add inc_tree i @@ I.of_int @@ divs_num - idx - 2;\n ) divs;\n let p = pw2.(k) in\n\n let new_divs =\n A.of_list @@\n L.tl @@\n L.fast_sort (fun x y -> -compare x y) @@\n divs @ L_.filter_map (fun d ->\n if (d * 2 < k && pw2.(d) == p) then Some (d * 2)\n else None\n ) divs in\n let sj_p = ref 0 and ptr_j = ref (-1) in\n A.iteri (fun idx i ->\n while (!ptr_j <> -1 && new_divs.(!ptr_j) + i <= k) do\n let cd = new_divs.(!ptr_j) in\n if (pw2.(cd) = p + 1) then sj_p := !sj_p - 1;\n ptr_j := !ptr_j - 1\n done;\n\n if (pw2.(i) = p + 1) then\n SegTree.add inc_tree i @@ I.of_int @@ !ptr_j + 1\n else\n SegTree.add inc_tree i @@ I.of_int !sj_p;\n\n while (!ptr_j + 1 <= idx && new_divs.(!ptr_j + 1) + i > k) do\n let cd = new_divs.(!ptr_j + 1) in\n if (pw2.(cd) = p + 1) then sj_p := !sj_p + 1;\n ptr_j := !ptr_j + 1\n done;\n ) new_divs;\n\n L.iter (fun q ->\n ans.(q.q_index) <- SegTree.sum inc_tree q.l k;\n ) events.(k)\n done;\n\n for i = 0 to q - 1 do\n let n = snd original_queries.(i) - fst original_queries.(i) + 1 in\n let real_ans =\n I.(sub\n (div\n (mul (mul (of_int n) (of_int @@ n - 1)) (of_int @@ n - 2))\n (of_int 6))\n ans.(i)) in\n pf \"%Ld\\n\" real_ans;\n done;"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet max_n = 200000\n\nmodule SegTree = struct\n type t = int64 array\n\n let init n = A.make (2 * n) I.zero\n\n let add t i x =\n let v = ref i in\n let n = A.length t in\n while !v < n do\n t.(!v) <- I.add t.(!v) x;\n v := !v lor (!v + 1);\n done\n\n let pref_sum t i =\n let r = ref i in\n let res = ref I.zero in\n while !r >= 0 do\n res := I.add !res t.(!r);\n r := (!r land (!r + 1)) - 1;\n done;\n !res\n\n let sum t l r = I.sub (pref_sum t r) (pref_sum t (l - 1))\nend\n\nmodule L_ = struct\n let filter_map f =\n let rec aux accu = function\n | [] -> L.rev accu\n | x :: l ->\n match f x with\n | None -> aux accu l\n | Some v -> aux (v :: accu) l\n in\n aux []\nend\n\ntype query = {\n l: int;\n q_index: int;\n}\n\nlet find_first_div n =\n let i = ref 2 in\n let found = ref (-1) in\n while !i * !i <= n && !found = -1 do\n if (n mod !i = 0) then found := !i;\n i := !i + 1;\n done;\n if (!found = -1) then n\n else !found\n\nlet () =\n let q = read_int () in\n let original_queries: (int * int) array = Array.make q (0, 0) in\n let ans = Array.make q I.zero in\n let (events: query list array) = Array.init (max_n + 1) (fun _ -> []) in\n for i = 0 to q - 1 do\n let l = read_int () in\n let r = read_int () in\n original_queries.(i) <- (l, r);\n events.(r) <- {l; q_index = i;} :: events.(r);\n done;\n\n let (divisors: int list array) = Array.make (max_n + 1) [] in\n let pw2 = Array.make (max_n + 1) 0 in\n divisors.(1) <- [1];\n\n let inc_tree = SegTree.init max_n in\n for k = 2 to max_n do\n let fd = find_first_div k in\n let divs_prev = divisors.(k / fd) in\n divisors.(k) <- L.sort_uniq compare (divs_prev @ List.map (fun x -> x * fd) divs_prev);\n if (k mod 2 = 0) then pw2.(k) <- pw2.(k / 2) + 1;\n\n let divs = divisors.(k) in\n let divs_num = L.length divs in\n L.iteri (fun idx i ->\n if (i <> k) then\n SegTree.add inc_tree i @@ I.of_int @@ divs_num - idx - 2;\n ) divs;\n let p = pw2.(k) in\n\n let new_divs =\n A.of_list @@\n L.tl @@\n L.fast_sort (fun x y -> -compare x y) @@\n divs @ L_.filter_map (fun d ->\n if (d * 2 < k && pw2.(d) == p) then Some (d * 2)\n else None\n ) divs in\n let sj_p = ref 0 and ptr_j = ref (-1) in\n A.iteri (fun idx i ->\n while (!ptr_j <> -1 && new_divs.(!ptr_j) + i <= k) do\n let cd = new_divs.(!ptr_j) in\n if (pw2.(cd) = p + 1) then sj_p := !sj_p - 1;\n ptr_j := !ptr_j - 1\n done;\n\n if (pw2.(i) = p + 1) then\n SegTree.add inc_tree i @@ I.of_int @@ !ptr_j + 1\n else\n SegTree.add inc_tree i @@ I.of_int !sj_p;\n\n while (!ptr_j + 1 <= idx && new_divs.(!ptr_j + 1) + i > k) do\n let cd = new_divs.(!ptr_j + 1) in\n if (pw2.(cd) = p + 1) then sj_p := !sj_p + 1;\n ptr_j := !ptr_j + 1\n done;\n ) new_divs;\n\n L.iter (fun q ->\n ans.(q.q_index) <- SegTree.sum inc_tree q.l k;\n ) events.(k)\n done;\n\n for i = 0 to q - 1 do\n let n = snd original_queries.(i) - fst original_queries.(i) + 1 in\n let real_ans =\n I.(sub\n (div\n (mul (mul (of_int n) (of_int @@ n - 1)) (of_int @@ n - 2))\n (of_int 6))\n ans.(i)) in\n pf \"%Ld\\n\" real_ans;\n done;"}], "negative_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet max_n = 200000\n\nmodule SegTree = struct\n let init = ()\n let add _i (_x: int64) = ()\n\n let sum _l _r: int64 = I.zero\n\nend\n\ntype query = {\n l: int;\n q_index: int;\n}\n\nlet find_first_div n =\n let i = ref 2 in\n let found = ref (-1) in\n while !i * !i <= n && !found = -1 do\n if (n mod !i = 0) then found := !i;\n i := !i + 1;\n done;\n if (!found = -1) then n\n else !found\n\nlet () =\n (* let q = read_int () in\n let original_queries: (int * int) array = Array.make q (0, 0) in\n let ans = Array.make q I.zero in\n let (events: query list array) = Array.init (max_n + 1) (fun _ -> []) in\n for i = 0 to q - 1 do\n let l = read_int () in\n let r = read_int () in\n original_queries.(i) <- (l, r);\n events.(r) <- {l; q_index = i;} :: events.(r);\n done; *)\n\n let (divisors: int list array) = Array.make (max_n + 1) [] in\n let pw2 = Array.make (max_n + 1) 0 in\n divisors.(1) <- [1];\n\n for i = 2 to max_n do\n let fd = find_first_div i in\n let divs_prev = divisors.(i / fd) in\n divisors.(i) <- L.sort_uniq compare (divs_prev @ List.map (fun x -> x * fd) divs_prev);\n if (i mod 2 = 0) then pw2.(i) <- pw2.(i / 2) + 1;\n done;\n\n"}, {"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet max_n = 200000\n\nmodule SegTree = struct\n let init = ()\n let add _i (_x: int64) = ()\n\n let sum _l _r: int64 = I.zero\n\nend\n\ntype query = {\n l: int;\n q_index: int;\n}\n\nlet find_first_div n =\n let i = ref 2 in\n let found = ref (-1) in\n while !i * !i <= n && !found = -1 do\n if (n mod !i = 0) then found := !i;\n i := !i + 1;\n done;\n if (!found = -1) then n\n else !found\n\nlet () =\n (* let q = read_int () in\n let original_queries: (int * int) array = Array.make q (0, 0) in\n let (events: query list array) = Array.init max_n (fun _ -> []) in\n for i = 0 to q - 1 do\n let l = read_int () in\n let r = read_int () in\n original_queries.(i) <- (l, r);\n events.(r) <- {l; q_index = i;} :: events.(r);\n done; *)\n\n let (divisors: int list array) = Array.make (max_n + 1) [] in\n let pw2 = Array.make (max_n + 1) 0 in\n divisors.(0) <- [1];\n\n for i = 2 to max_n do\n let fd = find_first_div i in\n let divs_prev = divisors.(i / fd) in\n divisors.(i) <- List.sort_uniq compare (divs_prev @ List.map (fun x -> x * fd) divs_prev);\n if (i mod 2 = 0) then pw2.(i) <- pw2.(i / 2) + 1;\n done;\n\n"}], "src_uid": "6a3043daecdb0442f4878ee08a8b70ba"} {"nl": {"description": "Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters \u2014 for different colours.", "input_spec": "The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters \u2014 the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order. The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order. ", "output_spec": "Output one of the four words without inverted commas: \u00abforward\u00bb \u2014 if Peter could see such sequences only on the way from A to B; \u00abbackward\u00bb \u2014 if Peter could see such sequences on the way from B to A; \u00abboth\u00bb \u2014 if Peter could see such sequences both on the way from A to B, and on the way from B to A; \u00abfantasy\u00bb \u2014 if Peter could not see such sequences. ", "sample_inputs": ["atob\na\nb", "aaacaaa\naca\naa"], "sample_outputs": ["forward", "both"], "notes": "NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and B."}, "positive_code": [{"source_code": "let (|>) x f = f x\n\nmodule String = struct\n include String\n\n exception Exit\n\n let find_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = pos to n-m do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let find str sub = find_from str 0 sub\n\n let rfind_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = min (n-m) pos downto 0 do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let rfind str sub = rfind_from str (String.length str) sub\n\n let rev str =\n let r = String.copy str in\n let rec go i j =\n if i < j then (\n let t = r.[i] in\n r.[i] <- r.[j];\n r.[j] <- t;\n go (i+1) (j-1)\n )\n in\n go 0 (String.length str-1);\n r\nend\n\nlet () =\n let a = read_line () in\n let aa = String.rev a in\n let b = read_line () in\n let c = read_line () in\n let b1 = String.find a b\n and b2 = String.find aa b\n and c1 = String.rfind a c\n and c2 = String.rfind aa c in\n print_endline [|\"fantasy\"; \"forward\"; \"backward\"; \"both\"|].(\n (if 0 <= b1 && b1+String.length b <= c1 then 1 else 0) + (if 0 <= b2 && b2+String.length b <= c2 then 2 else 0))\n"}], "negative_code": [{"source_code": "let (|>) x f = f x\n\nmodule String = struct\n include String\n\n exception Exit\n\n let find_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = pos to n-m do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let find str sub = find_from str 0 sub\n\n let rfind_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = min (n-m) pos downto 0 do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let rfind str sub = rfind_from str (String.length str) sub\nend\n\nlet () =\n let a = read_line () in\n let b = read_line () in\n let c = read_line () in\n let b1 = String.find a b\n and b2 = String.rfind a b\n and c1 = String.find a c\n and c2 = String.rfind a c in\n print_endline [|\"fantasy\"; \"forward\"; \"backward\"; \"both\"|].(\n (if b1+String.length b <= c2 then 1 else 0) + (if c1+String.length c <= b2 then 2 else 0))\n"}, {"source_code": "let (|>) x f = f x\n\nmodule String = struct\n include String\n\n exception Exit\n\n let find_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = pos to n-m do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let find str sub = find_from str 0 sub\n\n let rfind_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = min (n-m) pos downto 0 do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let rfind str sub = rfind_from str (String.length str) sub\n\n let rev str =\n let r = String.copy str in\n let rec go i j =\n if i < j then (\n let t = r.[i] in\n r.[i] <- r.[j];\n r.[j] <- t\n )\n in\n go 0 (String.length str-1);\n r\nend\n\nlet () =\n let a = read_line () in\n let aa = String.rev a in\n let b = read_line () in\n let c = read_line () in\n let b1 = String.find a b\n and b2 = String.find aa b\n and c1 = String.find a c\n and c2 = String.find aa c in\n print_endline [|\"fantasy\"; \"forward\"; \"backward\"; \"both\"|].(\n (if 0 <= b1 && b1+String.length b <= c2 then 1 else 0) + (if 0 <= c1 && c1+String.length c <= b2 then 2 else 0))\n"}, {"source_code": "let (|>) x f = f x\n\nmodule String = struct\n include String\n\n exception Exit\n\n let find_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = pos to n-m do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let find str sub = find_from str 0 sub\n\n let rfind_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = min (n-m) pos downto 0 do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let rfind str sub = rfind_from str (String.length str) sub\nend\n\nlet () =\n let a = read_line () in\n let b = read_line () in\n let c = read_line () in\n let b1 = String.find a b\n and b2 = String.rfind a b\n and c1 = String.find a c\n and c2 = String.rfind a c in\n print_endline [|\"fantasy\"; \"forward\"; \"backward\"; \"both\"|].((if b1 < c2 then 1 else 0) + (if c1 < b2 then 2 else 0))\n"}, {"source_code": "let (|>) x f = f x\n\nmodule String = struct\n include String\n\n exception Exit\n\n let find_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = pos to n-m do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let find str sub = find_from str 0 sub\n\n let rfind_from str pos sub =\n let n = length str\n and m = length sub in\n if m = 0 then\n pos\n else\n let found = ref (-1) in\n try\n for i = min (n-m) pos downto 0 do\n let j = ref 0 in\n while unsafe_get str (i + !j) = unsafe_get sub (!j) do\n incr j;\n if !j = m then (found := i; raise Exit)\n done\n done;\n -1\n with Exit ->\n !found\n\n let rfind str sub = rfind_from str (String.length str) sub\nend\n\nlet () =\n let a = read_line () in\n let b = read_line () in\n let c = read_line () in\n let b1 = String.find a b\n and b2 = String.rfind a b\n and c1 = String.find a c\n and c2 = String.rfind a c in\n print_endline [|\"fantasy\"; \"forward\"; \"backward\"; \"both\"|].(\n (if 0 <= b1 && b1+String.length b <= c2 then 1 else 0) + (if 0 <= c1 && c1+String.length c <= b2 then 2 else 0))\n"}], "src_uid": "c3244e952830643938d51ce14f043d7d"} {"nl": {"description": "Polycarp found under the Christmas tree an array $$$a$$$ of $$$n$$$ elements and instructions for playing with it: At first, choose index $$$i$$$ ($$$1 \\leq i \\leq n$$$)\u00a0\u2014 starting position in the array. Put the chip at the index $$$i$$$ (on the value $$$a_i$$$). While $$$i \\leq n$$$, add $$$a_i$$$ to your score and move the chip $$$a_i$$$ positions to the right (i.e. replace $$$i$$$ with $$$i + a_i$$$). If $$$i > n$$$, then Polycarp ends the game. For example, if $$$n = 5$$$ and $$$a = [7, 3, 1, 2, 3]$$$, then the following game options are possible: Polycarp chooses $$$i = 1$$$. Game process: $$$i = 1 \\overset{+7}{\\longrightarrow} 8$$$. The score of the game is: $$$a_1 = 7$$$. Polycarp chooses $$$i = 2$$$. Game process: $$$i = 2 \\overset{+3}{\\longrightarrow} 5 \\overset{+3}{\\longrightarrow} 8$$$. The score of the game is: $$$a_2 + a_5 = 6$$$. Polycarp chooses $$$i = 3$$$. Game process: $$$i = 3 \\overset{+1}{\\longrightarrow} 4 \\overset{+2}{\\longrightarrow} 6$$$. The score of the game is: $$$a_3 + a_4 = 3$$$. Polycarp chooses $$$i = 4$$$. Game process: $$$i = 4 \\overset{+2}{\\longrightarrow} 6$$$. The score of the game is: $$$a_4 = 2$$$. Polycarp chooses $$$i = 5$$$. Game process: $$$i = 5 \\overset{+3}{\\longrightarrow} 8$$$. The score of the game is: $$$a_5 = 3$$$. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$)\u00a0\u2014 the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output on a separate line one number\u00a0\u2014 the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from $$$1$$$ to $$$n$$$ in such a way as to maximize his result.", "sample_inputs": ["4\n5\n7 3 1 2 3\n3\n2 1 4\n6\n2 1000 2 3 995 1\n5\n1 1 1 1 1"], "sample_outputs": ["7\n6\n1000\n5"], "notes": "NoteThe first test case is explained in the statement.In the second test case, the maximum score can be achieved by choosing $$$i = 1$$$.In the third test case, the maximum score can be achieved by choosing $$$i = 2$$$.In the fourth test case, the maximum score can be achieved by choosing $$$i = 1$$$."}, "positive_code": [{"source_code": "(** https://codeforces.com/contest/1472/problem/C *)\n\nlet read_int () = Scanf.scanf \" %d \" (fun a -> a)\n\nlet get_array size_array =\n let arr = Array.make size_array 0L in\n let rec helper i =\n if i < size_array\n then (\n let new_val = \n if i = size_array-1\n then Scanf.scanf \"%Ld\\n\" (fun a -> a)\n else Scanf.scanf \" %Ld \" (fun a -> a) in\n arr.(i) <- new_val;\n helper (i+1)\n ) in\n helper 0;\n arr\n\nlet max_score arr =\n let (++) = Int64.add and\n (~++) = Int64.of_int and\n (~-+) = Int64.to_int and\n size = Array.length arr in\n let size64 = ~++size in\n let score_arr = Array.make size 0L in\n let rec helper i =\n if i >= 0\n then (\n let tile_delta = arr.(i) in\n if ~++i ++ tile_delta >= size64\n then score_arr.(i) <- tile_delta\n else score_arr.(i) <- score_arr.(i + (~-+tile_delta)) ++ tile_delta;\n helper (i-1)\n ) in\n helper (size-1);\n Array.fold_left\n (fun acc el -> if el > acc then el else acc)\n 0L\n score_arr\n\nlet solve_n nb_cases =\n let rec helper i =\n if i > 0\n then (\n let size_array = read_int () in\n let arr = get_array size_array in\n max_score arr\n |> Printf.printf \"%Ld\\n\";\n helper (i-1)\n ) in\n helper nb_cases\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "negative_code": [], "src_uid": "ee8ca9b2c6104d1ff9ba1fc39e9df277"} {"nl": {"description": "It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi,\u2009yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: Choose to stop or to continue to collect bottles. If the choice was to continue then choose some bottle and walk towards it. Pick this bottle and walk to the recycling bin. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin.", "input_spec": "First line of the input contains six integers ax, ay, bx, by, tx and ty (0\u2009\u2264\u2009ax,\u2009ay,\u2009bx,\u2009by,\u2009tx,\u2009ty\u2009\u2264\u2009109)\u00a0\u2014 initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109)\u00a0\u2014 position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct.", "output_spec": "Print one real number\u00a0\u2014 the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .", "sample_inputs": ["3 1 1 2 0 0\n3\n1 1\n2 1\n2 3", "5 0 4 2 2 0\n5\n5 2\n3 0\n5 5\n3 5\n3 3"], "sample_outputs": ["11.084259940083", "33.121375178000"], "notes": "NoteConsider the first sample.Adil will use the following path: .Bera will use the following path: .Adil's path will be units long, while Bera's path will be units long."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\n\nlet inf = 1e20\nlet argmin i j f = \n fold i j (\n fun k (index,v) -> let m = (f k) in if m x)\nlet read_float () = float (read_int())\nlet read2 () = let x = read_float() in (x, read_float())\n\nlet () = \n let a = read2() in\n let b = read2() in\n let t = read2() in\n let n = read_int () in\n\n let bot = Array.init n (fun i -> read2()) in\n\n let ca = Array.init n (fun i -> (dist bot.(i) a) -. (dist bot.(i) t)) in\n let cb = Array.init n (fun i -> (dist bot.(i) b) -. (dist bot.(i) t)) in\n\n let (besta, _) = argmin 0 (n-1) (fun i -> ca.(i)) in\n let (bestb, _) = argmin 0 (n-1) (fun i -> cb.(i)) in\n\n if n = 1 then\n let answer = (min (dist bot.(0) a) (dist bot.(0) b)) +. (dist bot.(0) t) in\n printf \"%.8f\\n\" answer\n else \n\n let adjust =\n let trypair besta bestb =\n match (ca.(besta) < 0.0, cb.(bestb) < 0.0) with\n\t| (true,true) -> ca.(besta) +. cb.(bestb)\n\t| (true,false) -> ca.(besta)\n\t| (false,true) -> cb.(bestb)\n\t| (false,false) -> min ca.(besta) cb.(bestb)\n in\n \n if besta = bestb then (\n let rec loop mincost i = if i=n then mincost else\n\t if i = besta then loop mincost (i+1)\n\t else (\n\t let opt1 = trypair besta i in\n\t let opt2 = trypair i besta in\n\t let bopt = min opt1 opt2 in\n\t loop (min bopt mincost) (i+1)\n\t )\n in\n loop inf 0\n ) else trypair besta bestb\n in\n\n let total = sum 0 (n-1) (fun i -> 2.0 *. (dist bot.(i) t)) in\n let answer = total +. adjust in\n\n printf \"%.8f\\n\" answer\n"}], "negative_code": [], "src_uid": "ae8687ed3cb5df080fb6ee79b040cef1"} {"nl": {"description": "You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.Initially, you have an integer $$$x = 0$$$. During one move, you can do one of the following two operations: Choose exactly one $$$i$$$ from $$$1$$$ to $$$n$$$ and increase $$$a_i$$$ by $$$x$$$ ($$$a_i := a_i + x$$$), then increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). Just increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). The first operation can be applied no more than once to each $$$i$$$ from $$$1$$$ to $$$n$$$.Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$ (the value $$$k$$$ is given).You have to answer $$$t$$$ independent test cases. ", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 2 \\cdot 10^5; 1 \\le k \\le 10^9$$$) \u2014 the length of $$$a$$$ and the required divisior. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$.", "sample_inputs": ["5\n4 3\n1 2 1 3\n10 6\n8 7 1 8 3 7 5 10 8 9\n5 10\n20 100 50 20 100500\n10 25\n24 24 24 24 24 24 24 24 24 24\n8 8\n1 2 3 4 5 6 7 8"], "sample_outputs": ["6\n18\n0\n227\n8"], "notes": "NoteConsider the first test case of the example: $$$x=0$$$, $$$a = [1, 2, 1, 3]$$$. Just increase $$$x$$$; $$$x=1$$$, $$$a = [1, 2, 1, 3]$$$. Add $$$x$$$ to the second element and increase $$$x$$$; $$$x=2$$$, $$$a = [1, 3, 1, 3]$$$. Add $$$x$$$ to the third element and increase $$$x$$$; $$$x=3$$$, $$$a = [1, 3, 3, 3]$$$. Add $$$x$$$ to the fourth element and increase $$$x$$$; $$$x=4$$$, $$$a = [1, 3, 3, 6]$$$. Just increase $$$x$$$; $$$x=5$$$, $$$a = [1, 3, 3, 6]$$$. Add $$$x$$$ to the first element and increase $$$x$$$; $$$x=6$$$, $$$a = [6, 3, 3, 6]$$$. We obtained the required array. Note that you can't add $$$x$$$ to the same element more than once."}, "positive_code": [{"source_code": "module A = Array\nmodule C = Char\nmodule I = Int64\nmodule L = List\nmodule Q = Queue\nmodule S = String\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet ssf = Scanf.sscanf\n\nlet l_init n f =\n let rec loop acc i =\n if i >= n then acc else loop ((f i) :: acc) (i+1)\n in List.rev (loop [] 0)\n\nlet read_int () = sf \"%d \" (fun x -> x)\nlet read_int64 () = sf \"%d \" (fun x -> I.of_int x)\nlet read_float () = sf \"%f \" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\nlet read_list read n = l_init n (fun _ -> read ())\nlet err s = raise (Failure s)\n\nlet inf = int_of_float 1e18\nlet eps = 1e-11\n\nlet delta0 k x = I.sub k (I.rem x k)\n\nlet deltas k d0s =\n let rec loop acc prevMod prevVal = function\n | [] -> L.rev acc\n | hd::tl when hd = prevMod -> let newVal = I.add prevVal k in\n loop (newVal::acc) prevMod newVal tl\n | hd::tl -> loop (hd::acc) hd hd tl\n in loop [] 0L 0L d0s\n\nlet countSteps k deltas =\n let rec loop acc x = function\n | [] -> acc\n | hd::tl -> loop (I.succ (I.add acc (I.sub hd x))) (I.succ hd) tl\n in loop 0L 0L deltas\n\nlet solveFor k xs =\n L.map (delta0 k) xs\n |> L.filter (fun x -> I.compare x k != 0)\n |> L.sort I.compare\n |> deltas k\n |> L.sort I.compare\n |> countSteps k\n\nlet () =\n for _ = 1 to (read_int ()) do\n let n = read_int () in\n let k = read_int64 () in\n pf \"%Ld\\n\" (solveFor k (read_list read_int64 n))\n done\n"}], "negative_code": [{"source_code": "module A = Array\nmodule C = Char\nmodule I = Int64\nmodule L = List\nmodule Q = Queue\nmodule S = String\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet ssf = Scanf.sscanf\n\nlet l_init n f =\n let rec loop acc i =\n if i >= n then acc else loop ((f i) :: acc) (i+1)\n in List.rev (loop [] 0)\n\nlet read_int () = sf \"%d \" (fun x -> x)\nlet read_int64 () = sf \"%d \" (fun x -> I.of_int x)\nlet read_float () = sf \"%f \" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\nlet read_list read n = l_init n (fun _ -> read ())\nlet err s = raise (Failure s)\n\nlet inf = int_of_float 1e18\nlet eps = 1e-11\n\nlet delta0 k x = I.sub k (I.rem x k)\n\nlet deltas k d0s =\n let rec loop acc prevMod prevVal = function\n | [] -> L.rev acc\n | hd::tl when hd = prevMod -> let newVal = I.add prevVal k in\n loop (newVal::acc) prevMod newVal tl\n | hd::tl -> loop (hd::acc) hd hd tl\n in loop [] 0L 0L d0s\n\nlet countSteps k deltas =\n let rec loop acc x = function\n | [] -> acc\n | hd::tl -> loop (I.succ (I.sub (I.add acc hd) x)) (I.succ hd ) tl\n in loop 0L 0L deltas\n\nlet solveFor k xs =\n L.map (delta0 k) xs\n |> L.filter (fun x -> x != k)\n |> L.sort I.compare\n |> deltas k\n |> L.sort I.compare\n |> countSteps k\n\nlet () =\n for _ = 1 to (read_int ()) do\n let n = read_int () in\n let k = read_int64 () in\n pf \"%Ld\\n\" (solveFor k (read_list read_int64 n))\n done\n"}, {"source_code": "module A = Array\nmodule C = Char\nmodule I = Int64\nmodule L = List\nmodule Q = Queue\nmodule S = String\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet ssf = Scanf.sscanf\n\nlet l_init n f =\n let rec loop acc i =\n if i >= n then acc else loop ((f i) :: acc) (i+1)\n in List.rev (loop [] 0)\n\nlet read_int () = sf \"%d \" (fun x -> x)\nlet read_float () = sf \"%f \" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\nlet read_list read n = l_init n (fun _ -> read ())\nlet err s = raise (Failure s)\n\nlet inf = int_of_float 1e18\nlet eps = 1e-11\n\nlet delta0 k x = k - (x mod k)\n\nlet x' k x d0 =\n if x <= d0 then d0\n else let v = (x - d0) in\n (((v / k) + (if (v mod k) = 0 then 0 else 1)) * k) + d0\n\nlet deltas k d0s =\n let rec loop acc prevMod prevVal = function\n | [] -> L.rev acc\n | hd::tl when hd = prevMod -> let newVal = (prevVal + k) in\n loop (newVal::acc) prevMod newVal tl\n | hd::tl -> loop (hd::acc) hd hd tl\n in loop [] 0 0 d0s\n\nlet countSteps k deltas =\n let rec loop acc x = function\n | [] -> acc\n | hd::tl -> loop (1 + acc + hd - x) (hd + 1) tl\n in loop 0 0 deltas\n\nlet solveFor k (xs: int list) =\n L.map (delta0 k) xs\n |> L.filter (fun x -> x != k)\n |> L.sort compare\n |> deltas k\n |> L.sort compare\n |> countSteps k\n\nlet () =\n for _ = 1 to (read_int ()) do\n let n = read_int () in\n let k = read_int () in\n pf \"%d\\n\" (solveFor k (read_list read_int n))\n done\n"}], "src_uid": "a8b4c115bedda3847e7c2e3620e3e19b"} {"nl": {"description": "Two players decided to play one interesting card game.There is a deck of $$$n$$$ cards, with values from $$$1$$$ to $$$n$$$. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has at least one card. The game goes as follows: on each turn, each player chooses one of their cards (whichever they want) and puts on the table, so that the other player doesn't see which card they chose. After that, both cards are revealed, and the player, value of whose card was larger, takes both cards in his hand. Note that as all cards have different values, one of the cards will be strictly larger than the other one. Every card may be played any amount of times. The player loses if he doesn't have any cards.For example, suppose that $$$n = 5$$$, the first player has cards with values $$$2$$$ and $$$3$$$, and the second player has cards with values $$$1$$$, $$$4$$$, $$$5$$$. Then one possible flow of the game is:The first player chooses the card $$$3$$$. The second player chooses the card $$$1$$$. As $$$3>1$$$, the first player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$, $$$3$$$, the second player has cards $$$4$$$, $$$5$$$.The first player chooses the card $$$3$$$. The second player chooses the card $$$4$$$. As $$$3<4$$$, the second player gets both cards. Now the first player has cards $$$1$$$, $$$2$$$. The second player has cards $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$1$$$. The second player chooses the card $$$3$$$. As $$$1<3$$$, the second player gets both cards. Now the first player has only the card $$$2$$$. The second player has cards $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$.The first player chooses the card $$$2$$$. The second player chooses the card $$$4$$$. As $$$2<4$$$, the second player gets both cards. Now the first player is out of cards and loses. Therefore, the second player wins.Who will win if both players are playing optimally? It can be shown that one of the players has a winning strategy.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 100$$$). The description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$, $$$k_2$$$ ($$$2 \\le n \\le 100, 1 \\le k_1 \\le n - 1, 1 \\le k_2 \\le n - 1, k_1 + k_2 = n$$$)\u00a0\u2014 the number of cards, number of cards owned by the first player and second player correspondingly. The second line of each test case contains $$$k_1$$$ integers $$$a_1, \\dots, a_{k_1}$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the values of cards of the first player. The third line of each test case contains $$$k_2$$$ integers $$$b_1, \\dots, b_{k_2}$$$ ($$$1 \\le b_i \\le n$$$)\u00a0\u2014 the values of cards of the second player. It is guaranteed that the values of all cards are different.", "output_spec": "For each test case, output \"YES\" in a separate line, if the first player wins. Otherwise, output \"NO\" in a separate line. You can print each letter in any case (upper or lower).", "sample_inputs": ["2\n2 1 1\n2\n1\n5 2 3\n2 3\n1 4 5"], "sample_outputs": ["YES\nNO"], "notes": "NoteIn the first test case of the example, there is only one possible move for every player: the first player will put $$$2$$$, the second player will put $$$1$$$. $$$2>1$$$, so the first player will get both cards and will win.In the second test case of the example, it can be shown that it is the second player who has a winning strategy. One possible flow of the game is illustrated in the statement."}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n\nopen Printf\nopen Array\n\nlet rec exists f a =\n fold_right f a false\n;;\nlet run () =\n let n = scan_int () in\n let k1 = scan_int () in\n let k2 = scan_int () in\n let a = init k1 (fun _x -> scan_int ()) in\n let _b = init k2 (fun _x -> scan_int ()) in\n if exists (fun x y -> x = n or y) a then\n printf \"YES\\n\"\n else printf \"NO\\n\"\n;;\n\nlet () =\n let t = scan_int () in\n for i = 1 to t do\n run ()\n done\n;;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n \nlet () =\n\n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let (k1,k2) = read_pair() in\n let cards1 = Array.init k1 read_int in\n let _ = Array.init k2 read_int in\n if exists 0 (k1-1) (fun i -> cards1.(i) = n) then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}], "negative_code": [], "src_uid": "3ef23f114be223255bd10131b2375b86"} {"nl": {"description": "Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya will beat all present opponents. Otherwise, if all opponents are present, then they will beat Arya.For each opponent Arya knows his schedule\u00a0\u2014 whether or not he is going to present on each particular day. Tell him the maximum number of consecutive days that he will beat all present opponents.Note, that if some day there are no opponents present, Arya still considers he beats all the present opponents.", "input_spec": "The first line of the input contains two integers n and d (1\u2009\u2264\u2009n,\u2009d\u2009\u2264\u2009100)\u00a0\u2014 the number of opponents and the number of days, respectively. The i-th of the following d lines contains a string of length n consisting of characters '0' and '1'. The j-th character of this string is '0' if the j-th opponent is going to be absent on the i-th day.", "output_spec": "Print the only integer\u00a0\u2014 the maximum number of consecutive days that Arya will beat all present opponents.", "sample_inputs": ["2 2\n10\n00", "4 1\n0100", "4 5\n1101\n1111\n0110\n1011\n1111"], "sample_outputs": ["2", "1", "2"], "notes": "NoteIn the first and the second samples, Arya will beat all present opponents each of the d days.In the third sample, Arya will beat his opponents on days 1, 3 and 4 and his opponents will beat him on days 2 and 5. Thus, the maximum number of consecutive winning days is 2, which happens on days 3 and 4."}, "positive_code": [{"source_code": "let () =\n match read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string with\n | [n; d] ->\n let cur = ref 0 in\n let r = ref 0 in\n for i = 1 to d do\n let present = read_line () |> Str.(split (regexp \"\")) |> List.map int_of_string in\n if List.exists (fun x -> x == 0) present then (\n incr cur;\n if !cur > !r then\n r := !cur\n ) else\n cur := 0\n done;\n Printf.printf \"%d\\n\" !r\n | _ -> assert false\n"}, {"source_code": "let f (mx,cur) next =\n let nx = if next then cur+1 else 0 in\n (max mx nx, nx)\nin let rec g q x =\n if q = 0 then x else g (q - 1) (f x (String.contains (Scanf.scanf \" %s\" (fun x->x)) '0'))\nin print_int @@ fst @@ Scanf.scanf \"%_d %d\" (fun d -> g d (0,0))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let d = read_int () in\n\n let all = String.make n '1' in\n\n let win_all = Array.init d (fun i ->\n read_string() <> all\n ) in\n\n let rec scan i len max_len = if i=d then max_len else\n let opt1 = if win_all.(i) then len+1 else 0 in\n scan (i+1) opt1 (max opt1 max_len)\n in\n\n let answer = scan 0 0 0 in\n\n printf \"%d\\n\" answer\n \n"}], "negative_code": [], "src_uid": "a6ee741df426fd2d06fdfda4ca369397"} {"nl": {"description": "You are given two positive integers $$$a$$$ and $$$b$$$. In one move you can increase $$$a$$$ by $$$1$$$ (replace $$$a$$$ with $$$a+1$$$). Your task is to find the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$. It is possible, that you have to make $$$0$$$ moves, as $$$a$$$ is already divisible by $$$b$$$. You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 10^9$$$).", "output_spec": "For each test case print the answer \u2014 the minimum number of moves you need to do in order to make $$$a$$$ divisible by $$$b$$$.", "sample_inputs": ["5\n10 4\n13 9\n100 13\n123 456\n92 46"], "sample_outputs": ["2\n5\n4\n333\n0"], "notes": null}, "positive_code": [{"source_code": "open Printf;;\n\nlet split_on_whitespace s =\n Str.split (Str.regexp \"[ \\t]+\") s\n;;\n\nlet t = int_of_string (read_line());;\nfor case = 1 to t do\n let s = read_line() in\n let two_numbers = split_on_whitespace s in\n let int_list = List.map int_of_string two_numbers in\n let a = List.nth int_list 0 in\n let b = List.nth int_list 1 in\n let r = a mod b in\n printf \"%d\\n\" ((b-r) mod b)\ndone;;"}], "negative_code": [], "src_uid": "d9fd10700cb122b148202a664e7f7689"} {"nl": {"description": "Try guessing the statement from this picture: You are given a non-negative integer $$$d$$$. You have to find two non-negative real numbers $$$a$$$ and $$$b$$$ such that $$$a + b = d$$$ and $$$a \\cdot b = d$$$.", "input_spec": "The first line contains $$$t$$$ ($$$1 \\le t \\le 10^3$$$) \u2014 the number of test cases. Each test case contains one integer $$$d$$$ $$$(0 \\le d \\le 10^3)$$$.", "output_spec": "For each test print one line. If there is an answer for the $$$i$$$-th test, print \"Y\", and then the numbers $$$a$$$ and $$$b$$$. If there is no answer for the $$$i$$$-th test, print \"N\". Your answer will be considered correct if $$$|(a + b) - a \\cdot b| \\le 10^{-6}$$$ and $$$|(a + b) - d| \\le 10^{-6}$$$.", "sample_inputs": ["7\n69\n0\n1\n4\n5\n999\n1000"], "sample_outputs": ["Y 67.985071301 1.014928699\nY 0.000000000 0.000000000\nN\nY 2.000000000 2.000000000\nY 3.618033989 1.381966011\nY 997.998996990 1.001003010\nY 998.998997995 1.001002005"], "notes": null}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet bsf ng ok f = let d = if ng < ok then 1. else -1. in\n let rec f0 c ng ok =\n if abs_float (ok -. ng) <= 10e-12 || c < 0L then ok\n else let mid = ng +. (ok -. ng) /. 2. in\n if f mid then f0 (c-1L) ng mid else f0 (c-1L) mid ok\n in f0 100000L ng ok\nlet ok a b d =\n abs_float ((a +. b) -. (a *. b)) > 10e-6 ||\n abs_float ((a +. b) -. d) > 10e-6\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let d = scanf \" %f\" @@ id in\n if d = 0. then (\n printf \"Y 0.000000000000 0.000000000000\\n\"\n ) else (\n let b = bsf 0. (d /. 2.) (fun b ->\n let a = d -. b in\n if a *. b > d then true else false\n ) in\n let a = d -. b in\n if abs_float (a *. b -. d) > 10e-6 || ok a b d then (\n printf \"N\\n\"\n ) else (\n printf \"Y %.14f %.14f\\n\" a b\n )\n )\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet newton start ?(count=100000L) ?(eps=1e-13) f f' =\n let g v = v -. f v /. f' v in\n let rec lp a = function\n | 0L -> a\n | c ->\n let b = g a in\n if abs_float (b -. a) <= eps then a\n else lp b (c-1L)\n in lp start count\n\nlet ok a b d =\n abs_float ((a +. b) -. (a *. b)) <= 10e-6 &&\n abs_float ((a +. b) -. d) <= 10e-6 &&\n abs_float ((a *. b) -. d) <= 10e-6\n\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let d = scanf \" %f\" @@ id in\n if d = 0. then\n printf \"Y 0.0000000000000000 0.0000000000000000\\n\"\n else\n let a = newton 0.\n (fun v -> v*.v -. d*.v +. d)\n (fun v -> 2.*.v -. d) in\n let b = d -. a in\n if ok a b d then\n printf \"Y %.16f %.16f\\n\" a b\n else printf \"N\\n\"\n )\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet newton d =\n let x = ref 0. in\n let f v = v -. (v*.v -. d*.v +. d) /. (2.*.v -. d) in\n let b = ref @@ f !x in\n let c = ref 10000L in\n while !c > 0L && abs_float (!b -. !x) > 1e-12 do\n c -= 1L;\n x := !b;\n b := f !x;\n done;\n (* printf \"%f %f : %f\\n\" !x (d -. !x) !b; *)\n if !c = 0L && (\n let a = !x in\n let b = d -. a in\n abs_float ((a +. b) -. (a *. b))>10e-6 ||\n abs_float ((a +. b) -. d) > 10e-6 ||\n abs_float ((a *. b) -. d) > 10e-6\n ) then None else Some !x\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let d = scanf \" %f\" @@ id in\n match newton d with\n | None -> printf \"N\\n\"\n | Some a -> (\n let b = d -. a in\n if (\n abs_float ((a +. b) -. (a *. b)) > 10e-6 ||\n abs_float ((a +. b) -. d) > 10e-6 ||\n abs_float ((a *. b) -. d) > 10e-6\n ) then printf \"N\\n\"\n else printf \"Y %.16f %.16f\\n\" (max a b) (min a b);\n (* printf \" %.12f %.12f\\n\" (a+.b) (a*.b); *)\n )\n )\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet newton d =\n let x = ref 0. in\n let f v = v -. (v*.v -. d*.v +. d) /. (2.*.v -. d) in\n let b = ref @@ f !x in\n let c = ref 10000L in\n while !c > 0L && abs_float (!b -. !x) > 10e-12 do\n c -= 1L;\n x := !b;\n b := f !x;\n done;\n (* printf \"%f %f : %f\\n\" !x (d -. !x) !b; *)\n if !c = 0L && (\n let a = !x in\n let b = d -. a in\n abs_float ((a +. b) -. (a *. b))>10e-6 ||\n abs_float ((a +. b) -. d) > 10e-6\n ) then None else Some !x\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let d = scanf \" %f\" @@ id in\n match newton d with\n | None -> printf \"N\\n\"\n | Some a -> (\n let b = d -. a in\n if (\n abs_float ((a +. b) -. (a *. b)) > 10e-6 ||\n abs_float ((a +. b) -. d) > 10e-6\n ) then printf \"N\\n\"\n else printf \"Y %.16f %.16f\\n\" (max a b) (min a b);\n (* printf \" %.12f %.12f\\n\" (a+.b) (a*.b); *)\n )\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet newton d =\n let x = ref 0. in\n let f v = v -. (v*.v -. d*.v +. d) /. (2.*.v -. d) in\n let b = ref @@ f !x in\n let c = ref 10000L in\n while !c > 0L && abs_float (!b -. !x) > 10e-8 do\n c -= 1L;\n x := !b;\n b := f !x;\n done;\n (* printf \"%f %f : %f\\n\" !x (d -. !x) !b; *)\n if !c = 0L then None else Some !x\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let d = scanf \" %f\" @@ id in\n match newton d with\n | None -> printf \"N\\n\"\n | Some a -> (\n let b = d -. a in\n printf \"Y %.12f %.12f\\n\" (max a b) (min a b);\n )\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet newton d =\n let x = ref 0. in\n let f v = v -. (v*.v -. d*.v +. d) /. (2.*.v -. d) in\n let b = ref @@ f !x in\n let c = ref 10000L in\n while !c > 0L && abs_float (!b -. !x) > 10e-9 do\n c -= 1L;\n x := !b;\n b := f !x;\n done;\n (* printf \"%f %f : %f\\n\" !x (d -. !x) !b; *)\n if !c = 0L && (\n let a = !x in\n let b = d -. a in\n abs_float ((a +. b) -. (a *. b))>10e-6 ||\n abs_float ((a +. b) -. d) > 10e-6\n ) then None else Some !x\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let d = scanf \" %f\" @@ id in\n match newton d with\n | None -> printf \"N\\n\"\n | Some a -> (\n let b = d -. a in\n if (\n abs_float ((a +. b) -. (a *. b)) > 10e-6 ||\n abs_float ((a +. b) -. d) > 10e-6\n ) then printf \"N\\n\"\n else printf \"Y %.16f %.16f\\n\" (max a b) (min a b);\n (* printf \" %.12f %.12f\\n\" (a+.b) (a*.b); *)\n )\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet newton d =\n let x = ref 0. in\n let f v = v -. (v*.v -. d*.v +. d) /. (2.*.v -. d) in\n let b = ref @@ f !x in\n let c = ref 10000L in\n while !c > 0L && abs_float (!b -. !x) > 10e-8 do\n c -= 1L;\n x := !b;\n b := f !x;\n done;\n (* printf \"%f %f : %f\\n\" !x (d -. !x) !b; *)\n if !c = 0L then None else Some !x\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let d = scanf \" %f\" @@ id in\n match newton d with\n | None -> printf \"N\\n\"\n | Some a -> (\n let b = d -. a in\n printf \"Y %.12f %.12f\\n\" a b;\n )\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet newton d =\n let x = ref 0. in\n let f v = v -. (v*.v -. d*.v +. d) /. (2.*.v -. d) in\n let b = ref @@ f !x in\n let c = ref 10000L in\n while !c > 0L && abs_float (!b -. !x) > 10e-9 do\n c -= 1L;\n x := !b;\n b := f !x;\n done;\n (* printf \"%f %f : %f\\n\" !x (d -. !x) !b; *)\n if !c = 0L && (\n abs_float ((!x+. !b) -. (!x*. !b))>10e-6 ||\n abs_float ((!x+. !b) -. d) > 10e-6\n ) then None else Some !x\nlet () =\n let t = get_i64 0 in\n rep 1L t (fun _ ->\n let d = scanf \" %f\" @@ id in\n match newton d with\n | None -> printf \"N\\n\"\n | Some a -> (\n let b = d -. a in\n printf \"Y %.12f %.12f\\n\" (max a b) (min a b);\n (* printf \" %.12f %.12f\\n\" (a+.b) (a*.b); *)\n )\n )\n\n\n\n\n\n\n\n\n"}], "src_uid": "6f5d41346419901c830233b3bf5c9e65"} {"nl": {"description": "A tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p\u2009=\u2009p1p2... pn, if for any two vertices of the tree u and v the condition holds: \"vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge\".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation.", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the size of the permutation (also equal to the size of the sought tree). The second line contains permutation pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009n).", "output_spec": "If the sought tree does not exist, print \"NO\" (without the quotes). Otherwise, print \"YES\", and then print n\u2009-\u20091 lines, each of which contains two integers \u2014 the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter. If there are multiple solutions, output any of them.", "sample_inputs": ["4\n4 3 2 1", "3\n3 1 2"], "sample_outputs": ["YES\n4 1\n4 2\n1 3", "NO"], "notes": "NoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet get_cycles n p =\n let bio = Array.make n false in\n let rec get_cycle i ans =\n if bio.(i) then ans\n else (bio.(i) <- true; get_cycle p.(i) (i::ans))\n in\n let rec go i ans =\n if i >= n then ans\n else if bio.(i) then go (i+1) ans\n else go (i+1) ((get_cycle i [])::ans)\n in\n go 0 []\n\nlet () =\n let n = read_int () in\n let p = Array.init n (fun _ -> (read_int ())-1) in\n let cycles = get_cycles n p in\n let rec lenf n l = (List.length l) = n in\n if List.exists (lenf 1) cycles then \n begin\n Printf.printf \"YES\\n\";\n let c = List.hd (List.find (lenf 1) cycles) in\n for i = 0 to n-1 do\n if i <> c then Printf.printf \"%d %d\\n\" (c+1) (i+1)\n done;\n end\n else if List.exists (lenf 2) cycles then\n begin\n let twos = List.find (lenf 2) cycles in\n let a = List.hd twos in\n let b = List.hd (List.tl twos) in\n let rec print_edges a b v =\n match v with\n | [] -> ()\n | hd::tl -> if hd <> a then \n begin\n Printf.printf \"%d %d\\n\" (a+1) ((List.hd v)+1);\n print_edges b a (List.tl v)\n end\n in\n if List.for_all (fun v -> (List.length v) mod 2 = 0) cycles then\n begin\n Printf.printf \"YES\\n\";\n Printf.printf \"%d %d\\n\" (a+1) (b+1);\n List.iter (print_edges a b) cycles;\n end\n else Printf.printf \"NO\\n\"\n end\n else Printf.printf \"NO\\n\";;\n"}], "negative_code": [], "src_uid": "5ecb8f82b073b374a603552fdd95391b"} {"nl": {"description": "One day Squidward, Spongebob and Patrick decided to go to the beach. Unfortunately, the weather was bad, so the friends were unable to ride waves. However, they decided to spent their time building sand castles.At the end of the day there were n castles built by friends. Castles are numbered from 1 to n, and the height of the i-th castle is equal to hi. When friends were about to leave, Squidward noticed, that castles are not ordered by their height, and this looks ugly. Now friends are going to reorder the castles in a way to obtain that condition hi\u2009\u2264\u2009hi\u2009+\u20091 holds for all i from 1 to n\u2009-\u20091.Squidward suggested the following process of sorting castles: Castles are split into blocks\u00a0\u2014 groups of consecutive castles. Therefore the block from i to j will include castles i,\u2009i\u2009+\u20091,\u2009...,\u2009j. A block may consist of a single castle. The partitioning is chosen in such a way that every castle is a part of exactly one block. Each block is sorted independently from other blocks, that is the sequence hi,\u2009hi\u2009+\u20091,\u2009...,\u2009hj becomes sorted. The partitioning should satisfy the condition that after each block is sorted, the sequence hi becomes sorted too. This may always be achieved by saying that the whole sequence is a single block. Even Patrick understands that increasing the number of blocks in partitioning will ease the sorting process. Now friends ask you to count the maximum possible number of blocks in a partitioning that satisfies all the above requirements.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of castles Spongebob, Patrick and Squidward made from sand during the day. The next line contains n integers hi (1\u2009\u2264\u2009hi\u2009\u2264\u2009109). The i-th of these integers corresponds to the height of the i-th castle.", "output_spec": "Print the maximum possible number of blocks in a valid partitioning.", "sample_inputs": ["3\n1 2 3", "4\n2 1 3 2"], "sample_outputs": ["3", "2"], "notes": "NoteIn the first sample the partitioning looks like that: [1][2][3]. In the second sample the partitioning is: [2, 1][3, 2] "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\n\nlet () = \n let n = read_int () in\n let h = Array.init n (fun _ -> read_int()) in\n\n if n=1 then printf \"1\\n\" else (\n \n let mintr = Array.make n 0 in\n let maxtl = Array.make n 0 in\n\n maxtl.(0) <- h.(0);\n for i=1 to n-2 do\n maxtl.(i) <- max maxtl.(i-1) h.(i)\n done;\n\n mintr.(n-2) <- h.(n-1);\n\n for i = n-3 downto 0 do\n mintr.(i) <- min mintr.(i+1) h.(i+1)\n done;\n\n let answer = 1 + sum 0 (n-2) (fun i -> if maxtl.(i) <= mintr.(i) then 1 else 0) 0 in\n\n printf \"%d\\n\" answer\n )\n"}], "negative_code": [], "src_uid": "c1158d23d3ad61c346c345f14e63ede4"} {"nl": {"description": "Find the minimum area of a square land on which you can place two identical rectangular $$$a \\times b$$$ houses. The sides of the houses should be parallel to the sides of the desired square land.Formally, You are given two identical rectangles with side lengths $$$a$$$ and $$$b$$$ ($$$1 \\le a, b \\le 100$$$)\u00a0\u2014 positive integers (you are given just the sizes, but not their positions). Find the square of the minimum area that contains both given rectangles. Rectangles can be rotated (both or just one), moved, but the sides of the rectangles should be parallel to the sides of the desired square. Two rectangles can touch each other (side or corner), but cannot intersect. Rectangles can also touch the sides of the square but must be completely inside it. You can rotate the rectangles. Take a look at the examples for a better understanding. The picture shows a square that contains red and green rectangles. ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$)\u00a0\u2014the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing two integers $$$a$$$, $$$b$$$ ($$$1 \\le a, b \\le 100$$$)\u00a0\u2014 side lengths of the rectangles.", "output_spec": "Print $$$t$$$ answers to the test cases. Each answer must be a single integer\u00a0\u2014 minimal area of square land, that contains two rectangles with dimensions $$$a \\times b$$$.", "sample_inputs": ["8\n3 2\n4 2\n1 1\n3 1\n4 7\n1 3\n7 4\n100 100"], "sample_outputs": ["16\n16\n4\n9\n64\n9\n64\n40000"], "notes": "NoteBelow are the answers for the first two test cases: "}, "positive_code": [{"source_code": "let t = Scanf.sscanf (read_line ()) \"%d\" @@ fun t -> t\nlet ab = Array.init t @@ fun _ -> Scanf.sscanf (read_line ()) \"%d %d\" @@ fun a b -> (a, b)\n\nlet () =\n Array.iter (fun (a, b) ->\n let c = max (max a b) ((min a b)* 2) in\n Printf.printf \"%d\\n\" (c * c)\n ) ab"}], "negative_code": [], "src_uid": "3bb093fb17d6b76ae340fab44b08fcb8"} {"nl": {"description": "Simon has a prime number x and an array of non-negative integers a1,\u2009a2,\u2009...,\u2009an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1\u2009+\u2009a2\u2009+\u2009...\u2009+\u2009an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109\u2009+\u20097).", "input_spec": "The first line contains two positive integers n and x (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 2\u2009\u2264\u2009x\u2009\u2264\u2009109) \u2014 the size of the array and the prime number. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009an\u2009\u2264\u2009109). ", "output_spec": "Print a single number \u2014 the answer to the problem modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"], "sample_outputs": ["8", "27", "73741817", "1"], "notes": "NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351\u2009=\u200913\u00b727, 729\u2009=\u200927\u00b727.In the third sample the answer to the problem is 1073741824\u00a0mod\u00a01000000007\u2009=\u200973741817.In the fourth sample . Thus, the answer to the problem is 1."}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n if skip = 0 then failwith \"fold_for\";\n let cmp = if skip > 0 then (<) else (>) in\n\n let rec iter cur acc =\n if not @@ cmp cur max then acc\n else iter (cur + skip) (f acc cur) in\n\n iter min init \n;;\n\nlet iter_for ?(skip=1) min max ~f =\n fold_for ~skip:skip min max ~init:() ~f:(fun _ i -> f i)\n;;\n\nlet input_n n fmt ~f =\n fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf fmt f :: acc) |> List.rev\n;;\n\nmodule Mod_arith = struct\n include Int64 ;;\n\n let m = 1000000007L ;;\n\n let (+) x y = rem (x + y) m ;;\n let (-) x y = rem (x - y) m ;;\n let ( * ) x y = rem (x * y) m ;;\n let ( / ) x y = rem (x / y) m ;;\n\nend\n;;\n\nlet gcd x y e =\n let open Mod_arith in\n let rec iter acc x i =\n if i = e then acc\n else if rem x y = 0L then iter (acc * y) (x / y) Int64.(i + 1L)\n else acc in\n iter 1L x 0L\n;;\n\nlet rec pow res x y =\n if y = 0L then res\n else if Int64.(rem y 2L = 0L) then pow res Mod_arith.(x * x) Int64.(y / 2L)\n else pow Mod_arith.(res * x) Mod_arith.(x * x) Int64.((y - 1L) / 2L)\n;;\n\nlet pow = pow 1L ;;\n\nmodule M = Map.Make (struct\n type t = int64\n let compare = compare ;;\nend) ;;\n\nlet update m i u =\n try\n let x = M.find i m in\n M.add i Int64.(x + u) m\n with\n | Not_found -> M.add i u m\n;; \n\nlet rec pow_mod x y =\n if Int64.rem x y <> 0L then (x, 0L)\n else\n let (p, e) = pow_mod Int64.(x / y) y in\n (p, Int64.(e + 1L))\n;;\n\nlet gcd x y =\n let rec aux x y = \n let open Int64 in\n if y = 0L then x\n else aux y (rem x y) in\n aux (max x y) (min x y)\n;;\n\nlet () =\n let n, x = Scanf.scanf \"%d %Ld \" ident2 in\n let an = input_n n \"%Ld \" ident in\n let max_an = List.fold_left an ~init:0L ~f:(max) in\n let sum_an = List.fold_left an ~init:0L ~f:(Int64.(+)) in\n if max_an = 0L then print_endline \"1\"\n else begin\n let en = List.map an ~f:(fun i -> Int64.(sum_an - i)) \n |> List.fold_left ~init:M.empty ~f:(fun acc i -> update acc i 1L) in\n \n let rec iter acc es =\n let (e, k) = M.min_binding es in\n let es = M.remove e es in\n let es = M.fold (fun key x m -> M.add Int64.(key - e) x m) es M.empty in\n let (k, new_e) = pow_mod k x in\n if Int64.(acc + e) >= sum_an then sum_an\n else if new_e = 0L then Int64.(acc + e)\n else iter Int64.(acc + e) (update es new_e k) in\n \n let e = iter 0L en in\n Printf.eprintf \"e = %Ld\\n\" e;\n Printf.printf \"%Ld\\n\" @@ Mod_arith.(pow x e)\n end\n;;\n"}], "negative_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n if skip = 0 then failwith \"fold_for\";\n let cmp = if skip > 0 then (<) else (>) in\n\n let rec iter cur acc =\n if not @@ cmp cur max then acc\n else iter (cur + skip) (f acc cur) in\n\n iter min init \n;;\n\nlet iter_for ?(skip=1) min max ~f =\n fold_for ~skip:skip min max ~init:() ~f:(fun _ i -> f i)\n;;\n\nlet input_n n fmt ~f =\n fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf fmt f :: acc) |> List.rev\n;;\n\nmodule Mod_arith = struct\n include Int64 ;;\n\n let m = 1000000007L ;;\n\n let (+) x y = rem (x + y) m ;;\n let (-) x y = rem (x - y) m ;;\n let ( * ) x y = rem (x * y) m ;;\n let ( / ) x y = rem (x / y) m ;;\n\nend\n;;\n\nlet gcd x y e =\n let open Mod_arith in\n let rec iter acc x i =\n if i = e then acc\n else if rem x y = 0L then iter (acc * y) Int64.(x / y) Int64.(i + 1L)\n else acc in\n iter 1L x 0L\n;;\n\nlet rec pow res x y =\n if y = 0L then res\n else if Int64.(rem y 2L = 0L) then pow res (Mod_arith.(x * x)) Int64.(y / 2L)\n else pow Mod_arith.(res * x) Mod_arith.(x * x) Int64.((y - 1L) / 2L)\n;;\n\nlet pow = pow 1L ;;\n\n \nlet () =\n let n, x = Scanf.scanf \"%d %Ld \" ident2 in\n let an = input_n n \"%Ld \" ident in\n let max_an = List.fold_left an ~init:0L ~f:(max) in\n if max_an = 0L then print_endline \"1\"\n else begin\n let k = List.filter an ~f:(fun x -> x = max_an) |> List.length in\n let sum_an = List.fold_left an ~init:0L ~f:(fun sum i -> Int64.(sum + i)) in\n let l = gcd (Int64.of_int k) x sum_an in\n Printf.eprintf \"l = %Ld\\n\" l;\n Printf.eprintf \"sum_an = %Ld\\n\" sum_an;\n Printf.printf \"%Ld\\n\" @@ Mod_arith.(l * pow x Int64.(sum_an - max_an))\n end\n;;\n"}, {"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n if skip = 0 then failwith \"fold_for\";\n let cmp = if skip > 0 then (<) else (>) in\n\n let rec iter cur acc =\n if not @@ cmp cur max then acc\n else iter (cur + skip) (f acc cur) in\n\n iter min init \n;;\n\nlet iter_for ?(skip=1) min max ~f =\n fold_for ~skip:skip min max ~init:() ~f:(fun _ i -> f i)\n;;\n\nlet input_n n fmt ~f =\n fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf fmt f :: acc) |> List.rev\n;;\n\nmodule Mod_arith = struct\n include Int64 ;;\n\n let m = 1000000007L ;;\n\n let (+) x y = rem (x + y) m ;;\n let (-) x y = rem (x - y) m ;;\n let ( * ) x y = rem (x * y) m ;;\n let ( / ) x y = rem (x / y) m ;;\n\nend\n;;\n\nlet gcd x y e =\n let open Mod_arith in\n let rec iter acc x i =\n if i = e then acc\n else if rem x y = 0L then iter (acc * y) (x / y) Int64.(i + 1L)\n else acc in\n iter 1L x 0L\n;;\n\nlet rec pow res x y =\n if y = 0L then res\n else if Int64.(rem y 2L = 0L) then pow res Mod_arith.(x * x) Int64.(y / 2L)\n else pow Mod_arith.(res * x) Mod_arith.(x * x) Int64.((y - 1L) / 2L)\n;;\n\nlet pow = pow 1L ;;\n\n \nlet () =\n let n, x = Scanf.scanf \"%d %Ld \" ident2 in\n let an = input_n n \"%Ld \" ident in\n let max_an = List.fold_left an ~init:0L ~f:(max) in\n if max_an = 0L then print_endline \"1\"\n else begin\n let k = List.filter an ~f:(fun x -> x = max_an) |> List.length in\n let sum_an = List.fold_left an ~init:0L ~f:(fun sum i -> Int64.(sum + i)) in\n let l = gcd (Int64.of_int k) x sum_an in\n Printf.eprintf \"l = %Ld\\n\" l;\n Printf.eprintf \"sum_an = %Ld\\n\" sum_an;\n Printf.printf \"%Ld\\n\" @@ Int64.rem Mod_arith.(l * pow x Int64.(sum_an - max_an)) Mod_arith.m\n end\n;;\n"}, {"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n if skip = 0 then failwith \"fold_for\";\n let cmp = if skip > 0 then (<) else (>) in\n\n let rec iter cur acc =\n if not @@ cmp cur max then acc\n else iter (cur + skip) (f acc cur) in\n\n iter min init \n;;\n\nlet iter_for ?(skip=1) min max ~f =\n fold_for ~skip:skip min max ~init:() ~f:(fun _ i -> f i)\n;;\n\nlet input_n n fmt ~f =\n fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf fmt f :: acc) |> List.rev\n;;\n\nmodule Mod_arith = struct\n include Int64 ;;\n\n let m = 1000000007L ;;\n\n let (+) x y = rem (x + y) m ;;\n let (-) x y = rem (x - y) m ;;\n let ( * ) x y = rem (x * y) m ;;\n let ( / ) x y = rem (x / y) m ;;\n\nend\n;;\n\nlet gcd x y e =\n let open Mod_arith in\n let rec iter acc x i =\n if i = e then acc\n else if rem x y = 0L then iter (acc * y) (x / y) Int64.(i + 1L)\n else acc in\n iter 1L x 0L\n;;\n\nlet rec pow res x y =\n if y = 0L then res\n else if Int64.(rem y 2L = 0L) then pow res Mod_arith.(x * x) Int64.(y / 2L)\n else pow Mod_arith.(res * x) Mod_arith.(x * x) Int64.((y - 1L) / 2L)\n;;\n\nlet pow = pow 1L ;;\n\nmodule M = Map.Make (struct\n type t = int64\n let compare = compare ;;\nend) ;;\n\nlet incr m i =\n try\n let x = M.find i m in\n M.add i Int64.(x + 1L) m\n with\n | Not_found -> M.add i 1L m\n;; \n\nlet rec pow_mod x y =\n if Int64.rem x y <> 0L then (x, 0L)\n else\n let (p, e) = pow_mod Int64.(x / y) y in\n (p, Int64.(e + 1L))\n;;\n\nlet gcd x y =\n let rec aux x y = \n let open Int64 in\n if y = 0L then x\n else aux y (rem x y) in\n aux (max x y) (min x y)\n;;\n\nlet () =\n let n, x = Scanf.scanf \"%d %Ld \" ident2 in\n let an = input_n n \"%Ld \" ident in\n let max_an = List.fold_left an ~init:0L ~f:(max) in\n let sum_an = List.fold_left an ~init:0L ~f:(Int64.(+)) in\n if max_an = 0L then print_endline \"1\"\n else begin\n let en = List.map an ~f:(fun i -> Int64.(sum_an - i)) \n |> List.fold_left ~init:M.empty ~f:(incr) in\n let rec iter acc es =\n let (e, k) = M.min_binding es in\n let es = M.remove e es in\n let es = M.fold (fun key x m -> M.add Int64.(key - e) x m) es M.empty in\n let (k, new_e) = pow_mod k x in\n if Int64.(acc + e) >= sum_an then (1L, sum_an)\n else if new_e = 0L then (gcd k x, Int64.(acc + e))\n else iter Int64.(acc + e) (M.add new_e k es) in\n let k, e = iter 0L en in\n Printf.eprintf \"k, e = %Ld, %Ld\\n\" k e;\n Printf.printf \"%Ld\\n\" @@ Mod_arith.(k * pow x e)\n end\n;;\n"}, {"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n if skip = 0 then failwith \"fold_for\";\n let cmp = if skip > 0 then (<) else (>) in\n\n let rec iter cur acc =\n if not @@ cmp cur max then acc\n else iter (cur + skip) (f acc cur) in\n\n iter min init \n;;\n\nlet iter_for ?(skip=1) min max ~f =\n fold_for ~skip:skip min max ~init:() ~f:(fun _ i -> f i)\n;;\n\nlet input_n n fmt ~f =\n fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf fmt f :: acc) |> List.rev\n;;\n\nmodule Mod_arith = struct\n include Int64 ;;\n\n let m = 1000000007L ;;\n\n let (+) x y = rem (x + y) m ;;\n let (-) x y = rem (x - y) m ;;\n let ( * ) x y = rem (x * y) m ;;\n let ( / ) x y = rem (x / y) m ;;\n\nend\n;;\n\nlet gcd x y e =\n let open Mod_arith in\n let rec iter acc x i =\n if i = e then acc\n else if rem x y = 0L then iter (acc * y) (x / y) Int64.(i + 1L)\n else acc in\n iter 1L x 0L\n;;\n\nlet rec pow res x y =\n if y = 0L then res\n else if Int64.(rem y 2L = 0L) then pow res Mod_arith.(x * x) Int64.(y / 2L)\n else pow Mod_arith.(res * x) Mod_arith.(x * x) Int64.((y - 1L) / 2L)\n;;\n\nlet pow = pow 1L ;;\n\nmodule M = Map.Make (struct\n type t = int64\n let compare = compare ;;\nend) ;;\n\nlet incr m i =\n try\n let x = M.find i m in\n M.add i Int64.(x + 1L) m\n with\n | Not_found -> M.add i 1L m\n;; \n\nlet rec pow_mod x y =\n if Int64.rem x y <> 0L then (x, 0L)\n else\n let (p, e) = pow_mod Int64.(x / y) y in\n (p, Int64.(e + 1L))\n;;\n\nlet () =\n let n, x = Scanf.scanf \"%d %Ld \" ident2 in\n let an = input_n n \"%Ld \" ident in\n let max_an = List.fold_left an ~init:0L ~f:(max) in\n let sum_an = List.fold_left an ~init:0L ~f:(Int64.(+)) in\n if max_an = 0L then print_endline \"1\"\n else begin\n let en = List.map an ~f:(fun i -> Int64.(sum_an - i)) \n |> List.fold_left ~init:M.empty ~f:(incr) in\n let rec iter acc es =\n let (e, k) = M.min_binding es in\n let es = M.remove e es in\n let es = M.fold (fun key x m -> M.add Int64.(key - e) x m) es M.empty in\n let (k, new_e) = pow_mod k x in\n if e = 0L then acc\n else if Int64.(acc + e) >= sum_an then sum_an\n else iter Int64.(acc + e) (M.add new_e k es) in\n Printf.printf \"%Ld\\n\" @@ pow x (iter 0L en)\n end\n;;\n"}], "src_uid": "4867d014809bfc1d90672b32ecf43b43"} {"nl": {"description": "Little Petya very much likes playing with little Masha. Recently he has received a game called \"Zero-One\" as a gift from his mother. Petya immediately offered Masha to play the game with him.Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101. The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.", "input_spec": "The first line contains a sequence of characters each of which can either be a \"0\", a \"1\" or a \"?\". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters \"?\" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.", "output_spec": "Print the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).", "sample_inputs": ["????", "1010", "1?1"], "sample_outputs": ["00\n01\n10\n11", "10", "01\n11"], "notes": "NoteIn the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes.In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will end."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let z = ref 0 in\n let o = ref 0 in\n let q = ref 0 in\n let z2 = ref 0 in\n let o2 = ref 0 in\n let q2 = ref 0 in\n for i = 0 to n - 3 do\n match s.[i] with\n\t| '0' -> incr z\n\t| '1' -> incr o\n\t| '?' -> incr q\n\t| _ -> assert false\n done;\n for i = n - 2 to n - 1 do\n match s.[i] with\n\t| '0' -> incr z2\n\t| '1' -> incr o2\n\t| '?' -> incr q2\n\t| _ -> assert false\n done;\n let ht = Hashtbl.create 4 in\n let solve' s =\n let s = ref s in\n let d = ref 1 in\n\twhile String.length !s > 2 do\n\t (*Printf.printf \"asd %s %d\\n\" !s !d;*)\n\t (try\n\t let i = String.index !s (Char.chr (!d + Char.code '0')) in\n\t s := String.sub !s 0 i ^\n\t\t String.sub !s (i + 1) (String.length !s - i - 1);\n\t with\n\t | Not_found ->\n\t\t s := String.sub !s 1 (String.length !s - 1)\n\t );\n\t d := 1 - !d;\n\tdone;\n\tHashtbl.replace ht !s ()\n in\n let solve _s z o q z2 o2 tail =\n (*for d = 0 to q do\n\tlet z = z + d\n\tand o = o + (q - d) in*)\n\t (*Printf.printf \"asd zoq %d %d %d\\n\" z o q;*)\n\t if n mod 2 = 0 then (\n\t if z + q >= o + 4\n\t then solve' (\"0000\" ^ tail);\n\t if z < o + q + 4 && z + q >= o + 2\n\t then solve' (\"00\" ^ tail);\n\t if o + q >= z + 4\n\t then solve' (\"1111\" ^ tail);\n\t if o < z + q + 4 && o + q >= z + 2\n\t then solve' (\"11\" ^ tail);\n\t if z <= o + q && o <= z + q\n\t then Hashtbl.replace ht tail ();\n\t ) else (\n\t if z + q >= o + 5\n\t then solve' (\"00000\" ^ tail);\n\t if z <= o + q + 5 && z + q >= o + 3\n\t then solve' (\"000\" ^ tail);\n\t if o + q >= z + 5\n\t then solve' (\"11111\" ^ tail);\n\t if o < z + q + 5 && o + q >= z + 3\n\t then solve' (\"111\" ^ tail);\n\t if z <= o + q + 1 && o + 1 <= z + q\n\t then solve' (\"0\" ^ tail);\n\t if z + 1 <= o + q && o <= z + 1 + q\n\t then solve' (\"1\" ^ tail);\n\t )\n (*done*)\n in\n (match s.[n - 2], s.[n - 1] with\n\t | '?', '?' ->\n\t solve s !z !o !q 2 0 \"00\";\n\t solve s !z !o !q 1 1 \"01\";\n\t solve s !z !o !q 1 1 \"10\";\n\t solve s !z !o !q 0 2 \"11\";\n\t | '?', _ ->\n\t solve s !z !o !q (!z2 + 1) !o2 (\"0\" ^ String.make 1 s.[n - 1]);\n\t solve s !z !o !q !z2 (!o2 + 1) (\"1\" ^ String.make 1 s.[n - 1]);\n\t | _, '?' ->\n\t solve s !z !o !q (!z2 + 1) !o2 (String.make 1 s.[n - 2] ^ \"0\");\n\t solve s !z !o !q !z2 (!o2 + 1) (String.make 1 s.[n - 2] ^ \"1\");\n\t | _ ->\n\t solve s !z !o !q !z2 !o2 (String.sub s (n - 2) 2);\n );\n if Hashtbl.mem ht \"00\" then Printf.printf \"00\\n\";\n if Hashtbl.mem ht \"01\" then Printf.printf \"01\\n\";\n if Hashtbl.mem ht \"10\" then Printf.printf \"10\\n\";\n if Hashtbl.mem ht \"11\" then Printf.printf \"11\\n\";\n"}, {"source_code": " let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let z = ref 0 in\n let o = ref 0 in\n let q = ref 0 in\n let z2 = ref 0 in\n let o2 = ref 0 in\n let q2 = ref 0 in\n for i = 0 to n - 3 do\n match s.[i] with\n | '0' -> incr z\n | '1' -> incr o\n | '?' -> incr q\n | _ -> assert false\n done;\n for i = n - 2 to n - 1 do\n match s.[i] with\n | '0' -> incr z2\n | '1' -> incr o2\n | '?' -> incr q2\n | _ -> assert false\n done;\n let ht = Hashtbl.create 4 in\n let solve' s =\n let s = ref s in\n let d = ref 1 in\n while String.length !s > 2 do\n (*Printf.printf \"asd %s\\n\" !s;*)\n (try\n let i = String.index !s (Char.chr (!d + Char.code '0')) in\n s := String.sub !s 0 i ^\n String.sub !s (i + 1) (String.length !s - i - 1);\n with\n | Not_found ->\n s := String.sub !s 1 (String.length !s - 1)\n );\n d := 1 - !d;\n done;\n Hashtbl.replace ht !s ()\n in\n let solve _s z o q z2 o2 tail =\n for d = 0 to q do\n let z = z + d\n and o = o + (q - d) in\n (*Printf.printf \"asd zoq %d %d %d\\n\" z o q;*)\n if n mod 2 = 0 then (\n if z >= o + 4\n then solve' (\"0000\" ^ tail)\n else if o >= z + 4\n then solve' (\"1111\" ^ tail)\n else if z >= o + 2\n then solve' (\"00\" ^ tail)\n else if o >= z + 2\n then solve' (\"11\" ^ tail)\n else if z = o\n then Hashtbl.replace ht tail ()\n else assert false\n ) else (\n if z >= o + 5\n then solve' (\"00000\" ^ tail)\n else if o >= z + 5\n then solve' (\"11111\" ^ tail)\n else if z >= o + 3\n then solve' (\"000\" ^ tail)\n else if o >= z + 3\n then solve' (\"111\" ^ tail)\n else if z = o + 1\n then solve' (\"0\" ^ tail)\n else if z + 1 = o\n then solve' (\"1\" ^ tail)\n else assert false\n )\n done\n in\n (match s.[n - 2], s.[n - 1] with\n | '?', '?' ->\n solve s !z !o !q 2 0 \"00\";\n solve s !z !o !q 1 1 \"01\";\n solve s !z !o !q 1 1 \"10\";\n solve s !z !o !q 0 2 \"11\";\n | '?', _ ->\n solve s !z !o !q (!z2 + 1) !o2 (\"0\" ^ String.make 1 s.[n - 1]);\n solve s !z !o !q !z2 (!o2 + 1) (\"1\" ^ String.make 1 s.[n - 1]);\n | _, '?' ->\n solve s !z !o !q (!z2 + 1) !o2 (String.make 1 s.[n - 2] ^ \"0\");\n solve s !z !o !q !z2 (!o2 + 1) (String.make 1 s.[n - 2] ^ \"1\");\n | _ ->\n solve s !z !o !q !z2 !o2 (String.sub s (n - 2) 2);\n );\n if Hashtbl.mem ht \"00\" then Printf.printf \"00\\n\";\n if Hashtbl.mem ht \"01\" then Printf.printf \"01\\n\";\n if Hashtbl.mem ht \"10\" then Printf.printf \"10\\n\";\n if Hashtbl.mem ht \"11\" then Printf.printf \"11\\n\";"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let z = ref 0 in\n let o = ref 0 in\n let q = ref 0 in\n let z2 = ref 0 in\n let o2 = ref 0 in\n let q2 = ref 0 in\n for i = 0 to n - 3 do\n match s.[i] with\n\t| '0' -> incr z\n\t| '1' -> incr o\n\t| '?' -> incr q\n\t| _ -> assert false\n done;\n for i = n - 2 to n - 1 do\n match s.[i] with\n\t| '0' -> incr z2\n\t| '1' -> incr o2\n\t| '?' -> incr q2\n\t| _ -> assert false\n done;\n let ht = Hashtbl.create 4 in\n let solve' s =\n let s = ref s in\n let d = ref 1 in\n\twhile String.length !s > 2 do\n\t (*Printf.printf \"asd %s\\n\" !s;*)\n\t (try\n\t let i = String.index !s (Char.chr (!d + Char.code '0')) in\n\t s := String.sub !s 0 i ^\n\t\t String.sub !s (i + 1) (String.length !s - i - 1);\n\t with\n\t | Not_found ->\n\t\t s := String.sub !s 1 (String.length !s - 1)\n\t );\n\t d := 1 - !d;\n\tdone;\n\tHashtbl.replace ht !s ()\n in\n let solve _s z o q z2 o2 tail =\n (*for d = 0 to q do\n\tlet z = z + d\n\tand o = o + (q - d) in*)\n\t (*Printf.printf \"asd zoq %d %d %d\\n\" z o q;*)\n\t if n mod 2 = 0 then (\n\t if z + q >= o + 4\n\t then solve' (\"0000\" ^ tail);\n\t if o + q >= z + 4\n\t then solve' (\"1111\" ^ tail);\n\t if z + q >= o + 2\n\t then solve' (\"00\" ^ tail);\n\t if o + q >= z + 2\n\t then solve' (\"11\" ^ tail);\n\t if 0 <= o - z + q && o - z <= q\n\t then Hashtbl.replace ht tail ();\n\t ) else (\n\t if z + q >= o + 5\n\t then solve' (\"00000\" ^ tail);\n\t if o + q >= z + 5\n\t then solve' (\"11111\" ^ tail);\n\t if z + q >= o + 3\n\t then solve' (\"000\" ^ tail);\n\t if o + q >= z + 3\n\t then solve' (\"111\" ^ tail);\n\t if 0 <= o - z + q + 1 && o - z + 1 <= q\n\t then solve' (\"0\" ^ tail);\n\t if 0 <= o - z + q - 1 && o - z - 1 <= q\n\t then solve' (\"1\" ^ tail);\n\t )\n (*done*)\n in\n (match s.[n - 2], s.[n - 1] with\n\t | '?', '?' ->\n\t solve s !z !o !q 2 0 \"00\";\n\t solve s !z !o !q 1 1 \"01\";\n\t solve s !z !o !q 1 1 \"10\";\n\t solve s !z !o !q 0 2 \"11\";\n\t | '?', _ ->\n\t solve s !z !o !q (!z2 + 1) !o2 (\"0\" ^ String.make 1 s.[n - 1]);\n\t solve s !z !o !q !z2 (!o2 + 1) (\"1\" ^ String.make 1 s.[n - 1]);\n\t | _, '?' ->\n\t solve s !z !o !q (!z2 + 1) !o2 (String.make 1 s.[n - 2] ^ \"0\");\n\t solve s !z !o !q !z2 (!o2 + 1) (String.make 1 s.[n - 2] ^ \"1\");\n\t | _ ->\n\t solve s !z !o !q !z2 !o2 (String.sub s (n - 2) 2);\n );\n if Hashtbl.mem ht \"00\" then Printf.printf \"00\\n\";\n if Hashtbl.mem ht \"01\" then Printf.printf \"01\\n\";\n if Hashtbl.mem ht \"10\" then Printf.printf \"10\\n\";\n if Hashtbl.mem ht \"11\" then Printf.printf \"11\\n\";\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let z = ref 0 in\n let o = ref 0 in\n let q = ref 0 in\n let z2 = ref 0 in\n let o2 = ref 0 in\n let q2 = ref 0 in\n for i = 0 to n - 3 do\n match s.[i] with\n\t| '0' -> incr z\n\t| '1' -> incr o\n\t| '?' -> incr q\n\t| _ -> assert false\n done;\n for i = n - 2 to n - 1 do\n match s.[i] with\n\t| '0' -> incr z2\n\t| '1' -> incr o2\n\t| '?' -> incr q2\n\t| _ -> assert false\n done;\n let ht = Hashtbl.create 4 in\n let solve' s =\n let s = ref s in\n let d = ref 1 in\n\twhile String.length !s > 2 do\n\t (*Printf.printf \"asd %s %d\\n\" !s !d;*)\n\t (try\n\t let i = String.index !s (Char.chr (!d + Char.code '0')) in\n\t s := String.sub !s 0 i ^\n\t\t String.sub !s (i + 1) (String.length !s - i - 1);\n\t with\n\t | Not_found ->\n\t\t s := String.sub !s 1 (String.length !s - 1)\n\t );\n\t d := 1 - !d;\n\tdone;\n\tHashtbl.replace ht !s ()\n in\n let solve _s z o q z2 o2 tail =\n (*for d = 0 to q do\n\tlet z = z + d\n\tand o = o + (q - d) in*)\n\t (*Printf.printf \"asd zoq %d %d %d\\n\" z o q;*)\n\t if n mod 2 = 0 then (\n\t if z + q >= o + 4\n\t then solve' (\"0000\" ^ tail)\n\t else if z + q >= o + 2\n\t then solve' (\"00\" ^ tail);\n\t if o + q >= z + 4\n\t then solve' (\"1111\" ^ tail)\n\t else if o + q >= z + 2\n\t then solve' (\"11\" ^ tail);\n\t if z <= o + q && o <= z + q\n\t then Hashtbl.replace ht tail ();\n\t ) else (\n\t if z + q >= o + 5\n\t then solve' (\"00000\" ^ tail)\n\t else if z + q >= o + 3\n\t then solve' (\"000\" ^ tail);\n\t if o + q >= z + 5\n\t then solve' (\"11111\" ^ tail)\n\t else if o + q >= z + 3\n\t then solve' (\"111\" ^ tail);\n\t if z <= o + q + 1 && o + 1 <= z + q\n\t then solve' (\"0\" ^ tail);\n\t if z + 1 <= o + q && o <= z + 1 + q\n\t then solve' (\"1\" ^ tail);\n\t )\n (*done*)\n in\n (match s.[n - 2], s.[n - 1] with\n\t | '?', '?' ->\n\t solve s !z !o !q 2 0 \"00\";\n\t solve s !z !o !q 1 1 \"01\";\n\t solve s !z !o !q 1 1 \"10\";\n\t solve s !z !o !q 0 2 \"11\";\n\t | '?', _ ->\n\t solve s !z !o !q (!z2 + 1) !o2 (\"0\" ^ String.make 1 s.[n - 1]);\n\t solve s !z !o !q !z2 (!o2 + 1) (\"1\" ^ String.make 1 s.[n - 1]);\n\t | _, '?' ->\n\t solve s !z !o !q (!z2 + 1) !o2 (String.make 1 s.[n - 2] ^ \"0\");\n\t solve s !z !o !q !z2 (!o2 + 1) (String.make 1 s.[n - 2] ^ \"1\");\n\t | _ ->\n\t solve s !z !o !q !z2 !o2 (String.sub s (n - 2) 2);\n );\n if Hashtbl.mem ht \"00\" then Printf.printf \"00\\n\";\n if Hashtbl.mem ht \"01\" then Printf.printf \"01\\n\";\n if Hashtbl.mem ht \"10\" then Printf.printf \"10\\n\";\n if Hashtbl.mem ht \"11\" then Printf.printf \"11\\n\";\n"}], "src_uid": "f03f1613292cacc36abbd3a3a25cbf86"} {"nl": {"description": "You are given a sequence of numbers a1,\u2009a2,\u2009...,\u2009an, and a number m.Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.", "input_spec": "The first line contains two numbers, n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009106, 2\u2009\u2264\u2009m\u2009\u2264\u2009103) \u2014 the size of the original sequence and the number such that sum should be divisible by it. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "In the single line print either \"YES\" (without the quotes) if there exists the sought subsequence, or \"NO\" (without the quotes), if such subsequence doesn't exist.", "sample_inputs": ["3 5\n1 2 3", "1 6\n5", "4 6\n3 1 1 3", "6 6\n5 5 5 5 5 5"], "sample_outputs": ["YES", "NO", "YES", "YES"], "notes": "NoteIn the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.In the third sample test you need to choose two numbers 3 on the ends.In the fourth sample test you can take the whole subsequence."}, "positive_code": [{"source_code": "exception Fini\n\nlet no_doubl l =\n\tlet rec aux = function\n\t\t| a::b::q\t-> if a=b\n\t\t\t\t\tthen aux (b::q)\n\t\t\t\t\telse a::(aux (b::q))\n\t\t| l'\t\t-> l'\n\tin aux (List.sort compare l)\n\nlet main () =\n\tlet (n,m) = Scanf.scanf \"%d %d\" (fun i j -> (i,j)) and l = ref [] in\n\t\ttry\n\t\t(\n\t\tfor i = 1 to n do\n\t\t\tlet j = Scanf.scanf \" %d\" (fun k -> k) in\n\t\t\t\tl := no_doubl (((j mod m) :: !l) @ (List.map (fun k -> (j+k) mod m) !l));\n\t\t\t\tif List.hd !l = 0\n\t\t\t\t\tthen raise Fini;\n\t\tdone; Printf.printf \"NO\"\n\t\t) with Fini -> Printf.printf \"YES\";;\n\nmain ();;\n"}], "negative_code": [], "src_uid": "25232f4244004fa4c130892957e5de84"} {"nl": {"description": "A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared \u2014 the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?", "input_spec": "The first line of the input contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the initial number of compilation errors. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the errors the compiler displayed for the first time. The third line contains n\u2009-\u20091 space-separated integers b1,\u2009b2,\u2009...,\u2009bn\u2009-\u20091 \u2014 the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n\u2009-\u20092 space-separated integers \u04411,\u2009\u04412,\u2009...,\u2009\u0441n\u2009-\u20092 \u2014 the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one. ", "output_spec": "Print two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively. ", "sample_inputs": ["5\n1 5 8 123 7\n123 7 5 1\n5 1 7", "6\n1 4 3 3 5 7\n3 7 5 4 3\n4 3 7 5"], "sample_outputs": ["8\n123", "1\n3"], "notes": "NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step. "}, "positive_code": [{"source_code": "open Printf\nopen Num\n\nlet n = Scanf.scanf \"%d \" (fun x -> x)\n\nlet my_hash = Hashtbl.create 1234567\n\nlet my_hash2 = Hashtbl.create 1234567\n\nlet () =\n for i = 0 to n-1 do\n let j = Scanf.scanf \"%d \" (fun x -> x) in\n Hashtbl.add my_hash j i\n done\n\nlet () =\n for i = 0 to n-2 do\n let j = Scanf.scanf \"%d \" (fun x -> x) in\n Hashtbl.add my_hash2 j i;\n Hashtbl.remove my_hash j\n done\n\nlet () = Hashtbl.iter (fun x y -> printf \"%d\\n\" x) my_hash\n\nlet () =\n for i = 0 to n-3 do\n let j = Scanf.scanf \"%d \" (fun x -> x) in\n Hashtbl.remove my_hash2 j;\n done\n\nlet () = Hashtbl.iter (fun x y -> printf \"%d\\n\" x) my_hash2\n\n \n \n"}, {"source_code": "open Printf\nopen Scanf\n\nlet increment h t d = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n if c+d = 0 then Hashtbl.remove h t else Hashtbl.replace h t (c+d)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let b = Array.init (n-1) (fun _ -> read_int()) in\n let c = Array.init (n-2) (fun _ -> read_int()) in\n\n let ha = Hashtbl.create 1000 in\n\n for i=0 to n-1 do\n increment ha a.(i) 1\n done;\n\n for i=0 to n-2 do\n increment ha b.(i) (-1)\n done;\n\n if Hashtbl.length ha <> 1 then failwith \"input wrong 1\";\n let e1 = ref (-1) in\n Hashtbl.iter (fun k v -> e1 := k) ha;\n\n let hb = Hashtbl.create 1000 in\n\n for i=0 to n-2 do\n increment hb b.(i) 1\n done;\n\n for i=0 to n-3 do\n increment hb c.(i) (-1)\n done;\n\n if Hashtbl.length hb <> 1 then failwith \"input wrong 2\";\n let e2 = ref (-1) in\n Hashtbl.iter (fun k v -> e2 := k) hb;\n\n printf \"%d\\n%d\\n\" !e1 !e2\n"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet get_list l =\n let rec loop i list =\n if i > 0\n then\n let var = read () in\n loop (i - 1) (var :: list)\n else\n List.sort (Pervasives.compare) list\n in loop l []\n\nlet subtract_lists first second = \n let rec subtract l1 l2 =\n match l1, l2 with \n | [], _ -> []\n | _, [] -> l1\n | hd :: tl, hhd :: ttl when hd = hhd -> subtract tl ttl\n | hd :: tl, _ -> hd :: (subtract tl l2) \n in subtract first second\n\nlet solve () = \n let n = read () in\n let first = get_list n in\n let second = get_list (n - 1) in\n let third = get_list (n - 2) in\n let bug_one = subtract_lists first second in\n let bug_two = subtract_lists second third in\n match bug_one, bug_two with\n | hd :: tl, hhd :: ttl -> (hd, hhd)\n | _ -> failwith \"Empty list\"\n\nlet print (a, b) = Printf.printf \"%d\\n%d\\n\" a b\nlet () = print (solve ())\n"}, {"source_code": "let _ = read_line () in\nlet ints _ = read_line () |> Str.split (Str.regexp \" +\") |> List.map int_of_string |> List.sort compare in\nlet rec diff x y = \n match (x ,y) with\n | ([e],[]) -> e\n | ((c :: cs), (d :: ds)) when c != d -> c\n | ((a :: ax), (b :: bx)) when a = b -> diff ax bx\n | _ -> failwith \"error\" in\n\nlet first = ints () and\n second = ints () and\n third = ints () in\nPrintf.printf \"%d\\n%d\" (diff first second) (diff second third)\n"}, {"source_code": "let next_int() =\n Scanf.scanf \"%d \" (fun x->x);;\n\nlet read_list n f =\n let rec loop idx =\n if idx == n then\n []\n else\n f()::loop (idx+1) in\n loop 0;;\n \nlet findDiff l1 l2 =\n let rec loop l1 l2 =\n match l1, l2 with\n | h1::t1, h2::t2 ->\n if h1 == h2 then\n loop t1 t2\n else\n h1\n | h1::t1, [] -> h1\n | _, _ -> 0 in\n loop (List.sort compare l1) (List.sort compare l2);;\n\nlet _ =\n let n = read_int() in\n let l1 = read_list n next_int in\n let l2 = read_list (n-1) next_int in\n let l3 = read_list (n-2) next_int in\n print_int(findDiff l1 l2);\n print_newline();\n print_int(findDiff l2 l3);\n print_newline();;\n"}, {"source_code": "let rec prem_dif = function\n\t|[a],[]\t\t-> a\n\t|t::q,t'::q'\t-> if t=t'\n\t\t\t\tthen prem_dif (q,q')\n\t\t\t\telse t;;\n\nlet main () =\n\tlet n = Scanf.scanf \"%d \" (fun i -> i) and prem = ref []\n\tand sec = ref [] and tro = ref [] in\n\t\tfor i = 1 to n do\n\t\t\tprem := (Scanf.scanf \"%d \" (fun j -> j))::!prem;\n\t\tdone;\n\t\tfor i = 1 to n-1 do\n\t\t\tsec := (Scanf.scanf \"%d \" (fun j -> j))::!sec;\n\t\tdone;\n\t\tfor i = 1 to n-2 do\n\t\t\ttro := (Scanf.scanf \"%d \" (fun j -> j))::!tro;\n\t\tdone;\n\t\tprem := List.sort compare !prem;\n\t\tsec := List.sort compare !sec;\n\t\ttro := List.sort compare !tro;\n\t\tPrintf.printf \"%d\\n%d\" (prem_dif (!prem,!sec)) (prem_dif (!sec,!tro));;\n\nmain ();;\n"}], "negative_code": [{"source_code": "let rec prem_dif = function\n\t|[a],[]\t\t-> a\n\t|t::q,t'::q'\t-> if t=t'\n\t\t\t\tthen prem_dif (q,q')\n\t\t\t\telse t;;\n\nlet main () =\n\tlet n = Scanf.scanf \"%d \" (fun i -> i) and prem = ref []\n\tand sec = ref [] and tro = ref [] in\n\t\tfor i = 1 to n do\n\t\t\tprem := (Scanf.scanf \"%d \" (fun j -> j))::!prem;\n\t\tdone;\n\t\tfor i = 1 to n-1 do\n\t\t\tsec := (Scanf.scanf \"%d \" (fun j -> j))::!sec;\n\t\tdone;\n\t\tfor i = 1 to n-2 do\n\t\t\ttro := (Scanf.scanf \"%d \" (fun j -> j))::!tro;\n\t\tdone;\n\t\tPrintf.printf \"%d\\n%d\" (prem_dif (!prem,!sec)) (prem_dif (!sec,!tro));;\n\nmain ();;\n"}], "src_uid": "1985566215ea5a7f22ef729bac7205ed"} {"nl": {"description": "Pavel loves grid mazes. A grid maze is an n\u2009\u00d7\u2009m rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly k empty cells into walls so that all the remaining cells still formed a connected area. Help him.", "input_spec": "The first line contains three integers n, m, k (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009500, 0\u2009\u2264\u2009k\u2009<\u2009s), where n and m are the maze's height and width, correspondingly, k is the number of walls Pavel wants to add and letter s represents the number of empty cells in the original maze. Each of the next n lines contains m characters. They describe the original maze. If a character on a line equals \".\", then the corresponding cell is empty and if the character equals \"#\", then the cell is a wall.", "output_spec": "Print n lines containing m characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as \"X\", the other cells must be left without changes (that is, \".\" and \"#\"). It is guaranteed that a solution exists. If there are multiple solutions you can output any of them.", "sample_inputs": ["3 4 2\n#..#\n..#.\n#...", "5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#"], "sample_outputs": ["#.X#\nX.#.\n#...", "#XXX\n#X#.\nX#..\n...#\n.#.#"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Tset = Set.Make (struct type t = int*(int*int) let compare = compare end)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n let maze = Array.init n (fun _ -> read_string()) in\n \n let is_open i j = maze.(i).[j] = '.' in\n\n let parent = Array.make_matrix n m None in\n\n let count = Array.make_matrix n m 0 in\n\n let avail (i,j) = i>=0 && j>=0 && i printf \"(%d,%d) \" i j) list;\n print_newline();\n*)\n let list' = List.fold_left (\n fun ac (i,j) -> \n\tlet moves = List.filter avail [(i+1,j);(i-1,j);(i,j+1);(i,j-1)] in\n\tList.fold_left (\n\t fun ac (i',j') -> \n\t parent.(i').(j') <- Some (i,j);\n\t count.(i).(j) <- count.(i).(j) + 1;\n\t (i',j')::ac\n\t) ac moves\n ) [] list\n in\n bfs list'\n )\n in\n\n let next (i,j) = if j 0 then failwith \"can't find a leaf\" else\n\tlet queue = Tset.remove (c,(i,j)) queue in\n\tmaze.(i).[j] <- 'X';\n\tmatch parent.(i).(j) with None -> failwith \"no parent\"\n\t | Some (i', j') -> \n\t let c = count.(i').(j') in\n\t count.(i').(j') <- count.(i').(j') - 1;\n\t if c=0 then failwith \"fail decrement parent count\" else\n\t let queue = Tset.add (c-1, (i',j')) (Tset.remove (c,(i',j')) queue) in\n\t markX queue (k-1)\n in\n \n markX queue k;\n\n for i=0 to n-1 do\n printf \"%s\\n\" maze.(i)\n done\n\n\n"}], "negative_code": [], "src_uid": "3aba4a129e24ca2f06f5f3ef13415b8b"} {"nl": {"description": "Pupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once.Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c1\u2009+\u2009c2\u00b7(x\u2009-\u20091)2 (in particular, if the group consists of one person, then the price is c1). All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group. ", "input_spec": "The first line contains three integers n, c1 and c2 (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000, 1\u2009\u2264\u2009c1,\u2009c2\u2009\u2264\u2009107)\u00a0\u2014 the number of visitors and parameters for determining the ticket prices for a group. The second line contains the string of length n, which consists of zeros and ones. If the i-th symbol of the string is zero, then the i-th visitor is a pupil, otherwise the i-th person is an adult. It is guaranteed that there is at least one adult. It is possible that there are no pupils.", "output_spec": "Print the minimum price of visiting the most extreme attraction for all pupils and their parents. Each of them should roll on the attraction exactly once.", "sample_inputs": ["3 4 1\n011", "4 7 2\n1101"], "sample_outputs": ["8", "18"], "notes": "NoteIn the first test one group of three people should go to the attraction. Then they have to pay 4\u2009+\u20091\u2009*\u2009(3\u2009-\u20091)2\u2009=\u20098.In the second test it is better to go to the attraction in two groups. The first group should consist of two adults (for example, the first and the second person), the second should consist of one pupil and one adult (the third and the fourth person). Then each group will have a size of two and for each the price of ticket is 7\u2009+\u20092\u2009*\u2009(2\u2009-\u20091)2\u2009=\u20099. Thus, the total price for two groups is 18."}, "positive_code": [{"source_code": "open Printf;;\nopen String;;\n\nlet ( +| ) a b = Int64.add a b;;\nlet ( -| ) a b = Int64.sub a b;;\nlet ( *| ) a b = Int64.mul a b;;\nlet ( /| ) a b = Int64.div a b;;\n\nlet inp = Str.split (Str.regexp \" \") (read_line());;\nlet n = int_of_string (List.nth inp 0);;\nlet c1 = Int64.of_string (List.nth inp 1);;\nlet c2 = Int64.of_string (List.nth inp 2);;\nlet s = read_line();;\n\nlet rec count_one idx =\n if idx = n then 0\n else (if (String.get s idx) = '1' then 1 else 0) + (count_one (idx + 1));;\n \nlet adults = count_one 0;;\n\nlet calc_single x = c1 +| (c2 *| ((x -| 1L) *| (x -| 1L)));;\n \nlet calc_total x = \n let nn = Int64.of_int n in\n let r = Int64.rem nn x in\n (r *| calc_single((nn /| x) +| 1L)) +|\n ((x -| r) *| calc_single(nn /| x));;\n \n\nlet rec process i ans = \n if i > adults then printf \"%Ld\\n\" ans else\n let newcost = calc_total (Int64.of_int i) in\n process (i + 1) (if ans > newcost then newcost else ans);;\n \nlet _ = process 1 Int64.max_int;;"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sq x = x ** x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let c1 = long (read_int ()) in\n let c2 = long (read_int ()) in\n let s = read_string() in\n let m = sum 0 (n-1) (fun i -> if s.[i] = '0' then 0 else 1) in (* number of adults *)\n\n let answer = minf 1 m (fun g -> (* g = number of groups *)\n let x1 = n/g in\n let x2 = x1 + 1 in\n let n2 = n - (g * x1) in\n let n1 = g - n2 in\n let (g,n1,n2,x1,x2) = (long g, long n1, long n2, long x1, long x2) in\n c1 ** g ++ c2 ** (n1 ** (sq (x1--1L)) ++ n2 ** (sq (x2 -- 1L)))\n ) in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [{"source_code": "open Printf;;\nopen String;;\n \nlet inp = Str.split (Str.regexp \" \") (read_line());;\nlet n = int_of_string (List.nth inp 0);;\nlet c1 = Int64.of_string (List.nth inp 1);;\nlet c2 = Int64.of_string (List.nth inp 2);;\nlet s = read_line();;\n\nlet rec can_group len idx adult =\n let slen = (String.length s) in\n if idx = slen then true\n else if (idx mod len) = 0 && (not adult) then false\n else can_group len (idx + 1) (((String.get s idx) = '1')\n || ((idx mod len) > 0 && adult));;\n\nlet rec process i ans = \n if i > n then printf \"%Ld\\n\" ans else\n let newcost = \n if (n mod i) = 0 && (can_group i 0 true) then\n let scost = Int64.add c1 (Int64.mul c2 (Int64.mul (Int64.of_int (i - 1)) (Int64.of_int (i - 1)))) in\n Int64.mul scost (Int64.div (Int64.of_int n) (Int64.of_int i))\n else Int64.max_int in\n process (i + 1) (if ans > newcost then newcost else ans);;\n \nlet _ = process 1 Int64.max_int;;"}, {"source_code": "open Printf;;\nopen String;;\n \nlet inp = Str.split (Str.regexp \" \") (read_line());;\nlet n = int_of_string (List.nth inp 0);;\nlet c1 = Int64.of_string (List.nth inp 1);;\nlet c2 = Int64.of_string (List.nth inp 2);;\nlet s = read_line();;\n\nlet rec can_group len idx adult =\n let slen = (String.length s) in\n if idx = slen then true\n else if (idx mod len) = 0 && (not adult) then false\n else can_group len (idx + 1) (((String.get s idx) = '1')\n || ((idx mod len) > 0 && adult));;\n\nlet rec process i ans = \n if i > n then printf \"%Ld\\n\" ans else\n let newcost = \n if (n mod i) = 0 && (can_group i 0 true) then\n let scost = Int64.add c1 (Int64.mul c2 (Int64.mul (Int64.of_int (i - 1)) (Int64.of_int (i - 1)))) in\n Int64.mul scost (Int64.div (Int64.of_int n) (Int64.of_int i))\n else 1000000000000000000L in\n process (i + 1) (if ans > newcost then newcost else ans);;\n \nlet _ = process 1 1000000000000000000L;;"}], "src_uid": "78d013b01497053b8e321fe7b6ce3760"} {"nl": {"description": "Sherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1\u2009\u2264\u2009p\u2009<\u2009|s|) and perform one of the following actions: either replace letter sp with the one that alphabetically follows it and replace letter sp\u2009+\u20091 with the one that alphabetically precedes it; or replace letter sp with the one that alphabetically precedes it and replace letter sp\u2009+\u20091 with the one that alphabetically follows it. Let us note that letter \"z\" doesn't have a defined following letter and letter \"a\" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed.Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations.Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109\u2009+\u20097).", "input_spec": "The input data contains several tests. The first line contains the only integer t (1\u2009\u2264\u2009t\u2009\u2264\u2009104) \u2014 the number of tests. Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ.", "output_spec": "For each word you should print the number of different other words that coincide with it in their meaning \u2014 not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["1\nab", "1\naaaaaaaaaaa", "2\nya\nklmbfxzb"], "sample_outputs": ["1", "0", "24\n320092793"], "notes": "NoteSome explanations about the operation: Note that for each letter, we can clearly define the letter that follows it. Letter \"b\" alphabetically follows letter \"a\", letter \"c\" follows letter \"b\", ..., \"z\" follows letter \"y\". Preceding letters are defined in the similar manner: letter \"y\" precedes letter \"z\", ..., \"a\" precedes letter \"b\". Note that the operation never changes a word's length. In the first sample you can obtain the only other word \"ba\". In the second sample you cannot obtain any other word, so the correct answer is 0.Consider the third sample. One operation can transform word \"klmbfxzb\" into word \"klmcexzb\": we should choose p\u2009=\u20094, and replace the fourth letter with the following one (\"b\" \u2009\u2192\u2009 \"c\"), and the fifth one \u2014 with the preceding one (\"f\" \u2009\u2192\u2009 \"e\"). Also, we can obtain many other words from this one. An operation can transform word \"ya\" only into one other word \"xb\". Word \"ya\" coincides in its meaning with words \"xb\", \"wc\", \"vd\", ..., \"ay\" (overall there are 24 other words). The word \"klmbfxzb has many more variants \u2014 there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 \u2014 the number 3320092814 modulo 109\u2009+\u20097"}, "positive_code": [{"source_code": "let _ =\n let mm = 1000000007 in\n let m = 1000000007l in\n let a = Array.make_matrix (100 + 1) (2500 + 1) 0 in\n let () =\n a.(0).(0) <- 1;\n for i = 1 to 100 do\n let cur = ref 0 in\n\tfor j = 0 to 2500 do\n\t cur := (Int32.to_int\n\t\t (Int32.rem\n\t\t (Int32.add\n\t\t\t (Int32.of_int !cur)\n\t\t\t (Int32.of_int a.(i - 1).(j)))\n\t\t m));\n\t if j - 26 >= 0 then (\n\t cur := (Int32.to_int\n\t\t (Int32.rem\n\t\t\t (Int32.sub\n\t\t\t (Int32.of_int !cur)\n\t\t\t (Int32.of_int a.(i - 1).(j - 26)))\n\t\t\t m));\n\t if !cur < 0\n\t then cur := !cur + mm;\n\t );\n\t a.(i).(j) <- !cur;\n\tdone\n done;\n in\n let sb = Scanf.Scanning.stdib in\n let cases = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for ca = 1 to cases do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let b = Array.init n (fun i -> Char.code s.[i] - Char.code 'a') in\n let sum = ref 0 in\n let () =\n\tfor i = 0 to n - 1 do\n\t sum := !sum + b.(i)\n\tdone;\n in\n let sum = !sum in\n\tlet res = a.(n).(sum) - 1 in\n\tlet res = if res < 0 then res + mm else res in\n\t Printf.printf \"%d\\n\" res;\n done\n"}], "negative_code": [], "src_uid": "75f64fc53b88a06c58a219f11da8efb7"} {"nl": {"description": "Madoka is a very strange girl, and therefore she suddenly wondered how many pairs of integers $$$(a, b)$$$ exist, where $$$1 \\leq a, b \\leq n$$$, for which $$$\\frac{\\operatorname{lcm}(a, b)}{\\operatorname{gcd}(a, b)} \\leq 3$$$.In this problem, $$$\\operatorname{gcd}(a, b)$$$ denotes the greatest common divisor of the numbers $$$a$$$ and $$$b$$$, and $$$\\operatorname{lcm}(a, b)$$$ denotes the smallest common multiple of the numbers $$$a$$$ and $$$b$$$.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first and the only line of each test case contains the integer $$$n$$$ ($$$1 \\le n \\le 10^8$$$).", "output_spec": "For each test case output a single integer \u2014 the number of pairs of integers satisfying the condition.", "sample_inputs": ["6\n\n1\n\n2\n\n3\n\n4\n\n5\n\n100000000"], "sample_outputs": ["1\n4\n7\n10\n11\n266666666"], "notes": "NoteFor $$$n = 1$$$ there is exactly one pair of numbers\u00a0\u2014 $$$(1, 1)$$$ and it fits.For $$$n = 2$$$, there are only $$$4$$$ pairs\u00a0\u2014 $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(2, 2)$$$ and they all fit.For $$$n = 3$$$, all $$$9$$$ pair are suitable, except $$$(2, 3)$$$ and $$$(3, 2)$$$, since their $$$\\operatorname{lcm}$$$ is $$$6$$$, and $$$\\operatorname{gcd}$$$ is $$$1$$$, which doesn't fit the condition."}, "positive_code": [{"source_code": "(* This is an OCaml editor.\r\n Enter your program here and send it to the toplevel using the \"Eval code\"\r\n button or [Ctrl-e]. *)\r\n\r\nlet i = read_int() in\r\nlet rec loop x= \r\n if x=0 then () else \r\n (let j = read_int() in print_int (j+ (j/2)*2 + (j/3)*2);print_newline() ; loop (x-1) )\r\n \r\nin loop i"}, {"source_code": "let rec loop (t : int) =\r\n if t = 0 then\r\n ()\r\n else\r\n let n = read_int () in\r\n let () = print_endline (string_of_int (n + 2*(n / 2) + 2*(n/3))) in\r\n loop (t-1)\r\n;;\r\n\r\nlet t = read_int () in loop t;;\r\n"}, {"source_code": "open Printf\r\nopen Scanf\r\n\r\nlet ( ** ) a b = Int64.mul a b\r\nlet ( ++ ) a b = Int64.add a b\r\nlet ( -- ) a b = Int64.sub a b\r\nlet ( // ) a b = Int64.div a b\r\nlet ( %% ) a b = Int64.rem a b\r\n\r\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\r\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\r\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\r\n\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \r\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\r\nlet read_tup _ = bscanf Scanning.stdin \" %d %d %d \" (fun x y z -> (x,y,z))\r\n\r\n\r\n\r\nlet rec inp (n : int) = \r\n if (n == 0) \r\n then []\r\n else\r\n let i = read_int () in\r\n let j = read_int () in\r\n let x = read_int () in\r\n \r\n (i - 1, j - 1, x) :: inp (n - 1)\r\n\r\n\r\nlet rec solve (n : int) (m : int) arr = \r\n if (m == 0) \r\n then Array.make n 0\r\n else\r\n let prev = solve n (m / 2) arr in\r\n let z = Array.make n 0 in\r\n let res = Array.make n 0 in\r\n let adj = Array.make n [] in\r\n let rec process aa = \r\n match aa with\r\n [] -> ()\r\n | (i, j, x) :: xs ->\r\n let () = (\r\n if ((x land m) == 0)\r\n then\r\n (* let () = printf \"A %d %d %d %d \\n\" i j x m in *)\r\n let () = Array.set z i 1 in\r\n Array.set z j 1\r\n else\r\n (* let () = printf \"B %d %d %d %d \\n\" i j x m in *)\r\n if (i == j)\r\n then Array.set res i m\r\n else\r\n (\r\n let oldi = Array.get adj i in\r\n let () = Array.set adj i (j :: oldi) in\r\n let oldj = Array.get adj j in\r\n let () = Array.set adj j (i :: oldj) in\r\n ()\r\n )\r\n ) in\r\n process xs\r\n in\r\n let () = process arr in\r\n \r\n let () = \r\n for i = 0 to (n - 1) do\r\n let rec uu aa = \r\n (\r\n match aa with\r\n [] -> ()\r\n | x :: xs -> \r\n let () = (\r\n if ((Array.get z x) == 1)\r\n then Array.set res i m\r\n else ()\r\n ) in\r\n uu xs \r\n )\r\n in\r\n let rec vv aa = \r\n (\r\n match aa with\r\n [] -> ()\r\n | x :: xs -> \r\n let () = Array.set res x m in\r\n (* let () = printf \"%d %d %d \\n\" m i x in *)\r\n vv xs \r\n )\r\n in\r\n let () = uu (Array.get adj i) in\r\n (\r\n if ((Array.get res i) == 0)\r\n then\r\n (* let () = Array.set z i 1 in *)\r\n vv (Array.get adj i)\r\n else \r\n ()\r\n )\r\n done\r\n in\r\n \r\n let () = \r\n for i = 0 to (n - 1) do\r\n Array.set res i ((Array.get res i) + (Array.get prev i))\r\n done\r\n in\r\n res\r\n\r\nlet () = \r\n let t = read_int () in\r\n \r\n for i = 1 to t do\r\n let n = read_int () in\r\n let a = n / 2 in\r\n let b = n / 3 in\r\n \tprintf \"%d\\n\" (n + a + a + b + b)\r\n done\r\n \r\n"}], "negative_code": [], "src_uid": "a6b6d9ff2ac5c367c00a64a387cc9e36"} {"nl": {"description": "Famil Door\u2019s City map looks like a tree (undirected connected acyclic graph) so other people call it Treeland. There are n intersections in the city connected by n\u2009-\u20091 bidirectional roads.There are m friends of Famil Door living in the city. The i-th friend lives at the intersection ui and works at the intersection vi. Everyone in the city is unhappy because there is exactly one simple path between their home and work.Famil Door plans to construct exactly one new road and he will randomly choose one among n\u00b7(n\u2009-\u20091)\u2009/\u20092 possibilities. Note, that he may even build a new road between two cities that are already connected by one.He knows, that each of his friends will become happy, if after Famil Door constructs a new road there is a path from this friend home to work and back that doesn't visit the same road twice. Formally, there is a simple cycle containing both ui and vi. Moreover, if the friend becomes happy, his pleasure is equal to the length of such path (it's easy to see that it's unique). For each of his friends Famil Door wants to know his expected pleasure, that is the expected length of the cycle containing both ui and vi if we consider only cases when such a cycle exists.", "input_spec": "The first line of the input contains integers n and m (2\u2009\u2264\u2009n,\u2009 m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of the intersections in the Treeland and the number of Famil Door's friends. Then follow n\u2009-\u20091 lines describing bidirectional roads. Each of them contains two integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n)\u00a0\u2014 the indices of intersections connected by the i-th road. Last m lines of the input describe Famil Door's friends. The i-th of these lines contain two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n,\u2009ui\u2009\u2260\u2009vi)\u00a0\u2014 indices of intersections where the i-th friend lives and works.", "output_spec": "For each friend you should print the expected value of pleasure if he will be happy. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["4 3\n2 4\n4 1\n3 2\n3 1\n2 3\n4 1", "3 3\n1 2\n1 3\n1 2\n1 3\n2 3"], "sample_outputs": ["4.00000000\n3.00000000\n3.00000000", "2.50000000\n2.50000000\n3.00000000"], "notes": "NoteConsider the second sample. Both roads (1,\u20092) and (2,\u20093) work, so the expected length if Roads (1,\u20093) and (2,\u20093) make the second friend happy. Same as for friend 1 the answer is 2.5 The only way to make the third friend happy is to add road (2,\u20093), so the answer is 3 "}, "positive_code": [{"source_code": "\n(* [@@@warning \"-30\"] *)\n\ntype vertex = {\n mutable adjacent : vertex array;\n mutable parent : vertex;\n mutable depth : int;\n mutable t_entr : int;\n mutable t_exit : int;\n mutable sigma_d : int64;\n mutable sigma'_d : int64;\n mutable count : int64;\n uf : uf;\n mutable ancestor : vertex;\n mutable colored : bool;\n}\nand uf = {\n mutable parent : vertex;\n mutable rank : int;\n}\n\nmodule H = Hashtbl.Make(struct type t = vertex let equal = (==) let hash v = v.t_entr end)\n\nlet none = -1\n\nlet dummy () =\n let rec v = {\n adjacent = [| |];\n parent = v;\n depth = none;\n t_entr = none;\n t_exit = none;\n sigma_d = 0L;\n sigma'_d = 0L;\n count = 0L;\n uf = { parent = v; rank = 0 };\n ancestor = v;\n colored = false\n }\n in\n v\n\nlet (+~), (-~), zero = Int64.(add, sub, zero)\n\nlet dfs1 root =\n let rec dfs d t p curr =\n curr.t_entr <- t;\n curr.depth <- d;\n curr.parent <- p;\n curr.count <- curr.count +~ 1L;\n let t =\n Array.fold_left\n (fun t v ->\n if v != p then begin\n let t = dfs (d + 1) (t + 1) curr v in\n curr.sigma_d <- curr.sigma_d +~ v.sigma_d +~ v.count;\n curr.count <- curr.count +~ v.count;\n t\n end else t)\n t\n curr.adjacent\n in\n curr.t_exit <- t;\n t\n in\n ignore @@ dfs 0 0 root root\n\nlet dfs2 root =\n let rec dfs curr =\n let p = curr.parent in\n curr.sigma'_d <-\n if p != curr then\n (if p.parent != p then p.sigma'_d +~ root.count -~ p.count else 0L) +~\n p.sigma_d -~ curr.sigma_d -~ curr.count\n else\n 0L;\n Array.iter (fun v -> if v != p then dfs v) curr.adjacent\n in\n dfs root\n\nlet tarjan_olca queries =\n let init v =\n v.uf.parent <- v;\n v.uf.rank <- 0\n in\n let rec find v =\n if v.uf.parent == v then\n v\n else\n let p = find v.uf.parent in\n v.uf.parent <- p;\n p\n in\n let union u v =\n let u, v = find u, find v in\n if u.uf.rank > v.uf.rank then\n v.uf.parent <- u\n else if u.uf.rank < v.uf.rank then\n u.uf.parent <- v\n else if u != v then begin\n v.uf.parent <- u;\n u.uf.rank <- u.uf.rank + 1\n end\n in\n let rec tarjan u =\n init u;\n u.ancestor <- u;\n Array.iter\n (fun v ->\n if v != u.parent then begin\n tarjan v;\n union u v;\n (find u).ancestor <- u\n end)\n u.adjacent;\n u.colored <- true;\n try\n H.iter\n (fun v a ->\n if v.colored then\n let r = (find v).ancestor in\n a := r;\n H.find (H.find queries v) u := r)\n (H.find queries u)\n with\n | Not_found -> ()\n in\n tarjan\n\ntype data = { low : vertex; sub : vertex }\n\ntype path_kind = I of data | V\n\nlet search queries u v =\n let search u v =\n let rec search l r =\n if l = r then u.adjacent.(l)\n else\n let m = l + (r - l) / 2 in\n let m = if u.adjacent.(m) == u.parent then m + 1 else m in\n if u.adjacent.(m).t_entr > v.t_entr then search l (m - 1)\n else if u.adjacent.(m).t_exit < v.t_exit then search (m + 1) r\n else u.adjacent.(m)\n in\n search 0 (Array.length u.adjacent - 1)\n in\n let kind =\n if u.t_entr <= v.t_entr && u.t_exit >= v.t_exit then I { low = v; sub = search u v }\n else if v.t_entr <= u.t_entr && v.t_exit >= u.t_exit then I { low = u; sub = search v u }\n else V\n in\n kind, u.depth + v.depth - 2 * (!H.(find (find queries u) v)).depth\n\nlet solve queries root u v =\n let fl, (+), (/) = Int64.to_float, (+.), (/.) in\n match search queries u v with\n | V, n ->\n float_of_int n + 1. + fl u.sigma_d / fl u.count + fl v.sigma_d / fl v.count\n | I { low; sub } , n ->\n float_of_int n + 1. + fl low.sigma_d / fl low.count + fl sub.sigma'_d / fl (root.count -~ sub.count)\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let vertices = Array.init n (fun _ -> dummy ()) in\n let root = vertices.(0) in\n let edges = Array.make n [] in\n let add a i e = a.(i) <- e :: a.(i) in\n for _ = 1 to n - 1 do\n scanf \"%d %d\\n\" @@ fun a b ->\n add edges (a - 1) vertices.(b - 1);\n add edges (b - 1) vertices.(a - 1)\n done;\n Array.iteri (fun i v -> v.adjacent <- Array.of_list edges.(i)) vertices;\n dfs1 root;\n dfs2 root;\n let queries, queries_list = H.create 32, ref [] in\n let add_query u v =\n H.replace\n (try H.find queries u with Not_found -> let h = H.create 16 in H.replace queries u h; h)\n v\n (ref root)\n in\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun u v ->\n let u, v = vertices.(u - 1), vertices.(v - 1) in\n add_query u v ;\n add_query v u;\n queries_list := (u, v) :: !queries_list\n done;\n tarjan_olca queries vertices.(0);\n List.(iter (fun (u, v) -> Printf.printf \"%.7f\\n\" @@ solve queries root u v) @@ rev !queries_list)\n"}, {"source_code": "\nmodule H = Hashtbl.Make(struct type t = int let equal = ((=) : int -> int -> _) let hash x = x end)\n\ntype tree = {\n verts : int array;\n edges : int array array;\n parent : int array;\n depth : int array;\n t_entr : int array;\n t_exit : int array;\n sigma_d : int64 array;\n sigma'_d : int64 array;\n count : int64 array;\n\n uf_parent : int array;\n uf_rank : int array;\n ancestor : int array;\n colored : bool array;\n queries : int ref H.t H.t;\n}\n\nlet (+~), (-~), zero, none = Int64.(add, sub, zero, -1)\n\nlet incr a i n = a.(i) <- a.(i) +~ n\n\nlet dfs1 { verts; edges; parent; depth; t_entr; t_exit; sigma_d; count } =\n let rec dfs d t p curr =\n verts.(t) <- curr;\n t_entr.(curr) <- t;\n depth.(curr) <- d;\n parent.(curr) <- p;\n incr count curr 1L;\n let t =\n Array.fold_left\n (fun t v ->\n if v <> p then begin\n let t = dfs (d + 1) (t + 1) curr v in\n incr sigma_d curr @@ sigma_d.(v) +~ count.(v);\n incr count curr @@ count.(v);\n t\n end else t)\n t\n edges.(curr)\n in\n t_exit.(curr) <- t;\n t\n in\n ignore @@ dfs 0 0 none 0\n\nlet dfs2 { edges; parent; sigma'_d; sigma_d; count } =\n let rec dfs curr =\n let p = parent.(curr) in\n sigma'_d.(curr) <-\n if p <> none then\n (if parent.(p) <> none then sigma'_d.(p) +~ count.(0) -~ count.(p) else 0L) +~\n sigma_d.(p) -~ sigma_d.(curr) -~ count.(curr)\n else\n 0L;\n Array.iter (fun v -> if v <> p then dfs v) edges.(curr)\n in\n dfs 0\n\nlet tarjan_olca { edges; parent; uf_parent; uf_rank; ancestor; colored; queries } =\n let init v =\n uf_parent.(v) <- v;\n uf_rank.(v) <- 0\n in\n let rec find v =\n if uf_parent.(v) == v then\n v\n else\n let p = find uf_parent.(v) in\n uf_parent.(v) <- p;\n p\n in\n let union u v =\n let u, v = find u, find v in\n if uf_rank.(u) > uf_rank.(v) then\n uf_parent.(v) <- u\n else if uf_rank.(u) < uf_rank.(v) then\n uf_parent.(u) <- v\n else if u <> v then begin\n uf_parent.(v) <- u;\n uf_rank.(u) <- uf_rank.(u) + 1\n end\n in\n let rec tarjan u =\n init u;\n ancestor.(u) <- u;\n Array.iter\n (fun v ->\n if v <> parent.(u) then begin\n tarjan v;\n union u v;\n ancestor.(find u) <- u\n end)\n edges.(u);\n colored.(u) <- true;\n try\n H.iter\n (fun v a ->\n if colored.(v) then\n let r = ancestor.(find v) in\n a := r;\n H.find (H.find queries v) u := r)\n (H.find queries u)\n with\n | Not_found -> ()\n in\n tarjan 0\n\ntype data = { low : int; sub : int }\n\ntype path_kind = I of data | V\n\nlet search { verts; edges; parent; t_entr; t_exit; depth; queries } u v =\n let search u v =\n let rec search l r =\n if l = r then edges.(u).(l)\n else\n let m = l + (r - l) / 2 in\n let m = if edges.(u).(m) = parent.(u) then m + 1 else m in\n if t_entr.(edges.(u).(m)) > t_entr.(v) then search l (m - 1)\n else if t_exit.(edges.(u).(m)) < t_exit.(v) then search (m + 1) r\n else edges.(u).(m)\n in\n search 0 (Array.length edges.(u) - 1)\n in\n let kind =\n if t_entr.(u) <= t_entr.(v) && t_exit.(u) >= t_exit.(v) then I { low = v; sub = search u v }\n else if t_entr.(v) <= t_entr.(u) && t_exit.(v) >= t_exit.(u) then I { low = u; sub = search v u }\n else V\n in\n kind, depth.(u) + depth.(v) - 2 * depth.(!H.(find (find queries u) v))\n\nlet solve ({ sigma_d; sigma'_d; count } as t) u v =\n let fl, (+), (/) = Int64.to_float, (+.), (/.) in\n match search t u v with\n | V, n ->\n float_of_int n + 1. + fl sigma_d.(u) / fl count.(u) + fl sigma_d.(v) / fl count.(v)\n | I { low; sub } , n ->\n float_of_int n + 1. + fl sigma_d.(low) / fl count.(low) + fl sigma'_d.(sub) / fl (count.(0) -~ count.(sub))\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let edges = Array.make n [] in\n let add a i e = a.(i) <- e :: a.(i) in\n for _ = 1 to n - 1 do\n scanf \"%d %d\\n\" @@ fun a b ->\n add edges (a - 1) (b - 1);\n add edges (b - 1) (a - 1)\n done;\n let t =\n Array.{\n verts = make n none;\n edges = init n (fun i -> Array.of_list edges.(i));\n parent = make n none;\n depth = make n none;\n t_entr = make n none;\n t_exit = make n none;\n sigma_d = make n zero;\n sigma'_d = make n zero;\n count = make n zero;\n\n uf_parent = make n none;\n uf_rank = make n none;\n ancestor = make n none;\n colored = make n false;\n queries = H.create 32;\n }\n in\n dfs1 t;\n dfs2 t;\n let queries = ref [] in\n let add_query u v =\n H.replace\n (try H.find t.queries u with Not_found -> let h = H.create 16 in H.replace t.queries u h; h)\n v\n (ref none)\n in\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun u v ->\n add_query (u - 1) (v - 1);\n add_query (v - 1) (u - 1);\n queries := (u - 1, v - 1) :: !queries\n done;\n tarjan_olca t;\n List.(iter (fun (u, v) -> Printf.printf \"%.7f\\n\" @@ solve t u v) @@ rev !queries)\n"}, {"source_code": " (* keywords: dynamic programming, tree DP, union find, tarjan LCA *)\n (* see also ~/Sync/contest-work/NCPC-2014/particle/ *)\n\nlet order (a,b) = (min a b, max a b)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\nlet float = Int64.to_float\n\nopen Printf\nopen Scanf\n\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n\n let tree = Array.make n [] in\n \n for i=1 to n-1 do\n let (a,b) = read_pair () in\n let (a,b) = (a-1,b-1) in\n tree.(a) <- b::tree.(a);\n tree.(b) <- a::tree.(b); \n done;\n\n let qgraph = Array.make n [] in\n let query = Array.make m (0,0) in\n \n for i=0 to m-1 do\n let (a,b) = read_pair () in\n let (a,b) = (a-1,b-1) in\n query.(i) <- (a,b);\n qgraph.(a) <- b::qgraph.(a);\n qgraph.(b) <- a::qgraph.(b); \n done;\n\n (* ------------------ union find ------------------- *)\n let uf = Array.make n (-1) in\n\n let rec find i = if uf.(i) < 0 then i else \n let r = find uf.(i) in\n uf.(i) <- r;\n r\n in\n \n let union i j =\n (* assume i and j are both canonical elements *)\n (* true union by rank (not size) *)\n let (wi,wj) = (-uf.(i), -uf.(j)) in\n let (wi,wj,i,j) = if wi < wj then (wi,wj,i,j) else (wj,wi,j,i) in\n uf.(j) <- - ((if wi=wj then 1 else 0) + wj);\n uf.(i) <- j;\n in\n (* ---------------- end union find ------------------ *)\n\n\n (* pure version\n (* ------------------ off-line LCA ------------------- *)\n let lca = Hashtbl.create 100 in\n let mark = Array.make n false in\n let ancestor = Array.make n 0 in\n \n let rec tarjan p u =\n List.iter (fun v -> if v <> p then (\n tarjan u v;\n union (find u) (find v);\n ancestor.(find u) <- u\n )) tree.(u);\n \n mark.(u) <- true;\n \n List.iter (fun v ->\n if mark.(v) then Hashtbl.replace lca (order (u,v)) ancestor.(find v)\n ) qgraph.(u)\n in\n tarjan (-1) 0;\n\n (* Hashtbl.iter (fun (u,v) a -> printf \"LCA(%d,%d) = %d\\n\" (u+1) (v+1) (a+1)) lca; *)\n (* ---------------- end off-line LCA ------------------ *) *)\n\n (* ------------------ customized off-line LCA ------------------- *)\n let nbr = Hashtbl.create 100 in\n let dist = Hashtbl.create 100 in \n let mark = Array.make n false in\n let on_stack = Array.make n false in \n let ancestor = Array.make n 0 in\n let current_child = Array.make n 0 in\n let parent = Array.make n 0 in\n let depth = Array.make n 0 in\n \n let rec tarjan p u d =\n parent.(u) <- p;\n depth.(u) <- d;\n on_stack.(u) <- true;\n List.iter (fun v -> if v <> p then (\n current_child.(u) <- v;\n tarjan u v (d+1);\n union (find u) (find v);\n ancestor.(find u) <- u\n )) tree.(u);\n\n on_stack.(u) <- false;\n mark.(u) <- true;\n \n List.iter (fun v ->\n if mark.(v) then (\n\tlet lca = ancestor.(find v) in\n\tlet distance = depth.(v) + depth.(u) - 2*depth.(lca) in\n\tHashtbl.add dist (order (u,v)) distance;\n\tif u <> lca then Hashtbl.add nbr (u,v) p;\n\tif v <> lca then Hashtbl.add nbr (v,u) parent.(v)\n ) else (\n\tif on_stack.(v) then Hashtbl.add nbr (v,u) current_child.(v)\n )\n ) qgraph.(u)\n in\n tarjan (-1) 0 0;\n (* --------------------------------------------------------------- *)\n\n (* now count paths *)\n\n let info = Hashtbl.create 100 in\n\n let rec dfs p u =\n try Hashtbl.find info (p,u) with Not_found ->\n let answer =\n\tList.fold_left (fun (ac_len, ac_n) v ->\n\t if v = p then (ac_len, ac_n) else\n\t let (pathlen, nnodes) = dfs u v in\n\t (ac_len ++ pathlen ++ nnodes, ac_n ++ nnodes)\n\t) (0L, 1L) tree.(u)\n in\n Hashtbl.add info (p,u) answer;\n answer\n in\n\n for i=0 to m-1 do\n let (u,v) = query.(i) in\n let nu = Hashtbl.find nbr (u,v) in\n let nv = Hashtbl.find nbr (v,u) in\n let (len_u, n_u) = dfs nu u in\n let (len_v, n_v) = dfs nv v in\n let ave_len_u = (float len_u) /. (float n_u) in\n let ave_len_v = (float len_v) /. (float n_v) in\n let path_dist = float (long (Hashtbl.find dist (order (u,v)))) in\n printf \"%.8f\\n\" (1.0 +. ave_len_u +. ave_len_v +. path_dist)\n done;\n"}], "negative_code": [{"source_code": "\ntype tree = {\n verts : int array;\n edges : int array array;\n parent : int array;\n depth : int array;\n t_entr : int array;\n t_exit : int array;\n sigma_d : int64 array;\n sigma'_d : int64 array;\n count : int64 array\n}\n\nlet (+~), (-~), zero, none = Int64.(add, sub, zero, -1)\n\nlet incr a i n = a.(i) <- a.(i) +~ n\n\nlet dfs1 { verts; edges; parent; depth; t_entr; t_exit; sigma_d; count } =\n let rec dfs d t p curr =\n verts.(t) <- curr;\n t_entr.(curr) <- t;\n depth.(curr) <- d;\n parent.(curr) <- p;\n incr count curr 1L;\n let t =\n Array.fold_left\n (fun t v ->\n if v <> p then begin\n let t = dfs (d + 1) (t + 1) curr v in\n incr sigma_d curr @@ sigma_d.(v) +~ count.(v);\n incr count curr @@ count.(v);\n t\n end else t)\n t\n edges.(curr)\n in\n t_exit.(curr) <- t;\n t\n in\n ignore @@ dfs 0 0 none 0\n\nlet dfs2 { edges; parent; sigma'_d; sigma_d; count } =\n let rec dfs curr =\n let p = parent.(curr) in\n sigma'_d.(curr) <-\n if p <> none then\n (if parent.(p) <> none then sigma'_d.(p) +~ count.(0) -~ count.(p) else 0L) +~\n sigma_d.(p) -~ sigma_d.(curr) -~ count.(curr)\n else\n 0L;\n Array.iter (fun v -> if v <> p then dfs v) edges.(curr)\n in\n dfs 0\n\ntype data = { low : int; sub : int }\n\ntype path_kind = I of data | V\n\nlet search { verts; edges; t_entr; t_exit; depth } u v =\n let search u v =\n let rec search l r =\n if l = r then edges.(u).(l)\n else\n let m = l + (r - l) / 2 in\n if t_entr.(edges.(u).(m)) > t_entr.(v) then search l (m - 1)\n else if t_exit.(edges.(u).(m)) < t_exit.(u) then search (m + 1) r\n else edges.(u).(m)\n in\n search 0 (Array.length edges.(u) - 1)\n in\n let kind =\n if t_entr.(u) <= t_entr.(v) && t_exit.(u) >= t_exit.(v) then I { low = v; sub = search u v }\n else if t_entr.(v) <= t_entr.(u) && t_exit.(v) >= t_exit.(u) then I { low = u; sub = search v u }\n else V\n in\n let rec search l r =\n if l = r then verts.(l)\n else\n let m = l + (r - l + 1) / 2 in\n (*Printf.eprintf \"m=%d(%d) t_entr.(m)=%d t_exit.(m)=%d t_entr.(u)=%d t_entr.(v)=%d\\n\"\n m verts.(m) t_entr.(verts.(m)) t_exit.(verts.(m)) t_entr.(u) t_entr.(v);*)\n if t_entr.(verts.(m)) > min t_entr.(u) t_entr.(v) ||\n t_exit.(verts.(m)) < max t_exit.(u) t_exit.(v)\n then search l (m - 1)\n else search m r\n in\n (*Printf.eprintf \"For u=%d v=%d search gave %d\\n\" u v (search 0 (Array.length verts - 1));*)\n kind, depth.(u) + depth.(v) - 2 * depth.(search 0 (Array.length verts - 1))\n\nlet solve ({ sigma_d; sigma'_d; count } as t) u v =\n let fl, (+), (/) = Int64.to_float, (+.), (/.) in\n match search t u v with\n | V, n ->\n float_of_int n + 1. + fl sigma_d.(u) / fl count.(u) + fl sigma_d.(v) / fl count.(v)\n | I { low; sub } , n ->\n (*Printf.eprintf \"u=%d v=%d n=%d s=%d l=%d fp=%f num=%f den=%f\\n\"\n u v n sub low\n (float_of_int n + 1. + fl sigma_d.(low) / fl count.(low))\n (fl sigma'_d.(sub))\n (fl (count.(0) -~ count.(sub)));*)\n float_of_int n + 1. + fl sigma_d.(low) / fl count.(low) + fl sigma'_d.(sub) / fl (count.(0) -~ count.(sub))\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let edges = Array.make n [] in\n let add a i e = a.(i) <- e :: a.(i) in\n for _ = 1 to n - 1 do\n scanf \"%d %d\\n\" @@ fun a b ->\n add edges (a - 1) (b - 1);\n add edges (b - 1) (a - 1)\n done;\n let t =\n Array.{\n verts = make n none;\n edges = init n (fun i -> Array.of_list edges.(i));\n parent = make n none;\n depth = make n none;\n t_entr = make n none;\n t_exit = make n none;\n sigma_d = make n zero;\n sigma'_d = make n zero;\n count = make n zero\n }\n in\n dfs1 t;\n dfs2 t;\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun u v -> Printf.printf \"%.7f\\n\" @@ solve t (u - 1) (v - 1)\n done\n"}, {"source_code": "\ntype tree = {\n verts : int array;\n edges : int array array;\n parent : int array;\n depth : int array;\n t_entr : int array;\n t_exit : int array;\n sigma_d : int64 array;\n sigma'_d : int64 array;\n count : int64 array\n}\n\nlet (+~), (-~), zero, none = Int64.(add, sub, zero, -1)\n\nlet incr a i n = a.(i) <- a.(i) +~ n\n\nlet dfs1 { verts; edges; parent; depth; t_entr; t_exit; sigma_d; count } =\n let rec dfs d t p curr =\n verts.(t) <- curr;\n t_entr.(curr) <- t;\n depth.(curr) <- d;\n parent.(curr) <- p;\n incr count curr 1L;\n let t =\n Array.fold_left\n (fun t v ->\n if v <> p then begin\n let t = dfs (d + 1) (t + 1) curr v in\n incr sigma_d curr @@ sigma_d.(v) +~ count.(v);\n incr count curr @@ count.(v);\n t\n end else t)\n t\n edges.(curr)\n in\n t_exit.(curr) <- t;\n t\n in\n ignore @@ dfs 0 0 none 0\n\nlet dfs2 { edges; parent; sigma'_d; sigma_d; count } =\n let rec dfs curr =\n let p = parent.(curr) in\n sigma'_d.(curr) <-\n if p <> none then\n (if parent.(p) <> none then sigma'_d.(p) +~ count.(0) -~ count.(p) else 0L) +~\n sigma_d.(p) -~ sigma_d.(curr) -~ count.(curr)\n else\n 0L;\n Array.iter (fun v -> if v <> p then dfs v) edges.(curr)\n in\n dfs 0\n\ntype data = { low : int; sub : int }\n\ntype path_kind = I of data | V\n\nlet search { verts; edges; parent; t_entr; t_exit; depth } u v =\n let search u v =\n let rec search l r =\n if l = r then edges.(u).(l)\n else\n let m = l + (r - l) / 2 in\n let m = if edges.(u).(m) = parent.(u) then m + 1 else m in\n if t_entr.(edges.(u).(m)) > t_entr.(v) then search l (m - 1)\n else if t_exit.(edges.(u).(m)) < t_exit.(v) then search (m + 1) r\n else edges.(u).(m)\n in\n search 0 (Array.length edges.(u) - 1)\n in\n let kind =\n if t_entr.(u) <= t_entr.(v) && t_exit.(u) >= t_exit.(v) then I { low = v; sub = search u v }\n else if t_entr.(v) <= t_entr.(u) && t_exit.(v) >= t_exit.(u) then I { low = u; sub = search v u }\n else V\n in\n let rec search best l r =\n (*Printf.eprintf \"best=%d l=%d r=%d\\n\" best l r;*)\n if l > r then verts.(best)\n else\n let m = l + (r - l + 1) / 2 in\n (*Printf.eprintf \"m=%d(%d) t_entr.(m)=%d t_exit.(m)=%d t_entr.(u)=%d t_entr.(v)=%d\\n\"\n m verts.(m) t_entr.(verts.(m)) t_exit.(verts.(m)) t_entr.(u) t_entr.(v);*)\n if t_entr.(verts.(m)) > min t_entr.(u) t_entr.(v) then search best l (m - 1)\n else if t_exit.(verts.(m)) < max t_exit.(u) t_exit.(v) then search best (m + 1) r\n else if m = r then verts.(m)\n else search m m r\n in\n (*Printf.eprintf \"For u=%d v=%d search gave %d\\n\" u v (search 0 0 (Array.length verts - 1));*)\n kind, depth.(u) + depth.(v) - 2 * depth.(search 0 0 (Array.length verts - 1))\n\nlet solve ({ sigma_d; sigma'_d; count } as t) u v =\n let fl, (+), (/) = Int64.to_float, (+.), (/.) in\n match search t u v with\n | V, n ->\n float_of_int n + 1. + fl sigma_d.(u) / fl count.(u) + fl sigma_d.(v) / fl count.(v)\n | I { low; sub } , n ->\n (*Printf.eprintf \"sub=%d\" sub;*)\n (*Printf.eprintf \"u=%d v=%d n=%d s=%d l=%d fp=%f num=%f den=%f\\n\"\n u v n sub low\n (float_of_int n + 1. + fl sigma_d.(low) / fl count.(low))\n (fl sigma'_d.(sub))\n (fl (count.(0) -~ count.(sub)));*)\n float_of_int n + 1. + fl sigma_d.(low) / fl count.(low) + fl sigma'_d.(sub) / fl (count.(0) -~ count.(sub))\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let edges = Array.make n [] in\n let add a i e = a.(i) <- e :: a.(i) in\n for _ = 1 to n - 1 do\n scanf \"%d %d\\n\" @@ fun a b ->\n add edges (a - 1) (b - 1);\n add edges (b - 1) (a - 1)\n done;\n let t =\n Array.{\n verts = make n none;\n edges = init n (fun i -> Array.of_list edges.(i));\n parent = make n none;\n depth = make n none;\n t_entr = make n none;\n t_exit = make n none;\n sigma_d = make n zero;\n sigma'_d = make n zero;\n count = make n zero\n }\n in\n dfs1 t;\n dfs2 t;\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun u v -> Printf.printf \"%.7f\\n\" @@ solve t (u - 1) (v - 1)\n done\n"}, {"source_code": "\ntype tree = {\n verts : int array;\n edges : int array array;\n parent : int array;\n depth : int array;\n t_entr : int array;\n t_exit : int array;\n sigma_d : int64 array;\n sigma'_d : int64 array;\n count : int64 array\n}\n\nlet (+~), (-~), zero, none = Int64.(add, sub, zero, -1)\n\nlet incr a i n = a.(i) <- a.(i) +~ n\n\nlet dfs1 { verts; edges; parent; depth; t_entr; t_exit; sigma_d; count } =\n let rec dfs d t p curr =\n verts.(t) <- curr;\n t_entr.(curr) <- t;\n depth.(curr) <- d;\n parent.(curr) <- p;\n incr count curr 1L;\n let t =\n Array.fold_left\n (fun t v ->\n if v <> p then begin\n let t = dfs (d + 1) (t + 1) curr v in\n incr sigma_d curr @@ sigma_d.(v) +~ count.(v);\n incr count curr @@ count.(v);\n t\n end else t)\n t\n edges.(curr)\n in\n t_exit.(curr) <- t;\n t\n in\n ignore @@ dfs 0 0 none 0\n\nlet dfs2 { edges; parent; sigma'_d; sigma_d; count } =\n let rec dfs curr =\n let p = parent.(curr) in\n sigma'_d.(curr) <-\n if p <> none then\n (if parent.(p) <> none then sigma'_d.(p) +~ count.(0) -~ count.(p) else 0L) +~\n sigma_d.(p) -~ sigma_d.(curr) -~ count.(curr)\n else\n 0L;\n Array.iter (fun v -> if v <> p then dfs v) edges.(curr)\n in\n dfs 0\n\ntype data = { low : int; sub : int }\n\ntype path_kind = I of data | V\n\nlet search { verts; edges; t_entr; t_exit; depth } u v =\n let search u v =\n let rec search l r =\n if l = r then edges.(u).(l)\n else\n let m = l + (r - l) / 2 in\n if t_entr.(edges.(u).(m)) > t_entr.(v) then search l (m - 1)\n else if t_exit.(edges.(u).(m)) < t_exit.(u) then search (m + 1) r\n else edges.(u).(m)\n in\n search 0 (Array.length edges.(u) - 1)\n in\n let kind =\n if t_entr.(u) <= t_entr.(v) && t_exit.(u) >= t_exit.(v) then I { low = v; sub = search u v }\n else if t_entr.(v) <= t_entr.(u) && t_exit.(v) >= t_exit.(u) then I { low = u; sub = search v u }\n else V\n in\n let rec search best l r =\n (*Printf.eprintf \"best=%d l=%d r=%d\\n\" best l r;*)\n if l > r then verts.(best)\n else\n let m = l + (r - l + 1) / 2 in\n (*Printf.eprintf \"m=%d(%d) t_entr.(m)=%d t_exit.(m)=%d t_entr.(u)=%d t_entr.(v)=%d\\n\"\n m verts.(m) t_entr.(verts.(m)) t_exit.(verts.(m)) t_entr.(u) t_entr.(v);*)\n if t_entr.(verts.(m)) > min t_entr.(u) t_entr.(v) then search best l (m - 1)\n else if t_exit.(verts.(m)) < max t_exit.(u) t_exit.(v) then search best (m + 1) r\n else if m = r then verts.(m)\n else search m m r\n in\n (*Printf.eprintf \"For u=%d v=%d search gave %d\\n\" u v (search 0 0 (Array.length verts - 1));*)\n kind, depth.(u) + depth.(v) - 2 * depth.(search 0 0 (Array.length verts - 1))\n\nlet solve ({ sigma_d; sigma'_d; count } as t) u v =\n let fl, (+), (/) = Int64.to_float, (+.), (/.) in\n match search t u v with\n | V, n ->\n float_of_int n + 1. + fl sigma_d.(u) / fl count.(u) + fl sigma_d.(v) / fl count.(v)\n | I { low; sub } , n ->\n (*Printf.eprintf \"u=%d v=%d n=%d s=%d l=%d fp=%f num=%f den=%f\\n\"\n u v n sub low\n (float_of_int n + 1. + fl sigma_d.(low) / fl count.(low))\n (fl sigma'_d.(sub))\n (fl (count.(0) -~ count.(sub)));*)\n float_of_int n + 1. + fl sigma_d.(low) / fl count.(low) + fl sigma'_d.(sub) / fl (count.(0) -~ count.(sub))\n\nlet () =\n let open Scanf in\n scanf \"%d %d\\n\" @@ fun n m ->\n let edges = Array.make n [] in\n let add a i e = a.(i) <- e :: a.(i) in\n for _ = 1 to n - 1 do\n scanf \"%d %d\\n\" @@ fun a b ->\n add edges (a - 1) (b - 1);\n add edges (b - 1) (a - 1)\n done;\n let t =\n Array.{\n verts = make n none;\n edges = init n (fun i -> Array.of_list edges.(i));\n parent = make n none;\n depth = make n none;\n t_entr = make n none;\n t_exit = make n none;\n sigma_d = make n zero;\n sigma'_d = make n zero;\n count = make n zero\n }\n in\n dfs1 t;\n dfs2 t;\n for _ = 1 to m do\n scanf \"%d %d\\n\" @@ fun u v -> Printf.printf \"%.7f\\n\" @@ solve t (u - 1) (v - 1)\n done\n"}], "src_uid": "2c1a2f8b91dd40e39763b5bedd8ad01a"} {"nl": {"description": "You have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi,\u2009yi (xi\u2009<\u2009yi) in the permuted array a. Let's define the value di\u2009=\u2009yi\u2009-\u2009xi \u2014 the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .", "input_spec": "The only line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105).", "output_spec": "Print 2n integers \u2014 the permuted array a that minimizes the value of the sum s.", "sample_inputs": ["2", "1"], "sample_outputs": ["1 1 2 2", "1 1"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make (2 * n) n in\n for i = 1 to n - 1 do\n let d = n - i in\n let x =\n\tif n mod 2 = 0 then (\n\t if d mod 2 = 0\n\t then i / 2 - 1 + n\n\t else i / 2\n\t) else (\n\t if d mod 2 = 0\n\t then i / 2\n\t else i / 2 - 1 + n\n\t)\n in\n let y = x + d in\n\ta.(x) <- i;\n\ta.(y) <- i;\n done;\n for i = 0 to 2 * n - 1 do\n Printf.printf \"%d \" a.(i)\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for i = 1 to n do\n Printf.printf \"%d %d \" i i\n done;\n Printf.printf \"\\n\"\n"}], "src_uid": "c234cb0321e2bd235cd539a63364b152"} {"nl": {"description": "A sequence of $$$n$$$ non-negative integers ($$$n \\ge 2$$$) $$$a_1, a_2, \\dots, a_n$$$ is called good if for all $$$i$$$ from $$$1$$$ to $$$n-1$$$ the following condition holds true: $$$$$$a_1 \\: \\& \\: a_2 \\: \\& \\: \\dots \\: \\& \\: a_i = a_{i+1} \\: \\& \\: a_{i+2} \\: \\& \\: \\dots \\: \\& \\: a_n,$$$$$$ where $$$\\&$$$ denotes the bitwise AND operation.You are given an array $$$a$$$ of size $$$n$$$ ($$$n \\geq 2$$$). Find the number of permutations $$$p$$$ of numbers ranging from $$$1$$$ to $$$n$$$, for which the sequence $$$a_{p_1}$$$, $$$a_{p_2}$$$, ... ,$$$a_{p_n}$$$ is good. Since this number can be large, output it modulo $$$10^9+7$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$), denoting the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$0 \\le a_i \\le 10^9$$$) \u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Output $$$t$$$ lines, where the $$$i$$$-th line contains the number of good permutations in the $$$i$$$-th test case modulo $$$10^9 + 7$$$.", "sample_inputs": ["4\n3\n1 1 1\n5\n1 2 3 4 5\n5\n0 2 0 3 0\n4\n1 3 5 1"], "sample_outputs": ["6\n0\n36\n4"], "notes": "NoteIn the first test case, since all the numbers are equal, whatever permutation we take, the sequence is good. There are a total of $$$6$$$ permutations possible with numbers from $$$1$$$ to $$$3$$$: $$$[1,2,3]$$$, $$$[1,3,2]$$$, $$$[2,1,3]$$$, $$$[2,3,1]$$$, $$$[3,1,2]$$$, $$$[3,2,1]$$$.In the second test case, it can be proved that no permutation exists for which the sequence is good.In the third test case, there are a total of $$$36$$$ permutations for which the sequence is good. One of them is the permutation $$$[1,5,4,2,3]$$$ which results in the sequence $$$s=[0,0,3,2,0]$$$. This is a good sequence because $$$ s_1 = s_2 \\: \\& \\: s_3 \\: \\& \\: s_4 \\: \\& \\: s_5 = 0$$$, $$$ s_1 \\: \\& \\: s_2 = s_3 \\: \\& \\: s_4 \\: \\& \\: s_5 = 0$$$, $$$ s_1 \\: \\& \\: s_2 \\: \\& \\: s_3 = s_4 \\: \\& \\: s_5 = 0$$$, $$$ s_1 \\: \\& \\: s_2 \\: \\& \\: s_3 \\: \\& \\: s_4 = s_5 = 0$$$. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n \nlet p = 1_000_000_007L\n\n(* mod safe for negative numbers *)\nlet ( %% ) x n = let y = Int64.rem x n in if y<0L then Int64.add y n else y\n(* Now, arithmetic modulo p, assuming the arguments a and b are in [0,p-1] *)\nlet ( ** ) a b = Int64.rem (Int64.mul a b) p\nlet ( ++ ) a b = let y = Int64.add a b in if y >= p then Int64.sub y p else y\nlet ( -- ) a b = let y = Int64.sub a b in if y<0L then Int64.add y p else y\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet prod i j f = fold i j (fun i a -> (f i) ** a) 1L \n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n let m = minf 0 (n-1) (fun i -> a.(i)) in\n (* the only way it can work is if m occurs at least twice\n and all other numbers are supersets of m *)\n let ms = sum 0 (n-1) (fun i -> if a.(i) = m then 1 else 0) in\n\n let badone = exists 0 (n-1) (fun i -> m land a.(i) <> m) in\n \n if ms < 2 || badone then printf \"0\\n\" else (\n let ans = (long ms)**(long (ms-1))**(prod 1 (n-2) (fun i -> long i)) in\n printf \"%Ld\\n\" ans\n )\n done\n"}], "negative_code": [], "src_uid": "e4685bb0a1bf8c2da326cd0e5b8f4fe7"} {"nl": {"description": "Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configuration?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950000). The second line contains n non-negative numbers that do not exceed 109, the i-th written number is the number of matches in the i-th matchbox. It is guaranteed that the total number of matches is divisible by n.", "output_spec": "Print the total minimum number of moves.", "sample_inputs": ["6\n1 6 2 5 3 7"], "sample_outputs": ["12"], "notes": null}, "positive_code": [{"source_code": "open Scanf;;\nopen Num;;\nopen Printf;;\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x);;\n\nlet imatch = Array.create n (num_of_int 0);;\nlet kmatch = ref (Num.num_of_int 0);;\n\nfor i = 0 to n-1 do\n let ni = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n imatch.(i) <- num_of_int ni; kmatch := (num_of_int ni) +/ !kmatch\ndone\n;;\n\n(*Remove the average*)\nlet av = div_num !kmatch (num_of_int n) in\nfor i = 0 to n - 1 do\n imatch.(i) <- imatch.(i) -/ av\ndone\n;;\n\n(*Array.iter (fun x -> print_int x; print_endline \"\") imatch;;*)\n\nlet sum_over i j =\n let total = ref (num_of_int 0) in\n for k = i to j do\n total := !total +/ imatch.(k)\n done; total\n;;\n\nlet rec direct_cal nl nr rslt = \n if nl = nr then\n rslt +/ !(sum_over nl nr)\n else\n let mid = (nl + nr) / 2 in\n let a = !(sum_over nl mid) in\n imatch.(mid) <- imatch.(mid) -/ a;\n imatch.(mid+1)<-imatch.(mid+1) +/ a;\n rslt +/ (abs_num a) +/ (direct_cal nl mid (num_of_int 0)) +/\n (direct_cal (mid + 1) nr (num_of_int 0)) \n;;\n\nlet rslt = direct_cal 0 (n-1) (num_of_int 0) in\nprint_endline (string_of_num \n (abs_num rslt) );;\n\n(* earlier dubug\nprintf \"%d %d\\n\" n !kmatch\n*)\n"}, {"source_code": "(**D. The Child and Sequence*)\n\nopen Scanf;;\nopen Num;;\nopen Printf;;\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x);;\n\nlet imatch = Array.create n (num_of_int 0);;\nlet kmatch = ref (Num.num_of_int 0);;\n\nfor i = 0 to n-1 do\n let ni = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) in\n imatch.(i) <- num_of_int ni; kmatch := (num_of_int ni) +/ !kmatch\ndone\n;;\n\n(*Remove the average*)\nlet av = div_num !kmatch (num_of_int n) in\nfor i = 0 to n - 1 do\n imatch.(i) <- imatch.(i) -/ av\ndone\n;;\n\n(*Array.iter (fun x -> print_int x; print_endline \"\") imatch;;*)\n\nlet sum_over i j =\n let total = ref (num_of_int 0) in\n for k = i to j do\n total := !total +/ imatch.(k)\n done; total\n;;\n\nlet rec direct_cal nl nr rslt = \n if nl = nr then\n rslt +/ !(sum_over nl nr)\n else\n let mid = (nl + nr) / 2 in\n let a = !(sum_over nl mid) in\n imatch.(mid) <- imatch.(mid) -/ a;\n imatch.(mid+1)<-imatch.(mid+1) +/ a;\n rslt +/ (abs_num a) +/ (direct_cal nl mid (num_of_int 0)) +/\n (direct_cal (mid + 1) nr (num_of_int 0)) \n;;\n\nlet rslt = direct_cal 0 (n-1) (num_of_int 0) in\nprint_endline (string_of_num \n (abs_num rslt) );;\n\n(* earlier dubug\nprintf \"%d %d\\n\" n !kmatch\n*)\n"}], "negative_code": [], "src_uid": "41ae8b0dee3b0f4e91bd06e4a0635492"} {"nl": {"description": "Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life \u00abinteresting graph and apples\u00bb. An undirected graph is called interesting, if each of its vertices belongs to one cycle only \u2014 a funny ring \u2014 and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too.She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1,\u2009y1),\u2009(x2,\u2009y2),\u2009...,\u2009(xn,\u2009yn), where xi\u2009\u2264\u2009yi, is lexicographically smaller than the set (u1,\u2009v1),\u2009(u2,\u2009v2),\u2009...,\u2009(un,\u2009vn), where ui\u2009\u2264\u2009vi, provided that the sequence of integers x1,\u2009y1,\u2009x2,\u2009y2,\u2009...,\u2009xn,\u2009yn is lexicographically smaller than the sequence u1,\u2009v1,\u2009u2,\u2009v2,\u2009...,\u2009un,\u2009vn. If you do not cope, Hexadecimal will eat you. ...eat you alive.", "input_spec": "The first line of the input data contains a pair of integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u200950, 0\u2009\u2264\u2009m\u2009\u2264\u20092500) \u2014 the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1\u2009\u2264\u2009xi, yi\u2009\u2264\u2009n) \u2014 the vertices that are already connected by edges. The initial graph may contain multiple edges and loops.", "output_spec": "In the first line output \u00abYES\u00bb or \u00abNO\u00bb: if it is possible or not to construct an interesting graph. If the answer is \u00abYES\u00bb, in the second line output k \u2014 the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero.", "sample_inputs": ["3 2\n1 2\n2 3"], "sample_outputs": ["YES\n1\n1 3"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet find djs x =\n let rec go x =\n if djs.(x) <> x then (\n djs.(x) <- djs.(djs.(x));\n go djs.(x)\n ) else\n x\n in go x\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let djs = Array.init n (fun x -> x) in\n let d = Array.make n 2 in\n let c = ref 0 in\n let rec go i =\n if i < m then (\n let x = read_int 0 - 1 in\n let y = read_int 0 - 1 in\n d.(x) <- d.(x)-1;\n d.(y) <- d.(y)-1;\n if d.(x) < 0 || d.(y) < 0 then (\n print_endline \"NO\";\n exit 0\n );\n let rx = find djs x in\n let ry = find djs y in\n if rx = ry then (\n incr c;\n if !c > 1 then (\n print_endline \"NO\";\n exit 0\n )\n ) else\n djs.(rx) <- ry;\n go (i+1)\n ) else if !c > 0 then\n print_endline (if n = m then \"YES\\n0\" else \"NO\")\n else (\n Printf.printf \"YES\\n%d\\n\" (n-m);\n for x = 0 to n-1 do\n let rx = find djs x in\n for y = x+1 to n-1 do\n if d.(x) > 0 && d.(y) > 0 then (\n let ry = find djs y in\n if rx <> ry then (\n Printf.printf \"%d %d\\n\" (x+1) (y+1);\n djs.(ry) <- rx;\n d.(x) <- d.(x)-1;\n d.(y) <- d.(y)-1\n )\n )\n done\n done;\n for x = 0 to n-1 do\n for j = 1 to d.(x) do\n Printf.printf \"%d \" (x+1)\n done\n done\n )\n in\n go 0\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet find djs x =\n let rec go x =\n if djs.(x) <> x then (\n djs.(x) <- djs.(djs.(x));\n go djs.(x)\n ) else\n x\n in go x\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let djs = Array.init n (fun x -> x) in\n let d = Array.make n 2 in\n let c = ref 0 in\n let rec go i =\n if i < m then (\n let x = read_int 0 - 1 in\n let y = read_int 0 - 1 in\n d.(x) <- d.(x)-1;\n d.(y) <- d.(y)-1;\n if d.(x) < 0 || d.(y) < 0 then (\n print_endline \"NO\";\n exit 0\n );\n let rx = find djs x in\n let ry = find djs y in\n if rx = ry then (\n incr c;\n if !c > 1 then (\n print_endline \"NO\";\n exit 0\n )\n );\n go (i+1)\n ) else if !c > 0 then\n print_endline (if n = m then \"YES\\n0\" else \"NO\")\n else (\n Printf.printf \"YES\\n%d\\n\" (n-m);\n for x = 0 to n-1 do\n let rx = find djs x in\n for y = x+1 to n-1 do\n if d.(x) > 0 && d.(y) > 0 then (\n let ry = find djs y in\n if rx <> ry then (\n Printf.printf \"%d %d\\n\" (x+1) (y+1);\n djs.(ry) <- rx;\n d.(x) <- d.(x)-1;\n d.(y) <- d.(y)-1\n )\n )\n done\n done;\n for x = 0 to n-1 do\n for j = 1 to d.(x) do\n Printf.printf \"%d \" (x+1)\n done\n done\n )\n in\n go 0\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet find djs x =\n let rec go x =\n if djs.(x) <> x then (\n djs.(x) <- djs.(djs.(x));\n go djs.(x)\n ) else\n x\n in go x\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let djs = Array.init n (fun x -> x) in\n let d = Array.make n 2 in\n let c = ref 0 in\n let rec go i =\n if i < m then (\n let x = read_int 0 - 1 in\n let y = read_int 0 - 1 in\n d.(x) <- d.(x)-1;\n d.(y) <- d.(y)-1;\n if d.(x) < 0 || d.(y) < 0 then (\n print_endline \"NO\";\n exit 0\n );\n let rx = find djs x in\n let ry = find djs y in\n if x = y then (\n incr c;\n if !c > 1 then (\n print_endline \"NO\";\n exit 0\n )\n );\n go (i+1)\n ) else if !c > 0 then\n print_endline (if n = m then \"YES\\n0\" else \"NO\")\n else (\n Printf.printf \"YES\\n%d\\n\" (n-m);\n for x = 0 to n-1 do\n let rx = find djs x in\n for y = x+1 to n-1 do\n if d.(x) > 0 && d.(y) > 0 then (\n let ry = find djs y in\n if rx <> ry then (\n Printf.printf \"%d %d\\n\" (x+1) (y+1);\n djs.(rx) <- ry;\n d.(x) <- d.(x)-1;\n d.(y) <- d.(y)-1\n )\n )\n done\n done;\n for x = 0 to n-1 do\n for j = 1 to d.(x) do\n Printf.printf \"%d \" (x+1)\n done\n done\n )\n in\n go 0\n"}], "src_uid": "bbcb051b08fa3d19a7cf285242d50451"} {"nl": {"description": "Given a sequence $$$a_1, a_2, \\ldots, a_n$$$, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every $$$2$$$ consecutive elements is even.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2,\\dots,a_n$$$ ($$$1\\leq a_i\\leq10^9$$$) \u2014 elements of the sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a single integer \u2014 the minimum number of elements to remove from the sequence such that the sum of every $$$2$$$ consecutive elements is even.", "sample_inputs": ["2\n\n5\n\n2 4 3 6 8\n\n6\n\n3 5 9 7 1 3"], "sample_outputs": ["1\n0"], "notes": "NoteIn the first test case, after removing $$$3$$$, the sequence becomes $$$[2,4,6,8]$$$. The pairs of consecutive elements are $$$\\{[2, 4], [4, 6], [6, 8]\\}$$$. Each consecutive pair has an even sum now. Hence, we only need to remove $$$1$$$ element to satisfy the condition asked.In the second test case, each consecutive pair already has an even sum so we need not remove any element."}, "positive_code": [{"source_code": "open String\n \nlet read_ints() = Array.map (int_of_string) (Array.of_list (Str.split (Str.regexp \" +\") (read_line())));;\nlet n = read_int();;\n\nfor i = 0 to (n - 1) do \n let size = read_int() and \n arr = read_ints() and \n cnt = ref 0 in (\n for j = 0 to (size - 1) do \n if arr.(j) mod 2 = 0\n then cnt := !cnt + 1\n done;\n print_int (min (size - !cnt) !cnt)\n );\n print_newline ()\ndone\n"}, {"source_code": "(* 2x-1+2y-1=2(x+y-1)\r\no + o = e, o+e=o\r\nwe either need all odd \r\nor all even\r\n\r\ne.g if we have odd anywhere in sequence,\r\nthe next number must be odd or it must be end of seq,\r\nif it end of seq , the numbers before must be odd\r\n*)\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x->x);;\r\nlet read_float () = Scanf.scanf \" %f\" (fun x->x);;\r\n\r\nlet rec read_seq = function\r\n| 0 -> 0\r\n| n ->\r\n let item = read_int () in\r\n if (item mod 2 ==0) then 1 + read_seq (n-1)\r\n else read_seq (n-1)\r\n;;\r\n \r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in\r\n let even_count = read_seq n in\r\n if (even_count<=n-even_count) then even_count\r\n else n-even_count\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> 0\r\n| n -> \r\n print_int (run_case ());\r\n print_newline ();\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t= read_int () in \r\niter_cases t;;"}], "negative_code": [{"source_code": "open String\nopen Printf \n \nlet read_ints() = Array.map (int_of_string) (Array.of_list (Str.split (Str.regexp \" +\") (read_line())));;\nlet n = read_int();;\n\nfor i = 0 to (n - 1) do \n let size = read_int() and \n arr = read_ints() and \n cnt = ref 0 in (\n for j = 0 to (size - 1) do \n if arr.(j) mod 2 = 0\n then cnt := !cnt + 1\n done;\n print_int (min (size - !cnt) !cnt)\n )\ndone\n"}, {"source_code": "(* 2x-1+2y-1=2(x+y-1)\r\no + o = e, o+e=o\r\nwe either need all odd \r\nor all even\r\n\r\ne.g if we have odd anywhere in sequence,\r\nthe next number must be odd or it must be end of seq,\r\nif it end of seq , the numbers before must be odd\r\n*)\r\n\r\nlet read_int () = Scanf.scanf \" %d\" (fun x->x);;\r\nlet read_float () = Scanf.scanf \" %f\" (fun x->x);;\r\n\r\nlet rec read_seq = function\r\n| 0 -> 0\r\n| n ->\r\n let item = read_int () in\r\n if (item mod 2 ==0) then 1 + read_seq (n-1)\r\n else read_seq (n-1)\r\n;;\r\n \r\nlet run_case = function\r\n| () -> \r\n let n = read_int () in\r\n let even_count = read_seq n in\r\n if (even_count<=n-even_count) then even_count\r\n else n-even_count\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0 -> 0\r\n| n -> \r\n print_int (run_case ());\r\n iter_cases (n-1)\r\n;;\r\n\r\nlet t= read_int () in \r\niter_cases t;;"}], "src_uid": "4b33db3950303b8993812cb265fa9819"} {"nl": {"description": "Allen is hosting a formal dinner party. $$$2n$$$ people come to the event in $$$n$$$ pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The $$$2n$$$ people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 100$$$), the number of pairs of people. The second line contains $$$2n$$$ integers $$$a_1, a_2, \\dots, a_{2n}$$$. For each $$$i$$$ with $$$1 \\le i \\le n$$$, $$$i$$$ appears exactly twice. If $$$a_j = a_k = i$$$, that means that the $$$j$$$-th and $$$k$$$-th people in the line form a couple.", "output_spec": "Output a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.", "sample_inputs": ["4\n1 1 2 3 3 2 4 4", "3\n1 1 2 2 3 3", "3\n3 1 2 3 1 2"], "sample_outputs": ["2", "0", "3"], "notes": "NoteIn the first sample case, we can transform $$$1 1 2 3 3 2 4 4 \\rightarrow 1 1 2 3 2 3 4 4 \\rightarrow 1 1 2 2 3 3 4 4$$$ in two steps. Note that the sequence $$$1 1 2 3 3 2 4 4 \\rightarrow 1 1 3 2 3 2 4 4 \\rightarrow 1 1 3 3 2 2 4 4$$$ also works in the same number of steps.The second sample case already satisfies the constraints; therefore we need $$$0$$$ swaps."}, "positive_code": [{"source_code": "(* Code Forces : Suit And Tie *)\n\nopen Scanf\nopen Printf\n\nlet n = scanf \"%d\" (fun n -> n)\n\nlet l = Array.to_list (Array.init (2*n) (fun i -> scanf \" %d\" (fun c -> c)))\n\nlet rec simpl l =\n match l with\n | [] -> []\n | c::c'::t ->\n if c = c' then\n simpl t\n else\n l\n\nlet redux l = List.rev (simpl (List.rev (simpl l)))\n\nlet rec swap x l out =\n match l with\n | [] -> List.rev out\n | c::(c'::t as l') ->\n if c' = x then\n List.rev (List.rev_append (c'::c::t) out)\n else\n swap x l' (c::out)\n\nlet print l = List.iter (fun c -> printf \"%d \" c) l; print_newline ()\n\nlet rec compute l out =\n match redux l with\n | [] -> out\n | c::l' ->\n (*print l;*)\n let l'' = swap c l' [] in\n compute (c::l'') (out+1)\n\nlet () =\n let out = compute l 0 in\n printf \"%d\\n\" out\n"}], "negative_code": [], "src_uid": "194bc63b192a4e24220b36984901fb3b"} {"nl": {"description": "We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t \u0422-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is \u0422-prime or not.", "input_spec": "The first line contains a single positive integer, n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1\u2009\u2264\u2009xi\u2009\u2264\u20091012). Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is advised to use the cin, cout streams or the %I64d specifier.", "output_spec": "Print n lines: the i-th line should contain \"YES\" (without the quotes), if number xi is \u0422-prime, and \"NO\" (without the quotes), if it isn't.", "sample_inputs": ["3\n4 5 6"], "sample_outputs": ["YES\nNO\nNO"], "notes": "NoteThe given test has three numbers. The first number 4 has exactly three divisors \u2014 1, 2 and 4, thus the answer for this number is \"YES\". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is \"NO\"."}, "positive_code": [{"source_code": "module I64 = struct\nlet ( / ) = Int64.div\nlet ( * ) = Int64.mul\nlet ( + ) = Int64.add\nlet ( - ) = Int64.sub\nlet ( mod ) = Int64.rem\nlet zero = Int64.zero\nlet one = Int64.one\nlet two = Int64.of_int 2\nend\n\nlet is_prime =\n let n = 1000000 in\n let a = Array.make (n + 1) true in\n let rec loop i =\n if i * i <= n\n then\n ((if a.(i)\n then\n let rec looper j =\n if j > n\n then\n ()\n else\n (Array.set a j false;\n looper (j + i))\n in looper (i * i)\n else\n ());\n loop (i + 1))\n else\n ()\n in loop 2;\n Array.set a 0 false;\n Array.set a 1 false;\n\n fun i -> a.(i)\n\nlet find_sqrt n =\n let open I64 in\n let r = Pervasives.sqrt (Int64.to_float n) in\n let rec loop (+) (<) approx =\n if approx * approx < n\n then\n loop (+) (<) (approx + one)\n else\n approx\n in \n let r = loop (-) (>) (loop (+) (<) (Int64.of_float r)) in\n if r * r = n\n then\n Some (Int64.to_int r)\n else\n None\n\nlet is_tprime n =\n match (find_sqrt n) with\n | Some r -> is_prime r\n | None -> false\n\nlet () = \n let length = Scanf.scanf \"%d \" (fun n -> n) in\n let rec loop i =\n if i < length\n then\n let number = Scanf.scanf \"%Ld \" (fun n -> n) in\n (if is_tprime number\n then\n Printf.printf \"YES\\n\"\n else\n Printf.printf \"NO\\n\");\n loop (i + 1)\n else\n ()\n in loop 0"}, {"source_code": "let split_words = Str.split (Str.regexp \" \")\n\nexception Break\n\nlet primes =\n let array = Array.make 1_000_001 true in\n array.(0) <- false;\n array.(1) <- false;\n begin try\n for i = 2 to Array.length array do\n if array.(i)\n then (\n if i * i >= Array.length array\n then (raise Break);\n for j = i to (Array.length array - 1) / i do\n array.(i * j) <- false\n done)\n done\n with\n | _ -> ()\n end;\n array\n;;\n\nlet is_prime n = primes.(Int64.to_int n)\n\nlet is_t_prime n =\n let sq = Int64.of_float (sqrt (Int64.to_float n)) in\n Int64.mul sq sq = n && is_prime sq\n;;\n\nlet () =\n ignore (input_line stdin);\n input_line stdin\n |> split_words\n |> List.map Int64.of_string\n |> List.iter (fun number ->\n if is_t_prime number\n then (print_endline \"YES\")\n else (print_endline \"NO\"))\n;;\n"}, {"source_code": "let sieve () =\n let nums = Array.make 1000001 true in\n nums.(0) <- false;\n nums.(1) <- false;\n for i = 2 to 1000000 do\n if nums.(i) then\n let rec walk j = \n\tif j > 1000000 then ()\n\telse begin\n\t nums.(j) <- false;\n\t walk (j + i) \n\tend in\n walk (i+i)\n done;\n nums\n\nlet main = \n let primes = sieve () in\n let n = Scanf.scanf \"%d\" (fun n -> n) in\n for i = 1 to n do\n let f = Scanf.scanf \" %f\" (fun f -> f) in\n let (ff, fi) = modf (sqrt f) in\n if ff > 0.000001 then \n Printf.printf \"NO\\n\"\n else \n Printf.printf \"%s\\n\" (if primes.(int_of_float fi) then \"YES\" else \"NO\")\n done;\n \n \n"}], "negative_code": [{"source_code": "module I64 = struct\nlet ( / ) = Int64.div\nlet ( * ) = Int64.mul\nlet ( + ) = Int64.add\nlet ( - ) = Int64.sub\nlet ( mod ) = Int64.rem\nlet zero = Int64.zero\nlet one = Int64.one\nlet two = Int64.of_int 2\nend\n\nlet is_prime =\n let n = 1000000 in\n let a = Array.make (n + 1) true in\n let rec loop i =\n if i * i <= n\n then\n if a.(i)\n then\n let rec looper j =\n if j > n\n then\n ()\n else\n (Array.set a j false;\n looper (j + i))\n in looper (i * i)\n else\n ()\n in loop 2;\n Array.set a 0 false;\n Array.set a 1 false;\n\n fun i -> a.(i)\n\nlet find_sqrt n =\n let open I64 in\n let r = Pervasives.sqrt (Int64.to_float n) in\n let rec loop (+) (<) approx =\n if approx * approx < n\n then\n loop (+) (<) (approx + one)\n else\n approx\n in \n let r = loop (-) (>) (loop (+) (<) (Int64.of_float r)) in\n if r * r = n\n then\n Some (Int64.to_int r)\n else\n None\n\nlet is_tprime n =\n match (find_sqrt n) with\n | Some r -> is_prime r\n | None -> false\n\nlet () = \n let length = Scanf.scanf \"%d \" (fun n -> n) in\n let rec loop i =\n if i < length\n then\n let number = Scanf.scanf \"%Ld \" (fun n -> n) in\n (if is_tprime number\n then\n Printf.printf \"YES\\n\"\n else\n Printf.printf \"NO\\n\");\n loop (i + 1)\n else\n ()\n in loop 0 "}], "src_uid": "6cebf9af5cfbb949f22e8b336bf07044"} {"nl": {"description": "Edo has got a collection of n refrigerator magnets!He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be positive integers.Edo figured out how he wants to place the magnets on the refrigerator. He introduced a system of coordinates on the plane, where each magnet is represented as a rectangle with sides parallel to the coordinate axes.Now he wants to remove no more than k magnets (he may choose to keep all of them) and attach all remaining magnets to the refrigerator door, and the area of \u200b\u200bthe door should be as small as possible. A magnet is considered to be attached to the refrigerator door if its center lies on the door or on its boundary. The relative positions of all the remaining magnets must correspond to the plan.Let us explain the last two sentences. Let's suppose we want to hang two magnets on the refrigerator. If the magnet in the plan has coordinates of the lower left corner (x1, y1) and the upper right corner (x2, y2), then its center is located at (, ) (may not be integers). By saying the relative position should correspond to the plan we mean that the only available operation is translation, i.e. the vector connecting the centers of two magnets in the original plan, must be equal to the vector connecting the centers of these two magnets on the refrigerator.The sides of the refrigerator door must also be parallel to coordinate axes.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 0\u2009\u2264\u2009k\u2009\u2264\u2009min(10,\u2009n\u2009-\u20091))\u00a0\u2014 the number of magnets that Edo has and the maximum number of magnets Edo may not place on the refrigerator. Next n lines describe the initial plan of placing magnets. Each line contains four integers x1,\u2009y1,\u2009x2,\u2009y2 (1\u2009\u2264\u2009x1\u2009<\u2009x2\u2009\u2264\u2009109, 1\u2009\u2264\u2009y1\u2009<\u2009y2\u2009\u2264\u2009109)\u00a0\u2014 the coordinates of the lower left and upper right corners of the current magnet. The magnets can partially overlap or even fully coincide.", "output_spec": "Print a single integer\u00a0\u2014 the minimum area of the door of refrigerator, which can be used to place at least n\u2009-\u2009k magnets, preserving the relative positions. ", "sample_inputs": ["3 1\n1 1 2 2\n2 2 3 3\n3 3 4 4", "4 1\n1 1 2 2\n1 9 2 10\n9 9 10 10\n9 1 10 2", "3 0\n1 1 2 2\n1 1 1000000000 1000000000\n1 3 8 12"], "sample_outputs": ["1", "64", "249999999000000001"], "notes": "NoteIn the first test sample it is optimal to remove either the first or the third magnet. If we remove the first magnet, the centers of two others will lie at points (2.5, 2.5) and (3.5, 3.5). Thus, it is enough to buy a fridge with door width 1 and door height 1, the area of the door also equals one, correspondingly.In the second test sample it doesn't matter which magnet to remove, the answer will not change \u2014 we need a fridge with door width 8 and door height 8.In the third sample you cannot remove anything as k\u2009=\u20090."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet ( ** ) a b = Int64.mul a b\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read4 () = bscanf Scanning.stdib \" %f %f %f %f \" (fun a b c d -> (a,b,c,d))\n \nlet () = \n let n = read_int () in\n let k = read_int () in\n let center = Array.make n (0.0, 0.0) in\n\n for i=0 to n-1 do\n let (x1,y1,x2,y2) = read4() in\n center.(i) <- ((x1+.x2)/.2.0, (y1+.y2)/.2.0)\n done;\n\n let x1 = Array.init n (fun i -> i) in\n let y1 = Array.copy x1 in\n\n Array.sort (fun i j -> compare (fst center.(i)) (fst center.(j))) x1;\n Array.sort (fun i j -> compare (snd center.(i)) (snd center.(j))) y1;\n let x2 = Array.init n (fun i -> x1.(n-1-i)) in\n let y2 = Array.init n (fun i -> y1.(n-1-i)) in \n\n (* partition k into four parts in all possible ways *)\n\n let c = Array.make 4 0 in\n\n let inset i s = List.exists (( = ) i) s in\n \n let rec score c =\n let rec buildused a j c used = if c=0 then used else\n\tif inset a.(j) used then (\n\t buildused a (j+1) c used\n\t) else (\n\t buildused a (j+1) (c-1) (a.(j)::used)\n\t)\n in\n let rec fu a used i = (* first unused *)\n if not (inset a.(i) used) then a.(i)\n else fu a used (i+1)\n in\n let u = buildused x1 0 c.(0) [] in\n let u = buildused y1 0 c.(1) u in\n let u = buildused x2 0 c.(2) u in\n let u = buildused y2 0 c.(3) u in\n let ind = [|fu x1 u 0; fu y1 u 0; fu x2 u 0; fu y2 u 0|] in\n let maxx = maxf 0 3 (fun i -> fst center.(ind.(i))) in\n let minx = minf 0 3 (fun i -> fst center.(ind.(i))) in\n let maxy = maxf 0 3 (fun i -> snd center.(ind.(i))) in \n let miny = minf 0 3 (fun i -> snd center.(ind.(i))) in \n let round z = if z=0.0 then 1L else Int64.of_float (ceil z) in\n (round (maxx -. minx)) ** (round (maxy -. miny))\n in\n \n let rec part4 i n = if i=3 then (\n c.(3) <- n;\n score c\n ) else (\n minf 0 n (fun v -> c.(i) <- v; part4 (i+1) (n-v))\n )\n in\n\n printf \"%Ld\\n\" (part4 0 k)\n"}], "negative_code": [], "src_uid": "a59bdb71c84434429798687d20da2a90"} {"nl": {"description": "Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: Its elements are in increasing order. That is an inequality ai\u2009<\u2009aj holds for any two indices i,\u2009j (i\u2009<\u2009j). For any two indices i and j (i\u2009<\u2009j), aj must not be divisible by ai. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with n elements.", "input_spec": "The input contains a single integer: n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "Output a line that contains n space-separated integers a1 a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009107), representing a possible Hungry sequence. Note, that each ai must not be greater than 10000000 (107) and less than 1. If there are multiple solutions you can output any one.", "sample_inputs": ["3", "5"], "sample_outputs": ["2 9 15", "11 14 20 27 31"], "notes": null}, "positive_code": [{"source_code": "let trim (line: string) =\n\t(* trim leading white space *)\n\tlet line = Str.replace_first (Str.regexp \"^[ \\t\\n\\r]+\") \"\" line in\n\t(* trim trailing white space *)\n\tlet line = Str.replace_first (Str.regexp \"[ \\t\\n\\r]+$\") \"\" line in\n\tline\n;;\n\n\nlet ints_of_string (line: string) = \n\tArray.of_list (List.map int_of_string (Str.split (Str.regexp \" \") (trim line)))\n;;\n\nlet solve (a: int array) =\n\tlet n = Array.length a in\n\tlet b = Array.create (1+n) 0 in\n\tb.(1) <- a.(0);\n\tfor i=2 to n do\n\t\tb.(i) <- b.(i-1) + a.(i-1)\n\tdone;\n\tlet sum i j = b.(j) - b.(i-1) in\n\t(*Printf.printf \"n = %d\\n\" n;\n\tfor i=0 to n do\n\t\tPrintf.printf \"%d \" b.(i)\n\tdone;\n*)\n\tlet best = ref 0 in\n\tfor i=1 to n do\n\t\tfor j=i to n do\n\t\t\tlet tmp = \n\t\t\t\tb.(i-1) + \n\t\t\t\t(j-i+1) - (b.(j) - b.(i-1)) +\n\t\t\t\tb.(n)-b.(j)\n\t\t\tin\n\t\t\tif tmp > !best then\n\t\t\t\tbest := !best + 1\n\t\tdone;\n\tdone;\n\tPrintf.printf \"%d\\n\" !best\n;;\n\n\n\nlet _ = \n\tlet n = int_of_string (read_line()) in\n\tfor i=n to n+n-1 do\n\t\tPrintf.printf \"%d \" i\n\tdone;\n\t\n\n\n\n\t\n"}, {"source_code": "(* Codeforces contest 327B - hungry seq *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet rec readlist n acc = match n with | 0 -> List.rev acc | _ -> readlist (n -1) (gr() :: acc);;\nlet rec readpairs n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readpairs\n\t\t\t\t(n -1)\n\t\t\t\t(\n\t\t\t\t\tlet a = gr() in\n\t\t\t\t\tlet b = gr() in\n\t\t\t\t\t(* let _ = Printf.printf \"a,b = %d %d\\n\" a b in *)\n\t\t\t\t\t(a, b) :: acc\n\t\t\t\t);;\nlet debug = false;;\n\nlet n = gr();; (* number of test data *)\n\nlet printseq n =\n\tfor i = n +5 to n + 4 + n do\n\t\t( print_int i; print_string \" \" )\n\tdone;;\n\nlet main() =\n\tprintseq n;;\n\nmain();;\n"}], "negative_code": [], "src_uid": "c047040426e736e9085395ed9666135f"} {"nl": {"description": "Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.You are given a string s consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.A substring of a string is a nonempty sequence of consecutive characters.For example if string s is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.", "input_spec": "The only line contains string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20093\u00b7105). The string s contains only digits from 0 to 9.", "output_spec": "Print integer a \u2014 the number of substrings of the string s that are divisible by 4. Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.", "sample_inputs": ["124", "04", "5810438174"], "sample_outputs": ["4", "3", "9"], "notes": null}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let c2i c = Char.code c - Char.code '0' in\n let res = ref 0L in\n for i = 1 to n - 1 do\n if (c2i s.[i - 1] * 10 + c2i s.[i]) mod 4 = 0\n then res := !res +| Int64.of_int i;\n done;\n for i = 0 to n - 1 do\n if c2i s.[i] mod 4 = 0\n then res := !res +| 1L;\n done;\n Printf.printf \"%Ld\\n\" !res\n"}], "negative_code": [], "src_uid": "c7d48d2c23ff33890a262447af5be660"} {"nl": {"description": "Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!", "input_spec": "The first line of the input contains one integer number $$$n$$$ ($$$2 \\le n \\le 100$$$) \u2014 the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$.", "output_spec": "Print one string of length $$$2n-2$$$ \u2014 the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any.", "sample_inputs": ["5\nba\na\nabab\na\naba\nbaba\nab\naba", "3\na\naa\naa\na", "2\na\nc"], "sample_outputs": ["SPPSPSPS", "PPSS", "PS"], "notes": "NoteThe only string which Ivan can guess in the first example is \"ababa\".The only string which Ivan can guess in the second example is \"aaa\". Answers \"SPSP\", \"SSPP\" and \"PSPS\" are also acceptable.In the third example Ivan can guess the string \"ac\" or the string \"ca\". The answer \"SP\" is also acceptable."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen = String.length\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nlet prefix s t =\n let f = ref true in\n repi 0 (String.length t-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if s.[j] <> t.[j] then f:=false\n ); !f\nlet suffix s t =\n let f = ref true in\n let d = String.length t-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if s.[String.length s-$1-$d+$j] <> t.[j] then f:=false\n ); !f\nlet () =\n let n = gi 0 in let n = i32 n in let m = 2*$n-$2 in\n let a = init m (fun _ -> scanf \" %s\" @@ id) in\n let len = make n [] in\n let unz = make n [] in\n iteri (fun i v ->\n len.(slen v) <- v :: len.(slen v);\n unz.(slen v) <- i :: unz.(slen v)\n ) a;\n let res = make m '_' in\n let p0,q0 = match len.(n-$1) with [p;q] -> p,q | _ -> fail 0 in\n let gen_str p q =\n p ^ (String.make 1 q.[n-$2])\n in\n let solve str =\n (* printf \"%s::\\n\" str; *)\n let f = ref true in\n repi_rev (n-$1) 1 (fun i ->\n let p,q = match len.(i) with [p;q] -> p,q | _ -> fail 0 in\n let u,v = match unz.(i) with [p;q] -> p,q | _ -> fail 0 in\n (* printf \" %s:%d; %s:%d\\n\" p u q v; *)\n if prefix str p && suffix str q then (\n res.(u) <- 'P';\n res.(v) <- 'S';\n ) else if suffix str p && prefix str q then (\n res.(u) <- 'S';\n res.(v) <- 'P';\n ) else f := false\n );\n if !f then (\n iter print_char res; exit 0\n )\n in\n solve (gen_str p0 q0);\n solve (gen_str q0 p0);\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen = String.length\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nlet prefix s t =\n String.(sub s 0 (length t)) = t\n (* let f = ref true in\n repi 0 (String.length t-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if s.[j] <> t.[j] then f:=false\n ); !f *)\nlet suffix s t =\n String.(sub s ((length s -$ 1) -$ (length t -$ 1)) (length t)) = t\n (* let f = ref true in\n let d = String.length t-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if s.[String.length s-$1-$d+$j] <> t.[j] then f:=false\n ); !f *)\nlet () =\n let n = gi 0 in let n = i32 n in let m = 2*$n-$2 in\n let a = init m (fun _ -> scanf \" %s\" @@ id) in\n let len = make n [] in\n let unz = make n [] in\n iteri (fun i v ->\n len.(slen v) <- v :: len.(slen v);\n unz.(slen v) <- i :: unz.(slen v)\n ) a;\n let res = make m '_' in\n let p0,q0 = match len.(n-$1) with [p;q] -> p,q | _ -> fail 0 in\n let gen_str p q =\n p ^ (String.make 1 q.[n-$2])\n in\n let solve str =\n (* printf \"%s::\\n\" str; *)\n let f = ref true in\n repi_rev (n-$1) 1 (fun i ->\n let p,q = match len.(i) with [p;q] -> p,q | _ -> fail 0 in\n let u,v = match unz.(i) with [p;q] -> p,q | _ -> fail 0 in\n (* printf \" %s:%d; %s:%d\\n\" p u q v; *)\n if prefix str p && suffix str q then (\n res.(u) <- 'P';\n res.(v) <- 'S';\n ) else if suffix str p && prefix str q then (\n res.(u) <- 'S';\n res.(v) <- 'P';\n ) else f := false\n );\n if !f then (\n iter print_char res; exit 0\n )\n in\n solve (gen_str p0 q0);\n solve (gen_str q0 p0);\n\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in\n let a = init (i32 @@ 2L*n-2L) (fun _ -> scanf \" %s\" @@ id) in\n let aa = init (i32 @@ 2L*n-2L) (fun i -> a.(i)) in\n sort (fun u v -> -compare (String.length u) (String.length v)) aa;\n let str = aa.(0) ^ (String.make 1 aa.(1).[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if aa.(0).[i] <> aa.(1).[i-$1] then ff := false\n );\n let res = make (i32 @@ 2L*n-2L) '_' in\n (* print_endline str; *)\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !f then (\n res.(i) <- 'P'\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- 'S'\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n iter (fun c -> printf \"%c\" c) res;\n exit 0\n )\n );\n (* let str = (String.make 1 a.(0).[0]) ^ a.(1) in *)\n let str = aa.(1) ^ (String.make 1 aa.(0).[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if aa.(1).[i] <> aa.(0).[i-$1] then ff := false\n );\n (* print_endline str; *)\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !f then (\n res.(i) <- 'P'\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- 'S'\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n iter (fun c -> printf \"%c\" c) res;\n exit 0\n )\n );\n raise Not_found\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet prefix s t =\n let f = ref true in\n repi 0 (String.length t-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if s.[j] <> t.[j] then f:=false\n ); !f\nlet suffix s t =\n let f = ref true in\n let d = String.length t-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if s.[String.length s-$1-$d+$j] <> t.[j] then f:=false\n ); !f\n\nlet () =\n let n = gi 0 in\n let a = init (i32 @@ 2L*n-2L) (fun _ -> scanf \" %s\" @@ id) in\n let aa = init (i32 @@ 2L*n-2L) (fun i -> a.(i),i) in\n sort (fun (u,i) (v,j) -> -compare (String.length u) (String.length v)) aa;\n let m = i32 @@ 2L*n -2L in\n (* print_array (fun (c,i) -> sprintf \"%s#%d\" c i) aa; *)\n let zip = make m 0 in\n let unzip = make (m) 0 in\n iteri (fun i (_,j) -> zip.(i) <- j; unzip.(j) <- i) aa;\n let a0,a1 = fst aa.(0),fst aa.(1) in\n let arr0 = a in\n let a = map (fun (v,i) -> v) aa in\n let res = make (i32 @@ 2L*n-2L) ('_',0) in\n (* print_array id a; *)\n\n\n let str = a0 ^ (String.make 1 a1.[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if a0.[i] <> a1.[i-$1] then ff := false\n );\n (* print_endline str; *)\n rep 0L (i64 m/2L-1L) (fun i ->\n let i = i32 @@ i * 2L in\n let u,v = a.(i),a.(i+$1) in\n (* printf \" %s %s\\n\" u v; *)\n let p,q,r,s = prefix str u,prefix str v,suffix str u,suffix str v in\n if p && s then (\n res.(i) <- ('P',i);\n res.(i+$1) <- ('S',i+$1);\n ) else if q && r then (\n res.(i) <- ('S',i);\n res.(i+$1) <- ('P',i+$1);\n ) else ff := false\n );\n if !ff then (\n let ress = make m 'x' in\n iter (fun (c,i) -> ress.(zip.(i)) <- c) res;\n iter (fun c -> printf \"%c\" c) ress;\n exit 0;\n );\n let a0,a1 = a1,a0 in\n let str = a0 ^ (String.make 1 a1.[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if a0.[i] <> a1.[i-$1] then ff := false\n );\n (* print_endline str; *)\n rep 0L (i64 m/2L) (fun i ->\n let i = i32 i in\n let u,v = a.(i),a.(i+$1) in\n let p,q,r,s = prefix str u,prefix str v,suffix str u,suffix str v in\n if p && s then (\n res.(i) <- ('P',i);\n res.(i+$1) <- ('S',i+$1);\n ) else if q && r then (\n res.(i) <- ('S',i);\n res.(i+$1) <- ('P',i+$1);\n ) else ff := false\n );\n if !ff then (\n let ress = make m 'x' in\n iter (fun (c,i) -> ress.(zip.(i)) <- c) res;\n iter (fun c -> printf \"%c\" c) ress;\n exit 0;\n );\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in\n let a = init (i32 @@ 2L*n-2L) (fun _ -> scanf \" %s\" @@ id) in\n let aa = init (i32 @@ 2L*n-2L) (fun i -> a.(i),i) in\n sort (fun (u,i) (v,j) -> -compare (String.length u) (String.length v)) aa;\n let m = i32 @@ 2L*n -2L in\n let zip = make m 0 in\n let unz = make (m) 0 in\n iteri (fun i (_,j) -> zip.(i) <- j; unz.(j) <- i) aa;\n let a0,a1 = fst aa.(0),fst aa.(1) in\n let arr0 = a in\n let a = map (fun (v,i) -> v) aa in\n let ffff = ref false in\n let res = make (i32 @@ 2L*n-2L) '_' in\n\n let str = a0 ^ (String.make 1 a1.[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if a0.[i] <> a1.[i-$1] then ff := false\n );\n (* print_endline str; *)\n let s,p = ref (i32 n-$1),ref (i32 n-$1) in\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !p > 0 && !f then (\n res.(i) <- 'P'; p:=!p-$1\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- 'S'; s := !s -$ 1\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n iter (fun c -> printf \"%c\" c) res;\n print_newline ();\n (* exit 0 *)\n ffff := true;\n )\n );\n if not !ffff then (\n (* let str = (String.make 1 a.(0).[0]) ^ a.(1) in *)\n let str = a1 ^ (String.make 1 a0.[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if a1.[i] <> a0.[i-$1] then ff := false\n );\n (* print_endline str; *)\n let s,p = ref (i32 n-$1),ref (i32 n-$1) in\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !p>0 && !f then (\n res.(i) <- 'P'\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- 'S'\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n iter (fun c -> printf \"%c\" c) res;\n (* exit 0 *)\n ffff := true;\n )\n );\n );\n (* raise Not_found *)\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet prefix s t =\n let f = ref true in\n repi 0 (String.length t-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if s.[j] <> t.[j] then f:=false\n ); !f\nlet suffix s t =\n let f = ref true in\n let d = String.length t-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if s.[String.length s-$1-$d+$j] <> t.[j] then f:=false\n ); !f\n\nlet () =\n let n = gi 0 in\n let a = init (i32 @@ 2L*n-2L) (fun _ -> scanf \" %s\" @@ id) in\n let aa = init (i32 @@ 2L*n-2L) (fun i -> a.(i),i) in\n sort (fun (u,i) (v,j) -> -compare (String.length u) (String.length v)) aa;\n let m = i32 @@ 2L*n -2L in\n (* print_array (fun (c,i) -> sprintf \"%s#%d\" c i) aa; *)\n let zip = make m 0 in\n let unzip = make (m) 0 in\n iteri (fun i (_,j) -> zip.(i) <- j; unzip.(j) <- i) aa;\n let a0,a1 = fst aa.(0),fst aa.(1) in\n let arr0 = a in\n let a = map (fun (v,i) -> v) aa in\n let res = make (i32 @@ 2L*n-2L) ('_',0) in\n (* print_array id a; *)\n\n\n let str = a0 ^ (String.make 1 a1.[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if a0.[i] <> a1.[i-$1] then ff := false\n );\n (* print_endline str; *)\n let ns,np = ref (i32 n-$1),ref (i32 n-$1) in\n rep 0L (i64 m/2L-1L) (fun i ->\n let i = i32 @@ i * 2L in\n let u,v = a.(i),a.(i+$1) in\n (* printf \" %s %s\\n\" u v; *)\n let p,q,r,s = prefix str u,prefix str v,suffix str u,suffix str v in\n (* if not p && r && q then (\n\n ) else if p && not q && then (\n\n ) else if not r && s then (\n\n ) else if r && not s then (\n\n ) else () *)\n if p && s then (\n res.(i) <- ('P',i);\n res.(i+$1) <- ('S',i+$1);\n ) else if q && r then (\n res.(i) <- ('S',i);\n res.(i+$1) <- ('P',i+$1);\n ) else ff := false\n );\n if !ff then (\n let ress = make m 'x' in\n iter (fun (c,i) -> ress.(zip.(i)) <- c) res;\n iter (fun c -> printf \"%c\" c) ress;\n exit 0;\n );\n let a0,a1 = a1,a0 in\n let str = a0 ^ (String.make 1 a1.[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if a0.[i] <> a1.[i-$1] then ff := false\n );\n (* print_endline str; *)\n let ns,np = ref (i32 n-$1),ref (i32 n-$1) in\n rep 0L (i64 m/2L) (fun i ->\n let i = i32 i in\n let u,v = a.(i),a.(i+$1) in\n let p,q,r,s = prefix str u,prefix str v,suffix str u,suffix str v in\n (* if not p && r && q then (\n\n ) else if p && not q && then (\n\n ) else if not r && s then (\n\n ) else if r && not s then (\n\n ) else () *)\n if p && s then (\n res.(i) <- ('P',i);\n res.(i+$1) <- ('S',i+$1);\n ) else if q && r then (\n res.(i) <- ('S',i);\n res.(i+$1) <- ('P',i+$1);\n ) else ff := false\n );\n if !ff then (\n let ress = make m 'x' in\n iter (fun (c,i) -> ress.(zip.(i)) <- c) res;\n iter (fun c -> printf \"%c\" c) ress;\n exit 0;\n );\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in\n let a = init (i32 @@ 2L*n-2L) (fun _ -> scanf \" %s\" @@ id) in\n let aa = init (i32 @@ 2L*n-2L) (fun i -> a.(i),i) in\n sort (fun (u,i) (v,j) -> -compare (String.length u) (String.length v)) aa;\n let m = i32 @@ 2L*n -2L in\n (* print_array (fun (c,i) -> sprintf \"%s#%d\" c i) aa; *)\n let zip = make m 0 in\n let unz = make (m) 0 in\n iteri (fun i (_,j) -> zip.(i) <- j; unz.(j) <- i) aa;\n let a0,a1 = fst aa.(0),fst aa.(1) in\n let arr0 = a in\n let a = map (fun (v,i) -> v) aa in\n let ffff = ref false in\n let res = make (i32 @@ 2L*n-2L) ('_',0) in\n\n let str = a0 ^ (String.make 1 a1.[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if a0.[i] <> a1.[i-$1] then ff := false\n );\n (* print_endline str; *)\n let s,p = ref (i32 n-$1),ref (i32 n-$1) in\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !p > 0 && !f then (\n res.(i) <- ('P',i); p:=!p-$1\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- ('S',i); s := !s -$ 1\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n let ress = make m 'x' in\n iter (fun (c,i) -> ress.(zip.(i)) <- c) res;\n iter (fun c -> printf \"%c\" c) ress;\n print_newline ();\n (* exit 0 *)\n ffff := true;\n )\n );\n if not !ffff then (\n (* let str = (String.make 1 a.(0).[0]) ^ a.(1) in *)\n let str = a1 ^ (String.make 1 a0.[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if a1.[i] <> a0.[i-$1] then ff := false\n );\n (* print_endline str; *)\n\n let s,p = ref (i32 n-$1),ref (i32 n-$1) in\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !p > 0 && !f then (\n res.(i) <- ('P',i); p:=!p-$1\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- ('S',i); s := !s -$ 1\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n let ress = make m 'x' in\n iter (fun (c,i) -> ress.(zip.(i)) <- c) res;\n iter (fun c -> printf \"%c\" c) ress;\n print_newline ();\n (* exit 0 *)\n ffff := true;\n )\n );\n );\n (* raise Not_found *)\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in\n let a = init (i32 @@ 2L*n-2L) (fun _ -> scanf \" %s\" @@ id) in\n let aa = init (i32 @@ 2L*n-2L) (fun i -> a.(i)) in\n sort (fun u v -> -compare (String.length u) (String.length v)) aa;\n let str = aa.(0) ^ (String.make 1 aa.(1).[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if aa.(0).[i] <> aa.(1).[i-$1] then ff := false\n );\n let res = make (i32 @@ 2L*n-2L) '_' in\n print_endline str;\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !f then (\n res.(i) <- 'P'\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- 'S'\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n iter (fun c -> printf \"%c\" c) res;\n exit 0\n )\n );\n (* let str = (String.make 1 a.(0).[0]) ^ a.(1) in *)\n let str = aa.(1) ^ (String.make 1 aa.(0).[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if aa.(1).[i] <> aa.(0).[i-$1] then ff := false\n );\n print_endline str;\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !f then (\n res.(i) <- 'P'\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- 'S'\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n iter (fun c -> printf \"%c\" c) res;\n exit 0\n )\n );\n raise Not_found\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in\n let a = init (i32 @@ 2L*n-2L) (fun _ -> scanf \" %s\" @@ id) in\n let aa = init (i32 @@ 2L*n-2L) (fun i -> a.(i)) in\n sort (fun u v -> -compare (String.length u) (String.length v)) aa;\n let str = aa.(0) ^ (String.make 1 aa.(1).[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if aa.(0).[i] <> aa.(1).[i-$1] then ff := false\n );\n let res = make (i32 @@ 2L*n-2L) '_' in\n (* print_endline str; *)\n let ffff = ref false in\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !f then (\n res.(i) <- 'P'\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- 'S'\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n iter (fun c -> printf \"%c\" c) res;\n print_newline ();\n (* exit 0 *)\n ffff := true;\n )\n );\n if not !ffff then (\n (* let str = (String.make 1 a.(0).[0]) ^ a.(1) in *)\n let str = aa.(1) ^ (String.make 1 aa.(0).[i32 n-$2]) in\n let ff = ref true in\n repi 1 (i32 n-$2) (fun i ->\n if aa.(1).[i] <> aa.(0).[i-$1] then ff := false\n );\n (* print_endline str; *)\n if !ff then (\n repi 0 (i32 @@ 2L*n-3L) (fun i ->\n let f = ref true in\n (* P *)\n (* printf \" %d\\n\" i; *)\n repi 0 (String.length a.(i)-$1) (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[j] a.(i).[j] (str.[j] = a.(i).[j]); *)\n if str.[j] <> a.(i).[j] then f:=false\n );\n if !f then (\n res.(i) <- 'P'\n ) else (\n let f = ref true in\n let d = String.length a.(i)-$1 in\n repi 0 d (fun j ->\n (* printf \" %d %d :: %c %c --> %b\\n\" i j str.[i32 n-$d+$j-$1] a.(i).[j] (str.[i32 n-$d+$j-$1] = a.(i).[j]); *)\n if str.[i32 n-$d+$j-$1] <> a.(i).[j] then f:=false\n );\n (* printf \" -> %b\\n\" !f; *)\n if !f then (\n res.(i) <- 'S'\n ) else ff := false\n )\n );\n if !ff then (\n (* print_array (String.make 1) res; *)\n iter (fun c -> printf \"%c\" c) res;\n (* exit 0 *)\n ffff := true;\n )\n );\n );\n (* raise Not_found *)\n\n\n\n\n\n\n\n\n\n\n\n"}], "src_uid": "ddbde202d00b928a858e9f4ff461e88c"} {"nl": {"description": "Amugae has a hotel consisting of $$$10$$$ rooms. The rooms are numbered from $$$0$$$ to $$$9$$$ from left to right.The hotel has two entrances \u2014 one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance.One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.", "input_spec": "The first line consists of an integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$), the number of events in Amugae's memory. The second line consists of a string of length $$$n$$$ describing the events in chronological order. Each character represents: 'L': A customer arrives from the left entrance. 'R': A customer arrives from the right entrance. '0', '1', ..., '9': The customer in room $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$ respectively) leaves. It is guaranteed that there is at least one empty room when a customer arrives, and there is a customer in the room $$$x$$$ when $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$) is given. Also, all the rooms are initially empty.", "output_spec": "In the only line, output the hotel room's assignment status, from room $$$0$$$ to room $$$9$$$. Represent an empty room as '0', and an occupied room as '1', without spaces.", "sample_inputs": ["8\nLLRL1RL1", "9\nL0L0LLRR9"], "sample_outputs": ["1010000011", "1100000010"], "notes": "NoteIn the first example, hotel room's assignment status after each action is as follows. First of all, all rooms are empty. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. L: one more customer from the left entrance. Assignment status is 1110000001. 1: the customer in room $$$1$$$ leaves. Assignment status is 1010000001. R: one more customer from the right entrance. Assignment status is 1010000011. L: one more customer from the left entrance. Assignment status is 1110000011. 1: the customer in room $$$1$$$ leaves. Assignment status is 1010000011. So after all, hotel room's final assignment status is 1010000011.In the second example, hotel room's assignment status after each action is as follows. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. 0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000 again. 0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. R: one more customer from the right entrance. Assignment status is 1100000011. 9: the customer in room $$$9$$$ leaves. Assignment status is 1100000010. So after all, hotel room's final assignment status is 1100000010."}, "positive_code": [{"source_code": "\nlet assign_left hotel =\n\tlet rec iter prev next =\n\t\tmatch next with\n\t\t| 0::res \t-> prev @ [1] @ res\n\t\t| 1::res \t-> iter (prev @ [1]) res\n\t\t| [] \t\t-> prev\n\t\t| _ \t\t-> failwith \"The Hotel is empty !\"\n\tin\n\titer [] hotel\n\n\nlet assign_right hotel =\n\tlet reverted = List.rev hotel in\n\tlet new_hotel = assign_left reverted in\n\tList.rev new_hotel\n\n\nlet leave i hotel =\t\n\tlet rec iter j prev next =\n\t\tmatch next with\n\t\t| 1::res when j = i -> prev @ [0] @ res\n\t\t| c::res -> iter (j+1) (prev @ [c]) res\n\t\t| _ -> failwith \"error\"\n\tin\n\titer 0 [] hotel\n\n\nlet handle client hotel =\n\tmatch client with\n\t| 'L' \t\t-> assign_left hotel\n\t| 'R' \t\t-> assign_right hotel\n\t| '0'..'9' \t-> leave (int_of_string (String.make 1 client)) hotel\n\t| _\t \t\t-> failwith \"Clients arrive from left or right only !\"\n\n\nlet rec pp l =\n\tmatch l with\n\t| [] -> () \n\t| i::tl -> print_int i; pp tl\n\n\nlet init n =\n\tlet rec iter i l =\n\t\tif i = n then l else iter (i+1) (0::l)\n\tin\n\titer 0 [] \n\nlet main =\n\tlet n = read_int () in\n\tlet s = read_line () in \n\tlet hotel = ref (init 10) in\n\tfor i=0 to (String.length s) - 1 do hotel := handle (s.[i]) !hotel done;\n\tpp !hotel\n\n\n\n"}], "negative_code": [{"source_code": "\nlet assign_left hotel =\n\tlet rec iter prev next =\n\t\tmatch next with\n\t\t| 0::res \t-> prev @ [1] @ res\n\t\t| 1::res \t-> iter (prev @ [1]) res\n\t\t| [] \t\t-> prev\n\t\t| _ \t\t-> failwith \"The Hotel is empty !\"\n\tin\n\titer [] hotel\n\n\nlet assign_right hotel =\n\tlet reverted = List.rev hotel in\n\tlet new_hotel = assign_left reverted in\n\tList.rev new_hotel\n\n\nlet leave i hotel =\t\n\tlet rec iter j prev next =\n\t\tmatch next with\n\t\t| 1::res when j = i -> prev @ [0] @ res\n\t\t| c::res -> iter (j+1) (prev @ [c]) res\n\t\t| _ -> failwith \"error\"\n\tin\n\titer 0 [] hotel\n\n\nlet handle client hotel =\n\tmatch client with\n\t| 'L' \t\t-> assign_left hotel\n\t| 'R' \t\t-> assign_right hotel\n\t| '0'..'9' \t-> leave (int_of_string (String.make 1 client)) hotel\n\t| _\t \t\t-> failwith \"Clients arrive from left or right only !\"\n\n\nlet rec pp l =\n\tmatch l with\n\t| [] -> () \n\t| i::tl -> print_int i; pp tl\n\n\nlet init n =\n\tlet rec iter i l =\n\t\tif i = n then l else iter (i+1) (0::l)\n\tin\n\titer 0 [] \n\nlet main =\n\tlet n = read_int () in\n\tlet s = read_line () in \n\tlet hotel = ref (init n) in\n\tfor i=0 to (String.length s) - 1 do hotel := handle (s.[i]) !hotel done;\n\tpp !hotel\n\n\n\n"}], "src_uid": "a6cbf01d72d607ca95fe16df4fb16693"} {"nl": {"description": "At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.Each class must present two couples to the ball. In Vasya's class, $$$a$$$ boys and $$$b$$$ girls wish to participate. But not all boys and not all girls are ready to dance in pairs.Formally, you know $$$k$$$ possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair.For example, if $$$a=3$$$, $$$b=4$$$, $$$k=4$$$ and the couples $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(3, 4)$$$ are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below): $$$(1, 3)$$$ and $$$(2, 2)$$$; $$$(3, 4)$$$ and $$$(1, 3)$$$; But the following combinations are not possible: $$$(1, 3)$$$ and $$$(1, 2)$$$\u00a0\u2014 the first boy enters two pairs; $$$(1, 2)$$$ and $$$(2, 2)$$$\u00a0\u2014 the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$a$$$, $$$b$$$ and $$$k$$$ ($$$1 \\le a, b, k \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains $$$k$$$ integers $$$a_1, a_2, \\ldots a_k$$$. ($$$1 \\le a_i \\le a$$$), where $$$a_i$$$ is the number of the boy in the pair with the number $$$i$$$. The third line of each test case contains $$$k$$$ integers $$$b_1, b_2, \\ldots b_k$$$. ($$$1 \\le b_i \\le b$$$), where $$$b_i$$$ is the number of the girl in the pair with the number $$$i$$$. It is guaranteed that the sums of $$$a$$$, $$$b$$$, and $$$k$$$ over all test cases do not exceed $$$2 \\cdot 10^5$$$. It is guaranteed that each pair is specified at most once in one test case.", "output_spec": "For each test case, on a separate line print one integer\u00a0\u2014 the number of ways to choose two pairs that match the condition above.", "sample_inputs": ["3\n3 4 4\n1 1 2 3\n2 3 2 4\n1 1 1\n1\n1\n2 2 4\n1 1 2 2\n1 2 1 2"], "sample_outputs": ["4\n0\n2"], "notes": "NoteIn the first test case, the following combinations of pairs fit: $$$(1, 2)$$$ and $$$(3, 4)$$$; $$$(1, 3)$$$ and $$$(2, 2)$$$; $$$(1, 3)$$$ and $$$(3, 4)$$$; $$$(2, 2)$$$ and $$$(3, 4)$$$. There is only one pair in the second test case.In the third test case, the following combinations of pairs fit: $$$(1, 1)$$$ and $$$(2, 2)$$$; $$$(1, 2)$$$ and $$$(2, 1)$$$. "}, "positive_code": [{"source_code": "let print_list a =\n let print_elem e =\n print_int e;\n print_string \" \"\n in List.iter print_elem a;\n print_newline ();;\n\nlet print_tuple_list a =\n let print_elem e =\n let a,b = e in\n Printf.printf \"(%d, %d) \" a b\n in List.iter print_elem a;\n print_newline ();;\n\nmodule MyInt = struct\n type t = int\n let compare a b = \n if a < b then\n -1\n else if a > b then\n 1\n else\n 0\nend\n\nmodule IntSet = Set.Make(MyInt)\n\n(* \nRepresent the possible pairings as a Bipartite Graph, with Boys on one side and Girls on the other.\nFor each edge (u,v), you can calculate the number of valid pairings by knowing the degrees of\nu and v in the graph.\n\nProcedure:\nSum of: for each edge u,v:\n b_degree = number of edges incident with u - 1\n g_degree = number of edges incident with v - 1\n We subtract 1 because one edge is shared (the edge being considered)\n\n all_other_edges = k-1\n number of possible pairs with u,v = all_other_edges - (b_degree+g_degree)\n\n return number of possible pairs\n \nThe answer is the above sum divided by 2. We divide by two because the above\nalgorithm considers the pairings a,b and b,a unique. But the problem does not.\nSo, by dividing by 2 we remove the \"symmetrical\"/\"mirror\" pairings. \n*)\n\n(* Record for easily getting a,b, and k *)\ntype constraints = {\n a: int;\n b: int;\n k: int;\n}\n\n(* Ripped straight out of the Stdlib because this is only available since 4.05 *)\n(* But codeforces is using 4.02.... *)\n(* You -can- use a method from Str to split with a regex, but that could be slow. *)\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n\n(* Helper for reading a,b, and k *)\nlet read_three_ints () =\n split_on_char ' ' (read_line ())\n |> List.map int_of_string\n |> fun list -> {\n a = List.nth list 0; \n b = List.nth list 1; \n k = List.nth list 2;\n }\n\n(* So thankful there are lots of Haskell answers on stack overflow *)\n(* Filters a list down to its unique elements *)\n(* This could be really slow.... *)\n(* let rec uniq l =\n match l with\n | [] -> []\n | h :: tl -> h :: uniq (List.filter (fun e -> e != h) tl);; *)\n\n(* Lets use a set instead *)\nlet uniq l =\n IntSet.of_list l |> IntSet.elements\n\n(* Creates a simple array of pairs where each k is paired with how many times it appears *)\nlet init_assoc keys size =\n let assoc = Array.make size (0,0) in\n let create_tuple k =\n Array.set assoc (k-1) (k, 0)\n in List.iter create_tuple keys;\n assoc;;\n\n(* Increments the 2nd element of the pair at index k-1 *)\nlet update k assoc =\n let new_value = \n match Array.get assoc (k-1) with\n | (k, v) -> (k, v+1)\n in Array.set assoc (k-1) new_value;;\n\n(* \nThe dream:\nl => [1; 1; 1; 2; 3; 3;]\nreturns = [(1, 3); (2, 1); (3, 2)]\n*)\nlet compute_vertex_degree keys size =\n let assoc = init_assoc keys size in\n let increment k =\n update k assoc\n in List.iter increment keys;\n assoc;;\n\nlet read_int_list () =\n split_on_char ' ' (read_line ())\n |> List.map int_of_string\n\nlet iter f n =\n for i = 1 to n do\n f n\n done;;\n\nlet fetch_degree degree_array node =\n let _, degree = degree_array.(node-1) in\n degree\n\nlet sum list =\n List.fold_left ( Int64.add ) 0L list\n\n\nlet halve n =\n Int64.div n 2L\n\nlet lookup_edge n edges =\n Array.get edges (n-1)\n\nlet count_pairings edges b_degree g_degree k =\n let count_for_edge e =\n let b, g = e in\n let b_incident = (fetch_degree b_degree b) - 1 in\n let g_incident = (fetch_degree g_degree g) - 1 in\n (k-1) - (b_incident + g_incident)\n in List.map count_for_edge edges\n |> List.map Int64.of_int\n |> sum \n |> halve;;\n\n\nlet num_cases = read_int () in\nlet process_test test_number = \n (* Read in all the stuff *)\n let constraints = read_three_ints () in\n let bs = read_int_list () in\n let gs = read_int_list () in\n (* Create the edges for looking up edge degrees *)\n let edges = List.combine bs gs in\n (* Compute the degrees *)\n let b_degree = compute_vertex_degree bs constraints.a in\n let g_degree = compute_vertex_degree gs constraints.b in\n (* Compute the number *)\n Printf.printf \"%Ld\\n\" (count_pairings edges b_degree g_degree constraints.k)\nin iter process_test num_cases\n"}], "negative_code": [{"source_code": "let print_list a =\n let print_elem e =\n print_int e;\n print_string \" \"\n in List.iter print_elem a;\n print_newline ();;\n\nlet print_tuple_list a =\n let print_elem e =\n let a,b = e in\n Printf.printf \"(%d, %d) \" a b\n in List.iter print_elem a;\n print_newline ();;\n\nmodule MyInt = struct\n type t = int64\n let compare a b = \n if a < b then\n -1\n else if a > b then\n 1\n else\n 0\nend\n\nmodule IntSet = Set.Make(MyInt)\n\n(* \nRepresent the possible pairings as a Bipartite Graph, with Boys on one side and Girls on the other.\nFor each edge (u,v), you can calculate the number of valid pairings by knowing the degrees of\nu and v in the graph.\n\nProcedure:\nSum of: for each edge u,v:\n b_degree = number of edges incident with u - 1\n g_degree = number of edges incident with v - 1\n We subtract 1 because one edge is shared (the edge being considered)\n\n all_other_edges = k-1\n number of possible pairs with u,v = all_other_edges - (b_degree+g_degree)\n\n return number of possible pairs\n \nThe answer is the above sum divided by 2. We divide by two because the above\nalgorithm considers the pairings a,b and b,a unique. But the problem does not.\nSo, by dividing by 2 we remove the \"symmetrical\"/\"mirror\" pairings. \n*)\n\n(* Record for easily getting a,b, and k *)\ntype constraints = {\n a: int;\n b: int;\n k: int;\n}\n\n(* Ripped straight out of the Stdlib because this is only available since 4.05 *)\n(* But codeforces is using 4.02.... *)\n(* You -can- use a method from Str to split with a regex, but that could be slow. *)\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n\n(* Helper for reading a,b, and k *)\nlet read_three_ints () =\n split_on_char ' ' (read_line ())\n |> List.map int_of_string\n |> fun list -> {\n a = List.nth list 0; \n b = List.nth list 1; \n k = List.nth list 2;\n }\n\n(* So thankful there are lots of Haskell answers on stack overflow *)\n(* Filters a list down to its unique elements *)\n(* This could be really slow.... *)\n(* let rec uniq l =\n match l with\n | [] -> []\n | h :: tl -> h :: uniq (List.filter (fun e -> e != h) tl);; *)\n\n(* Lets use a set instead *)\nlet uniq l =\n IntSet.of_list l |> IntSet.elements\n\n(* Creates a simple array of pairs where each k is paired with how many times it appears *)\nlet init_assoc keys size =\n let assoc = Array.make size (0,0) in\n let create_tuple k =\n Array.set assoc (k-1) (k, 0)\n in List.iter create_tuple keys;\n assoc;;\n\n(* Increments the 2nd element of the pair at index k-1 *)\nlet update k assoc =\n let new_value = \n match Array.get assoc (k-1) with\n | (k, v) -> (k, v+1)\n in Array.set assoc (k-1) new_value;;\n\n(* \nThe dream:\nl => [1; 1; 1; 2; 3; 3;]\nreturns = [(1, 3); (2, 1); (3, 2)]\n*)\nlet compute_vertex_degree l size =\n let keys = l in\n let assoc = init_assoc keys size in\n let increment k =\n update k assoc\n in List.iter increment keys;\n assoc;;\n\nlet read_int_list () =\n split_on_char ' ' (read_line ())\n |> List.map int_of_string\n\nlet iter f n =\n for i = 1 to n do\n f n\n done;;\n\nlet fetch_degree degree_array node =\n let _, degree = degree_array.(node-1) in\n degree\n\nlet sum list =\n List.fold_left ( + ) 0 list\n\nlet halve n =\n n / 2\n\nlet lookup_edge n edges =\n Array.get edges (n-1)\n\nlet count_pairings edges b_degree g_degree k =\n let count_for_edge e =\n let b, g = e in\n let b_incident = (fetch_degree b_degree b) - 1 in\n let g_incident = (fetch_degree g_degree g) - 1 in\n (k-1) - (b_incident + g_incident)\n in List.map count_for_edge edges |> sum |> halve;;\n\n\nlet num_cases = read_int () in\nlet process_test test_number = \n (* Read in all the stuff *)\n let constraints = read_three_ints () in\n let bs = read_int_list () in\n let gs = read_int_list () in\n (* Create the edges for looking up edge degrees *)\n let edges = List.combine bs gs in\n (* Compute the degrees *)\n let b_degree = compute_vertex_degree bs constraints.a in\n let g_degree = compute_vertex_degree gs constraints.b in\n (* Compute the number *)\n Printf.printf \"%d\\n\" (count_pairings edges b_degree g_degree constraints.k)\nin iter process_test num_cases\n"}, {"source_code": "let print_list a =\n let print_elem e =\n print_int e;\n print_string \" \"\n in List.iter print_elem a;\n print_newline ();;\n\nlet print_tuple_list a =\n let print_elem e =\n let a,b = e in\n Printf.printf \"(%d, %d) \" a b\n in List.iter print_elem a;\n print_newline ();;\n\nmodule MyInt = struct\n type t = int\n let compare a b = \n if a < b then\n -1\n else if a > b then\n 1\n else\n 0\nend\n\nmodule IntSet = Set.Make(MyInt)\n\n(* \nRepresent the possible pairings as a Bipartite Graph, with Boys on one side and Girls on the other.\nFor each edge (u,v), you can calculate the number of valid pairings by knowing the degrees of\nu and v in the graph.\n\nProcedure:\nSum of: for each edge u,v:\n b_degree = number of edges incident with u - 1\n g_degree = number of edges incident with v - 1\n We subtract 1 because one edge is shared (the edge being considered)\n\n all_other_edges = k-1\n number of possible pairs with u,v = all_other_edges - (b_degree+g_degree)\n\n return number of possible pairs\n \nThe answer is the above sum divided by 2. We divide by two because the above\nalgorithm considers the pairings a,b and b,a unique. But the problem does not.\nSo, by dividing by 2 we remove the \"symmetrical\"/\"mirror\" pairings. \n*)\n\n(* Record for easily getting a,b, and k *)\ntype constraints = {\n a: int;\n b: int;\n k: int;\n}\n\n(* Ripped straight out of the Stdlib because this is only available since 4.05 *)\n(* But codeforces is using 4.02.... *)\n(* You -can- use a method from Str to split with a regex, but that could be slow. *)\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n\n(* Helper for reading a,b, and k *)\nlet read_three_ints () =\n split_on_char ' ' (read_line ())\n |> List.map int_of_string\n |> fun list -> {\n a = List.nth list 0; \n b = List.nth list 1; \n k = List.nth list 2;\n }\n\n(* So thankful there are lots of Haskell answers on stack overflow *)\n(* Filters a list down to its unique elements *)\n(* This could be really slow.... *)\n(* let rec uniq l =\n match l with\n | [] -> []\n | h :: tl -> h :: uniq (List.filter (fun e -> e != h) tl);; *)\n\n(* Lets use a set instead *)\nlet uniq l =\n IntSet.of_list l |> IntSet.elements\n\n(* Creates a simple array of pairs where each k is paired with how many times it appears *)\nlet init_assoc keys size =\n let assoc = Array.make size (0,0) in\n let create_tuple k =\n Array.set assoc (k-1) (k, 0)\n in List.iter create_tuple keys;\n assoc;;\n\n(* Increments the 2nd element of the pair at index k-1 *)\nlet update k assoc =\n let new_value = \n match Array.get assoc (k-1) with\n | (k, v) -> (k, v+1)\n in Array.set assoc (k-1) new_value;;\n\n(* \nThe dream:\nl => [1; 1; 1; 2; 3; 3;]\nreturns = [(1, 3); (2, 1); (3, 2)]\n*)\nlet compute_vertex_degree l size =\n let keys = l in\n let assoc = init_assoc keys size in\n let increment k =\n update k assoc\n in List.iter increment keys;\n assoc;;\n\nlet read_int_list () =\n split_on_char ' ' (read_line ())\n |> List.map int_of_string\n\nlet iter f n =\n for i = 1 to n do\n f n\n done;;\n\nlet fetch_degree degree_array node =\n let _, degree = degree_array.(node-1) in\n degree\n\nlet sum list =\n List.fold_left ( + ) 0 list\n\nlet halve n =\n n / 2\n\nlet lookup_edge n edges =\n Array.get edges (n-1)\n\nlet count_pairings edges b_degree g_degree k =\n let count_for_edge e =\n let b, g = e in\n let b_incident = (fetch_degree b_degree b) - 1 in\n let g_incident = (fetch_degree g_degree g) - 1 in\n (k-1) - (b_incident + g_incident)\n in List.map count_for_edge edges |> sum |> halve;;\n\n\nlet num_cases = read_int () in\nlet process_test test_number = \n (* Read in all the stuff *)\n let constraints = read_three_ints () in\n let bs = read_int_list () in\n let gs = read_int_list () in\n (* Create the edges for looking up edge degrees *)\n let edges = List.combine bs gs in\n (* Compute the degrees *)\n let b_degree = compute_vertex_degree bs constraints.a in\n let g_degree = compute_vertex_degree gs constraints.b in\n (* Compute the number *)\n Printf.printf \"%d\\n\" (count_pairings edges b_degree g_degree constraints.k)\nin iter process_test num_cases\n"}], "src_uid": "14ce451a31c0dbc2b2f4e04a939b199d"} {"nl": {"description": "Maksim has $$$n$$$ objects and $$$m$$$ boxes, each box has size exactly $$$k$$$. Objects are numbered from $$$1$$$ to $$$n$$$ in order from left to right, the size of the $$$i$$$-th object is $$$a_i$$$.Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the $$$i$$$-th object fits in the current box (the remaining size of the box is greater than or equal to $$$a_i$$$), he puts it in the box, and the remaining size of the box decreases by $$$a_i$$$. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has. Your task is to say the maximum number of objects Maksim can pack in boxes he has.Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).", "input_spec": "The first line of the input contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \\le n, m \\le 2 \\cdot 10^5$$$, $$$1 \\le k \\le 10^9$$$) \u2014 the number of objects, the number of boxes and the size of each box. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le k$$$), where $$$a_i$$$ is the size of the $$$i$$$-th object.", "output_spec": "Print the maximum number of objects Maksim can pack using the algorithm described in the problem statement.", "sample_inputs": ["5 2 6\n5 2 1 4 2", "5 1 4\n4 2 3 4 1", "5 3 3\n1 2 3 1 1"], "sample_outputs": ["4", "1", "5"], "notes": "NoteIn the first example Maksim can pack only $$$4$$$ objects. Firstly, he tries to pack all the $$$5$$$ objects. Distribution of objects will be $$$[5], [2, 1]$$$. Maxim cannot pack the next object in the second box and he has no more empty boxes at all. Next he will throw out the first object and the objects distribution will be $$$[2, 1], [4, 2]$$$. So the answer is $$$4$$$.In the second example it is obvious that Maksim cannot pack all the objects starting from first, second, third and fourth (in all these cases the distribution of objects is $$$[4]$$$), but he can pack the last object ($$$[1]$$$).In the third example Maksim can pack all the objects he has. The distribution will be $$$[1, 2], [3], [1, 1]$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet () =\n\tlet n,m,k = get_3_i64 0 in\n\tlet a = input_i64_array n |> Array.to_list |> List.rev |> Array.of_list\n\tin\n\tlet cur = ref 0L in\n\tlet boxes = ref 1L in\n\tlet res = ref 0L in\n\trepi 0 (i32 @@ n-1L) (fun i ->\n\t\tlet v = a.(i) in\n\t\t(* printf \"%d %Ld: %Ld %Ld %Ld\\n\" i v !cur !boxes !res; *)\n\t\tif v + !cur <= k then (cur += v; res += 1L; `Ok)\n\t\telse (\n\t\t\tboxes += 1L; cur := v;\n\t\t\tif !boxes > m then (\n\t\t\t\t`Break\n\t\t\t) else (\n\t\t\t\tres += 1L; `Ok\n\t\t\t)\n\t\t)\n\t);\n\t!res |> printf \"%Ld\\n\"\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "869f8763211a7771ecd73d56b5c34479"} {"nl": {"description": "Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.Pavel has a plan: a permutation p and a sequence b1,\u2009b2,\u2009...,\u2009bn, consisting of zeros and ones. Each second Pavel move skewer on position i to position pi, and if bi equals 1 then he reverses it. So he hope that every skewer will visit every position in both directions.Unfortunately, not every pair of permutation p and sequence b suits Pavel. What is the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements? Note that after changing the permutation should remain a permutation as well.There is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation p and a sequence b suit him if there is an integer k (k\u2009\u2265\u20092n), so that after k seconds each skewer visits each of the 2n placements.It can be shown that some suitable pair of permutation p and sequence b exists for any n.", "input_spec": "The first line contain the integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the number of skewers. The second line contains a sequence of integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n)\u00a0\u2014 the permutation, according to which Pavel wants to move the skewers. The third line contains a sequence b1,\u2009b2,\u2009...,\u2009bn consisting of zeros and ones, according to which Pavel wants to reverse the skewers.", "output_spec": "Print single integer\u00a0\u2014 the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements.", "sample_inputs": ["4\n4 3 2 1\n0 1 1 1", "3\n2 3 1\n0 0 0"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first example Pavel can change the permutation to 4,\u20093,\u20091,\u20092.In the second example Pavel can change any element of b to 1."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let p = Array.make n 0 in\n let b = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n p.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1;\n done;\n for i = 0 to n - 1 do\n b.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n done;\n in\n (*let p' = Array.make (2 * n) 0 in\n let _ =\n for i = 0 to n - 1 do\n if b.(p.(i)) = 0 then (\n\tp'.(i) <- p.(i);\n\tp'.(i + n) <- p.(i) + n;\n ) else (\n\tp'.(i) <- p.(i) + n;\n\tp'.(i + n) <- p.(i);\n )\n done;\n in\n let p = p' in*)\n let used = Array.make n false in\n let rec dfs i =\n if not used.(i) then (\n used.(i) <- true;\n dfs p.(i)\n )\n in\n let res = ref 0 in\n let c = ref 0 in\n let cb = ref 0 in\n for i = 0 to n - 1 do\n if not used.(i) then (\n\tdfs i;\n\tincr c;\n )\n done;\n for i = 0 to n - 1 do\n cb := !cb + b.(i);\n done;\n if !cb mod 2 = 0\n then incr res;\n if !c > 1\n then res := !res + !c;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [], "src_uid": "1b2a2c8afcaf16b4055002a9511c6f23"} {"nl": {"description": "Polycarpus just has been out of luck lately! As soon as he found a job in the \"Binary Cat\" cafe, the club got burgled. All ice-cream was stolen.On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character \"+\" in his notes. Similarly, each time a visitor left the club, Polycarpus put character \"-\" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.", "input_spec": "The only line of the input contains a sequence of characters \"+\" and \"-\", the characters are written one after another without any separators. The characters are written in the order, in which the corresponding events occurred. The given sequence has length from 1 to 300 characters, inclusive.", "output_spec": "Print the sought minimum number of people", "sample_inputs": ["+-+-+", "---"], "sample_outputs": ["1", "3"], "notes": null}, "positive_code": [{"source_code": "let tail s = \n (String.sub s 1 ((String.length s) - 1))\nin\n\nlet minmax record =\n let rec helper record curr (cur_min, cur_max) =\n if record = \"\" then (cur_min, cur_max)\n else\n let curr =\n match record.[0] with\n | '+' -> curr + 1\n | '-' -> curr - 1\n | _ -> -1000\n in\n let cur_min = min cur_min curr \n and cur_max = max cur_max curr\n in helper (tail record) curr (cur_min, cur_max)\n in helper record 0 (0, 0)\nin\n\nlet record = Scanf.scanf \" %s\" (fun x -> x) in\nlet a, b = minmax record in\nPrintf.printf \"%d\\n\" (b - a)\n\n"}], "negative_code": [], "src_uid": "a9cd99d74418b5f227b358a910496b02"} {"nl": {"description": "You have unweighted tree of $$$n$$$ vertices. You have to assign a positive weight to each edge so that the following condition would hold: For every two different leaves $$$v_{1}$$$ and $$$v_{2}$$$ of this tree, bitwise XOR of weights of all edges on the simple path between $$$v_{1}$$$ and $$$v_{2}$$$ has to be equal to $$$0$$$. Note that you can put very large positive integers (like $$$10^{(10^{10})}$$$).It's guaranteed that such assignment always exists under given constraints. Now let's define $$$f$$$ as the number of distinct weights in assignment. In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is $$$0$$$. $$$f$$$ value is $$$2$$$ here, because there are $$$2$$$ distinct edge weights($$$4$$$ and $$$5$$$). In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex $$$1$$$ and vertex $$$6$$$ ($$$3, 4, 5, 4$$$) is not $$$0$$$. What are the minimum and the maximum possible values of $$$f$$$ for the given tree? Find and print both.", "input_spec": "The first line contains integer $$$n$$$ ($$$3 \\le n \\le 10^{5}$$$)\u00a0\u2014 the number of vertices in given tree. The $$$i$$$-th of the next $$$n-1$$$ lines contains two integers $$$a_{i}$$$ and $$$b_{i}$$$ ($$$1 \\le a_{i} \\lt b_{i} \\le n$$$)\u00a0\u2014 it means there is an edge between $$$a_{i}$$$ and $$$b_{i}$$$. It is guaranteed that given graph forms tree of $$$n$$$ vertices.", "output_spec": "Print two integers\u00a0\u2014 the minimum and maximum possible value of $$$f$$$ can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.", "sample_inputs": ["6\n1 3\n2 3\n3 4\n4 5\n5 6", "6\n1 3\n2 3\n3 4\n4 5\n4 6", "7\n1 2\n2 7\n3 4\n4 7\n5 6\n6 7"], "sample_outputs": ["1 4", "3 3", "1 6"], "notes": "NoteIn the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. In the second example, possible assignments for each minimum and maximum are described in picture below. The $$$f$$$ value of valid assignment of this tree is always $$$3$$$. In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. "}, "positive_code": [{"source_code": "(* Solved at at 12:12, 7 minutes late *)\n\nopen Printf\nopen Scanf\n\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let tree = Array.make n [] in\n\n let addedge i j =\n tree.(i) <- j::tree.(i);\n tree.(j) <- i::tree.(j)\n in\n\n for xx=0 to n-2 do\n let i = -1 + read_int() in\n let j = -1 + read_int() in\n addedge i j\n done;\n\n let is_leaf i = match tree.(i) with [x] -> true | _ -> false in\n\n let rec find_root i =\n if not (is_leaf i) then i else find_root (i+1)\n in\n\n let root = find_root 0 in\n\n let depth = Array.make n 0 in\n\n let rec dfs1 p i d =\n depth.(i) <- d;\n List.iter (fun j -> if j <> p then dfs1 i j (d+1)) tree.(i)\n in\n\n dfs1 (-1) root 0;\n\n let even = exists 0 (n-1) (fun i -> is_leaf i && depth.(i) mod 2 = 0) in\n let odd = exists 0 (n-1) (fun i -> is_leaf i && depth.(i) mod 2 = 1) in\n\n let mincount = if odd && even then 3 else 1 in\n\n let mark = Array.make n 0 in \n \n let rec dfs2 p i = (* i is non-leaf *)\n let first = ref true in\n List.iter (fun j -> if j <> p then (\n if is_leaf j then (\n\tif !first then (\n\t mark.(j) <- 1;\n\t first := false\n\t)\n ) else (\n\tmark.(j) <- 1;\n\tdfs2 i j\n )\n )) tree.(i)\n in\n\n dfs2 (-1) root;\n\n let maxcount = sum 0 (n-1) (fun i -> mark.(i)) in\n\n printf \"%d %d\\n\" mincount maxcount\n\n\n\n \n"}], "negative_code": [], "src_uid": "e65b974a85067500f20b316275dc5821"} {"nl": {"description": "Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1\u2009\u2264\u2009x\u2009\u2264\u2009n the maximum strength among all groups of size x.", "input_spec": "The first line of input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u2009\u00d7\u2009105), the number of bears. The second line contains n integers separated by space, a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), heights of bears.", "output_spec": "Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.", "sample_inputs": ["10\n1 2 3 4 5 4 3 2 1 6"], "sample_outputs": ["6 4 4 3 3 2 2 1 1 1"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n(* Bears !*)\n\n(* Size-keeping union find: the root knows how big the group is *)\nlet rec find a s i =\n if a.(i) = i then (i, s.(i))\n else let (i',_) as p = find a s a.(i) in (a.(i) <- i'; p)\n\nlet rec union a s i j =\n let (i',si) = find a s i in\n let (j',sj) = find a s j in\n if i' = j' then (i', si)\n else (a.(i') <- j'; s.(j') <- si+sj; (j', si+sj))\n\nlet _ =\n let n = read_int () in\n let a = Array.init n (fun _ -> read_int ()) in\n let present = Array.make n false in\n let inv = Array.init n (fun i -> (a.(i),i)) in\n let u = Array.init n (fun i -> i) in\n let s = Array.make n 1 in\n let answ = Array.make n 0 in\n Array.sort compare inv;\n (* Add bears in strength order. We get an info \"all groups of size < i have strength > s\" *)\n for k = n-1 downto 0 do\n let (str,i) = inv.(k) in\n present.(i) <- true;\n if (i > 0 && present.(i-1)) then ignore (union u s (i-1) i);\n if (i+1 < n && present.(i+1)) then ignore (union u s i (i+1));\n let (_,s) = find u s i in\n(* Printf.eprintf \"Adding size %d strength %d\\n\" s str; *)\n answ.(s-1) <- max answ.(s-1) str\n done;\n (* Now update asnw lazily *)\n for i = n-2 downto 0 do\n answ.(i) <- max answ.(i) answ.(i+1);\n done;\n for i = 0 to n-1 do\n Printf.printf \"%d%c\" answ.(i) (if i = n-1 then '\\n' else ' ')\n done\n"}], "negative_code": [], "src_uid": "5cf25cd4a02ce8020258115639c0ee64"} {"nl": {"description": "Polycarp has a string $$$s$$$. Polycarp performs the following actions until the string $$$s$$$ is empty ($$$t$$$ is initially an empty string): he adds to the right to the string $$$t$$$ the string $$$s$$$, i.e. he does $$$t = t + s$$$, where $$$t + s$$$ is a concatenation of the strings $$$t$$$ and $$$s$$$; he selects an arbitrary letter of $$$s$$$ and removes from $$$s$$$ all its occurrences (the selected letter must occur in the string $$$s$$$ at the moment of performing this action). Polycarp performs this sequence of actions strictly in this order.Note that after Polycarp finishes the actions, the string $$$s$$$ will be empty and the string $$$t$$$ will be equal to some value (that is undefined and depends on the order of removing).E.g. consider $$$s$$$=\"abacaba\" so the actions may be performed as follows: $$$t$$$=\"abacaba\", the letter 'b' is selected, then $$$s$$$=\"aacaa\"; $$$t$$$=\"abacabaaacaa\", the letter 'a' is selected, then $$$s$$$=\"c\"; $$$t$$$=\"abacabaaacaac\", the letter 'c' is selected, then $$$s$$$=\"\" (the empty string). You need to restore the initial value of the string $$$s$$$ using only the final value of $$$t$$$ and find the order of removing letters from $$$s$$$.", "input_spec": "The first line contains one integer $$$T$$$ ($$$1 \\le T \\le 10^4$$$) \u2014 the number of test cases. Then $$$T$$$ test cases follow. Each test case contains one string $$$t$$$ consisting of lowercase letters of the Latin alphabet. The length of $$$t$$$ doesn't exceed $$$5 \\cdot 10^5$$$. The sum of lengths of all strings $$$t$$$ in the test cases doesn't exceed $$$5 \\cdot 10^5$$$.", "output_spec": "For each test case output in a separate line: $$$-1$$$, if the answer doesn't exist; two strings separated by spaces. The first one must contain a possible initial value of $$$s$$$. The second one must contain a sequence of letters \u2014 it's in what order one needs to remove letters from $$$s$$$ to make the string $$$t$$$. E.g. if the string \"bac\" is outputted, then, first, all occurrences of the letter 'b' were deleted, then all occurrences of 'a', and then, finally, all occurrences of 'c'. If there are multiple solutions, print any one. ", "sample_inputs": ["7\nabacabaaacaac\nnowyouknowthat\npolycarppoycarppoyarppyarppyrpprppp\nisi\neverywherevrywhrvryhrvrhrvhv\nhaaha\nqweqeewew"], "sample_outputs": ["abacaba bac\n-1\npolycarp lcoayrp\nis si\neverywhere ewyrhv\n-1\n-1"], "notes": "NoteThe first test case is considered in the statement."}, "positive_code": [{"source_code": "\r\n(*LMAOOOOOOOOOO'*)\r\n\r\nclass ['a] vector =\r\n object (self)\r\n val mutable a = ([||] : 'a array) \r\n val mutable size = 0\r\n method check = \r\n if size = Array.length a then\r\n a <- Array.append a a \r\n method pop = \r\n if size = 0 then false\r\n else \r\n let () = size <- size - 1 in\r\n true\r\n method push x =\r\n if Array.length a = 0 then\r\n let () = a <- Array.make 1 x in\r\n size <- 1\r\n else\r\n let () = self#check in\r\n let () = a.(size) <- x in \r\n size <- size + 1 \r\n method size =\r\n size\r\n method get i =\r\n a.(i)\r\n method con (other : 'a vector) = \r\n for i = 0 to other#size do\r\n self#push (other#get i)\r\n done\r\n method sub l r = \r\n let ans = (new vector : 'a vector) in \r\n let () = \r\n for i = l to r do \r\n ans#push (self#get i)\r\n done in \r\n ans\r\n method from_string s = \r\n for i = 0 to String.length s - 1 do\r\n self#push s.[i]\r\n done\r\n method eq (other : 'a vector) = \r\n if self#size <> other#size then false\r\n else \r\n let pos = ref true in\r\n let () = \r\n for i = 0 to self#size - 1 do\r\n if (self#get i) <> (other#get i) then pos := false\r\n done in\r\n !pos\r\n method string =\r\n String.init self#size (fun i -> self#get i) \r\n end;;\r\n\r\nlet readInt() = Scanf.scanf \" %d\" (fun i -> i);; \r\nlet readLine() = input_line stdin;;\r\nlet print_number x = print_string ((string_of_int x) ^ \" \");;\r\nlet print_char c = print_string (Char.escaped c);;\r\nlet print_array a = \r\n let () = \r\n for i = 0 to Array.length a - 1 do\r\n print_number a.(i)\r\n done in\r\n print_string \"\\n\";;\r\nlet f c = int_of_char(c) - int_of_char('a');;\r\nlet build s1 order = \r\n let ans = new vector in\r\n let () = \r\n let banned = Array.make 26 false in\r\n for i = 0 to Array.length order - 1 do\r\n let j = ref 0 in\r\n let quit_loop = ref false in\r\n let () = \r\n while not !quit_loop do\r\n let () = \r\n if ans#size = 500000 then quit_loop := true\r\n else if !j = s1#size then quit_loop := true\r\n else if not banned.(f (s1#get !j)) then\r\n ans#push (s1#get !j) in\r\n j := !j + 1\r\n done in\r\n banned.(order.(i)) <- true\r\n done in\r\n ans;;\r\n\r\nlet check s1 s2 order = \r\n (build s1 order)#eq s2;;\r\n \r\n(*let a = new vector in\r\n let b = new vector in\r\n let () = a#from_string \"abacaba\" in\r\n let () = b#from_string \"abacabaaacaac\" in\r\n (build a [|1; 0; 2|])#string;;*)\r\n\r\nlet da x = ()\r\nlet reverse a n = Array.init (n+1) (fun i -> a.(n - i));;\r\nlet t = readLine() in \r\nfor i = 1 to int_of_string t do\r\n let inp = readLine() in\r\n let s = new vector in\r\n let () = (s#from_string inp) in\r\n let ptr = ref (-1) in\r\n let seen = Array.make 26 0 in\r\n let rev_order = Array.make 26 0 in\r\n let freq = Array.make 26 0 in\r\n let possible = ref true in\r\n let sum = ref 0 in\r\n let () = \r\n for j = 0 to s#size - 1 do\r\n let rj = s#size - 1 - j in\r\n let c = f (s#get rj) in\r\n let () = \r\n freq.(c) <- freq.(c) + 1 in\r\n if seen.(c) = 0 then \r\n let () = seen.(c) <- 1 in\r\n let () = ptr := !ptr + 1 in\r\n rev_order.(!ptr) <- c\r\n done in\r\n let order = reverse rev_order !ptr in \r\n let () = \r\n for j = 0 to Array.length order - 1 do\r\n let c = order.(j) in\r\n let () = \r\n if freq.(c) mod (j+1) <> 0 then\r\n possible := false\r\n else\r\n freq.(c) <- freq.(c) / (j+1) in\r\n sum := !sum + freq.(c)\r\n done in\r\n let sb = s#sub 0 (!sum - 1) in\r\n let ord = String.init (Array.length order) (fun i -> char_of_int (order.(i) + int_of_char('a'))) in\r\n if (check sb s order) then\r\n print_string (sb#string ^ \" \" ^ ord ^ \"\\n\")\r\n else\r\n print_string \"-1\\n\"\r\ndone;;"}, {"source_code": "\r\n(*LMAOOOOOOOOOO*)\r\n\r\nclass ['a] vector =\r\n object (self)\r\n val mutable a = ([||] : 'a array) \r\n val mutable size = 0\r\n method check = \r\n if size = Array.length a then\r\n a <- Array.append a a \r\n method pop = \r\n if size = 0 then false\r\n else \r\n let () = size <- size - 1 in\r\n true\r\n method push x =\r\n if Array.length a = 0 then\r\n let () = a <- Array.make 1 x in\r\n size <- 1\r\n else\r\n let () = self#check in\r\n let () = a.(size) <- x in \r\n size <- size + 1 \r\n method size =\r\n size\r\n method get i =\r\n a.(i)\r\n method con (other : 'a vector) = \r\n for i = 0 to other#size do\r\n self#push (other#get i)\r\n done\r\n method sub l r = \r\n let ans = (new vector : 'a vector) in \r\n let () = \r\n for i = l to r do \r\n ans#push (self#get i)\r\n done in \r\n ans\r\n method from_string s = \r\n for i = 0 to String.length s - 1 do\r\n self#push s.[i]\r\n done\r\n method eq (other : 'a vector) = \r\n if self#size <> other#size then false\r\n else \r\n let pos = ref true in\r\n let () = \r\n for i = 0 to self#size - 1 do\r\n if (self#get i) <> (other#get i) then pos := false\r\n done in\r\n !pos\r\n method string =\r\n String.init self#size (fun i -> self#get i) \r\n end;;\r\n\r\nlet readInt() = Scanf.scanf \" %d\" (fun i -> i);; \r\nlet readLine() = input_line stdin;;\r\nlet print_number x = print_string ((string_of_int x) ^ \" \");;\r\nlet print_char c = print_string (Char.escaped c);;\r\nlet print_array a = \r\n let () = \r\n for i = 0 to Array.length a - 1 do\r\n print_number a.(i)\r\n done in\r\n print_string \"\\n\";;\r\nlet f c = int_of_char(c) - int_of_char('a');;\r\nlet build s1 order = \r\n let ans = new vector in\r\n let () = \r\n let banned = Array.make 26 false in\r\n for i = 0 to Array.length order - 1 do\r\n let j = ref 0 in\r\n let quit_loop = ref false in\r\n let () = \r\n while not !quit_loop do\r\n let () = \r\n if ans#size = 500000 then quit_loop := true\r\n else if !j = s1#size then quit_loop := true\r\n else if not banned.(f (s1#get !j)) then\r\n ans#push (s1#get !j) in\r\n j := !j + 1\r\n done in\r\n banned.(order.(i)) <- true\r\n done in\r\n ans;;\r\n\r\nlet check s1 s2 order = \r\n (build s1 order)#eq s2;;\r\n \r\n(*let a = new vector in\r\n let b = new vector in\r\n let () = a#from_string \"abacaba\" in\r\n let () = b#from_string \"abacabaaacaac\" in\r\n (build a [|1; 0; 2|])#string;;*)\r\n\r\nlet da x = ()\r\nlet reverse a n = Array.init (n+1) (fun i -> a.(n - i));;\r\nlet t = readLine() in \r\nfor i = 1 to int_of_string t do\r\n let inp = readLine() in\r\n let s = new vector in\r\n let () = (s#from_string inp) in\r\n let ptr = ref (-1) in\r\n let seen = Array.make 26 0 in\r\n let rev_order = Array.make 26 0 in\r\n let freq = Array.make 26 0 in\r\n let possible = ref true in\r\n let sum = ref 0 in\r\n let () = \r\n for j = 0 to s#size - 1 do\r\n let rj = s#size - 1 - j in\r\n let c = f (s#get rj) in\r\n let () = \r\n freq.(c) <- freq.(c) + 1 in\r\n if seen.(c) = 0 then \r\n let () = seen.(c) <- 1 in\r\n let () = ptr := !ptr + 1 in\r\n rev_order.(!ptr) <- c\r\n done in\r\n let order = reverse rev_order !ptr in \r\n let () = \r\n for j = 0 to Array.length order - 1 do\r\n let c = order.(j) in\r\n let () = \r\n if freq.(c) mod (j+1) <> 0 then\r\n possible := false\r\n else\r\n freq.(c) <- freq.(c) / (j+1) in\r\n sum := !sum + freq.(c)\r\n done in\r\n let sb = s#sub 0 (!sum - 1) in\r\n let ord = String.init (Array.length order) (fun i -> char_of_int (order.(i) + int_of_char('a'))) in\r\n if (check sb s order) then\r\n print_string (sb#string ^ \" \" ^ ord ^ \"\\n\")\r\n else\r\n print_string \"-1\\n\"\r\ndone;;"}], "negative_code": [], "src_uid": "8705adec1bea1f898db1ca533e15d5c3"} {"nl": {"description": "The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of boys. The second line contains sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009100) \u2014 the number of girls. The fourth line contains sequence b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bj\u2009\u2264\u2009100), where bj is the j-th girl's dancing skill.", "output_spec": "Print a single number \u2014 the required maximum possible number of pairs.", "sample_inputs": ["4\n1 4 6 2\n5\n5 1 5 7 9", "4\n1 2 3 4\n4\n10 11 12 13", "5\n1 1 1 1 1\n3\n1 2 3"], "sample_outputs": ["3", "0", "2"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet make_list () = \n let n = read () in\n let rec loop i list =\n if i < n\n then\n let temp = read () in\n loop (i + 1) (temp :: list)\n else\n List.sort (Pervasives.compare) list\n in loop 0 []\n\nlet input () = \n let boys = make_list () in\n let girls = make_list () in\n (boys, girls)\n\nlet pair boy girl =\n if boy = girl || boy = girl + 1 || boy = girl - 1\n then\n `Paired\n else\n if boy <= girl - 2\n then\n `Next_boy\n else\n `Next_girl\n\nlet solve (boys, girls) =\n let rec loop l ll count = \n match (l, ll) with\n | (hd :: tl), (hhd :: ttl) -> \n (match (pair hd hhd) with\n | `Paired -> loop tl ttl (count + 1)\n | `Next_boy -> loop tl ll count\n | `Next_girl -> loop l ttl count)\n | _, [] -> count\n | [], _ -> count\n | [], [] -> count\n in loop boys girls 0\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet make_list () = \n let n = read () in\n let rec loop i list =\n if i < n\n then\n let temp = read () in\n loop (i + 1) (temp :: list)\n else\n List.sort (Pervasives.compare) list\n in loop 0 []\n\nlet input () = \n let boys = make_list () in\n let girls = make_list () in\n (boys, girls)\n\nlet pair boy girl =\n if boy = girl || boy = girl + 1 || boy = girl - 1\n then\n `Paired\n else\n if boy <= girl - 2\n then\n `Next_boy\n else\n `Next_girl\n\nlet solve (boys, girls) =\n let rec loop l ll count = \n match (l, ll) with\n | (hd :: tl), (hhd :: ttl) -> \n (match (pair hd hhd) with\n | `Paired -> loop tl ttl (count + 1)\n | `Next_boy -> loop tl ll count\n | `Next_girl -> loop l ttl count)\n | _, _ -> count\n in loop boys girls 0\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}], "negative_code": [], "src_uid": "62766ef9a0751cbe7987020144de7512"} {"nl": {"description": "Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.", "input_spec": "You are given 8 pairs of integers, a pair per line \u2014 the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.", "output_spec": "Print in the first output line \"YES\" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers \u2014 point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word \"NO\" (without the quotes), after which no output is needed.", "sample_inputs": ["0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1"], "sample_outputs": ["YES\n5 6 7 8\n1 2 3 4", "NO", "YES\n1 2 3 4\n5 6 7 8"], "notes": "NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = 8 in\n let a = Array.make n (0, 0) in\n let _ =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- (x, y)\n done\n in\n let is_right (x, y) (x1, y1) (x2, y2) =\n (x1 - x) * (x2 - x) + (y1 - y) * (y2 - y) = 0\n in\n let is_rect p1 p2 p3 p4 =\n is_right p1 p2 p4 &&\n is_right p2 p1 p3 &&\n is_right p3 p2 p4\n in\n let sqr x = x * x in\n let dist2 (x1, y1) (x2, y2) =\n sqr (x1 - x2) + sqr (y1 - y2)\n in\n let is_square p1 p2 p3 p4 =\n is_rect p1 p2 p3 p4 &&\n dist2 p1 p2 = dist2 p2 p3\n in\n let b = Array.make n 0 in\n let u = Array.make n false in\n let rec bf k =\n if k >= 0 then (\n for i = 0 to n - 1 do\n\tif not u.(i) then (\n\t u.(i) <- true;\n\t b.(k) <- i;\n\t bf (k - 1);\n\t u.(i) <- false;\n\t)\n done\n ) else (\n if is_square a.(b.(0)) a.(b.(1)) a.(b.(2)) a.(b.(3)) &&\n\tis_rect a.(b.(4)) a.(b.(5)) a.(b.(6)) a.(b.(7))\n then (\n\tPrintf.printf \"YES\\n\";\n\tfor i = 0 to 3 do\n\t Printf.printf \"%d \" (b.(i) + 1)\n\tdone;\n\tPrintf.printf \"\\n\";\n\tfor i = 4 to 7 do\n\t Printf.printf \"%d \" (b.(i) + 1)\n\tdone;\n\tPrintf.printf \"\\n\";\n\texit 0\n )\n )\n in\n bf (n - 1);\n Printf.printf \"NO\\n\"\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = 8 in\n let a = Array.make n (0, 0) in\n let _ =\n for i = 0 to n - 1 do\n let x = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\ta.(i) <- (x, y)\n done\n in\n let is_right (x, y) (x1, y1) (x2, y2) =\n (x1 - x) * (x2 - x) + (y1 - y) * (y2 - y) = 0\n in\n let is_rect p1 p2 p3 p4 =\n is_right p1 p2 p4 &&\n is_right p2 p1 p3 &&\n is_right p3 p2 p4\n in\n let sqr x = x * x in\n let dist2 (x1, y1) (x2, y2) =\n sqr (x1 - x2) + sqr (y1 - y2)\n in\n let is_square p1 p2 p3 p4 =\n is_rect p1 p2 p3 p4 &&\n dist2 p1 p2 = dist2 p2 p3\n in\n let b = Array.make n 0 in\n let u = Array.make n false in\n let rec bf k =\n if k >= 0 then (\n for i = 0 to n - 1 do\n\tif not u.(i) then (\n\t u.(i) <- true;\n\t b.(k) <- i;\n\t bf (k - 1);\n\t u.(i) <- false;\n\t)\n done\n ) else (\n if is_square a.(b.(0)) a.(b.(1)) a.(b.(2)) a.(b.(3)) &&\n\tis_rect a.(b.(4)) a.(b.(5)) a.(b.(6)) a.(b.(7))\n then (\n\tPrintf.printf \"YES\\n\";\n\tfor i = 0 to 3 do\n\t Printf.printf \"%d \" (b.(i) + 1)\n\tdone;\n\tPrintf.printf \"\\n\";\n\tfor i = 4 to 7 do\n\t Printf.printf \"%d \" (b.(i) + 1)\n\tdone;\n\tPrintf.printf \"\\n\";\n\texit 0\n )\n )\n in\n bf (n - 1);\n Printf.printf \"NO\\n\"\n"}], "negative_code": [], "src_uid": "a36fb51b1ebb3552308e578477bdce8f"} {"nl": {"description": "ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k\u2009=\u200920 such ATM can give sums 100\u2009000 burles and 96\u2009000 burles, but it cannot give sums 99\u2009000 and 101\u2009000 burles.Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n\u2009\u2264\u20095000, 1\u2009\u2264\u2009k\u2009\u2264\u200920). The next line contains n space-separated integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009107) \u2014 the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order. The next line contains integer q (1\u2009\u2264\u2009q\u2009\u2264\u200920) \u2014 the number of requests for cash withdrawal that you will make. The next q lines contain numbers xi (1\u2009\u2264\u2009xi\u2009\u2264\u20092\u00b7108) \u2014 the sums of money in burles that you are going to withdraw from the ATM.", "output_spec": "For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print \u2009-\u20091, if it is impossible to get the corresponding sum.", "sample_inputs": ["6 20\n10 50 100 500 1000 5000\n8\n4200\n100000\n95000\n96000\n99000\n10100\n2015\n9950", "5 2\n1 2 3 5 8\n8\n1\n3\n5\n7\n9\n11\n13\n15"], "sample_outputs": ["6\n20\n19\n20\n-1\n3\n-1\n-1", "1\n1\n1\n2\n2\n2\n2\n-1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let k = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let q = read_int () in\n let x = Array.init q (fun _ -> read_int()) in\n \n let h = Hashtbl.create 10 in\n\n for i = 0 to n-1 do\n for j = 1 to k do\n Hashtbl.replace h (j*a.(i)) j\n done\n done;\n\n let solve x =\n (* return the answer for an amount x *)\n minf 0 (n-1) (fun i -> minf 1 k (\n fun j ->\n\tlet x' = x - j*a.(i) in\n\tif x' < 0 then max_int else if x' = 0 then j else\n\t let j' = try Hashtbl.find h x' with Not_found -> -1 in\n\t if j'<0 || j+j'>k then max_int else j + j'\n ))\n in\n \n for l=0 to q-1 do\n let answer = solve x.(l) in\n if answer = max_int then printf \"-1\\n\" else printf \"%d\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "5d8521e467cad53cf9403200e4c99b89"} {"nl": {"description": "There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $$$n$$$ packets with inflatable balloons, where $$$i$$$-th of them has exactly $$$a_i$$$ balloons inside.They want to divide the balloons among themselves. In addition, there are several conditions to hold: Do not rip the packets (both Grigory and Andrew should get unbroken packets); Distribute all packets (every packet should be given to someone); Give both Grigory and Andrew at least one packet; To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions.", "input_spec": "The first line of input contains a single integer $$$n$$$ ($$$1 \\le n \\le 10$$$)\u00a0\u2014 the number of packets with balloons. The second line contains $$$n$$$ integers: $$$a_1$$$, $$$a_2$$$, $$$\\ldots$$$, $$$a_n$$$ ($$$1 \\le a_i \\le 1000$$$)\u00a0\u2014 the number of balloons inside the corresponding packet.", "output_spec": "If it's impossible to divide the balloons satisfying the conditions above, print $$$-1$$$. Otherwise, print an integer $$$k$$$\u00a0\u2014 the number of packets to give to Grigory followed by $$$k$$$ distinct integers from $$$1$$$ to $$$n$$$\u00a0\u2014 the indices of those. The order of packets doesn't matter. If there are multiple ways to divide balloons, output any of them.", "sample_inputs": ["3\n1 2 1", "2\n5 5", "1\n10"], "sample_outputs": ["2\n1 2", "-1", "-1"], "notes": "NoteIn the first test Grigory gets $$$3$$$ balloons in total while Andrey gets $$$1$$$.In the second test there's only one way to divide the packets which leads to equal numbers of balloons.In the third test one of the boys won't get a packet at all."}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\n\nlet n = scanf \"%d\" (fun n -> n)\n\nlet l = Array.to_list (Array.init n (fun i -> i+1, scanf \" %d\" (fun i -> i)))\n\nlet l = List.sort (fun (i, c) (i', c') -> compare c c') l\n\nlet rec compute l =\n match l with\n | [] -> None\n | [h] -> None\n | (ih, ch)::t ->\n let s = List.fold_left (fun out (i, c) -> out + c) 0 t in\n(* printf \"s = %d and %d\\n\" s ch;*)\n if s <> ch then\n Some ih\n else\n None\n\nlet () =\n match compute l with\n | None -> printf \"-1\\n\"\n | Some i -> printf \"1\\n%d\\n\" i\n"}], "negative_code": [], "src_uid": "2b55012c899645bac8d293e85e73148f"} {"nl": {"description": "The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.", "input_spec": "The single line contains three integers r, s and p (1\u2009\u2264\u2009r,\u2009s,\u2009p\u2009\u2264\u2009100)\u00a0\u2014 the original number of individuals in the species of rock, scissors and paper, respectively.", "output_spec": "Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10\u2009-\u20099.", "sample_inputs": ["2 2 2", "2 1 2", "1 1 3"], "sample_outputs": ["0.333333333333 0.333333333333 0.333333333333", "0.150000000000 0.300000000000 0.550000000000", "0.057142857143 0.657142857143 0.285714285714"], "notes": null}, "positive_code": [{"source_code": "let rec solve mat (r,s,p) =\n\tif mat.(r).(s).(p) = (0.,0.,0.)\n\t\tthen begin\n\t\t\tlet r_s = float (r*s) and s_p = float (s*p)\n\t\t\tand p_r = float (p*r) in\n\t\t\tlet tot = r_s +. s_p +. p_r in\n\t\t\tlet (a,b,c) = solve mat (r-1,s,p)\n\t\t\tand (aa,bb,cc) = solve mat (r,s-1,p)\n\t\t\tand (aaa,bbb,ccc) = solve mat (r,s,p-1)\n\t\t\tin\n\t\t\tlet res =\n\t\t\t((a*.p_r +. aa *. r_s +. aaa *. s_p) /. tot,\n\t\t\t(b*.p_r +. bb *. r_s +. bbb *. s_p) /. tot,\n\t\t\t(c*.p_r +. cc *. r_s +. ccc *. s_p) /. tot)\n\t\t\tin mat.(r).(s).(p) <- res;\n\t\t\t res\n\t\t end\n\t\telse mat.(r).(s).(p)\n\n\nlet f a b c =\n\tlet mat = Array.init (a+1) (fun i -> Array.init (b+1) (fun j -> \tArray.init (c+1) (fun k -> (0.,0.,0.)))) in\n\t\tfor i=0 to b do\n\t\tfor j=0 to c do\n\t\t\tmat.(0).(i).(j) <- (0.,1.,0.);\n\t\tdone;\n\t\tdone;\n\t\tfor i=0 to a do\n\t\tfor j=0 to c do\n\t\t\tmat.(i).(0).(j) <- (0.,0.,1.);\n\t\tdone;\n\t\tdone;\n\t\tfor i=0 to a do\n\t\tfor j=0 to b do\n\t\t\tmat.(i).(j).(0) <- (1.,0.,0.);\n\t\tdone;\n\t\tdone;\n\t\tsolve mat (a,b,c)\n\nlet _ =\n\tlet (a,b,c) = Scanf.scanf \"%d %d %d\" (fun i j k -> (i,j,k)) in\n\t\tlet (d,e,f) = f a b c in\n\t\t\tPrintf.printf \"%F %F %F\" d e f\n"}], "negative_code": [{"source_code": "let rec solve mat (r,s,p) =\n\tif mat.(r).(s).(p) = (0.,0.,0.)\n\t\tthen begin\n\t\t\tlet r_s = float (r*s) and s_p = float (s*p)\n\t\t\tand p_r = float (p*r) in\n\t\t\tlet tot = r_s +. s_p +. p_r in\n\t\t\tlet (a,b,c) = solve mat (r-1,s,p)\n\t\t\tand (aa,bb,cc) = solve mat (r,s-1,p)\n\t\t\tand (aaa,bbb,ccc) = solve mat (r,s,p-1)\n\t\t\tin\n\t\t\tlet res =\n\t\t\t((a*.p_r +. aa *. r_s +. aaa *. s_p) /. tot,\n\t\t\t(b*.p_r +. bb *. r_s +. bbb *. s_p) /. tot,\n\t\t\t(c*.p_r +. cc *. r_s +. ccc *. s_p) /. tot)\n\t\t\tin mat.(r).(s).(p) <- res;\n\t\t\t res\n\t\t end\n\t\telse mat.(r).(s).(p)\n\n\nlet f a b c =\n\tlet mat = Array.init (a+1) (fun i -> Array.init (b+1) (fun j -> \tArray.init (c+1) (fun k -> (0.,0.,0.)))) in\n\t\tfor i=0 to b do\n\t\tfor j=0 to c do\n\t\t\tmat.(0).(i).(j) <- (0.,1.,0.);\n\t\tdone;\n\t\tdone;\n\t\tfor i=0 to a do\n\t\tfor j=0 to c do\n\t\t\tmat.(i).(0).(j) <- (0.,0.,1.);\n\t\tdone;\n\t\tdone;\n\t\tfor i=0 to a do\n\t\tfor j=0 to b do\n\t\t\tmat.(i).(j).(0) <- (1.,0.,0.);\n\t\tdone;\n\t\tdone;\n\t\tsolve mat (a,b,c)\n\nlet _ =\n\tlet (a,b,c) = Scanf.scanf \"%d %d %d\" (fun i j k -> (i,j,k)) in\n\t\tlet (d,e,f) = f a b c in\n\t\t\tPrintf.printf \"%f %f %f\" d e f\n"}], "src_uid": "35736970c6d629c2764eaf23299e0356"} {"nl": {"description": "Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none \u2014 in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k\u2009+\u20091) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r,\u2009c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys \"Up\", \"Down\", \"Right\" and \"Left\". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r,\u2009c), then Vasya pushed key: \"Up\": if the cursor was located in the first line (r\u2009=\u20091), then it does not move. Otherwise, it moves to the previous line (with number r\u2009-\u20091), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r\u2009-\u20091; \"Down\": if the cursor was located in the last line (r\u2009=\u2009n), then it does not move. Otherwise, it moves to the next line (with number r\u2009+\u20091), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r\u2009+\u20091; \"Right\": if the cursor can move to the right in this line (c\u2009<\u2009ar\u2009+\u20091), then it moves to the right (to position c\u2009+\u20091). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the \"Right\" key; \"Left\": if the cursor can move to the left in this line (c\u2009>\u20091), then it moves to the left (to position c\u2009-\u20091). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the \"Left\" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1,\u2009c1) to position (r2,\u2009c2).", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of lines in the file. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009105), separated by single spaces. The third line contains four integers r1,\u2009c1,\u2009r2,\u2009c2 (1\u2009\u2264\u2009r1,\u2009r2\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009c1\u2009\u2264\u2009ar1\u2009+\u20091,\u20091\u2009\u2264\u2009c2\u2009\u2264\u2009ar2\u2009+\u20091).", "output_spec": "Print a single integer \u2014 the minimum number of times Vasya should push a key to move the cursor from position (r1,\u2009c1) to position (r2,\u2009c2).", "sample_inputs": ["4\n2 1 6 4\n3 4 4 2", "4\n10 5 6 4\n1 11 4 2", "3\n10 1 10\n1 10 1 1"], "sample_outputs": ["3", "6", "3"], "notes": "NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: \"Left\", \"Down\", \"Left\"."}, "positive_code": [{"source_code": "let chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet () = \n let n = read_int() in\n let len = Array.init n (fun i -> read_int()) in\n let s = -1 + read_int() in\n let c1 = -1 + read_int() in\n let t = -1 + read_int() in\n let c2 = -1 + read_int() in\n\n let minc a b = (* min cursor position in the range a...b inclusive *)\n minf (min a b) (max a b) (fun i -> len.(i))\n in\n\n let score a b = \n (* the score of the path that goes s-->a-->b-->t *)\n let m = min (min (minc s a) (minc a b)) (min c1 (minc b t)) in\n (abs (s-a)) + (abs (a-b)) + (abs (b-t)) + (abs (c2-m))\n in\n\n let answer = minf 0 (n-1) (fun a -> minf 0 (n-1) (fun b -> score a b)) in\n print_string (string_of_int answer);\n print_string \"\\n\"\n"}], "negative_code": [{"source_code": "let chan = Scanf.Scanning.from_channel (open_in \"input.txt\")\nlet read_int () = Scanf.bscanf chan \" %d \" (fun x -> x)\n\nlet ochan = open_out \"output.txt\"\nlet print_string s = Printf.fprintf ochan \"%s\" s\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet () = \n let n = read_int() in\n let len = Array.init n (fun i -> read_int()) in\n let s = -1 + read_int() in\n let c1 = -1 + read_int() in\n let t = -1 + read_int() in\n let c2 = -1 + read_int() in\n\n let minc a b = (* min cursor position in the range a...b inclusive *)\n minf a b (fun i -> len.(i))\n in\n\n let score a b = \n (* the score of the path that goes s-->a-->b-->t *)\n let m = min (min (minc s a) (minc a b)) (min c1 (minc b t)) in\n (abs (s-a)) + (abs (a-b)) + (abs (b-t)) + (abs (c2-m))\n in\n\n let answer = minf 0 (n-1) (fun a -> minf 0 (n-1) (fun b -> score a b)) in\n print_string (string_of_int answer);\n print_string \"\\n\"\n"}], "src_uid": "d02e8f3499c4eca03e0ae9c23f80dc95"} {"nl": {"description": "There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai,\u2009bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi\u2009<\u2009bi\u2009+\u20091 for all i\u2009<\u2009n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai\u2009\u2260\u2009ai\u2009+\u20091 for all i\u2009<\u2009n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of participants and bids. Each of the following n lines contains two integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009bi\u2009\u2264\u2009109,\u2009bi\u2009<\u2009bi\u2009+\u20091)\u00a0\u2014 the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of question you have in mind. Each of next q lines contains an integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009n), followed by k integers lj (1\u2009\u2264\u2009lj\u2009\u2264\u2009n)\u00a0\u2014 the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200\u2009000.", "output_spec": "For each question print two integer\u00a0\u2014 the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.", "sample_inputs": ["6\n1 10\n2 100\n3 1000\n1 10000\n2 100000\n3 1000000\n3\n1 3\n2 2 3\n2 1 2", "3\n1 10\n2 100\n1 1000\n2\n2 1 2\n2 2 3"], "sample_outputs": ["2 100000\n1 10\n3 1000", "0 0\n1 10"], "notes": "NoteConsider the first sample: In the first question participant number 3 is absent so the sequence of bids looks as follows: 1 10 2 100 1 10\u2009000 2 100\u2009000 Participant number 2 wins with the bid 100\u2009000. In the second question participants 2 and 3 are absent, so the sequence of bids looks: 1 10 1 10\u2009000 The winner is, of course, participant number 1 but the winning bid is 10 instead of 10\u2009000 as no one will ever increase his own bid (in this problem). In the third question participants 1 and 2 are absent and the sequence is: 3 1\u2009000 3 1\u2009000\u2009000 The winner is participant 3 with the bid 1\u2009000. "}, "positive_code": [{"source_code": "module Int =\nstruct\n\ttype t = int\n\tlet compare = compare\nend\n\nmodule IS = Set.Make(Int)\nmodule IM = Map.Make(Int)\n\nlet add map x bid =\n\tif IM.mem x map\n\t\tthen IM.add x (IS.add bid (IM.find x map)) map\n\t\telse IM.add x (IS.singleton bid) map\n\nlet rec f map = function\n\t| [] -> map\n\t| (a,b)::l -> f (add map a b) l\n\nlet trans map =\n\tList.sort (fun a b -> - (compare a b))\n\t(IM.fold (fun x bids ans -> (IS.max_elt bids,x)::ans) map [])\n\nlet highers set x =\n\tlet (_,_,a) = IS.split x set in\n\t\ta\n\nlet rec solve map set = function\n\t| (bid,x)::l when IS.mem x set -> solve map set l\n\t| x::(_,a)::l when IS.mem a set -> solve map set (x::l) \n\t| (_,x)::(a,_)::_ -> (IS.min_elt (highers (IM.find x map) a),x)\n\t| [_,x] -> (IS.min_elt (IM.find x map),x)\n\t| [] -> (0,0)\n\nlet finish req map =\n\tlet l = trans map in\n\t\tPrintf.printf \"LOL\\n\";\n\t\tList.iter (fun (a,b) -> Printf.printf \"%d %d\\n\" a b) l;\n\t\tPrintf.printf \"LOL\\n\";\n\t\tsolve map req l\n\nlet _ =\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) in\n\tlet inputs = Array.init n (fun _ -> Scanf.scanf \" %d %d\"\n\t\t(fun a b -> (a,b))) in\n\tlet map = Array.fold_right (fun (a,b) map -> add map a b)\n\t\tinputs IM.empty\n\tin\n\tlet l = trans map in\n\tlet q = Scanf.scanf \" %d\" (fun q -> q) in\n\t\tfor i = 1 to q do\n\t\t\tlet set = ref IS.empty in\n\t\t\tlet sz = Scanf.scanf \" %d\" (fun sz -> sz) in\n\t\t\t\tfor i = 1 to sz do\n\t\t\t\t\tScanf.scanf \" %d\" (fun x -> set := IS.add x !set)\n\t\t\t\tdone;\n\t\t\t\tlet (x,y) = solve map !set l in\n\t\t\t\t\tPrintf.printf \"%d %d\\n\" y x\n\t\tdone"}], "negative_code": [], "src_uid": "33ec0c97192b7b9e2ebff32f8ea4681c"} {"nl": {"description": "Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word \"Bulbasaur\" (without quotes) and sticks it on his wall. Bash is very particular about case\u00a0\u2014 the first letter of \"Bulbasaur\" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word \"Bulbasaur\" from the newspaper.Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?Note: uppercase and lowercase letters are considered different.", "input_spec": "Input contains a single line containing a string s (1\u2009\u2009\u2264\u2009\u2009|s|\u2009\u2009\u2264\u2009\u2009105)\u00a0\u2014 the text on the front page of the newspaper without spaces and punctuation marks. |s| is the length of the string s. The string s contains lowercase and uppercase English letters, i.e. .", "output_spec": "Output a single integer, the answer to the problem.", "sample_inputs": ["Bulbbasaur", "F", "aBddulbasaurrgndgbualdBdsagaurrgndbb"], "sample_outputs": ["1", "0", "2"], "notes": "NoteIn the first case, you could pick: Bulbbasaur.In the second case, there is no way to pick even a single Bulbasaur.In the third case, you can rearrange the string to BulbasaurBulbasauraddrgndgddgargndbb to get two words \"Bulbasaur\"."}, "positive_code": [{"source_code": "let yolo hasht x =\n\ttry\n\t\tHashtbl.find hasht x\n\twith _ -> 0\n\nlet _ =\n\tlet hasht = Hashtbl.create 0 in\n\tlet s = Scanf.scanf \"%s\" (fun s -> s) in\n\t\tfor i = 0 to String.length s - 1 do\n\t\t\tlet x = s.[i] in\n\t\t\tlet a = yolo hasht x in\n\t\t\t\tHashtbl.add hasht x (a+1)\n\t\tdone;\n\tlet bleu = List.fold_left min max_int\n\t\t(List.map (yolo hasht) ['B';'l';'b';'s';'r'])\n\tin\n\tlet rouge = min bleu ((yolo hasht 'u') / 2) in\n\tlet vert = min rouge ((yolo hasht 'a') / 2) in\n\t\tprint_int vert"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let a = Array.make 256 0 in\n let _ =\n for i = 0 to String.length s - 1 do\n let c = Char.code s.[i] in\n\ta.(c) <- a.(c) + 1\n done;\n in\n let r = a.(Char.code 'B') in\n let r = min r (a.(Char.code 'u') / 2) in\n let r = min r a.(Char.code 'l') in\n let r = min r a.(Char.code 'b') in\n let r = min r (a.(Char.code 'a') / 2) in\n let r = min r a.(Char.code 's') in\n let r = min r a.(Char.code 'r') in\n Printf.printf \"%d\\n\" r\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let s = read_string () in\n let n = String.length s in\n\n let count c = sum 0 (n-1) (fun i -> if s.[i] = c then 1 else 0) in\n let nB = count 'B' in\n let ns = count 's' in\n let nl = count 'l' in\n let nu = count 'u' in\n let nr = count 'r' in\n let na = count 'a' in\n let nb = count 'b' in \n\n let answer = min nB (min (nu/2) (min nl (min nb (min (na/2) (min ns nr))))) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "9c429fd7598ea75acce09805a15092d0"} {"nl": {"description": "Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1,\u2009a2,\u2009...,\u2009an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. \"But why split the money equally?\" \u2014 you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009100) \u2014 the coins' values. All numbers are separated with spaces.", "output_spec": "In the single line print the single number \u2014 the minimum needed number of coins.", "sample_inputs": ["2\n3 3", "3\n2 1 2"], "sample_outputs": ["2", "2"], "notes": "NoteIn the first sample you will have to take 2 coins (you and your twin have sums equal to 6,\u20090 correspondingly). If you take 1 coin, you get sums 3,\u20093. If you take 0 coins, you get sums 0,\u20096. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.In the second sample one coin isn't enough for us, too. You can pick coins with values 1,\u20092 or 2,\u20092. In any case, the minimum number of coins equals 2. "}, "positive_code": [{"source_code": "let input () = let number_of_coins = Scanf.scanf \"%d \" (fun n -> n) in\n (*List.init number_of_coins (fun _ -> Scanf.scanf \"%d \" (fun n -> n))\n *)\n let rec read list n =\n if n > 0\n then\n let var = Scanf.scanf \"%d \" (fun n -> n) in\n read (var :: list) (n - 1)\n else\n list\n in read [] number_of_coins\n\nlet sort list = List.rev(List.sort(Pervasives.compare) list)\n\nlet get_total list = List.fold_left(fun a b -> a + b) 0 list\n\nlet more_than_half total = (total / 2) + 1\n\nlet get_big_coins list amount =\n let rec loop list amount count = \n if amount > 0\n then \n match list with\n |(a :: tail) -> loop tail (amount - a) (count + 1)\n |[] -> failwith \"No money. Now cry\"\n else\n count\n in loop list amount 0\n\nlet solve input = get_big_coins (sort input)(more_than_half(get_total input))\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input ()))"}, {"source_code": "open Array;;\nlet main () =\n let a = ref 0\n in let summ = ref 0\n in let n = read_int ()\n in let f n = \n let tmp = Scanf.scanf \"%d \" (fun x->x) in \n summ := !summ + tmp; tmp\n in let ar = init n f\n in fast_sort (-) ar;\n for i = n-1 downto 0 do\n if !a > !summ then( print_int (n-1-i);exit 0)\n else( a:= !a + ar.(i); summ:= !summ - ar.(i); ())\n done;\n print_int n\n;;\nmain()"}, {"source_code": "\nlet sum seq = List.fold_left (+) 0 seq;;\n\nlet coins lst = \n let rec inner llst num get rest =\n if rest < get then\n num\n else\n let curr = List.hd llst\n in\n inner (List.tl llst) (num + 1) (get + curr) (rest - curr)\n in\n inner lst 0 0 (sum lst);;\n\nlet () =\n let arr = Scanf.scanf \"%d \"\n (fun n -> Array.init\n n\n (fun _ -> Scanf.scanf \"%d \" (fun m -> m))) in\n let _ = Array.fast_sort compare arr\n in\n Printf.printf \"%d\\n\" (coins (List.rev (Array.to_list arr)));;\n \n"}, {"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\nlet a = Array.make n (-1);;\n\nfor i = 0 to n-1 do\n let j = Scanf.scanf \"%d \" ( fun x -> x ) in\n a.(i)<-j;\ndone\n\nlet sum = Array.fold_left (fun x y -> x + y ) 0 a\n\nlet () = Array.sort (fun x y -> y - x) a\n\n(*\nlet () = printf \"%d \\n\" sum\nlet () = Array.iter (fun x -> printf \"%d \" x) a\n*)\n\nlet rec loop s i =\n let s' = s+a.(i) in\n if s' > (sum - s') || i >= n then\n printf \"%d\\n\" (i+1)\n else\n loop s' (i+1)\nin loop 0 0\n\n"}], "negative_code": [{"source_code": "open Array;;\nlet main () =\n let a = ref 0\n in let summ = ref 0\n in let n = read_int ()\n in let f n = \n let tmp = Scanf.scanf \"%d \" (fun x->x) in \n summ := !summ + tmp; tmp\n in let ar = init n f\n in fast_sort (-) ar;\n for i = n-1 downto 0 do\n if !a > !summ then( print_int (i-1);exit 0)\n else( a:= !a + ar.(i); summ:= !summ - ar.(i); ())\n done;\n print_int n\n;;\nmain()"}, {"source_code": "\nlet sum seq = List.fold_left (+) 0 seq;;\n\nlet coins lst = \n let rec inner llst num get rest =\n if rest < get then\n num\n else\n let curr = List.hd llst\n in\n inner (List.tl llst) (num + 1) (get + curr) (rest - curr)\n in\n inner lst 0 0 (sum lst);;\n\nlet () =\n let arr = Scanf.scanf \"%d \"\n (fun n -> Array.init\n n\n (fun _ -> Scanf.scanf \"%d \" (fun m -> m))) in\n let _ = Array.fast_sort compare arr\n in\n Printf.printf \"%d\\n\" (coins (Array.to_list arr));;\n \n"}], "src_uid": "ee535e202b7662dbaa91e869c8c6cee1"} {"nl": {"description": "Pashmak has fallen in love with an attractive girl called Parmida since one year ago...Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.", "input_spec": "The first line contains four space-separated x1,\u2009y1,\u2009x2,\u2009y2 (\u2009-\u2009100\u2009\u2264\u2009x1,\u2009y1,\u2009x2,\u2009y2\u2009\u2264\u2009100) integers, where x1 and y1 are coordinates of the first tree and x2 and y2 are coordinates of the second tree. It's guaranteed that the given points are distinct.", "output_spec": "If there is no solution to the problem, print -1. Otherwise print four space-separated integers x3,\u2009y3,\u2009x4,\u2009y4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them. Note that x3,\u2009y3,\u2009x4,\u2009y4 must be in the range (\u2009-\u20091000\u2009\u2264\u2009x3,\u2009y3,\u2009x4,\u2009y4\u2009\u2264\u20091000).", "sample_inputs": ["0 0 0 1", "0 0 1 1", "0 0 1 2"], "sample_outputs": ["1 0 1 1", "0 1 1 0", "-1"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let x1 = read () in\n let y1 = read () in\n let x2 = read () in\n let y2 = read () in\n (x1, y1, x2, y2)\n\nlet solve (x1, y1, x2, y2) =\n let lx = Pervasives.abs (x1 - x2) in\n let ly = Pervasives.abs (y1 - y2) in\n if lx = 0\n then\n let x3 = ly + x1 in\n let x4 = ly + x2 in\n [x3; y1; x4; y2]\n else\n if ly = 0\n then\n let y3 = lx + y1 in\n let y4 = lx + y2 in\n [x1; y3; x2; y4]\n else\n if lx = ly\n then\n [x1; y2; x2; y1]\n else\n [-1]\n\nlet print result = List.iter (Printf.printf \"%d \") result\n\nlet () = print (solve (input ()))"}], "negative_code": [], "src_uid": "71dea31e1244797f916adf5f526f776e"} {"nl": {"description": "After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1,\u2009a2,\u2009...,\u2009an), consisting of integers and integer k, not exceeding n.This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1\u00a0\u2009+\u2009\u00a0a2\u00a0...\u00a0\u2009+\u2009\u00a0ak,\u2009\u00a0a2\u00a0\u2009+\u2009\u00a0a3\u00a0\u2009+\u2009\u00a0...\u00a0\u2009+\u2009\u00a0ak\u2009+\u20091,\u2009\u00a0...,\u2009\u00a0an\u2009-\u2009k\u2009+\u20091\u00a0\u2009+\u2009\u00a0an\u2009-\u2009k\u2009+\u20092\u00a0\u2009+\u2009\u00a0...\u00a0\u2009+\u2009\u00a0an), then those numbers will form strictly increasing sequence.For example, for the following sample: n\u2009=\u20095,\u2009\u00a0k\u2009=\u20093,\u2009\u00a0a\u2009=\u2009(1,\u2009\u00a02,\u2009\u00a04,\u2009\u00a05,\u2009\u00a06) the sequence of numbers will look as follows: (1\u00a0\u2009+\u2009\u00a02\u00a0\u2009+\u2009\u00a04,\u2009\u00a02\u00a0\u2009+\u2009\u00a04\u00a0\u2009+\u2009\u00a05,\u2009\u00a04\u00a0\u2009+\u2009\u00a05\u00a0\u2009+\u2009\u00a06)\u00a0=\u00a0(7,\u2009\u00a011,\u2009\u00a015), that means that sequence a meets the described property. Obviously the sequence of sums will have n\u2009-\u2009k\u2009+\u20091 elements.Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively. The next line contains n space-separated elements ai (1\u2009\u2264\u2009i\u2009\u2264\u2009n). If ai\u00a0\u2009=\u2009\u00a0?, then the i-th element of Arthur's sequence was replaced by a question mark. Otherwise, ai (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109) is the i-th element of Arthur's sequence.", "output_spec": "If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string \"Incorrect sequence\" (without the quotes). Otherwise, print n integers \u2014 Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.", "sample_inputs": ["3 2\n? 1 2", "5 1\n-10 -9 ? -7 -6", "5 3\n4 6 7 2 9"], "sample_outputs": ["0 1 2", "-10 -9 -8 -7 -6", "Incorrect sequence"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let k = read_int () in\n\n let q = Array.make n false in\n\n let a = Array.make n 0 in\n\n for i=0 to n-1 do\n let s = read_string () in\n if s=\"?\" then q.(i) <- true\n else a.(i) <- int_of_string s;\n done;\n\n let verify (st,en) =\n (* the chain is [st, st+k, st+2k, ..., en]. If the chain is valid (or\n can be made valid by filling in the variables), set its variables\n to their optimum values, and return true. otherwise return\n false. The starting point st could be < 0 indicating before the\n start, and en could be >= n, indicating after the end. *)\n\n let len = (en-st)/k - 1 in (* number of variables inside the chain *)\n for i=1 to len do\n a.(st+i*k) <- i-1-(len/2);\n done;\n\n if st>=0 && st+k= a.(st+k) then (\n (* first constraint violated, so push up all the values *)\n let delta = a.(st) - a.(st+k) + 1 in\n for i=1 to len do\n\ta.(st+i*k) <- a.(st+i*k) + delta\n done;\n en >=n || en-k<0 || a.(en-k) < a.(en)\n ) else if en= 0 && a.(en-k) >= a.(en) then (\n let delta = a.(en-k) - a.(en) + 1 in\n for i=1 to len do\n\ta.(st+i*k) <- a.(st+i*k) - delta\n done;\n st<0 || st+k>=n || a.(st) < a.(st+k) \n ) else true\n in\n\n let ans = forall 0 (k-1) (\n fun i -> \n let rec loop j = if j>=n then true else\n\t let rec chain j = \n\t if j>=n || not q.(j) then j\n\t else chain (j+k)\n\t in\n\t \n\t let endchain = chain j in\n\t let startchain = j-k in\n\t (verify (startchain, endchain)) && loop (endchain+k)\n in\n loop i\n )\n in\n\n if ans then (\n for i=0 to n-1 do\n printf \"%d \" a.(i)\n done;\n print_newline()\n ) else (\n printf \"Incorrect sequence\\n\"\n )\n"}], "negative_code": [], "src_uid": "d42e599073345659188ffea3b2cdd4c7"} {"nl": {"description": "Author has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: \"+ x\"\u00a0\u2014 add integer x to multiset A. \"- x\"\u00a0\u2014 erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. \"? x\"\u00a0\u2014 you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed.", "input_spec": "The first line of the input contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of queries Vasiliy has to perform. Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009109). It's guaranteed that there is at least one query of the third type. Note, that the integer 0 will always be present in the set A.", "output_spec": "For each query of the type '?' print one integer\u00a0\u2014 the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.", "sample_inputs": ["10\n+ 8\n+ 9\n+ 11\n+ 6\n+ 1\n? 3\n- 8\n? 3\n? 8\n? 11"], "sample_outputs": ["11\n10\n14\n13"], "notes": "NoteAfter first five operations multiset A contains integers 0, 8, 9, 11, 6 and 1.The answer for the sixth query is integer \u00a0\u2014 maximum among integers , , , and ."}, "positive_code": [{"source_code": "type tree = Leaf | Node of tree * tree * int\n\nlet rec chain d x =\n if d = -1 then Node (Leaf,Leaf,1) else\n if x land (1 lsl d) = 0 then Node (chain (d-1) x, Leaf, 1)\n else Node (Leaf, chain (d-1) x, 1)\n \nlet rec insert t d x =\n match t with\n | Leaf -> chain d x\n | Node (l,r,size) ->\n if d = -1 then Node (l,r,size+1)\n else if x land (1 lsl d) = 0 then Node (insert l (d-1) x, r, size+1)\n else Node (l, insert r (d-1) x, size+1)\n\nlet rec delete t d x =\n match t with\n | Leaf -> failwith \"deleting from leaf\"\n | Node (l,r,size) ->\n if size = 1 then Leaf\n else if d = -1 then Node (l, r, size-1)\n else if x land (1 lsl d) = 0 then Node (delete l (d-1) x, r, size-1)\n else Node (l, delete r (d-1) x, size-1)\n\nlet rec find t d x ac =\n match t with\n | Leaf -> failwith \"failed find\"\n | Node (l,r,size) ->\n let bit = (x lsr d) land 1 in\n if l <> Leaf && bit = 1 then find l (d-1) x (ac + (1 lsl d))\n else if r <> Leaf && bit = 0 then find r (d-1) x (ac + (1 lsl d))\n else if l <> Leaf then find l (d-1) x ac\n else if r <> Leaf then find r (d-1) x ac\n else ac\n\t\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let q = read_int () in\n\n let rec loop t i = if i loop (insert t 29 x) (i+1)\n\t| \"-\" -> loop (delete t 29 x) (i+1)\n\t| \"?\" ->\n\t let answer = (find t 29 x 0) in\n\t printf \"%d\\n\" answer;\n\t loop t (i+1)\n\t| _ -> failwith \"bad input\"\n in\n\n let t = insert Leaf 29 0 in\n loop t 0\n"}], "negative_code": [], "src_uid": "add040eecd8322630fbbce0a2a1de45e"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots , a_n$$$ consisting of integers from $$$0$$$ to $$$9$$$. A subarray $$$a_l, a_{l+1}, a_{l+2}, \\dots , a_{r-1}, a_r$$$ is good if the sum of elements of this subarray is equal to the length of this subarray ($$$\\sum\\limits_{i=l}^{r} a_i = r - l + 1$$$).For example, if $$$a = [1, 2, 0]$$$, then there are $$$3$$$ good subarrays: $$$a_{1 \\dots 1} = [1], a_{2 \\dots 3} = [2, 0]$$$ and $$$a_{1 \\dots 3} = [1, 2, 0]$$$.Calculate the number of good subarrays of the array $$$a$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the array $$$a$$$. The second line of each test case contains a string consisting of $$$n$$$ decimal digits, where the $$$i$$$-th digit is equal to the value of $$$a_i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer \u2014 the number of good subarrays of the array $$$a$$$.", "sample_inputs": ["3\n3\n120\n5\n11011\n6\n600005"], "sample_outputs": ["3\n6\n1"], "notes": "NoteThe first test case is considered in the statement.In the second test case, there are $$$6$$$ good subarrays: $$$a_{1 \\dots 1}$$$, $$$a_{2 \\dots 2}$$$, $$$a_{1 \\dots 2}$$$, $$$a_{4 \\dots 4}$$$, $$$a_{5 \\dots 5}$$$ and $$$a_{4 \\dots 5}$$$. In the third test case there is only one good subarray: $$$a_{2 \\dots 6}$$$."}, "positive_code": [{"source_code": "(* \u7ed9\u5b9a\u4e00\u4e2a\u4ec5\u542b 0 \u5230 9 \u7684\u4e32\uff0c\u627e\u51fa\u6709\u591a\u5c11\u4e2a good subarray *)\n(* (Definition) good subarray: the sum of elements of this subarray is equal to the length of this subarray *)\n\nlet explode str =\n let len = String.length str in\n let rec f accu i =\n if i = len then accu\n else f (Int64.of_int (Char.code str.[i] - Char.code '1') :: accu) (i + 1)\n in\n f [] 0 |> List.rev\n\nmodule SumValues = struct\n include Map.Make (Int64)\n\n let touch key m =\n let count =\n match mem key m with false -> 1L | true -> Int64.add 1L (find key m)\n in\n add key count m\nend\n\nlet main =\n let test_cases = Scanf.scanf \" %d\" (fun x -> x) in\n\n for i = 0 to test_cases - 1 do\n let len = Scanf.scanf \" %d\" (fun x -> x) in\n\n let xs = Scanf.scanf \" %s\" explode in\n\n let f (r, sum, map) x =\n let sum' = Int64.add sum x in\n let r' =\n match SumValues.mem sum' map with\n | true -> Int64.add r (SumValues.find sum' map)\n | false -> r\n in\n (r', sum', SumValues.touch sum' map)\n in\n let r, _, _ = List.fold_left f (0L, 0L, SumValues.(add 0L 1L empty)) xs in\n\n print_endline (Int64.to_string r)\n done\n"}], "negative_code": [{"source_code": "(* \u7ed9\u5b9a\u4e00\u4e2a\u4ec5\u542b 0 \u5230 9 \u7684\u4e32\uff0c\u627e\u51fa\u6709\u591a\u5c11\u4e2a good subarray *)\n(* (Definition) good subarray: the sum of elements of this subarray is equal to the length of this subarray *)\n\nlet explode str =\n let len = String.length str in\n let rec f accu i =\n if i = len then accu\n else f ((Char.code str.[i] - Char.code '1') :: accu) (i + 1)\n in\n f [] 0 |> List.rev\n\nmodule SumValues = struct\n include Map.Make (struct\n type t = int\n\n let compare = compare\n end)\n\n let touch key m =\n let count = match mem key m with false -> 1 | true -> 1 + find key m in\n add key count m\nend\n\nlet main =\n let test_cases = Scanf.scanf \" %d\" (fun x -> x) in\n\n for i = 0 to test_cases - 1 do\n let len = Scanf.scanf \" %d\" (fun x -> x) in\n\n let xs = Scanf.scanf \" %s\" explode in\n\n let f (r, sum, map) x =\n let sum' = sum + x in\n let r' =\n match SumValues.mem sum' map with\n | true -> r + SumValues.find sum' map\n | false -> r\n in\n (r', sum', SumValues.touch sum' map)\n in\n let r, _, _ = List.fold_left f (0, 0, SumValues.(add 0 1 empty)) xs in\n\n print_endline (string_of_int r)\n done\n"}], "src_uid": "e5244179b8ef807b1c6abfe113bd4f3b"} {"nl": {"description": "Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that: there wouldn't be a pair of any side-adjacent cards with zeroes in a row; there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.", "input_spec": "The first line contains two integers: n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of cards containing number 0; m (1\u2009\u2264\u2009m\u2009\u2264\u2009106) \u2014 the number of cards containing number 1.", "output_spec": "In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.", "sample_inputs": ["1 2", "4 8", "4 10", "1 5"], "sample_outputs": ["101", "110110110101", "11011011011011", "-1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n\n let overlap (a,b) (c,d) = max a c <= min b d in\n\n let possible n m startwith = (* n zeros, m ones *)\n let bal n m = \n let zlo = n in\n let zhi = n in\n let olo = (m+1)/2 in\n let ohi = m in\n n>=0 && m>=0 && overlap (zlo,zhi) (olo,ohi)\n in\n if bal n m then true else\n if startwith = 0 then bal (n-1) m\n else bal n (m-1) || bal n (m-2)\n in\n\n let mcount = [|1;2|]in\n\n if not (possible n m 0 || possible n m 1) then printf \"-1\\n\" else (\n\n let rec loop current maxremain n m =\n if m=0 && n=0 then () \n else if n=0 then (printf \"1\"; loop 1 (maxremain-1) n (m-1))\n else if m=0 then (printf \"0\"; loop 0 (maxremain-1) (n-1) m)\n else (\n\tif maxremain = 0 then (\n\t let current = 1-current in\n\t loop current mcount.(current) n m\n\t) else (\n\t let nc = if possible n m current then current else 1-current in\n\t printf \"%d\" nc;\n\t let n = if nc = 0 then n-1 else n in\n\t let m = if nc = 1 then m-1 else m in\n\t let maxremain = if nc=current then maxremain-1 else mcount.(nc)-1 in\n\t loop nc maxremain n m\n\t)\n )\n in\n \n let current = if possible n m 1 then 1 else 0 in\n printf \"%d\" current;\n let n = if current = 0 then n-1 else n in\n let m = if current = 1 then m-1 else m in\n loop current (mcount.(current) - 1) n m;\n printf \"\\n\"\n \n )\n\n"}, {"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int();;\n\nlet rec print_list a b=\nif b>a+1 then (if b=2 then print_int 11 else (print_int 110;print_list (a-1) (b-2)))\nelse if a>b then (print_int 0;print_list (a-1) b)\nelse if (a=b)&&(a<>0) then (print_int 10;print_list (a-1) (b-1))\nelse if a+1=b then (if b=1 then print_int 1 else (print_int 10;print_list (a-1) (b-1)));;\n\nif n>m+1 then print_int (-1)\nelse if (m/2)+(m mod 2)>n+1 then print_int (-1)\nelse print_list n m;;\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n\n let overlap (a,b) (c,d) = max a c <= min b d in\n\n let possible n m startwith = (* n zeros, m ones *)\n let bal n m = \n let zlo = (n+1)/2 in\n let zhi = n in\n let olo = (m+1)/2 in\n let ohi = m in\n n>=0 && m>=0 && overlap (zlo,zhi) (olo,ohi)\n in\n if bal n m then true else\n if startwith = 0 then bal (n-1) m || bal (n-2) m\n else bal n (m-1) || bal n (m-2)\n in\n\n let mcount = [|2;2|]in\n\n if not (possible n m 0 || possible n m 1) then printf \"-1\\n\" else (\n\n let rec loop current maxremain n m =\n if m=0 && n=0 then () \n else if n=0 then (printf \"1\"; loop 1 (maxremain-1) n (m-1))\n else if m=0 then (printf \"0\"; loop 0 (maxremain-1) (n-1) m)\n else (\n\tif maxremain = 0 then (\n\t let current = 1-current in\n\t loop current mcount.(current) n m\n\t) else (\n\t let nc = if possible n m current then current else 1-current in\n\t printf \"%d\" nc;\n\t let n = if nc = 0 then n-1 else n in\n\t let m = if nc = 1 then m-1 else m in\n\t let maxremain = if nc=current then maxremain-1 else mcount.(nc)-1 in\n\t loop nc maxremain n m\n\t)\n )\n in\n \n let current = if possible n m 1 then 1 else 0 in\n printf \"%d\" current;\n let n = if current = 0 then n-1 else n in\n let m = if current = 1 then m-1 else m in\n loop current (mcount.(current) - 1) n m;\n printf \"\\n\"\n \n )\n\n"}], "src_uid": "854c561539596722b1dbc8f99cbdca78"} {"nl": {"description": "ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of rows of seats in the bus. Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row. Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details. ", "output_spec": "If it is possible for Chris and ZS to sit at neighbouring empty seats, print \"YES\" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output). If there is no pair of seats for Chris and ZS, print \"NO\" (without quotes) in a single line. If there are multiple solutions, you may print any of them.", "sample_inputs": ["6\nOO|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX", "4\nXO|OX\nXO|XX\nOX|OX\nXX|OX", "5\nXX|XX\nXX|XX\nXO|OX\nXO|OO\nOX|XO"], "sample_outputs": ["YES\n++|OX\nXO|XX\nOX|OO\nXX|OX\nOO|OO\nOO|XX", "NO", "YES\nXX|XX\nXX|XX\nXO|OX\nXO|++\nOX|XO"], "notes": "NoteNote that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.O+|+XXO|XXOX|OOXX|OXOO|OOOO|XX"}, "positive_code": [{"source_code": "let list_init n f =\n let rec loop i list = \n if i < n\n then\n let element = f(i) in\n loop (i + 1) (element :: list)\n else\n List.rev list\n in loop 0 []\n \nlet mod_first list f =\n let rec loop prev list =\n match list with\n | [] -> None\n | (hd :: tl) -> \n match (f hd) with\n | None -> loop (hd :: prev) tl\n | Some hd' -> Some (List.rev_append (hd' :: prev) tl)\n in loop [] list\n\nlet read_input () =\n let n = Scanf.scanf \"%d \" (fun n -> n) in \n let read_row () = Scanf.scanf \"%c%c%c%c%c \" (fun a b c d e -> ((a, b) :: (d, e) :: [])) in\n let bus = list_init n (fun _ -> read_row ()) in\n bus\n\nlet seat bus = mod_first bus (fun row -> mod_first row (fun pair ->\n if pair = ('O', 'O')\n then\n Some ('+', '+')\n else\n None))\n\nlet print_row row =\n match row with\n | [a, b; c, d] -> Printf.printf \"%c%c|%c%c\\n\" a b c d\n | _ -> failwith \"Invalid bus\"\n \nlet print_bus bus = \n match bus with\n | Some bus -> \n Printf.printf \"YES\\n\";\n List.iter print_row bus\n | _ -> Printf.printf \"NO\\n\"\n\nlet () = print_bus (seat (read_input ()))"}, {"source_code": "let list_init n f =\n let rec loop i list = \n if i < n\n then\n let element = f(i) in\n loop (i + 1) (element :: list)\n else\n List.rev list\n in loop 0 []\n \nlet mod_first list f =\n let rec loop prev list =\n match list with\n | [] -> None\n | (hd :: tl) -> \n match (f hd) with\n | None -> loop (hd :: prev) tl\n | Some hd' -> Some (List.rev_append (hd' :: prev) tl)\n in loop [] list \n\nlet read_input () =\n let n = Scanf.scanf \"%d \" (fun n -> n) in \n let read_row () = Scanf.scanf \"%c%c%c%c%c \" (fun a b c d e -> ((a, b) :: (d, e) :: [])) in\n let bus = list_init n (fun _ -> read_row ()) in\n bus\n\nlet seat bus = mod_first bus (fun row -> mod_first row (fun pair ->\n if pair = ('O', 'O')\n then\n Some ('+', '+')\n else\n None))\n\nlet print_char char =\n Printf.printf \"%c\" char\n\nlet print_str str = \n Printf.printf \"%s\\n\" str\n\nlet print_side (a, b) =\n Printf.printf \"%c%c\" a b\n\nlet print_row row =\n match row with\n | [left; right] -> \n print_side left; \n print_char '|';\n print_side right; \n print_char '\\n'\n | _ -> failwith \"Invalid bus\"\n \nlet print_bus bus = \n match bus with\n | Some bus -> \n print_str \"YES\";\n List.iter print_row bus\n | _ -> print_str \"NO\"\n\nlet () = print_bus (seat (read_input ()))\n"}, {"source_code": "let read_int () = Scanf.scanf \"%d \" (fun n -> n)\nlet read_char () = Scanf.scanf \"%c \" (fun c -> c)\nlet print option = \n match option with\n | Some array -> Printf.printf \"YES\\n\";\n Array.iter (fun row -> \n Array.iter (Printf.printf \"%c\") row;\n Printf.printf \"\\n\") array\n | None -> Printf.printf \"NO\\n\"\n \nlet input () = \n let n = read_int () in \n let all_rows = Array.init n (fun _ -> Array.init 5 (fun _ -> read_char ())) in\n (all_rows, n)\n\nlet modify row =\n let rec loop i = \n if i < 5\n then\n let char = row.(i) in\n let prev = row.(i - 1) in\n if char = 'O' && char = prev\n then\n (Array.set row i '+';\n Array.set row (i - 1) '+';\n true)\n else\n loop (i + 1)\n else\n false\n in loop 1\n\nlet solve (all_rows, n) =\n let rec loop i = \n if i < n\n then\n let row = all_rows.(i) in\n if modify row\n then\n Some all_rows\n else\n loop (i + 1)\n else\n None\n in loop 0\n\nlet () = print (solve (input ()))"}, {"source_code": "open Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\ntype result =\n | YES of (char * char * char * char) list\n | NO\n\nlet print_result (r:result) =\n match r with\n | NO -> print_string \"NO\"\n | YES l ->\n match l with\n | [] -> print_string \"NO\"\n | l ->\n print_string \"YES\\n\";\n let rec print result_l =\n match result_l with\n | [] -> print_string \"\"\n | (a,b,c,d)::tl ->\n Printf.printf \"%c%c|%c%c\\n\" a b c d;\n print tl\n in print l\n\nlet find_and_replace_seats row_arr =\n let row_l = Array.to_list row_arr in\n let rec helper acc row_l =\n match row_l with\n | [] -> NO\n | (a,b,c,d)::tl ->\n if a = 'O' && b = 'O' then YES (List.rev (List.rev tl @ [('+','+',c,d)] @ acc))\n else if c = 'O' && d = 'O' then YES (List.rev (List.rev tl @ [(a,b,'+','+')] @ acc))\n else helper ((a,b,c,d)::acc) tl\n in helper [] row_l\n\nlet () =\n let n = read_int () in\n let row_arr = Array.init n (fun _ ->\n let input = read_string () in\n let a = input.[0] in\n let b = input.[1] in\n let c = input.[3] in\n let d = input.[4] in\n (a,b,c,d)\n )\n in\n find_and_replace_seats row_arr\n |> print_result\n"}], "negative_code": [], "src_uid": "e77787168e1c87b653ce1f762888ac57"} {"nl": {"description": "You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105) \u2014 the number of points on the line. The second line contains n integers xi (\u2009-\u2009109\u2009\u2264\u2009xi\u2009\u2264\u2009109) \u2014 the coordinates of the given n points.", "output_spec": "Print the only integer x \u2014 the position of the optimal point on the line. If there are several optimal points print the position of the leftmost one. It is guaranteed that the answer is always the integer.", "sample_inputs": ["4\n1 2 3 4"], "sample_outputs": ["2"], "notes": null}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a\n in\n let k = (n - 1) / 2 in\n Printf.printf \"%d\\n\" a.(k)\n"}], "negative_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let k = (n - 1) / 2 in\n Printf.printf \"%d\\n\" a.(k)\n"}], "src_uid": "fa9cc3ba103ed1f940c9e80a7ea75f72"} {"nl": {"description": "A sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Given two integers $$$n$$$ and $$$k$$$, construct a permutation $$$a$$$ of numbers from $$$1$$$ to $$$n$$$ which has exactly $$$k$$$ peaks. An index $$$i$$$ of an array $$$a$$$ of size $$$n$$$ is said to be a peak if $$$1 < i < n$$$ and $$$a_i \\gt a_{i-1}$$$ and $$$a_i \\gt a_{i+1}$$$. If such permutation is not possible, then print $$$-1$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ lines follow, each containing two space-separated integers $$$n$$$ ($$$1 \\leq n \\leq 100$$$) and $$$k$$$ ($$$0 \\leq k \\leq n$$$)\u00a0\u2014 the length of an array and the required number of peaks.", "output_spec": "Output $$$t$$$ lines. For each test case, if there is no permutation with given length and number of peaks, then print $$$-1$$$. Otherwise print a line containing $$$n$$$ space-separated integers which forms a permutation of numbers from $$$1$$$ to $$$n$$$ and contains exactly $$$k$$$ peaks. If there are multiple answers, print any.", "sample_inputs": ["5\n1 0\n5 2\n6 6\n2 1\n6 1"], "sample_outputs": ["1 \n2 4 1 5 3 \n-1\n-1\n1 3 6 5 4 2"], "notes": "NoteIn the second test case of the example, we have array $$$a = [2,4,1,5,3]$$$. Here, indices $$$i=2$$$ and $$$i=4$$$ are the peaks of the array. This is because $$$(a_{2} \\gt a_{1} $$$, $$$a_{2} \\gt a_{3})$$$ and $$$(a_{4} \\gt a_{3}$$$, $$$a_{4} \\gt a_{5})$$$. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let (n,k) = read_pair() in\n match (n,k) with\n | (1,0) -> printf \"1\\n\"\n | (2,0) -> printf \"1 2\\n\"\n | (2,_) | (1,_) -> printf \"-1\\n\"\n | _ -> (\n\tlet m = (n-1)/2 in\n\tif k > m then printf \"-1\\n\" else (\n\t let p = Array.init n (fun i -> i+1) in\n\t let swap i j =\n\t let (pi,pj) = (p.(i),p.(j)) in\n\t p.(i) <- pj;\n\t p.(j) <- pi\n\t in\n\t \n\t for l = 0 to k-1 do\n\t let j = n-1 - 2*l in\n\t let i = j-1 in\n\t swap i j\n\t done;\n\t for i=0 to n-1 do\n\t printf \"%d \" p.(i)\n\t done;\n\t print_newline()\n\t)\n ) \n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let (n,k) = read_pair() in\n match (n,k) with\n | (1,0) -> printf \"1\\n\"\n | (2,0) -> printf \"1 2\\n\"\n | (2,_) | (1,_) -> printf \"-1\\n\"\n | _ -> (\n\tlet m = n/2 in\n\tif k > m then printf \"-1\\n\" else (\n\t let p = Array.init n (fun i -> i+1) in\n\t let swap i j =\n\t let (pi,pj) = (p.(i),p.(j)) in\n\t p.(i) <- pj;\n\t p.(j) <- pi\n\t in\n\t \n\t for l = 0 to k-1 do\n\t let j = n-1 - 2*l in\n\t let i = j-1 in\n\t swap i j\n\t done;\n\t for i=0 to n-1 do\n\t printf \"%d \" p.(i)\n\t done;\n\t print_newline()\n\t)\n ) \n done\n"}], "src_uid": "b4bb11ea4650ead54026453ea9a76f39"} {"nl": {"description": "Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number \u2014 the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.", "input_spec": "The first line contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of contests where the coder participated. The next line contains n space-separated non-negative integer numbers \u2014 they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.", "output_spec": "Print the single number \u2014 the number of amazing performances the coder has had during his whole history of participating in the contests.", "sample_inputs": ["5\n100 50 200 150 200", "10\n4664 6496 5814 7010 5762 5736 6944 4850 3698 7242"], "sample_outputs": ["2", "4"], "notes": "NoteIn the first sample the performances number 2 and 3 are amazing.In the second sample the performances number 2, 4, 9 and 10 are amazing."}, "positive_code": [{"source_code": "let rdint =\n let l = ref 0 in\n let i = ref 0 in\n let s = String.create 65536 in\n let refill () =\n let n = input stdin s 0 65536 in\n i := 0;\n l := n in\n refill ();\n\n fun () ->\n let rec loop2 j k t f =\n let fin j t f =\n let _ = i := j in\n t * f in\n\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop2 !i !l t f else fin j t f\n ) else if s.[j] >= '0' && s.[j] <= '9' then\n loop2 (j + 1) k (t * 10 + Char.code s.[j] - 48) f\n else fin j t f in\n\n let rec loop1 j k =\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop1 !i !l else 0\n ) else if s.[j] = '-' then loop2 (j + 1) k 0 (-1)\n else if s.[j] >= '0' && s.[j] <= '9' then loop2 (j + 1) k (Char.code s.[j] - 48) 1\n else loop1 (j + 1) k in\n loop1 !i !l\n\nlet main () =\n let rec loop i min0 max0 acc =\n if i = 0 then Printf.printf \"%d\\n\" acc else\n let k = rdint () in\n let acc = if k < min0 || k > max0 then acc + 1 else acc in\n loop (i - 1) (min min0 k) (max max0 k) acc\n in\n let n = rdint() in\n let s = rdint() in\n loop (n - 1) s s 0\n;;\nmain ()\n"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet solve () =\n let n = read () in\n let first = read () in\n let rec loop i count max min =\n if i < n\n then\n let score = read () in\n if score < min\n then\n loop (i + 1) (count + 1) max score\n else\n if score > max\n then\n loop (i + 1) (count + 1) score min\n else\n loop (i + 1) count max min\n else\n count\n in loop 1 0 first first\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve ()) "}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x) in\nlet n = read_int() in\n let f = read_int() in \n let mmin = ref f and mmax = ref f in\n let count = ref 0 in\n for i = 1 to n-1 do\n let next = read_int() in\n if next > !mmax then begin\n mmax := next;\n incr count;\n end else if next < !mmin then begin\n mmin := next;\n incr count;\n end;\n done;\n print_int !count;\n print_newline();;"}], "negative_code": [], "src_uid": "a61b96d4913b419f5715a53916c1ae93"} {"nl": {"description": "This is an interactive problem. In the output section below you will see the information about flushing the output.Bear Limak thinks of some hidden number\u00a0\u2014 an integer from interval [2,\u2009100]. Your task is to say if the hidden number is prime or composite.Integer x\u2009>\u20091 is called prime if it has exactly two distinct divisors, 1 and x. If integer x\u2009>\u20091 is not prime, it's called composite.You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2,\u2009100]. The system will answer \"yes\" if your integer is a divisor of the hidden number. Otherwise, the answer will be \"no\".For example, if the hidden number is 14 then the system will answer \"yes\" only if you print 2, 7 or 14.When you are done asking queries, print \"prime\" or \"composite\" and terminate your program.You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2,\u2009100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).", "input_spec": "After each query you should read one string from the input. It will be \"yes\" if the printed integer is a divisor of the hidden number, and \"no\" otherwise.", "output_spec": "Up to 20 times you can ask a query\u00a0\u2014 print an integer from interval [2,\u2009100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input. In any moment you can print the answer \"prime\" or \"composite\" (without the quotes). After that, flush the output and terminate your program. To flush you can use (just after printing an integer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. Hacking. To hack someone, as the input you should print the hidden number\u00a0\u2014 one integer from the interval [2,\u2009100]. Of course, his/her solution won't be able to read the hidden number from the input.", "sample_inputs": ["yes\nno\nyes", "no\nyes\nno\nno\nno"], "sample_outputs": ["2\n80\n5\ncomposite", "58\n59\n78\n78\n2\nprime"], "notes": "NoteThe hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.59 is a divisor of the hidden number. In the interval [2,\u2009100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries)."}, "positive_code": [{"source_code": "(*\n2\n3\n5\n7\n11\n13\n17\n19\n23\n29\n31\n37\n41\n43\n47\n4\n9\n25\n49\n\n*)\n\nlet _ =\n let tab =\n[|\n3;\n5;\n7;\n11;\n13;\n17;\n19;\n23;\n29;\n31;\n37;\n41;\n43;\n47;\n4;\n9;\n25;\n49\n|] in\n let cpt = ref (Printf.printf \"2\\n\"; flush stdout; Scanf.scanf \"%s\" (fun i -> if i = \"yes\" then 1 else 0)) in\n Array.iter (fun i -> Printf.printf \"%d\\n\" i; flush stdout; Scanf.scanf \" %s\" (fun i -> if i = \"yes\" then incr cpt)) tab;\n if !cpt < 2\n then Printf.printf \"prime\"\n else Printf.printf \"composite\";\n flush stdout\n"}, {"source_code": "open Printf\nopen String\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n \nlet primes_small = [2; 3; 5; 7]\nlet primes_big = [11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47]\nlet squares = [4; 9; 25; 49]\n\nlet () = \n\n let try_a_d d =\n printf \"%d\\n%!\" d;\n let s = read_line() in\n match s with \"yes\" -> true | \"no\" -> false | _ -> failwith \"bad input\"\n in\n\n let countlist li = List.fold_left (\n fun ac e -> if try_a_d e then ac+1 else ac\n ) 0 li in\n\n\n let nsmall = countlist primes_small in\n let nbig = countlist primes_big in\n let nsquares = countlist squares in\n \n if nsmall = 0 then printf \"prime\\n\"\n else if nsmall >= 2 || nsquares > 0 then printf \"composite\\n\"\n else if nbig = 0 then printf \"prime\\n\"\n else printf \"composite\\n\"\n"}], "negative_code": [{"source_code": "open Printf\nopen String\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n \nlet primes_small = [2; 3; 5; 7]\nlet primes_big = [11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47]\nlet squares = [4; 9; 25; 49]\n\nlet () = \n\n let try_a_d d =\n printf \"%d\\n%!\" d;\n let s = read_line() in\n match s with \"yes\" -> true | \"no\" -> false | _ -> failwith \"bad input\"\n in\n\n let countlist li = List.fold_left (\n fun ac e -> if try_a_d e then 1 else 0\n ) 0 li in\n\n\n let nsmall = countlist primes_small in\n let nbig = countlist primes_big in\n let nsquares = countlist squares in\n \n if nsmall = 0 then printf \"prime\\n\"\n else if nsmall >= 2 || nsquares > 0 then printf \"composite\\n\"\n else if nbig = 0 then printf \"prime\\n\"\n else printf \"composite\\n\"\n"}], "src_uid": "8cf479fd47050ba96d21f3d8eb43c8f0"} {"nl": {"description": "A permutation p is an ordered group of numbers p1,\u2009\u2009\u2009p2,\u2009\u2009\u2009...,\u2009\u2009\u2009pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1,\u2009\u2009\u2009p2,\u2009\u2009\u2009...,\u2009\u2009\u2009pn.Simon has a positive integer n and a non-negative integer k, such that 2k\u2009\u2264\u2009n. Help him find permutation a of length 2n, such that it meets this equation: .", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u200950000, 0\u2009\u2264\u20092k\u2009\u2264\u2009n).", "output_spec": "Print 2n integers a1,\u2009a2,\u2009...,\u2009a2n \u2014 the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them.", "sample_inputs": ["1 0", "2 1", "4 0"], "sample_outputs": ["1 2", "3 2 1 4", "2 7 4 6 1 3 5 8"], "notes": "NoteRecord |x| represents the absolute value of number x. In the first sample |1\u2009-\u20092|\u2009-\u2009|1\u2009-\u20092|\u2009=\u20090.In the second sample |3\u2009-\u20092|\u2009+\u2009|1\u2009-\u20094|\u2009-\u2009|3\u2009-\u20092\u2009+\u20091\u2009-\u20094|\u2009=\u20091\u2009+\u20093\u2009-\u20092\u2009=\u20092.In the third sample |2\u2009-\u20097|\u2009+\u2009|4\u2009-\u20096|\u2009+\u2009|1\u2009-\u20093|\u2009+\u2009|5\u2009-\u20098|\u2009-\u2009|2\u2009-\u20097\u2009+\u20094\u2009-\u20096\u2009+\u20091\u2009-\u20093\u2009+\u20095\u2009-\u20098|\u2009=\u200912\u2009-\u200912\u2009=\u20090."}, "positive_code": [{"source_code": "let (|>) x f = f x ;;\nlet (@@) f x = f x ;;\n\nlet ident x = x ;;\nlet ident2 x y = (x, y) ;;\nlet ident3 x y z = (x, y, z) ;;\nlet ident4 x y z w = (x, y, z, w) ;;\nlet ident5 x y z w v = (x, y, z, w, v) ;;\n\nlet char_to_int x = int_of_char x - int_of_char '0' ;;\nlet int_to_char x = char_of_int (x + int_of_char '0') ;;\n\nmodule List = struct\n include ListLabels ;;\n\n let rec iteri i f = function\n | [] -> ()\n | a::l -> f i a; iteri (i + 1) f l\n\n let iteri ~f l = iteri 0 f l\nend\n;;\n\nmodule Array = struct\n include ArrayLabels ;;\n\n let reduce ~f xs =\n let acc = ref xs.(0) in\n for i = 1 to length xs - 1 do\n acc := f !acc xs.(i)\n done;\n !acc\n ;;\nend\n;;\n\nmodule String = struct\n include StringLabels ;;\n\n let map_to_list ~f ss =\n let res = ref [] in\n iter ss ~f:(fun c -> res := f c :: !res);\n List.rev !res\n ;;\n\n let of_char_list ss =\n let res = String.create @@ List.length ss in\n List.iteri ss ~f:(fun i c -> res.[i] <- c);\n res\n ;;\n\n let iteri ~f a =\n for i = 0 to length a - 1 do f i (unsafe_get a i) done\n ;;\nend\n;;\n\nmodule Float = struct\n let (+) = (+.)\n let (-) = (-.)\n let ( * ) = ( *. )\n let (/) = (/.)\nend\n;;\n\nmodule Int64 = struct\n include Int64\n let (+) = add\n let (-) = sub\n let ( * ) = mul\n let (/) = div\nend\n;;\n\nlet fold_for ?(skip=1) min max ~init ~f =\n if skip = 0 then failwith \"fold_for\";\n let cmp = if skip > 0 then (<) else (>) in\n\n let rec iter cur acc =\n if not @@ cmp cur max then acc\n else iter (cur + skip) (f acc cur) in\n\n iter min init \n;;\n\nlet iter_for ?(skip=1) min max ~f =\n fold_for ~skip:skip min max ~init:() ~f:(fun _ i -> f i)\n;;\n\nlet input_n n fmt ~f =\n fold_for 0 n ~init:[] ~f:(fun acc _ ->\n Scanf.scanf fmt f :: acc) |> List.rev\n;;\n\n\nmodule SI = Set.Make (struct\n type t = int ;;\n let compare = compare ;;\nend)\n\nlet () =\n let n, k = Scanf.scanf \"%d %d\" ident2 in\n if k = 0 then begin\n iter_for 1 (2 * n + 1) ~f:(fun i -> Printf.printf \"%d \" i); print_endline \"\";\n end else begin\n let set = fold_for 1 (2 * n + 1) ~init:SI.empty ~f:(fun acc i -> SI.add i acc)\n |> SI.remove 1 |> SI.remove (k + 1) in\n Printf.printf \"%d %d \" (k + 1) 1;\n SI.iter (Printf.printf \"%d \") set;\n print_endline \"\"\n end\n;;\n"}], "negative_code": [], "src_uid": "82de6d4c892f4140e72606386ec2ef59"} {"nl": {"description": "The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples: $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points; $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points; $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point; $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 500$$$) \u2014 the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \\le n \\le 50$$$, $$$0 \\le m \\le n$$$, $$$2 \\le k \\le n$$$, $$$k$$$ is a divisors of $$$n$$$).", "output_spec": "For each test case, print one integer \u2014 the maximum number of points a player can get for winning the game.", "sample_inputs": ["4\n8 3 2\n4 2 4\n9 6 3\n42 0 7"], "sample_outputs": ["3\n0\n1\n0"], "notes": "NoteTest cases of the example are described in the statement."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let k = read_int() in\n let win_jokers = min m (n/k) in\n let lose_jokers = (m - win_jokers + k-2)/(k-1) in\n printf \"%d\\n\" (win_jokers - lose_jokers)\n done\n"}], "negative_code": [], "src_uid": "6324ca46b6f072f8952d2619cb4f73e6"} {"nl": {"description": "Burenka is about to watch the most interesting sporting event of the year \u2014 a fighting tournament organized by her friend Tonya.$$$n$$$ athletes participate in the tournament, numbered from $$$1$$$ to $$$n$$$. Burenka determined the strength of the $$$i$$$-th athlete as an integer $$$a_i$$$, where $$$1 \\leq a_i \\leq n$$$. All the strength values are different, that is, the array $$$a$$$ is a permutation of length $$$n$$$. We know that in a fight, if $$$a_i > a_j$$$, then the $$$i$$$-th participant always wins the $$$j$$$-th.The tournament goes like this: initially, all $$$n$$$ athletes line up in ascending order of their ids, and then there are infinitely many fighting rounds. In each round there is exactly one fight: the first two people in line come out and fight. The winner goes back to the front of the line, and the loser goes to the back.Burenka decided to ask Tonya $$$q$$$ questions. In each question, Burenka asks how many victories the $$$i$$$-th participant gets in the first $$$k$$$ rounds of the competition for some given numbers $$$i$$$ and $$$k$$$. Tonya is not very good at analytics, so he asks you to help him answer all the questions.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$2 \\leq n \\leq 10^5$$$, $$$1 \\leq q \\leq 10^5$$$) \u2014 the number of tournament participants and the number of questions. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq n$$$) \u2014 the array $$$a$$$, which is a permutation. The next $$$q$$$ lines of a test case contain questions. Each line contains two integers $$$i$$$ and $$$k$$$ ($$$1 \\leq i \\leq n$$$, $$$1 \\leq k \\leq 10^9$$$) \u2014 the number of the participant and the number of rounds. It is guaranteed that the sum of $$$n$$$ and the sum of $$$q$$$ over all test cases do not exceed $$$10^5$$$.", "output_spec": "For each Burenka's question, print a single line containing one integer \u2014 the answer to the question.", "sample_inputs": ["3\n\n3 1\n\n3 1 2\n\n1 2\n\n4 2\n\n1 3 4 2\n\n4 5\n\n3 2\n\n5 2\n\n1 2 3 5 4\n\n5 1000000000\n\n4 6"], "sample_outputs": ["2\n0\n1\n0\n4"], "notes": "NoteIn the first test case, the first numbered athlete has the strength of $$$3$$$, in the first round he will defeat the athlete with the number $$$2$$$ and the strength of $$$1$$$, and in the second round, the athlete with the number $$$3$$$ and the strength of $$$2$$$.In the second test case, we list the strengths of the athletes fighting in the first $$$5$$$ fights: $$$1$$$ and $$$3$$$, $$$3$$$ and $$$4$$$, $$$4$$$ and $$$2$$$, $$$4$$$ and $$$1$$$, $$$4$$$ and $$$3$$$. The participant with the number $$$4$$$ in the first $$$5$$$ rounds won $$$0$$$ times (his strength is $$$2$$$). The participant with the number $$$3$$$ has a strength of $$$4$$$ and won $$$1$$$ time in the first two fights by fighting $$$1$$$ time."}, "positive_code": [{"source_code": "module A = Array\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet bin_search ~(cmp : 'a -> 'a -> int) (target:int) (a: 'a array) =\n let l = ref (-1) in\n let r = ref (A.length a) in\n while !l < !r - 1 do\n let m = (!l + !r) / 2 in\n if cmp a.(m) target < 0 then\n l := m\n else\n r := m;\n done;\n !r\n\nlet snd (_, y) = y\n\nlet safe_get a i =\n if (i < 0) then 0\n else a.(i)\n\nlet compute_wins (a: int array) =\n let n = A.length a in\n let res = A.make n 0 in\n let imx = ref 0 in\n for i = 1 to n - 1 do\n if a.(i) > a.(!imx) then begin\n res.(i) <- 1;\n imx := i;\n end else\n res.(!imx) <- res.(!imx) + 1;\n done;\n (!imx, res)\n\nlet compute_pref_sums (a: int array) =\n let n = A.length a in\n let res = A.make n 0 in\n res.(0) <- a.(0);\n for i = 1 to n - 1 do\n res.(i) <- res.(i - 1) + a.(i);\n done;\n res\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let q = read_int () in\n let a = read_array read_int n in\n let (pos_mx, wins) = compute_wins a in\n let pref_sums = compute_pref_sums wins in\n for _ = 1 to q do\n let pos = read_int () - 1 in\n let k = read_int () in\n let last_win_pos = bin_search ~cmp:compare k pref_sums in\n if pos > last_win_pos || n = 1 then\n pf \"0\\n\"\n else if pos < last_win_pos then\n begin\n if (last_win_pos = n && pos = pos_mx) then\n pf \"%d\\n\" (k - safe_get pref_sums (pos_mx - 1))\n else\n pf \"%d\\n\" wins.(pos)\n end\n else\n pf \"%d\\n\" (k - safe_get pref_sums (pos - 1));\n done;\n done;"}], "negative_code": [], "src_uid": "7372994c95acc3b999dd9657abd35a24"} {"nl": {"description": "Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k\u2009=\u20095 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1,\u2009a2,\u2009...,\u2009an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times. Write a program that will find the minumum number of additional walks and the appropriate schedule\u00a0\u2014 the sequence of integers b1,\u2009b2,\u2009...,\u2009bn (bi\u2009\u2265\u2009ai), where bi means the total number of walks with the dog on the i-th day.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009500)\u00a0\u2014 the number of days and the minimum number of walks with Cormen for any two consecutive days. The second line contains integers a1,\u2009a2,\u2009...,\u2009an (0\u2009\u2264\u2009ai\u2009\u2264\u2009500)\u00a0\u2014 the number of walks with Cormen on the i-th day which Polycarp has already planned. ", "output_spec": "In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days. In the second line print n integers b1,\u2009b2,\u2009...,\u2009bn, where bi\u00a0\u2014 the total number of walks on the i-th day according to the found solutions (ai\u2009\u2264\u2009bi for all i from 1 to n). If there are multiple solutions, print any of them. ", "sample_inputs": ["3 5\n2 0 1", "3 1\n0 0 0", "4 6\n2 4 3 5"], "sample_outputs": ["4\n2 3 2", "1\n0 1 0", "0\n2 4 3 5"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n\tlet n = read_int ()\n\tand m = read_int () \n\tand wyn = ref 0 in\n\n\tlet tab = Array.make (n + 1) 100000 in\n\n\tfor i = 0 to n - 1 do \n\t\ttab.(i) <- read_int ()\n\tdone;\n\n\tfor i = 1 to n - 1 do \n\t\tif tab.(i) + tab.(i - 1) < m then begin\n\t\t\twyn := !wyn + abs(m - (tab.(i) + tab.(i - 1)));\n\t\t\ttab.(i) <- m - tab.(i - 1);\n\t\tend;\n\tdone;\n\n\tprintf \"%d\\n\" !wyn;\n\n\tfor i = 0 to n - 1 do \n\t\tprintf \"%d \" tab.(i)\n\tdone;"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let n = read () in\n let k = read () in \n let arr = Array.append (Array.make 1 k) (Array.init n (fun n -> read ())) in\n (n, k, arr)\n\nlet solve (n, k, arr) =\n let rec loop sum i = \n if i < n + 1\n then \n let a = arr.(i - 1) in\n let b = arr.(i) in\n if a + b < k \n then\n (arr.(i) <- k - a;\n let new_sum = sum + (k - a - b) in\n loop new_sum (i + 1))\n else\n loop sum (i + 1)\n else\n (sum, Array.sub arr 1 n)\n in loop 0 1\n\nlet print (sum, array) = \n Printf.printf \"%d\\n\" sum;\n Array.iter (Printf.printf \"%d \") array;\n Printf.printf \"\\n\"\n\nlet () = print (solve (input ()))\n"}, {"source_code": "open Printf\n\nlet (n1,k1) = Scanf.scanf \"%d %d \" (fun x y -> (x,y) )\n\nlet rec readi n a =\n match n with\n | 0 -> (List.rev a)\n | _ -> let x = Scanf.scanf \"%d \" (fun x -> x) in\n readi (n-1) (x::a)\n\nlet l = readi n1 []\n\n(*\nlet () =\n List.iter (fun x -> printf \"%d \" x) l;\n print_endline \"\"\n *)\n\nlet rec f a al ll = \n match ll with\n |[] -> (a, List.rev al)\n |x1::[] -> (a,List.rev (x1::al))\n |x1::(x2::tl) -> \n if x1+x2 printf \"%d \" x) al\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n\tlet n = read_int ()\n\tand m = read_int () \n\tand wyn = ref 0 in\n\n\tlet tab = Array.make (n + 1) 100000 in\n\n\tfor i = 0 to n - 1 do \n\t\ttab.(i) <- read_int ()\n\tdone;\n\n\tfor i = 1 to n - 1 do \n\t\tif tab.(i) + tab.(i - 1) < m then\n\t\t\twyn := !wyn + abs(tab.(i) - tab.(i - 1));\n\t\ttab.(i) <- m - tab.(i - 1);\n\tdone;\n\n\tprintf \"%d\\n\" !wyn;\n\t\n\tfor i = 0 to n - 1 do \n\t\tprintf \"%d \" tab.(i)\n\tdone;"}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n\tlet n = read_int ()\n\tand m = read_int () \n\tand wyn = ref 0 in\n\n\tlet tab = Array.make (n + 1) 100000 in\n\n\tfor i = 0 to n - 1 do \n\t\ttab.(i) <- read_int ()\n\tdone;\n\n\tfor i = 1 to n - 1 do \n\t\tif tab.(i) + tab.(i - 1) < m then\n\t\t\twyn := !wyn + abs(m - (tab.(i) + tab.(i - 1)));\n\t\ttab.(i) <- m - tab.(i - 1);\n\tdone;\n\n\tprintf \"%d\\n\" !wyn;\n\n\tfor i = 0 to n - 1 do \n\t\tprintf \"%d \" tab.(i)\n\tdone;"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let n = read () in\n let k = read () in \n let arr = Array.append (Array.make 1 k) (Array.init n (fun n -> read ())) in\n (n, k, arr)\n\nlet solve (n, k, arr) =\n let rec loop sum i = \n if i < n + 1\n then \n let a = arr.(i - 1) in\n let b = arr.(i) in\n if a + b < k \n then\n (arr.(i) <- k - a;\n let new_sum = sum + (k - a) in\n loop new_sum (i + 1))\n else\n loop sum (i + 1)\n else\n (sum, Array.sub arr 1 n)\n in loop 0 1\n\nlet print (sum, array) = \n Printf.printf \"%d\\n\" sum;\n Array.iter (Printf.printf \"%d \") array;\n Printf.printf \"\\n\"\n\nlet () = print (solve (input ()))\n"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let n = read () in\n let k = read () in \n let arr = Array.append (Array.make 1 k) (Array.init n (fun n -> read ())) in\n (n, k, arr)\n\nlet solve (n, k, arr) =\n let rec loop i = \n if i < n + 1\n then \n let a = arr.(i - 1) in\n let b = arr.(i) in\n if a + b < k \n then\n (arr.(i) <- k - a;\n loop (i + 1))\n else\n loop (i + 1)\n else\n Array.sub arr 1 n \n in loop 1\n\nlet print array = Array.iter (Printf.printf \"%d \") array;\n Printf.printf \"\\n\"\n\nlet () = print (solve (input ()))"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let n = read () in\n let k = read () in \n let arr = Array.append (Array.make 1 k) (Array.init n (fun n -> read ())) in\n (n, k, arr)\n\nlet solve (n, k, arr) =\n let rec loop sum i = \n if i < n + 1\n then \n let a = arr.(i - 1) in\n let b = arr.(i) in\n if a + b < k \n then\n (arr.(i) <- k - a - b;\n let new_sum = sum + (k - a) in\n loop new_sum (i + 1))\n else\n loop sum (i + 1)\n else\n (sum, Array.sub arr 1 n)\n in loop 0 1\n\nlet print (sum, array) = \n Printf.printf \"%d\\n\" sum;\n Array.iter (Printf.printf \"%d \") array;\n Printf.printf \"\\n\"\n\nlet () = print (solve (input ()))\n"}], "src_uid": "1956e31a9694b4fd7690f1a75028b9a1"} {"nl": {"description": "Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k\u2009+\u20091)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t\u2009-\u20091 gestures (if the icon is on the screen t), and then make another gesture \u2014 press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.", "input_spec": "The first line of the input contains three numbers n,\u2009m,\u2009k (1\u2009\u2264\u2009n,\u2009m,\u2009k\u2009\u2264\u2009105)\u00a0\u2014\u00a0the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains n integers, permutation a1,\u2009a2,\u2009...,\u2009an\u00a0\u2014\u00a0the initial order of icons from left to right in the menu (from the first to the last one), ai\u00a0\u2014\u00a0 is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai. The third line contains m integers b1,\u2009b2,\u2009...,\u2009bm(1\u2009\u2264\u2009bi\u2009\u2264\u2009n)\u00a0\u2014\u00a0the ids of the launched applications in the planned order. One application may be launched multiple times.", "output_spec": "Print a single number \u2014 the number of gestures that Anya needs to make to launch all the applications in the desired order.", "sample_inputs": ["8 3 3\n1 2 3 4 5 6 7 8\n7 8 1", "5 4 2\n3 1 5 2 4\n4 4 4 4"], "sample_outputs": ["7", "8"], "notes": "NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1,\u20092,\u20093, the second screen contains icons 4,\u20095,\u20096, the third screen contains icons 7,\u20098. After application 7 is launched, we get the new arrangement of the icons\u00a0\u2014\u00a0(123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n\n let a = Array.init n (fun _ -> -1 + read_int()) in\n let b = Array.init m (fun _ -> -1 + read_int()) in\n\n let index = Array.make n 0 in\n\n for i=0 to n-1 do\n index.(a.(i)) <- i\n done;\n\n let swap i = \n if i>0 then (\n let (x,y) = (a.(i), a.(i-1)) in\n index.(x) <- i-1;\n index.(y) <- i;\n a.(i) <- y;\n a.(i-1) <- x;\n )\n in\n\n let count = ref 0L in\n\n for j=0 to m-1 do\n let i = index.(b.(j)) in\n swap i;\n count := !count ++ (long (i/k)) ++ 1L\n done;\n\n printf \"%Ld\\n\" !count\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n\n let a = Array.init n (fun _ -> -1 + read_int()) in\n let b = Array.init m (fun _ -> -1 + read_int()) in\n\n let index = Array.make n 0 in\n\n for i=0 to n-1 do\n index.(a.(i)) <- i\n done;\n\n let swap i = \n if i>0 then (\n let (x,y) = (a.(i), a.(i-1)) in\n index.(x) <- i-1;\n index.(y) <- i;\n a.(i) <- y;\n a.(i-1) <- x;\n )\n in\n\n let count = ref 0 in\n\n for j=0 to m-1 do\n let i = index.(b.(j)) in\n swap i;\n count := !count + (i/k) + 1\n done;\n\n printf \"%d\\n\" !count\n"}], "src_uid": "3b0fb001333e53da458e1fb7ed760e32"} {"nl": {"description": "Stanley and Megan decided to shop in the \"Crossmarket\" grocery store, which can be represented as a matrix with $$$n$$$ rows and $$$m$$$ columns. Stanley and Megan can move to an adjacent cell using $$$1$$$ unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her portals with her, and she leaves one in each cell she visits (if there is no portal yet). If a person (Stanley or Megan) is in a cell with a portal, that person can use $$$1$$$ unit of power to teleport to any other cell with a portal, including Megan's starting cell.They decided to split up: Stanley will go from the upper-left cell (cell with coordinates $$$(1, 1)$$$) to the lower-right cell (cell with coordinates $$$(n, m)$$$), whilst Megan needs to get from the lower-left cell (cell with coordinates $$$(n, 1)$$$) to the upper-right cell (cell with coordinates $$$(1, m)$$$).What is the minimum total energy needed for them both to do that?Note that they can choose the time they move. Time does not affect energy.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The only line in the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 10^5$$$).", "output_spec": "For each test case print a single integer on a new line \u2013 the answer.", "sample_inputs": ["7\n\n7 5\n\n5 7\n\n1 1\n\n100000 100000\n\n57 228\n\n1 5\n\n5 1"], "sample_outputs": ["15\n15\n0\n299998\n340\n5\n5"], "notes": "Note In the first test case they can stick to the following plan: Megan (red circle) moves to the cell $$$(7, 3)$$$. Then she goes to the cell $$$(1, 3)$$$, and Stanley (blue circle) does the same. Stanley uses the portal in that cell (cells with portals are grey) to get to the cell $$$(7, 3)$$$. Then he moves to his destination\u00a0\u2014 cell $$$(7, 5)$$$. Megan also finishes her route and goes to the cell $$$(1, 5)$$$. The total energy spent is $$$(2 + 6) + (2 + 1 + 2) + (2)= 15$$$, which is our final answer."}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nmodule Opt = struct\n let get = function\n | None -> assert false\n | Some v -> v\nend\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\n\nlet read_long () = sf \" %Ld\" (fun x -> x)\n\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet i_bit x i = (x lsr i) land 1\n\nlet () =\n let t = read_int () in\n\n for _ = 1 to t do\n let n = read_int () in\n let m = read_int () in\n if (n = 1 && m = 1) then pf \"0\\n\"\n else if (n = 1 || m = 1) then pf \"%d\\n\" (max n m)\n else pf \"%d\\n\" (n + m - 2 + min n m)\n done;"}], "negative_code": [], "src_uid": "f9287ed16ef943006ffb821ba3678545"} {"nl": {"description": "Let's call a string good if its length is at least $$$2$$$ and all of its characters are $$$\\texttt{A}$$$ except for the last character which is $$$\\texttt{B}$$$. The good strings are $$$\\texttt{AB},\\texttt{AAB},\\texttt{AAAB},\\ldots$$$. Note that $$$\\texttt{B}$$$ is not a good string.You are given an initially empty string $$$s_1$$$.You can perform the following operation any number of times: Choose any position of $$$s_1$$$ and insert some good string in that position. Given a string $$$s_2$$$, can we turn $$$s_1$$$ into $$$s_2$$$ after some number of operations?", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single string $$$s_2$$$ ($$$1 \\leq |s_2| \\leq 2 \\cdot 10^5$$$). It is guaranteed that $$$s_2$$$ consists of only the characters $$$\\texttt{A}$$$ and $$$\\texttt{B}$$$. It is guaranteed that the sum of $$$|s_2|$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print \"YES\" (without quotes) if we can turn $$$s_1$$$ into $$$s_2$$$ after some number of operations, and \"NO\" (without quotes) otherwise. You can output \"YES\" and \"NO\" in any case (for example, strings \"yEs\", \"yes\" and \"Yes\" will be recognized as a positive response).", "sample_inputs": ["4\n\nAABAB\n\nABB\n\nAAAAAAAAB\n\nA"], "sample_outputs": ["YES\nNO\nYES\nNO"], "notes": "NoteIn the first test case, we transform $$$s_1$$$ as such: $$$\\varnothing \\to \\color{red}{\\texttt{AAB}} \\to \\texttt{A}\\color{red}{\\texttt{AB}}\\texttt{AB}$$$.In the third test case, we transform $$$s_1$$$ as such: $$$\\varnothing \\to \\color{red}{\\texttt{AAAAAAAAB}}$$$.In the second and fourth test case, it can be shown that it is impossible to turn $$$s_1$$$ into $$$s_2$$$."}, "positive_code": [{"source_code": "let read_word () = Scanf.scanf \" %s\" (fun x -> x);;\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\nlet rec create_char_list input input_length = function\r\n | 0 -> []\r\n | n -> (String.get input (input_length-n))::(create_char_list input input_length (n-1))\r\n;;\r\n\r\ntype acceptable_char = A | B | AB ;;\r\n\r\nlet rec run_case a_count = function\r\n | A, [x] -> false\r\n | _, [x] -> if (x=='B') then true else false\r\n | A, x::xs -> \r\n if (x=='A') then run_case (a_count+1) (AB, xs) \r\n else false\r\n | B, x::xs -> \r\n if (x=='B') then run_case (a_count-1) (A, xs) \r\n else false\r\n | AB, x::xs -> \r\n if (x=='B' && a_count==1) then run_case 0 (A, xs) \r\n else if (x=='B') then run_case (a_count-1) (AB, xs)\r\n else run_case (a_count+1) (AB, xs)\r\n;;\r\n\r\nlet rec run_cases = function\r\n | 0 -> 0\r\n | n -> \r\n let str_case = read_word () in \r\n let lst_case = create_char_list str_case (String.length str_case) (String.length str_case) in\r\n if (run_case 0 (A, lst_case)) then begin\r\n print_string \"YES\";\r\n print_newline ();\r\n run_cases (n-1)\r\n end\r\n else begin\r\n print_string \"NO\";\r\n print_newline ();\r\n run_cases (n-1)\r\n end\r\n;;\r\n\r\nlet num_cases = read_int () in\r\nrun_cases num_cases;;\r\n"}, {"source_code": "let n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let str = (input_line stdin) in\r\n let rep = ref true in \r\n if str.[0] = 'B' || str.[String.length str -1] = 'A' then rep := false \r\n else begin\r\n let tot = ref 0 in\r\n for j = 0 to String.length str -1 do\r\n if str.[j] = 'B' then incr tot else decr tot ;\r\n if !tot > 0 then rep := false\r\n done;\r\n end;\r\n if !rep then print_endline \"YES\" else print_endline \"NO\";\r\ndone;;"}], "negative_code": [{"source_code": "let read_word () = Scanf.scanf \" %s\" (fun x -> x);;\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\nlet rec create_char_list input input_length = function\r\n | 0 -> []\r\n | n -> (String.get input (input_length-n))::(create_char_list input input_length (n-1))\r\n;;\r\n\r\ntype acceptable_char = A | B | AB ;;\r\n\r\nlet rec run_case = function\r\n | A, [x] -> false\r\n | _, [x] -> if (x=='B') then true else false\r\n | A, x::xs -> if (x=='A') then run_case (AB, xs) else false\r\n | B, x::xs -> if (x=='B') then run_case (A, xs) else false\r\n | AB, x::xs -> run_case (AB, xs)\r\n;;\r\n\r\nlet rec run_cases = function\r\n | 0 -> 0\r\n | n -> \r\n let str_case = read_word () in \r\n let lst_case = create_char_list str_case (String.length str_case) (String.length str_case) in\r\n if (run_case (A, lst_case)) then begin\r\n print_string \"YES\";\r\n print_newline ();\r\n run_cases (n-1)\r\n end\r\n else begin\r\n print_string \"NO\";\r\n print_newline ();\r\n run_cases (n-1)\r\n end\r\n;;\r\n\r\nlet num_cases = read_int () in\r\nrun_cases num_cases;;\r\n"}, {"source_code": "let read_word () = Scanf.scanf \" %s\" (fun x -> x);;\r\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x);;\r\n\r\nlet rec create_char_list input input_length = function\r\n | 0 -> []\r\n | n -> (String.get input (input_length-n))::(create_char_list input input_length (n-1))\r\n;;\r\n\r\ntype acceptable_char = A | B | AB ;;\r\n\r\nlet rec run_case = function\r\n | A, [x] -> false\r\n | _, [x] -> if (x=='B') then true else false\r\n | A, x::xs -> if (x=='A') then run_case (AB, xs) else false\r\n | B, x::xs -> if (x=='B') then run_case (A, xs) else false\r\n | AB, x::xs -> if (x=='B') then run_case (A, xs) else run_case (AB, xs)\r\n;;\r\n\r\nlet rec run_cases = function\r\n | 0 -> 0\r\n | n -> \r\n let str_case = read_word () in \r\n let lst_case = create_char_list str_case (String.length str_case) (String.length str_case) in\r\n if (run_case (A, lst_case)) then begin\r\n print_string \"YES\";\r\n print_newline ();\r\n run_cases (n-1)\r\n end\r\n else begin\r\n print_string \"NO\";\r\n print_newline ();\r\n run_cases (n-1)\r\n end\r\n;;\r\n\r\nlet num_cases = read_int () in\r\nrun_cases num_cases;;\r\n\r\n"}, {"source_code": "let n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let str = (input_line stdin) in\r\n let rep = ref true in \r\n if str.[0] = 'B' || str.[String.length str -1] = 'A' then rep := false \r\n else begin\r\n for j = 0 to String.length str -2 do\r\n if str.[j] = 'B' && str.[j+1] = 'B' then rep := false\r\n done;\r\n end;\r\n if !rep then print_endline \"YES\" else print_endline \"NO\";\r\ndone;;"}], "src_uid": "0b9be2f076cfa13cdc76c489bf1ea416"} {"nl": {"description": "You came to the exhibition and one exhibit has drawn your attention. It consists of $$$n$$$ stacks of blocks, where the $$$i$$$-th stack consists of $$$a_i$$$ blocks resting on the surface.The height of the exhibit is equal to $$$m$$$. Consequently, the number of blocks in each stack is less than or equal to $$$m$$$.There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks. Find the maximum number of blocks you can remove such that the views for both the cameras would not change.Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 100\\,000$$$, $$$1 \\le m \\le 10^9$$$)\u00a0\u2014 the number of stacks and the height of the exhibit. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le m$$$)\u00a0\u2014 the number of blocks in each stack from left to right.", "output_spec": "Print exactly one integer\u00a0\u2014 the maximum number of blocks that can be removed.", "sample_inputs": ["5 6\n3 3 3 3 3", "3 5\n1 2 4", "5 5\n2 3 1 4 4", "1 1000\n548", "3 3\n3 1 1"], "sample_outputs": ["10", "3", "9", "0", "1"], "notes": "NoteThe following pictures illustrate the first example and its possible solution.Blue cells indicate removed blocks. There are $$$10$$$ blue cells, so the answer is $$$10$$$. "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,m = get_2_i64 0 in\n let a = input_i64_array n in\n sort compare a;\n let need = ref n in\n let height = fold_left (fun height v ->\n if height >= v then height\n else height + 1L\n ) 0L a in\n let mx = a.(i32 n-$1) in\n if mx > height then need += (mx - height);\n let sum = fold_left (+) 0L a in\n printf \"%Ld\\n\" @@ sum - !need\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "ffa76f2558c8a70ab5c1ecb9e8561f25"} {"nl": {"description": "A line on the plane is described by an equation Ax\u2009+\u2009By\u2009+\u2009C\u2009=\u20090. You are to find any point on this line, whose coordinates are integer numbers from \u2009-\u20095\u00b71018 to 5\u00b71018 inclusive, or to find out that such points do not exist.", "input_spec": "The first line contains three integers A, B and C (\u2009-\u20092\u00b7109\u2009\u2264\u2009A,\u2009B,\u2009C\u2009\u2264\u20092\u00b7109) \u2014 corresponding coefficients of the line equation. It is guaranteed that A2\u2009+\u2009B2\u2009>\u20090.", "output_spec": "If the required point exists, output its coordinates, otherwise output -1.", "sample_inputs": ["2 5 3"], "sample_outputs": ["6 -3"], "notes": null}, "positive_code": [{"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\n\nopen Int64\n\nlet blankinship a b =\n let rec go a b u v x y =\n if a = 0L then\n b,x,y\n else\n let q = div b a in\n go (sub b (mul q a)) a (sub x (mul q u)) (sub y (mul q v)) u v\n in go a b 1L 0L 0L 1L\n\nlet () =\n let a = read_int64 0 in\n let b = read_int64 0 in\n let c = read_int64 0 in\n let d,x,y = blankinship a b in\n if rem c d = 0L then\n let t = div (neg c) d in\n Printf.printf \"%Ld %Ld\\n\" (mul x t) (mul y t)\n else\n print_endline \"-1\"\n"}], "negative_code": [{"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\n\nopen Int64\n\nlet blankinship a b =\n let rec go a b u v x y =\n if a = 0L then\n b,x,y\n else\n let q = div b a in\n go (sub b (mul q a)) a (sub x (mul q u)) (sub y (mul q v)) u v\n in go a b 1L 0L 0L 1L\n\nlet () =\n let a = read_int64 0 in\n let b = read_int64 0 in\n let c = read_int64 0 in\n let d,x,y = blankinship a b in\n let t = div (neg c) d in\n Printf.printf \"%Ld %Ld\\n\" (mul x t) (mul y t)\n"}], "src_uid": "a01e1c545542c1641eca556439f0692e"} {"nl": {"description": "Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them\u00a0\u2014 those with biggest ti.Your task is to handle queries of two types: \"1 id\"\u00a0\u2014 Friend id becomes online. It's guaranteed that he wasn't online before. \"2 id\"\u00a0\u2014 Check whether friend id is displayed by the system. Print \"YES\" or \"NO\" in a separate line. Are you able to help Limak and answer all queries of the second type?", "input_spec": "The first line contains three integers n, k and q (1\u2009\u2264\u2009n,\u2009q\u2009\u2264\u2009150\u2009000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009min(6,\u2009n))\u00a0\u2014 the number of friends, the maximum number of displayed online friends and the number of queries, respectively. The second line contains n integers t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009ti\u2009\u2264\u2009109) where ti describes how good is Limak's relation with the i-th friend. The i-th of the following q lines contains two integers typei and idi (1\u2009\u2264\u2009typei\u2009\u2264\u20092,\u20091\u2009\u2264\u2009idi\u2009\u2264\u2009n)\u00a0\u2014 the i-th query. If typei\u2009=\u20091 then a friend idi becomes online. If typei\u2009=\u20092 then you should check whether a friend idi is displayed. It's guaranteed that no two queries of the first type will have the same idi becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (typei\u2009=\u20092) so the output won't be empty.", "output_spec": "For each query of the second type print one line with the answer\u00a0\u2014 \"YES\" (without quotes) if the given friend is displayed and \"NO\" (without quotes) otherwise.", "sample_inputs": ["4 2 8\n300 950 500 200\n1 3\n2 4\n2 3\n1 1\n1 2\n2 1\n2 2\n2 3", "6 3 9\n50 20 51 17 99 24\n1 3\n1 4\n1 5\n1 2\n2 4\n2 2\n1 1\n2 4\n2 3"], "sample_outputs": ["NO\nYES\nNO\nYES\nYES", "NO\nYES\nNO\nYES"], "notes": "NoteIn the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries: \"1 3\"\u00a0\u2014 Friend 3 becomes online. \"2 4\"\u00a0\u2014 We should check if friend 4 is displayed. He isn't even online and thus we print \"NO\". \"2 3\"\u00a0\u2014 We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print \"YES\". \"1 1\"\u00a0\u2014 Friend 1 becomes online. The system now displays both friend 1 and friend 3. \"1 2\"\u00a0\u2014 Friend 2 becomes online. There are 3 friends online now but we were given k\u2009=\u20092 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t1\u2009<\u2009t2,\u2009t3) so friend 1 won't be displayed \"2 1\"\u00a0\u2014 Print \"NO\". \"2 2\"\u00a0\u2014 Print \"YES\". \"2 3\"\u00a0\u2014 Print \"YES\". "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let k = read_int () in\n let q = read_int () in \n\n let t = Array.init n (fun _ -> read_int()) in\n\n let set = fold 0 (k-1) (fun i ac -> Pset.add (-i,0) ac) Pset.empty in \n\n ignore (\n fold 1 q (fun _ set ->\n match read_int() with\n\t| 1 ->\n\t let id = -1 + read_int() in\n\t let set = Pset.add (t.(id), id) set in\n\t let y = Pset.min_elt set in\n\t Pset.remove y set\n\t| 2 ->\n\t let id = -1 + read_int() in\n\t if Pset.mem (t.(id),id) set then printf \"YES\\n\" else printf \"NO\\n\";\n\t set\n\t| _ -> failwith \"bad input\"\n ) set\n )\n"}], "negative_code": [], "src_uid": "7c778289806ceed506543ef816c587c9"} {"nl": {"description": "Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros.", "input_spec": "A single input line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "Print a single integer \u2014 the answer to the problem without leading zeroes, or \"-1\" (without the quotes), if the number that meet the problem condition does not exist.", "sample_inputs": ["1", "5"], "sample_outputs": ["-1", "10080"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 248B PaperWork done *)\n\nopen Big_int;;\nopen List;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet sp = [2; 3; 5; 7];;\n\nlet cvo o p = (o * 10) mod p;;\n\n(* remainders 10^n from dividing by 2 3 5 7 *)\nlet rec ostat n p o = match n with \n| 0 -> o\n| _ -> ostat (n-1) p (cvo o p);; \n\nlet checkonep o p k = ((o + k) mod p) = 0;;\n\nlet rec checklp lo lp k = match lo with \n| [] -> true\n| h :: t -> (checkonep h (List.hd lp) k) && (checklp t (List.tl lp) k);;\n\nlet rec findfirst lo lp k = \n\tif checklp lo lp k then k\n\telse findfirst lo lp (k+1);;\n\t\nlet rec pow10 n = match n with\n| 0 -> Big_int.unit_big_int\n| _ ->\n\tif n < 10 then Big_int.mult_int_big_int 10 (pow10 (n-1))\n\telse \n\t\tlet a = n/2 in\n\t\tlet b = n - 2*a in\n\t\tlet pa = pow10 a in\n\t\tlet pb = pow10 b in\n\t\tBig_int.mult_big_int pa (Big_int.mult_big_int pa pb);;\n\nlet main () =\n\tlet n = gr() in\n\tlet lo = List.map (fun p -> ostat (n-1) p 1) sp in\n\tlet k = findfirst lo sp 1 in\n\tif n < 3 then print_string \"-1\"\n\telse begin\n\t\t(* print_string \"lo = \"; *)\n\t\t(* printlisti lo; *)\n\t\t(* print_string (\"\\nk = \" ^ (string_of_int k) ^ \"\\n\"); *)\n\t\tlet pown = pow10 (n-1) in\n\t\tlet ret = Big_int.add_int_big_int k pown in\n\t\tprint_string (Big_int.string_of_big_int ret)\n\tend;;\n\nmain();;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec pow n = if n=0 then 1 else \n let m = n/2 in\n let p = pow m in\n (if m+m=n then 1 else 10)*p*p mod 210\n\nlet () = \n let n = read_int() in\n if n<=2 then print_string \"-1\\n\"\n else if n=3 then print_string \"210\\n\"\n else \n let x = pow (n-1) in\n let y = 210-x in\n\tprint_string \"1\";\n\tfor i=2 to n-3 do\n\t print_string \"0\"\n\tdone;\n\tPrintf.printf \"%03d\\n\" y\n\t\n\t\n"}], "negative_code": [], "src_uid": "386345016773a06b9e190a55cc3717fa"} {"nl": {"description": "Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0,\u20091]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [k\u2009-\u2009d,\u2009k\u2009+\u2009d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k\u2009-\u2009d,\u2009k]. If she escapes to the right, her new interval will be [k,\u2009k\u2009+\u2009d].You are given a string s of length n. If the i-th character of s is \"l\" or \"r\", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.", "input_spec": "The input consists of only one line. The only line contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u2009106). Each character in s will be either \"l\" or \"r\".", "output_spec": "Output n lines \u2014 on the i-th line you should print the i-th stone's number from the left.", "sample_inputs": ["llrlr", "rrlll", "lrlrr"], "sample_outputs": ["3\n5\n4\n2\n1", "1\n2\n5\n4\n3", "2\n4\n5\n3\n1"], "notes": "NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1."}, "positive_code": [{"source_code": "module Pset = Set.Make (struct type t = int*int let compare = compare end)\nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let dir = read_string() in\n let n = String.length dir in\n\n let rec loop i s lo hi = if i=0 then s else (\n if dir.[i-1] = 'r' \n then loop (i-1) (Pset.add (lo-1, i) s) (lo-1) hi\n else loop (i-1) (Pset.add (hi+1, i) s) lo (hi+1)\n ) in\n \n let s = loop (n-1) (Pset.singleton (0,n)) 0 0 in\n\n Pset.iter (fun (i,j) -> Printf.printf \"%d\\n\" j) s;\n"}], "negative_code": [], "src_uid": "9d3c0f689ae1e6215448463def55df32"} {"nl": {"description": "Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.", "input_spec": "The first line of the input contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009m\u2009\u2264\u200910\u2009000, n\u2009\u2265\u20092m)\u00a0\u2014 the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.", "output_spec": "Print m lines. On the i-th line print the team of the i-th region\u00a0\u2014 the surnames of the two team members in an arbitrary order, or a single character \"?\" (without the quotes) if you need to spend further qualifying contests in the region.", "sample_inputs": ["5 2\nIvanov 1 763\nAndreev 2 800\nPetrov 1 595\nSidorov 1 790\nSemenov 2 503", "5 2\nIvanov 1 800\nAndreev 2 763\nPetrov 1 800\nSidorov 1 800\nSemenov 2 503"], "sample_outputs": ["Sidorov Ivanov\nAndreev Semenov", "?\nAndreev Semenov"], "notes": "NoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: \"Petrov\"-\"Sidorov\", \"Ivanov\"-\"Sidorov\", \"Ivanov\" -\"Petrov\", so it is impossible to determine a team uniquely."}, "positive_code": [{"source_code": "open Scanf \nopen Printf \n \nlet scan_int () = Scanf.scanf \" %d \" (fun i -> i);; \nlet scan_string () = Scanf.scanf \" %s\" (fun i -> i);; \n \ntype result = \n { \n name: string; \n score: int; \n };; \n \nlet insert_reg_team team res = \n let rec aux team res n = \n if n = 0 then [] \n else match team with \n | [] -> [] \n | h::t -> if res.score > h.score \n then res::(aux team {name=\"\"; score=(-1)} (n-1)) \n else h::(aux t res (n-1)) \n in aux team res 3;; \n \nlet () = \n let n = scan_int () in \n let m = scan_int () in \n \n let teams = Array.make m [{name= \"\"; score=(-1)}; {name= \"\"; score=(-1)}; {name= \"\"; score=(-1)}] in \n \n for i=1 to n do \n let name = scan_string () in \n let reg = scan_int () in \n let score = scan_int() in \n let team = Array.get teams (reg - 1) in \n let new_team = insert_reg_team team { name = name; score = score; } in \n Array.set teams (reg - 1) new_team \n done; \n (* Array.iter (fun team -> List.iter (fun p -> Printf.printf \"%s %d\\n\" p.name p.score) team; Printf.printf \"\\n\" ) t\neams; *) \n Array.iter (fun team -> \n let p1 = List.nth team 0 in \n let p2 = List.nth team 1 in \n if List.length team > 2 \n then \n let p3 = List.nth team 2 in \n if p3.score = p2.score \n then Printf.printf \"?\\n\" \n else Printf.printf \"%s %s\\n\" p1.name p2.name \n else Printf.printf \"%s %s\\n\" p1.name p2.name \n ) teams; \n "}], "negative_code": [{"source_code": "open Scanf \nopen Printf \n \nlet scan_int () = Scanf.scanf \" %d \" (fun i -> i);; \nlet scan_string () = Scanf.scanf \" %s\" (fun i -> i);; \n \ntype result = \n { \n name: string; \n score: int; \n };; \n \nlet insert_reg_team team res = \n let rec aux team res n = \n if n = 0 then [] \n else match team with \n | [] -> [] \n | h::t -> if res.score > h.score \n then res::(aux team {name=\"\"; score=0} (n-1)) \n else h::(aux t res (n-1)) \n in aux team res 3;; \n \nlet () = \n let n = scan_int () in \n let m = scan_int () in \n \n let teams = Array.make m [{name= \"\"; score= 0}; {name= \"\"; score= 0}; {name= \"\"; score= 0}] in \n \n for i=1 to n do \n let name = scan_string () in \n let reg = scan_int () in \n let score = scan_int() in \n let team = Array.get teams (reg - 1) in \n let new_team = insert_reg_team team { name = name; score = score; } in \n Array.set teams (reg - 1) new_team \n done; \n (* Array.iter (fun team -> List.iter (fun p -> Printf.printf \"%s %d\\n\" p.name p.score) team; Printf.printf \"\\n\" ) t\neams; *) \n Array.iter (fun team -> \n let p1 = List.nth team 0 in \n let p2 = List.nth team 1 in \n if List.length team > 2 \n then \n let p3 = List.nth team 2 in \n if p3.score = p2.score \n then Printf.printf \"?\\n\" \n else Printf.printf \"%s %s\\n\" p1.name p2.name \n else Printf.printf \"%s %s\\n\" p1.name p2.name \n ) teams; \n "}, {"source_code": "open Scanf \nopen Printf \n \nlet scan_int () = Scanf.scanf \" %d \" (fun i -> i);; \nlet scan_string () = Scanf.scanf \" %s\" (fun i -> i);; \n \ntype result = \n { \n name: string; \n score: int; \n };; \n \nlet insert_reg_team team res = \n let rec aux team res n = \n match team with \n | [] -> if n > 2 then [] else [res] \n | h :: t -> if h.score >= res.score \n then h :: (aux t res (n + 1)) \n else if n > 2 then team else res :: team \n in (aux team res 0);; \n \nlet () = \n let n = scan_int () in \n let m = scan_int () in \n \n let teams = Array.make m [] in \n \n for i=1 to n do \n let name = scan_string () in \n let reg = scan_int () in \n let score = scan_int() in \n let team = Array.get teams (reg - 1) in \n let new_team = insert_reg_team team { name = name; score = score; } in \n Array.set teams (reg - 1) new_team \n done; \n Array.iter (fun team -> \n let p1 = List.nth team 0 in \n let p2 = List.nth team 1 in \n if List.length team = 3 \n then \n let p3 = List.nth team 2 in \n if p3.score = p2.score \n then Printf.printf \"?\\n\" \n else Printf.printf \"%s %s\\n\" p1.name p2.name \n else Printf.printf \"%s %s\\n\" p1.name p2.name \n ) teams; "}, {"source_code": "open Scanf\nopen Printf\n\nlet scan_int () = Scanf.scanf \" %d \" (fun i -> i);;\nlet scan_string () = Scanf.scanf \" %s\" (fun i -> i);;\n\ntype result =\n {\n name: string;\n score: int;\n };;\n\nlet insert_reg_team team res =\n let rec aux team res n =\n match team with\n | [] -> if n > 2 then [] else [res]\n | h :: t -> if h.score >= res.score\n then h :: (aux t res (n + 1))\n else if n > 2 then team else res :: team\n in (aux team res 0);;\n\nlet () =\n let n = scan_int () in\n let m = scan_int () in\n\n let teams = Array.make m [] in\n\n for i=1 to n do\n let name = scan_string () in\n let reg = scan_int () in\n let score = scan_int() in\n let team = Array.get teams (reg - 1) in\n let new_team = insert_reg_team team { name = name; score = score; } in\n Array.set teams (reg - 1) new_team\n done;\n Array.iter (fun team ->\n let p1 = List.nth team 0 in\n let p2 = List.nth team 1 in\n if List.length team = 3\n then\n let p3 = List.nth team 2 in\n if p3.score = p2.score || p1.score = p2.score\n then Printf.printf \"?\\n\"\n else Printf.printf \"%s %s\\n\" p1.name p2.name\n else Printf.printf \"%s %s\\n\" p1.name p2.name\n ) teams;"}, {"source_code": "open Scanf\nopen Printf\n\nlet scan_int () = Scanf.scanf \" %d \" (fun i -> i);;\nlet scan_string () = Scanf.scanf \" %s\" (fun i -> i);;\n\ntype result =\n {\n name: string;\n score: int;\n };;\n\nlet insert_reg_team team res =\n let rec aux team res n =\n if n = 0 then []\n else match team with\n | [] -> []\n | h::t -> if res.score > h.score\n then res::(aux team {name=\"\"; score=0} (n-1))\n else h::(aux t res (n-1))\n in aux team res 3;;\n\nlet () =\n let n = scan_int () in\n let m = scan_int () in\n\n let teams = Array.make m [{name= \"\"; score= 0}; {name= \"\"; score= 0}; {name= \"\"; score= 0}] in\n\n for i=1 to n do\n let name = scan_string () in\n let reg = scan_int () in\n let score = scan_int() in\n let team = Array.get teams (reg - 1) in\n let new_team = insert_reg_team team { name = name; score = score; } in\n Array.set teams (reg - 1) new_team\n done;\n Array.iter (fun team -> List.iter (fun p -> Printf.printf \"%s %d\\n\" p.name p.score) team; Printf.printf \"\\n\" ) teams;\n Array.iter (fun team ->\n let p1 = List.nth team 0 in\n let p2 = List.nth team 1 in\n if List.length team > 2\n then\n let p3 = List.nth team 2 in\n if p3.score = p2.score\n then Printf.printf \"?\\n\"\n else Printf.printf \"%s %s\\n\" p1.name p2.name\n else Printf.printf \"%s %s\\n\" p1.name p2.name\n ) teams;\n"}], "src_uid": "a1ea9eb8db25289958a6f730c555362f"} {"nl": {"description": "Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following: if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \\cdot n_a \\cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.", "input_spec": "The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \\leq n \\leq 30$$$, $$$1 \\leq k \\leq 10^5$$$, $$$1 \\leq A,B \\leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \\ldots, a_{k}$$$ ($$$1 \\leq a_{i} \\leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.", "output_spec": "Output one integer \u2014 the minimum power needed to destroy the avengers base.", "sample_inputs": ["2 2 1 2\n1 3", "3 2 1 2\n1 7"], "sample_outputs": ["6", "8"], "notes": "NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \\cdot 2 \\cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \\cdot 1 \\cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \\cdot 1 \\cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$."}, "positive_code": [{"source_code": "(* keywords: binary search *)\n(* There's a bug.\n3 2 5 1\n7 8\n\nOutput\n8\n\nAnswer\n12\n\nChecker Log\nwrong answer 1st numbers differ - expected: '12', found: '8'\n\n*)\n\n(* 6 minutes after the end got this *)\n\nopen Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_long _ = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let (aa,bb) = read_pair () in\n let a = Array.init k (fun _ -> short (read_long() -- 1L)) in\n \n let h = Hashtbl.create 10 in\n \n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n for i=0 to k-1 do\n increment a.(i)\n done;\n\n let np = Hashtbl.length h in\n let p = Array.make np 0 in (* places where there is something *)\n let s = Array.make np 0 in\n\n let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in\n Array.sort compare p;\n for i=0 to np-1 do\n s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))\n done;\n\n (* s.(i) = the number of avengers in positions p.(0), p.(1) ... p.(i) *)\n\n let prefix_count x =\n (* the number of things at positions <= x *)\n let rec bsearch lo hi =\n (* know that p.(lo) <= x < p.(hi) *)\n if lo + 1 = hi then s.(lo) else\n\tlet m = (hi+lo)/2 in\n\tif p.(m) <= x then bsearch m hi else bsearch lo m\n in\n\n if x < p.(0) then 0\n else if x >= p.(np-1) then s.(np-1)\n else bsearch 0 (np-1)\n in\n\n let count_range x y = (* the number in range [x..y] *)\n (prefix_count y) - (prefix_count (x-1))\n in\n\n let rec eval i j =\n let len' = j-i in (* can't represent 2^30 in 31 bit signed arithmetic *)\n let c = count_range i j in\n if c = 0 then long aa else (\n let opt1 = (long bb) ** (long c) ** (1L++(long len')) in\n if len' = 0 then opt1 else \n\tlet opt2 = (eval i (i + len'/2)) ++ (eval (i+1+(len'/2)) j) in\n\tmin opt1 opt2\n )\n in\n\n let answer = eval 0 ((1 lsl n)-1) in (* have to avoid 1 lsl 30 *)\n printf \"%Ld\\n\" answer\n"}], "negative_code": [{"source_code": "(* keywords: binary search *)\n(* There's a bug.\n3 2 5 1\n7 8\n\nOutput\n8\n\nAnswer\n12\n\nChecker Log\nwrong answer 1st numbers differ - expected: '12', found: '8'\n\n*)\n\n(* 6 minutes after the end got this *)\n\nopen Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_long _ = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let (aa,bb) = read_pair () in\n let a = Array.init k (fun _ -> short (read_long() -- 1L)) in\n \n let h = Hashtbl.create 10 in\n \n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n for i=0 to k-1 do\n increment a.(i)\n done;\n\n let np = Hashtbl.length h in\n let p = Array.make np 0 in (* places where there is something *)\n let s = Array.make np 0 in\n\n let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in\n Array.sort compare p;\n for i=0 to np-1 do\n s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))\n done;\n\n (* s.(i) = the number of avengers in positions p.(0), p.(1) ... p.(i) *)\n\n let prefix_count x =\n (* the number of things at positions <= x *)\n let rec bsearch lo hi =\n (* know that p.(lo) <= x < p.(hi) *)\n if lo + 1 = hi then s.(lo) else\n\tlet m = (hi+lo)/2 in\n\tif p.(m) < x then bsearch m hi else bsearch lo m\n in\n\n if x < p.(0) then 0\n else if x >= p.(np-1) then s.(np-1)\n else bsearch 0 (np-1)\n in\n\n let count_range x y = (* the number in range [x..y] *)\n (prefix_count y) - (prefix_count (x-1))\n in\n\n let rec eval i j =\n let len = j-i+1 in\n let c = count_range i j in\n if c = 0 then long aa else (\n let opt1 = (long bb) ** (long c) ** (long len) in\n if len = 1 then opt1 else \n\tlet opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in\n\tmin opt1 opt2\n )\n in\n\n let answer = eval 0 ((1 lsl n)-1) in (* have to avoid 1 lsl 30 *)\n printf \"%Ld\\n\" answer\n"}, {"source_code": "(* keywords: binary search *)\n(* There's a bug.\n3 2 5 1\n7 8\n\nOutput\n8\n\nAnswer\n12\n\nChecker Log\nwrong answer 1st numbers differ - expected: '12', found: '8'\n\n*)\n\n(* 6 minutes after the end got this *)\n\nopen Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let (aa,bb) = read_pair () in\n let a = Array.init k (fun _ -> -1+read_int()) in\n \n let h = Hashtbl.create 10 in\n \n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n for i=0 to k-1 do\n increment a.(i)\n done;\n\n let np = Hashtbl.length h in\n let p = Array.make np 0 in (* places where there is something *)\n let s = Array.make np 0 in\n\n let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in\n Array.sort compare p;\n for i=0 to np-1 do\n s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))\n done;\n\n (* s.(i) = the number of avengers in positions p.(0), p.(1) ... p.(i) *)\n\n let prefix_count x =\n (* the number of things at positions <= x *)\n let rec bsearch lo hi =\n (* know that p.(lo) <= x < p.(hi) *)\n if lo + 1 = hi then s.(lo) else\n\tlet m = lo + (hi-lo)/2 in\n\tif p.(m) < x then bsearch m hi else bsearch lo m\n in\n\n if x < p.(0) then 0\n else if x >= p.(np-1) then s.(np-1)\n else bsearch 0 (np-1)\n in\n\n let count_range x y = (* the number in range [x..y] *)\n (prefix_count y) - (prefix_count (x-1))\n in\n\n let rec eval i j =\n let len = j-i+1 in\n let c = count_range i j in\n if c = 0 then long aa else (\n let opt1 = (long bb) ** (long c) ** (long len) in\n if len = 1 then opt1 else \n\tlet opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in\n\tmin opt1 opt2\n )\n in\n\n let answer = eval 0 ((1 lsl n)-1) in (* have to avoid 1 lsl 30 *)\n printf \"%Ld\\n\" answer\n"}, {"source_code": "(* keywords: binary search *)\n(* There's a bug.\n3 2 5 1\n7 8\n\nOutput\n8\n\nAnswer\n12\n\nChecker Log\nwrong answer 1st numbers differ - expected: '12', found: '8'\n\n*)\n\n(* 6 minutes after the end got this *)\n\nopen Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let (aa,bb) = read_pair () in\n let a = Array.init k (fun _ -> -1+read_int()) in\n \n let h = Hashtbl.create 10 in\n \n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n for i=0 to k-1 do\n increment a.(i)\n done;\n\n let np = Hashtbl.length h in\n let p = Array.make np 0 in (* places where there is something *)\n let s = Array.make np 0 in\n\n let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in\n Array.sort compare p;\n for i=0 to np-1 do\n s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))\n done;\n\n (* s.(i) = p.(0) + a.(1) + ... + a.(i) *)\n\n let prefix_count x =\n (* the number of things at positions <= x *)\n let rec bsearch lo hi =\n (* know that p.(lo) < x <= p.(hi) *)\n if lo + 1 = hi then if x=p.(hi) then s.(hi) else s.(lo) else (\n\tlet m = lo + (hi-lo)/2 in\n\tif p.(m) < x then bsearch m hi else bsearch lo m\n )\n in\n\n if x < p.(0) then 0 else if x=p.(0) then s.(0) else bsearch 0 (np-1)\n in\n\n let count_range x y =\n (prefix_count y) - (prefix_count (x-1))\n in\n\n let rec eval i j =\n let len = j-i+1 in\n let c = count_range i j in\n if c = 0 then long aa else (\n let opt1 = (long bb) ** (long c) ** (long len) in\n if len = 1 then opt1 else \n\tlet opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in\n\tmin opt1 opt2\n )\n in\n\n let answer = eval 0 ((1 lsl n)-1) in\n printf \"%Ld\\n\" answer\n"}, {"source_code": "(* keywords: binary search *)\n\n(* 6 minutes after the end got this *)\n\nopen Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let (aa,bb) = read_pair () in\n let a = Array.init k read_int in\n \n let h = Hashtbl.create 10 in\n \n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n for i=0 to k-1 do\n increment a.(i)\n done;\n\n let np = Hashtbl.length h in\n let p = Array.make np 0 in (* places where there is something *)\n let s = Array.make np 0 in\n\n let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in\n Array.sort compare p;\n for i=0 to np-1 do\n s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))\n done;\n\n (* s.(i) = p.(0) + a.(1) + ... + a.(i) *)\n\n let prefix_count x =\n (* the number of things at positions <= x *)\n let rec bsearch lo hi =\n (* know that p.(lo) < x <= p.(hi) *)\n if lo + 1 = hi then if x=p.(hi) then s.(hi) else s.(lo) else (\n\tlet m = lo + (hi-lo)/2 in\n\tif p.(m) < x then bsearch m hi else bsearch lo m\n )\n in\n\n if x < p.(0) then 0 else if x=p.(0) then s.(0) else bsearch 0 (np-1)\n in\n\n let count_range x y =\n (prefix_count y) - (prefix_count (x-1))\n in\n\n let rec eval i j =\n let len = j-i+1 in\n let c = count_range i j in\n if c = 0 then long aa else (\n let opt1 = (long bb) ** (long c) ** (long len) in\n if len = 1 then opt1 else \n\tlet opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in\n\tmin opt1 opt2\n )\n in\n\n let answer = eval 0 ((1 lsl n)-1) in\n printf \"%Ld\\n\" answer\n"}, {"source_code": "(* keywords: binary search *)\n(* There's a bug.\n3 2 5 1\n7 8\n\nOutput\n8\n\nAnswer\n12\n\nChecker Log\nwrong answer 1st numbers differ - expected: '12', found: '8'\n\n*)\n\n(* 6 minutes after the end got this *)\n\nopen Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,k) = read_pair () in\n let (aa,bb) = read_pair () in\n let a = Array.init k read_int in\n \n let h = Hashtbl.create 10 in\n \n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n for i=0 to k-1 do\n increment a.(i)\n done;\n\n let np = Hashtbl.length h in\n let p = Array.make np 0 in (* places where there is something *)\n let s = Array.make np 0 in\n\n let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in\n Array.sort compare p;\n for i=0 to np-1 do\n s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))\n done;\n\n (* s.(i) = the number of avengers in positions p.(0), p.(1) ... p.(i) *)\n\n let prefix_count x =\n (* the number of things at positions <= x *)\n let rec bsearch lo hi =\n (* know that p.(lo) < x <= p.(hi) *)\n if lo + 1 = hi then if x = p.(hi) then s.(hi) else s.(lo) else\n\tlet m = lo + (hi-lo)/2 in\n\tif p.(m) < x then bsearch m hi else bsearch lo m\n in\n\n if x < p.(0) then 0\n else if x=p.(0) then s.(0)\n else if x > p.(np-1) then s.(np-1) else bsearch 0 (np-1)\n in\n\n let count_range x y = (* the number in range [x..y] *)\n (prefix_count y) - (prefix_count (x-1))\n in\n\n let rec eval i j =\n let len = j-i+1 in\n let c = count_range i j in\n if c = 0 then long aa else (\n let opt1 = (long bb) ** (long c) ** (long len) in\n if len = 1 then opt1 else \n\tlet opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in\n\tmin opt1 opt2\n )\n in\n\n let answer = eval 1 (1 lsl n) in\n printf \"%Ld\\n\" answer\n"}], "src_uid": "4695aa2b3590a0734ef2c6c580e471a9"} {"nl": {"description": "An array $$$b$$$ is called to be a subarray of $$$a$$$ if it forms a continuous subsequence of $$$a$$$, that is, if it is equal to $$$a_l$$$, $$$a_{l + 1}$$$, $$$\\ldots$$$, $$$a_r$$$ for some $$$l, r$$$.Suppose $$$m$$$ is some known constant. For any array, having $$$m$$$ or more elements, let's define it's beauty as the sum of $$$m$$$ largest elements of that array. For example: For array $$$x = [4, 3, 1, 5, 2]$$$ and $$$m = 3$$$, the $$$3$$$ largest elements of $$$x$$$ are $$$5$$$, $$$4$$$ and $$$3$$$, so the beauty of $$$x$$$ is $$$5 + 4 + 3 = 12$$$. For array $$$x = [10, 10, 10]$$$ and $$$m = 2$$$, the beauty of $$$x$$$ is $$$10 + 10 = 20$$$.You are given an array $$$a_1, a_2, \\ldots, a_n$$$, the value of the said constant $$$m$$$ and an integer $$$k$$$. Your need to split the array $$$a$$$ into exactly $$$k$$$ subarrays such that: Each element from $$$a$$$ belongs to exactly one subarray. Each subarray has at least $$$m$$$ elements. The sum of all beauties of $$$k$$$ subarrays is maximum possible.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le m$$$, $$$2 \\le k$$$, $$$m \\cdot k \\le n$$$)\u00a0\u2014 the number of elements in $$$a$$$, the constant $$$m$$$ in the definition of beauty and the number of subarrays to split to. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$).", "output_spec": "In the first line, print the maximum possible sum of the beauties of the subarrays in the optimal partition. In the second line, print $$$k-1$$$ integers $$$p_1, p_2, \\ldots, p_{k-1}$$$ ($$$1 \\le p_1 < p_2 < \\ldots < p_{k-1} < n$$$) representing the partition of the array, in which: All elements with indices from $$$1$$$ to $$$p_1$$$ belong to the first subarray. All elements with indices from $$$p_1 + 1$$$ to $$$p_2$$$ belong to the second subarray. $$$\\ldots$$$. All elements with indices from $$$p_{k-1} + 1$$$ to $$$n$$$ belong to the last, $$$k$$$-th subarray. If there are several optimal partitions, print any of them.", "sample_inputs": ["9 2 3\n5 2 5 2 4 1 1 3 2", "6 1 4\n4 1 3 2 2 3", "2 1 2\n-1000000000 1000000000"], "sample_outputs": ["21\n3 5", "12\n1 3 5", "0\n1"], "notes": "NoteIn the first example, one of the optimal partitions is $$$[5, 2, 5]$$$, $$$[2, 4]$$$, $$$[1, 1, 3, 2]$$$. The beauty of the subarray $$$[5, 2, 5]$$$ is $$$5 + 5 = 10$$$. The beauty of the subarray $$$[2, 4]$$$ is $$$2 + 4 = 6$$$. The beauty of the subarray $$$[1, 1, 3, 2]$$$ is $$$3 + 2 = 5$$$. The sum of their beauties is $$$10 + 6 + 5 = 21$$$.In the second example, one optimal partition is $$$[4]$$$, $$$[1, 3]$$$, $$$[2, 2]$$$, $$$[3]$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n let k = read_int () in\n let b = Array.init n read_int in\n let a = Array.init n (fun i -> (b.(i), i)) in\n Array.sort (fun x y -> compare y x) a;\n\n let mark = Array.make n 0 in\n\n for i=0 to m*k-1 do\n mark.(snd a.(i)) <- 1\n done;\n\n let p = Array.make (k+1) (-1) in\n \n for j=1 to k-1 do\n let rec loop i need = \n let need = need - mark.(i) in\n if need = 0 then p.(j) <- i else loop (i+1) need\n in\n loop (p.(j-1)+1) m\n done;\n\n let total = sum 0 (n-1) (fun i ->\n long (mark.(i) * b.(i))\n ) in\n\n printf \"%Ld\\n\" total;\n \n for j=1 to k-1 do\n printf \"%d \" (p.(j)+1)\n done;\n\n print_newline()\n"}], "negative_code": [], "src_uid": "e9cf68a68b55fe075099c384cb6a7e9e"} {"nl": {"description": "Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of snow drifts. Each of the following n lines contains two integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u20091000) \u2014 the coordinates of the i-th snow drift. Note that the north direction coin\u0441ides with the direction of Oy axis, so the east direction coin\u0441ides with the direction of the Ox axis. All snow drift's locations are distinct.", "output_spec": "Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.", "sample_inputs": ["2\n2 1\n1 2", "2\n2 1\n4 1"], "sample_outputs": ["1", "0"], "notes": null}, "positive_code": [{"source_code": "open Scanf;;\nopen Printf;;\n\nmodule UF = struct\n type t = int array\n\n let make n = Array.make n (-1)\n\n let rec root x uf =\n if uf.(x) < 0 then x \n else (uf.(x) <- root uf.(x) uf; uf.(x))\n\n let union_set x y uf =\n let x = root x uf and\n y = root y uf in\n begin\n if x != y then \n let x, y = if uf.(y) < uf.(x) then y, x else x, y in\n begin\n uf.(x) <- uf.(x) + uf.(y);\n uf.(y) <- x\n end\n end;\n x != y\n\n let find_set x y uf = root x uf = root y uf\n\n let size x uf = - uf.(x)\nend\n\nmodule S = Set.Make(struct \n type t = int \n let compare x y = x - y\nend)\n\nlet input () =\n let n = scanf \"%d \" (fun x -> x) in\n let arr = Array.make n (0, 0) in\n for i = 0 to (n - 1) do\n arr.(i) <- scanf \"%d %d \" (fun x y -> (x, y))\n done;\n (n, arr)\n\nlet solve (n, arr) =\n let uf = UF.make n in\n for i = 0 to (n - 1) do\n let (x1, y1) = arr.(i) in\n for j = 0 to (i - 1) do\n let (x2, y2) = arr.(j) in\n if x1 = x2 || y1 = y2 then\n ignore(UF.union_set i j uf)\n done\n done;\n\n let s = ref S.empty in\n for i = 0 to (n - 1) do\n s := S.add (UF.root i uf) !s\n done;\n S.cardinal !s\n\nlet () = \n let inp = input () in\n let n = solve inp in\n printf \"%d\\n\" (n - 1)\n"}], "negative_code": [], "src_uid": "cb4dbff31d967c3dab8fe0495eb871dc"} {"nl": {"description": "Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string\u00a0\u2014\u00a0each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s|\u2009-\u2009ai\u2009+\u20091. It is guaranteed that 2\u00b7ai\u2009\u2264\u2009|s|.You face the following task: determine what Pasha's string will look like after m days.", "input_spec": "The first line of the input contains Pasha's string s of length from 2 to 2\u00b7105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105)\u00a0\u2014\u00a0 the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1\u2009\u2264\u2009ai; 2\u00b7ai\u2009\u2264\u2009|s|)\u00a0\u2014\u00a0the position from which Pasha started transforming the string on the i-th day.", "output_spec": "In the first line of the output print what Pasha's string s will look like after m days.", "sample_inputs": ["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"], "sample_outputs": ["aedcbf", "vwxyz", "fbdcea"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let m = String.length s in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a;\n let b = ref false in\n let pos = ref 0 in\n for i = 0 to m / 2 - 1 do\n\twhile !pos < n && a.(!pos) <= i + 1 do\n\t incr pos;\n\t b := not !b;\n\tdone;\n\tif !b then (\n\t let tmp = s.[i] in\n\t s.[i] <- s.[m - i - 1];\n\t s.[m - i - 1] <- tmp;\n\t)\n done;\n Printf.printf \"%s\\n\" s;\n"}], "negative_code": [], "src_uid": "9d46ae53e6dc8dc54f732ec93a82ded3"} {"nl": {"description": "Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?", "input_spec": "First line of input contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of players. The second line contains n integer numbers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the bids of players.", "output_spec": "Print \"Yes\" (without the quotes) if players can make their bids become equal, or \"No\" otherwise.", "sample_inputs": ["4\n75 150 75 50", "3\n100 150 250"], "sample_outputs": ["Yes", "No"], "notes": "NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\n(* returns true iff f t = true for all i <= t <= j *)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in \n let a = Array.init n (fun _ -> read_int()) in\n\n let rec remove d x = if x mod d = 0 then remove d (x/d) else x in\n\n for i=0 to n-1 do\n a.(i) <- remove 3 (remove 2 a.(i))\n\n done;\n\n if forall 1 (n-1) (fun i -> (a.(0) = a.(i))) \n then printf \"Yes\\n\" else printf \"No\\n\""}, {"source_code": "module IntMap = Map.Make(struct type t = int let compare = compare end)\n\n(* factorise : int -> (int * int) list *)\nlet reachable n =\n let rec aux d n =\n if n = 1 then true else\n if d > 3 then false else\n if n mod d = 0 then aux d (n / d) else aux (d + 1) n\n in\n aux 2 n\n\nlet rec gcd n m =\n if m = 0 then n else gcd m (n mod m)\n\nlet () = Scanf.scanf \"%d\\n\" (fun n ->\n let a = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n (* calculate lcm *)\n let g = Array.fold_left (fun a b -> gcd a b)\n a.(0) (Array.sub a 1 (Array.length a - 1))\n in\n let ap = Array.map (fun n -> reachable (n / g)) a in\n print_endline (if List.for_all (fun x -> x) (Array.to_list ap) then \"Yes\" else \"No\"))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet id x = x\n\nlet rec gen_norm k x = if x mod k = 0 then gen_norm k (x / k) else x\nlet norm x = gen_norm 2 (gen_norm 3 x)\n\nlet () =\n let n = scanf \" %d\" id in\n let a = scanf \" %d\" norm in\n let rec check = function\n | 0 -> true\n | n -> (scanf \" %d\" norm = a) && check (n - 1) in\n printf \"%s\\n\" (if check (n - 1) then \"Yes\" else \"No\")\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let rec remove d x = if x mod d = 0 then remove d (x/d) else x in\n\n for i=0 to n-1 do\n a.(i) <- remove 3 (remove 2 a.(i))\n done;\n\n if forall 1 (n-1) (fun i -> a.(0) = a.(i)) then printf \"Yes\\n\" else printf \"No\\n\"\n\n \n"}], "negative_code": [], "src_uid": "2bb893703cbffe9aeaa0bed02f42a05c"} {"nl": {"description": "Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n space-separated integers h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u2009109) \u2014 sizes of towers.", "output_spec": "Print the number of operations needed to destroy all towers.", "sample_inputs": ["6\n2 1 4 6 2 2", "7\n3 3 3 1 3 3 3"], "sample_outputs": ["3", "2"], "notes": "NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let h = Array.make (n+2) 0 in\n\n for i=1 to n do\n h.(i) <- read_int()\n done;\n\n for i=1 to n do (* L-->R pass *)\n h.(i) <- min h.(i) (1 + h.(i-1))\n done;\n\n for i=n downto 1 do (* R-->L pass *)\n h.(i) <- min h.(i) (1 + h.(i+1))\n done;\n\n let answer = maxf 1 n (fun i-> h.(i)) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "a548737890b4bf322d0f8989e5cd25ac"} {"nl": {"description": "Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point $$$T$$$, which coordinates to be found out.Bob travelled around the world and collected clues of the treasure location at $$$n$$$ obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?As everyone knows, the world is a two-dimensional plane. The $$$i$$$-th obelisk is at integer coordinates $$$(x_i, y_i)$$$. The $$$j$$$-th clue consists of $$$2$$$ integers $$$(a_j, b_j)$$$ and belongs to the obelisk $$$p_j$$$, where $$$p$$$ is some (unknown) permutation on $$$n$$$ elements. It means that the treasure is located at $$$T=(x_{p_j} + a_j, y_{p_j} + b_j)$$$. This point $$$T$$$ is the same for all clues.In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.Note that you don't need to find the permutation. Permutations are used only in order to explain the problem.", "input_spec": "The first line contains an integer $$$n$$$\u00a0($$$1 \\leq n \\leq 1000$$$)\u00a0\u2014 the number of obelisks, that is also equal to the number of clues. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$\u00a0($$$-10^6 \\leq x_i, y_i \\leq 10^6$$$)\u00a0\u2014 the coordinates of the $$$i$$$-th obelisk. All coordinates are distinct, that is $$$x_i \\neq x_j$$$ or $$$y_i \\neq y_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \\neq j$$$. Each of the next $$$n$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$\u00a0($$$-2 \\cdot 10^6 \\leq a_i, b_i \\leq 2 \\cdot 10^6$$$)\u00a0\u2014 the direction of the $$$i$$$-th clue. All coordinates are distinct, that is $$$a_i \\neq a_j$$$ or $$$b_i \\neq b_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \\neq j$$$. It is guaranteed that there exists a permutation $$$p$$$, such that for all $$$i,j$$$ it holds $$$\\left(x_{p_i} + a_i, y_{p_i} + b_i\\right) = \\left(x_{p_j} + a_j, y_{p_j} + b_j\\right)$$$. ", "output_spec": "Output a single line containing two integers $$$T_x, T_y$$$\u00a0\u2014 the coordinates of the treasure. If there are multiple answers, you may print any of them.", "sample_inputs": ["2\n2 5\n-6 4\n7 -2\n-1 -3", "4\n2 2\n8 2\n-7 0\n-2 6\n1 -14\n16 -12\n11 -18\n7 -14"], "sample_outputs": ["1 2", "9 -12"], "notes": "NoteAs $$$n = 2$$$, we can consider all permutations on two elements. If $$$p = [1, 2]$$$, then the obelisk $$$(2, 5)$$$ holds the clue $$$(7, -2)$$$, which means that the treasure is hidden at $$$(9, 3)$$$. The second obelisk $$$(-6, 4)$$$ would give the clue $$$(-1,-3)$$$ and the treasure at $$$(-7, 1)$$$. However, both obelisks must give the same location, hence this is clearly not the correct permutation.If the hidden permutation is $$$[2, 1]$$$, then the first clue belongs to the second obelisk and the second clue belongs to the first obelisk. Hence $$$(-6, 4) + (7, -2) = (2,5) + (-1,-3) = (1, 2)$$$, so $$$T = (1,2)$$$ is the location of the treasure. In the second sample, the hidden permutation is $$$[2, 3, 4, 1]$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\nmodule IMap = Map.Make (struct\n type t = int64 * int64\n let compare = compare\nend)\nlet () =\n let n = gi 0 in\n let x,y = make (i32 n) 0L, make (i32 n) 0L in\n repi 1 (i32 n) (fun i ->\n let p,q = g2 0 in\n x.(i-$1) <- p; y.(i-$1) <- q;\n );\n let a,b = make (i32 n) 0L, make (i32 n) 0L in\n let m = ref IMap.empty in\n repi 1 (i32 n) (fun i ->\n let p,q = g2 0 in\n a.(i-$1) <- p; b.(i-$1) <- q;\n m := IMap.add (p,q) (i-$1) !m;\n );\n repi 1 (i32 n) (fun i ->\n let a,b = a.(i-$1),b.(i-$1) in\n let p,q = x.(0) + a, y.(0) + b in\n let used = make (i32 n) false in\n let f = ref true in\n repi 1 (i32 n) (fun i ->\n let x,y = x.(i-$1),y.(i-$1) in\n let a0,b0 = p-x, q-y in\n try\n let j = IMap.find (a0,b0) !m in\n if used.(j) then raise Not_found\n else (\n used.(j) <- true;\n )\n with _ -> (\n f := false;\n )\n );\n if !f then (\n printf \"%Ld %Ld\\n\" p q; exit 0\n )\n )\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "ba526a7f29cf7f83afa0b71bcd06e86b"} {"nl": {"description": "Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $$$26$$$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $$$s$$$ appeared on the screen. When Polycarp presses a button with character $$$c$$$, one of the following events happened: if the button was working correctly, a character $$$c$$$ appeared at the end of the string Polycarp was typing; if the button was malfunctioning, two characters $$$c$$$ appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $$$\\rightarrow$$$ abb $$$\\rightarrow$$$ abba $$$\\rightarrow$$$ abbac $$$\\rightarrow$$$ abbaca $$$\\rightarrow$$$ abbacabb $$$\\rightarrow$$$ abbacabba.You are given a string $$$s$$$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases in the input. Then the test cases follow. Each test case is represented by one line containing a string $$$s$$$ consisting of no less than $$$1$$$ and no more than $$$500$$$ lowercase Latin letters.", "output_spec": "For each test case, print one line containing a string $$$res$$$. The string $$$res$$$ should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, $$$res$$$ should be empty.", "sample_inputs": ["4\na\nzzaaz\nccff\ncbddbb"], "sample_outputs": ["a\nz\n\nbc"], "notes": null}, "positive_code": [{"source_code": "module S = Set.Make(struct type t = char let compare = compare end)\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let s = input_line stdin in\n let n = String.length s in\n if n = 1 then\n Format.printf \"%c@.\" s.[0]\n else\n let i = ref 0 in\n let l = ref S.empty in\n while !i <= (n - 2) do\n if s.[!i] = s.[!i+1] then\n i := !i +2\n else begin\n l := S.add s.[!i] !l;\n i := !i + 1\n end;\n done;\n if !i < n then\n l := S.add s.[!i] !l;\n let rec pp fmt = function\n | [] -> Format.printf \"@.\"\n | x::l -> Format.printf \"%c%a\" x pp l\n in\n Format.printf \"%a\" pp (List.sort compare (S.elements !l));\n done\n"}], "negative_code": [{"source_code": "module S = Set.Make(struct type t = char let compare = compare end)\n\nlet to_set string =\n let s = ref S.empty in\n String.iter (fun c -> s := S.add c !s) string;\n !s\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let s = input_line stdin in\n let n = String.length s in\n if n = 1 then\n Format.printf \"%c@.\" s.[0]\n else\n let i = ref 0 in\n let l = ref [] in\n while !i <= (n - 2) do\n if s.[!i] = s.[!i+1] then\n i := !i +2\n else begin\n l := s.[!i]::!l;\n i := !i + 1\n end;\n done;\n if !i < n then\n l := s.[!i]::!l;\n let rec pp fmt = function\n | [] -> Format.printf \"@.\"\n | x::l -> Format.printf \"%c%a\" x pp l\n in\n Format.printf \"%a\" pp !l;\n done\n"}], "src_uid": "586a15030f4830c68f2ea1446e80028c"} {"nl": {"description": "Two integers x and y are compatible, if the result of their bitwise \"AND\" equals zero, that is, a & b\u2009=\u20090. For example, numbers 90 (10110102) and 36 (1001002) are compatible, as 10110102 & 1001002\u2009=\u200902, and numbers 3 (112) and 6 (1102) are not compatible, as 112 & 1102\u2009=\u2009102.You are given an array of integers a1,\u2009a2,\u2009...,\u2009an. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of elements in the given array. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u20094\u00b7106) \u2014 the elements of the given array. The numbers in the array can coincide.", "output_spec": "Print n integers ansi. If ai isn't compatible with any other element of the given array a1,\u2009a2,\u2009...,\u2009an, then ansi should be equal to -1. Otherwise ansi is any such number, that ai & ansi\u2009=\u20090, and also ansi occurs in the array a1,\u2009a2,\u2009...,\u2009an.", "sample_inputs": ["2\n90 36", "4\n3 6 3 6", "5\n10 6 9 8 2"], "sample_outputs": ["36 90", "-1 -1 -1 -1", "-1 8 2 2 8"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let rdint =\n let l = ref 0 in\n let i = ref 0 in\n let s = String.create 65536 in\n let refill () =\n let n = input stdin s 0 65536 in\n i := 0;\n l := n in\n refill ();\n\n fun () ->\n let rec loop2 j k t f =\n let fin j t f =\n let _ = i := j in\n t * f in\n\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop2 !i !l t f else fin j t f\n ) else if s.[j] >= '0' && s.[j] <= '9' then\n loop2 (j + 1) k (t * 10 + Char.code s.[j] - 48) f\n else fin j t f in\n\n let rec loop1 j k =\n if j = k then (\n let _ = refill () in\n if !l > 0 then loop1 !i !l else 0\n ) else if s.[j] = '-' then loop2 (j + 1) k 0 (-1)\n else if s.[j] >= '0' && s.[j] <= '9' then loop2 (j + 1) k (Char.code s.[j] - 48) 1\n else loop1 (j + 1) k in\n loop1 !i !l\n in\n let main () =\n let n = rdint () in\n let bit = Array.create 4194303 (-1) in \n let arr = Array.init n (fun _ -> let k = rdint () in bit.(k) <- k; k) in\n Array.iteri (fun s v ->\n if v >= 0 then\n for i = 0 to 21 do\n if (1 lsl i) land s == 0 then\n let q = s lor (1 lsl i) in\n if q < 4194303 then bit.(q) <- v\n done) bit;\n Array.iteri (fun i v ->\n let t = (lnot v) land 0x3FFFFF in\n Printf.printf \"%s%d\" (if i > 0 then \" \" else \"\") bit.(t)) arr;\n print_newline ()\n in\n main ()\n\n"}], "negative_code": [], "src_uid": "50f58b33d6ed6c591da2838fdd103bde"} {"nl": {"description": "As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the i-th friend sent to Alexander a card number i.Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules: He will never send to a firend a card that this friend has sent to him. Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times.Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to n. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card.Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible.Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.", "input_spec": "The first line contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009300) \u2014 the number of Alexander's friends, equal to the number of cards. Next n lines contain his friends' preference lists. Each list consists of n different integers from 1 to n. The last line contains Alexander's preference list in the same format.", "output_spec": "Print n space-separated numbers: the i-th number should be the number of the friend, whose card Alexander receives right before he should send a card to the i-th friend. If there are several solutions, print any of them.", "sample_inputs": ["4\n1 2 3 4\n4 1 3 2\n4 3 1 2\n3 4 2 1\n3 1 2 4"], "sample_outputs": ["2 1 1 4"], "notes": "NoteIn the sample, the algorithm of actions Alexander and his friends perform is as follows: Alexander receives card 1 from the first friend. Alexander sends the card he has received (at the moment he only has one card, and therefore it is the most preferable for him) to friends with the numbers 2 and 3. Alexander receives card 2 from the second friend, now he has two cards \u2014 1 and 2. Alexander sends a card to the first friend. Despite the fact that Alexander likes card 1 more, he sends card 2 as he cannot send a friend the card sent by that very friend. Alexander receives card 3 from the third friend. Alexander receives card 4 from the fourth friend. Among the cards Alexander has number 3 is his favorite and he sends it to the fourth friend. Note that Alexander can send cards to multiple friends at a time (in this case the second and the third one). Alexander can send card 3 to the fourth friend after he receives the third card or after he receives the fourth card (both variants are correct)."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n n 0 in\n let b = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\ta.(i).(j) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1\n done\n done;\n for i = 0 to n - 1 do\n b.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s) - 1\n done;\n in\n let c = Array.make_matrix n n (-1) in\n for i = 0 to n - 1 do\n let c1 = ref (-1) in\n let c2 = ref (-1) in\n\tfor j = 0 to n - 1 do\n\t if b.(j) <= i then (\n\t if !c1 < 0\n\t then c1 := b.(j)\n\t else if !c2 < 0\n\t then c2 := b.(j)\n\t )\n\tdone;\n\tfor j = 0 to n - 1 do\n\t if j <> !c1\n\t then c.(j).(!c1) <- i\n\t else if !c2 >= 0\n\t then c.(j).(!c2) <- i\n\tdone\n done;\n let res = Array.make n (-1) in\n (*for i = 0 to n - 1 do\n\tfor j = 0 to n - 1 do\n\t Printf.printf \"%d \" (c.(i).(j) + 1)\n\tdone;\n\tPrintf.printf \"\\n\"\n done;*)\n for i = 0 to n - 1 do\n\tfor j = 0 to n - 1 do\n\t if res.(i) < 0 && c.(i).(a.(i).(j)) >= 0\n\t then res.(i) <- c.(i).(a.(i).(j))\n\tdone\n done;\n for i = 0 to n - 1 do\n\tPrintf.printf \"%d \" (res.(i) + 1)\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "d8f8be420c1d9553240708f28f8ba4b2"} {"nl": {"description": "A sequence of square brackets is regular if by inserting symbols \"+\" and \"1\" into it, you can get a regular mathematical expression from it. For example, sequences \"[[]][]\", \"[]\" and \"[[][[]]]\" \u2014 are regular, at the same time \"][\", \"[[]\" and \"[[]]][\" \u2014 are irregular. Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height \u2014 use symbols '+', '-' and '|'. For example, the sequence \"[[][]][]\" should be represented as: +- -++- -+ |+- -++- -+|| ||| || ||| ||+- -++- -+|| |+- -++- -+Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height. The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique. ", "input_spec": "The first line contains an even integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the length of the sequence of brackets. The second line contains the sequence of brackets \u2014 these are n symbols \"[\" and \"]\". It is guaranteed that the given sequence of brackets is regular. ", "output_spec": "Print the drawn bracket sequence in the format which is given in the condition. Don't print extra (unnecessary) spaces. ", "sample_inputs": ["8\n[[][]][]", "6\n[[[]]]", "6\n[[][]]", "2\n[]", "4\n[][]"], "sample_outputs": ["+- -++- -+\n|+- -++- -+|| |\n|| || ||| |\n|+- -++- -+|| |\n+- -++- -+", "+- -+\n|+- -+|\n||+- -+||\n||| |||\n||+- -+||\n|+- -+|\n+- -+", "+- -+\n|+- -++- -+|\n|| || ||\n|+- -++- -+|\n+- -+", "+- -+\n| |\n+- -+", "+- -++- -+\n| || |\n+- -++- -+"], "notes": null}, "positive_code": [{"source_code": "let ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( ** ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet read_int _ = Scanf.scanf \" %d \" (fun n -> n)\nlet read_word _ = Scanf.scanf \" %s \" (fun n -> n)\n\nlet plus mx ht =\n String.init (2*mx+1)\n (fun i ->\n let d = abs (mx-i) in\n if d\n let d = abs (mx-i) in\n if d=ht then '-'\n else ' ')\n\nlet plusminus mx ht =\n String.init (2*mx+1)\n (fun i ->\n let d = abs (mx-i) in\n if d0 && g (i-1) && g i) || (i ()\n |s::ss -> (print_char (String.get s i); iter ss) in\n iter ls in\n let rec iter i =\n if i=n then ()\n else (print_row i; print_newline (); iter (i+1)) in\n iter 0\n"}], "negative_code": [], "src_uid": "7d9fb64a0a324a51432fbb01b4cc2c0e"} {"nl": {"description": "Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times.", "input_spec": "A single line contains two integers m and n (1\u2009\u2264\u2009m,\u2009n\u2009\u2264\u2009105).", "output_spec": "Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10\u2009\u2009-\u20094.", "sample_inputs": ["6 1", "6 3", "2 2"], "sample_outputs": ["3.500000000000", "4.958333333333", "1.750000000000"], "notes": "NoteConsider the third test example. If you've made two tosses: You can get 1 in the first toss, and 2 in the second. Maximum equals to 2. You can get 1 in the first toss, and 1 in the second. Maximum equals to 1. You can get 2 in the first toss, and 1 in the second. Maximum equals to 2. You can get 2 in the first toss, and 2 in the second. Maximum equals to 2. The probability of each outcome is 0.25, that is expectation equals to: You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value"}, "positive_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\n\nmodule Array = ArrayLabels ;;\nmodule List = ListLabels ;;\n\nopen Num ;;\n\nlet foi = float_of_int ;;\n\nlet rec pow x n =\n if n = 0 then 1.\n else if n mod 2 = 0 then\n let p2 = pow x (n / 2) in\n p2 *. p2\n else\n x *. pow x (n - 1)\n;;\n\nlet () =\n sf \"%d %d \"(fun m n ->\n let s = ref (foi m) in\n for i = m - 1 downto 1 do\n s := !s -. pow (foi i /. foi m) n;\n done;\n pf \"%f\\n\" !s)\n;;\n"}], "negative_code": [], "src_uid": "f70ac2c4e0f62f9d6ad1e003aedd86b2"} {"nl": {"description": "You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20090\u2009\u2264\u2009m\u2009\u2264\u2009105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009wi\u2009\u2264\u2009106), where ai,\u2009bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.", "output_spec": "Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.", "sample_inputs": ["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"], "sample_outputs": ["1 4 3 5", "1 4 3 5"], "notes": null}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";; let pnl () = print_newline ();;\nlet b2i x = if x == true then 1 else 0;;\nlet dbg x = print_int(x); pnl();;\n\n\nmodule PSet = struct\n type 'k set =\n | Empty\n | Node of 'k set * 'k * 'k set * int\n\n type 'k t =\n {\n cmp : 'k -> 'k -> int;\n set : 'k set;\n }\n\n let height = function\n | Node (_, _, _, h) -> h\n | Empty -> 0\n\n let make l k r = Node (l, k, r, max (height l) (height r) + 1)\n\n let bal l k r =\n let hl = height l in\n let hr = height r in\n if hl > hr + 2 then\n match l with\n | Node (ll, lk, lr, _) ->\n if height ll >= height lr then make ll lk (make lr k r)\n else\n (match lr with\n | Node (lrl, lrk, lrr, _) ->\n make (make ll lk lrl) lrk (make lrr k r)\n | Empty -> assert false)\n | Empty -> assert false\n else if hr > hl + 2 then\n match r with\n | Node (rl, rk, rr, _) ->\n if height rr >= height rl then make (make l k rl) rk rr\n else\n (match rl with\n | Node (rll, rlk, rlr, _) ->\n make (make l k rll) rlk (make rlr rk rr)\n | Empty -> assert false)\n | Empty -> assert false\n else Node (l, k, r, max hl hr + 1)\n\n let rec min_elt = function\n | Node (Empty, k, _, _) -> k\n | Node (l, _, _, _) -> min_elt l\n | Empty -> raise Not_found\n\n let rec remove_min_elt = function\n | Node (Empty, _, r, _) -> r\n | Node (l, k, r, _) -> bal (remove_min_elt l) k r\n | Empty -> invalid_arg \"PSet.remove_min_elt\"\n\n let merge t1 t2 =\n match t1, t2 with\n | Empty, _ -> t2\n | _, Empty -> t1\n | _ ->\n let k = min_elt t2 in\n bal t1 k (remove_min_elt t2)\n\n let create cmp = { cmp = cmp; set = Empty }\n let empty = { cmp = compare; set = Empty }\n\n let is_empty x = \n x.set = Empty\n\n let rec add_one cmp x = function\n | Node (l, k, r, h) ->\n let c = cmp x k in\n if c = 0 then Node (l, x, r, h)\n else if c < 0 then\n let nl = add_one cmp x l in\n bal nl k r\n else\n let nr = add_one cmp x r in\n bal l k nr\n | Empty -> Node (Empty, x, Empty, 1)\n\n let add x { cmp = cmp; set = set } =\n { cmp = cmp; set = add_one cmp x set }\n\n let rec join cmp l v r =\n match (l, r) with\n (Empty, _) -> add_one cmp v r\n | (_, Empty) -> add_one cmp v l\n | (Node(ll, lv, lr, lh), Node(rl, rv, rr, rh)) ->\n if lh > rh + 2 then bal ll lv (join cmp lr v r) else\n if rh > lh + 2 then bal (join cmp l v rl) rv rr else\n make l v r\n\n let split x { cmp = cmp; set = set } =\n let rec loop x = function\n Empty ->\n (Empty, false, Empty)\n | Node (l, v, r, _) ->\n let c = cmp x v in\n if c = 0 then (l, true, r)\n else if c < 0 then\n let (ll, pres, rl) = loop x l in (ll, pres, join cmp rl v r)\n else\n let (lr, pres, rr) = loop x r in (join cmp l v lr, pres, rr)\n in\n let setl, pres, setr = loop x set in\n { cmp = cmp; set = setl }, pres, { cmp = cmp; set = setr }\n\n let remove x { cmp = cmp; set = set } =\n let rec loop = function\n | Node (l, k, r, _) ->\n let c = cmp x k in\n if c = 0 then merge l r else\n if c < 0 then bal (loop l) k r else bal l k (loop r)\n | Empty -> Empty in\n { cmp = cmp; set = loop set }\n\n let mem x { cmp = cmp; set = set } =\n let rec loop = function\n | Node (l, k, r, _) ->\n let c = cmp x k in\n c = 0 || loop (if c < 0 then l else r)\n | Empty -> false in\n loop set\n\n let exists = mem\n\n let iter f { set = set } =\n let rec loop = function\n | Empty -> ()\n | Node (l, k, r, _) -> loop l; f k; loop r in\n loop set\n\n let fold f { cmp = cmp; set = set } acc =\n let rec loop acc = function\n | Empty -> acc\n | Node (l, k, r, _) ->\n loop (f k (loop acc l)) r in\n loop acc set\n\n let elements { set = set } = \n let rec loop acc = function\n Empty -> acc\n | Node(l, k, r, _) -> loop (k :: loop acc r) l in\n loop [] set\nend;;\n\nmodule type GRAPH_LABELS = \n sig \n type label\n end;;\n\n(* Typ modu\u0142u implementuj\u0105cego grafy o wierzcho\u0142kach numerowanych od 0 do n-1. *)\nmodule type GRAPH = \n sig \n (* Etykiety kraw\u0119dzi. *)\n type label\n\n (* Typ graf\u00f3w o wierzcho\u0142kach typu 'a. *)\n type graph\n \n (* Pusty graf. *)\n val init : int -> graph\n\n (* Rozmiar grafu *)\n val size : graph -> int\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_directed_edge : graph -> int -> int -> label -> unit\n\n (* Dodanie kraw\u0119dzi nieskierowanej (dwukierunkowej) \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n val insert_edge : graph -> int -> int -> label -> unit\n\n (* Lista incydencji danego wierzcho\u0142ka. *)\n val neighbours : graph -> int -> (int*label) list\n end;;\n\nmodule Graph = functor (L : GRAPH_LABELS) -> \n(struct\n (* Etykiety kraw\u0119dzi. *)\n type label = L.label\n \n (* Typ graf\u00f3w - tablica list s\u0105siedztwa. *)\n type graph = {n : int; e : (int*label) list array}\n \n (* Pusty graf. *)\n let init s = {n = s; e = Array.make s []}\n\n (* Rozmiar grafu. *)\n let size g = g.n\n \n (* Dodanie kraw\u0119dzi skierowanej \u0142\u0105cz\u0105cej dwa wierzcho\u0142ki. *)\n let insert_directed_edge g x y l = \n assert ((x<>y) && (x >= 0) && (x < size g) && (y >= 0) && (y < size g));\n g.e.(x) <- (y,l)::g.e.(x)\n \n (* Dodanie kraw\u0119dzi \u0142\u0105cz\u0105cej dwa (istniej\u0105ce) wierzcho\u0142ki. *)\n let insert_edge g x y l =\n insert_directed_edge g x y l;\n insert_directed_edge g y x l\n \n (* Lista incydencji danego wierzcho\u0142ka. *)\n let neighbours g x =\n g.e.(x)\nend : GRAPH with type label = L.label);;\n\nmodule IntLabel = \n struct\n type label = int\n end;;\n\nmodule G = Graph(IntLabel);;\n\nopen G;;\nopen PSet;;\nlet n = scan_int() and m = scan_int();;\nlet g = G.init n;;\n\nlet zbior = ref empty;;\n\nfor i = 1 to m do\n let a = scan_int() - 1 and b = scan_int() - 1 and c = scan_int() in\n G.insert_edge g a b c;\ndone;;\n\nlet dijkstra g = (*wierzcholki numerujemy od 0*)\n zbior := add (Int64.zero, 0) !zbior;\n let dis = Array.make n Int64.max_int and pred = Array.make n (-1) in\n while is_empty !zbior = false do\n let (odl, u) = min_elt (!zbior).set in\n zbior := {cmp = (!zbior).cmp; set = remove_min_elt (!zbior).set};\n List.iter (fun (v, w) ->\n let waga = Int64.add odl (Int64.of_int(w)) in\n if waga < dis.(v) then begin\n dis.(v) <- waga;\n pred.(v) <- u;\n zbior := add (waga, v) !zbior;\n end;\n ) (neighbours g u);\n done;\n pred;\n;;\n\nlet wyn = dijkstra g;;\n\nif wyn.(n - 1) = -1 then begin\n print_string(\"-1\");\n exit 0;\nend;;\n\nlet odp = ref [];;\nlet rec petla x =\n odp := (x + 1) :: !odp;\n if x <> 0 then petla (wyn.(x));;\npetla (n - 1);\n\nList.iter (fun x -> print_int (x); psp()) !odp;;"}], "negative_code": [], "src_uid": "bda2ca1fd65084bb9d8659c0a591743d"} {"nl": {"description": "Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x\u2009-\u2009p vertices where 1\u2009\u2264\u2009p\u2009<\u2009x is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of tests Peter is about to make. The second line contains n space separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), i-th of them stands for the number of vertices in the cycle added before the i-th test.", "output_spec": "Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.", "sample_inputs": ["3\n1 2 3", "5\n1 1 5 1 1"], "sample_outputs": ["2\n1\n1", "2\n2\n2\n2\n2"], "notes": "NoteIn the first sample test:In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.In the second sample test:Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3. If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses. If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let rec loop ac i = if i n)\n\nlet input () = \n let total = (read ()) - 1 in\n let destination = (read ()) - 1 in\n let portals = Array.init total (fun n -> read ()) in\n (total, destination, portals)\n\nlet solve (total, destination, portals) = \n let rec loop i =\n if i < total\n then\n let portal_in = portals.(i) in\n let portal_out = portal_in + i in\n if portal_out < destination\n then\n loop (portal_out) \n else\n if portal_out = destination\n then\n \"YES\"\n else\n \"NO\"\n else\n failwith \"Corrupted input\"\n in loop 0\n\nlet print result = Printf.printf \"%s\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "let () = Scanf.scanf \"%d %d\\n\" (fun n t ->\n let p = Array.init (n - 1) (fun _ ->\n Scanf.scanf \"%d%_c\" (fun x -> x))\n in\n let rec f i =\n if i > t then false\n else if i = t then true\n else f (i + p.(i - 1))\n in\n print_endline (if f 1 then \"YES\" else \"NO\")\n)\n"}, {"source_code": "\nlet words line = Str.split (Str.regexp \" \") line;;\n\nlet transport curr arr = curr + arr.(curr - 1);;\n\nlet rec step arr start goal =\n if start = goal then\n \"YES\"\n else if goal < start then\n \"NO\"\n else\n step arr (transport start arr) goal\n;;\n\nlet () =\n let nk = words (read_line ()) in\n let goal = int_of_string (List.nth nk 1) in\n let line = words (read_line ()) in\n let arr = Array.of_list (List.map int_of_string line)\n in\n Printf.printf \"%s\\n\"\n (step arr 1 goal)\n;;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let t = read_int () in\n let a = Array.init n (fun i -> if i=0 then 0 else read_int()) in\n \n let rec scan c =\n if c = t then true else if c = n then false else scan (c + a.(c))\n in\n\n if scan 1 then printf \"YES\\n\" else printf \"NO\\n\"\n"}], "negative_code": [{"source_code": "let input () = Scanf.scanf \"%d %d \" (fun n m -> (n, m))\n\nlet solve (n, m) =\n let rec loop i =\n if i < n\n then\n let portal_in = Scanf.scanf \"%d \" (fun p -> p) in\n let portal_out = portal_in + i in\n if portal_out < m\n then\n loop (i + 1) \n else\n if portal_out = m\n then\n \"YES\"\n else\n \"NO\"\n else\n failwith \"Corrupted input\"\n in loop 1\n\nlet print result = Printf.printf \"%s\\n\" result\nlet () = print (solve (input ()))"}], "src_uid": "9ee3d548f93390db0fc2f72500d9eeb0"} {"nl": {"description": "Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105) \u2014 the number of lines. Next n lines contain commands. A command consists of a character that represents the operation (\"&\", \"|\" or \"^\" for AND, OR or XOR respectively), and the constant xi 0\u2009\u2264\u2009xi\u2009\u2264\u20091023.", "output_spec": "Output an integer k (0\u2009\u2264\u2009k\u2009\u2264\u20095) \u2014 the length of your program. Next k lines must contain commands in the same format as in the input.", "sample_inputs": ["3\n| 3\n^ 2\n| 1", "3\n& 1\n& 3\n& 5", "3\n^ 1\n^ 2\n^ 3"], "sample_outputs": ["2\n| 3\n^ 2", "1\n& 1", "0"], "notes": "NoteYou can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation.Second sample:Let x be an input of the Petya's program. It's output is ((x&1)&3)&5\u2009=\u2009x&(1&3&5)\u2009=\u2009x&1. So these two programs always give the same outputs."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let prog = Array.init n (fun _ ->\n let op = (read_string ()).[0] in\n let k = read_int () in\n (op,k)\n ) in\n\n let execute k =\n let rec loop i ac = if i=n then ac else (\n let ac = match prog.(i) with\n\t| ('^', c) -> ac lxor c\n\t| ('&', c) -> ac land c\n\t| ('|', c) -> ac lor c\n\t| _ -> failwith \"bad program\"\n in\n loop (i+1) ac\n )\n in\n loop 0 k\n in\n\n let does_to_bit b =\n let b0 = ((execute (0 lsl b)) lsr b) land 1 in \n let b1 = ((execute (1 lsl b)) lsr b) land 1 in\n (b0,b1)\n in\n\n let xor_part = ref 0 in\n let or_part = ref 0 in\n let and_part = ref 1023 in\n \n for b=0 to 9 do\n let x = 1 lsl b in\n match does_to_bit b with\n | (0,0) -> and_part := !and_part land (lnot x)\n | (0,1) -> ()\n | (1,0) -> xor_part := !xor_part lor x\n | (1,1) -> or_part := !or_part lor x\n | _ -> failwith \"bad bits\"\n done;\n\n printf \"3\\n\";\n printf \"^ %d\\n\" !xor_part;\n printf \"| %d\\n\" !or_part;\n printf \"& %d\\n\" !and_part\n"}], "negative_code": [], "src_uid": "19c32b8c1d3db5ab10aca271135aa9b8"} {"nl": {"description": "One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2\u00b7m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2\u00b7m from left to right, then the j-th flat of the i-th floor has windows 2\u00b7j\u2009-\u20091 and 2\u00b7j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.", "input_spec": "The first line of the input contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100)\u00a0\u2014 the number of floors in the house and the number of flats on each floor respectively. Next n lines describe the floors from top to bottom and contain 2\u00b7m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.", "output_spec": "Print a single integer\u00a0\u2014 the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.", "sample_inputs": ["2 2\n0 0 0 1\n1 0 1 1", "1 3\n1 1 0 1 0 0"], "sample_outputs": ["3", "2"], "notes": "NoteIn the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off."}, "positive_code": [{"source_code": "let [n; m]= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) and ans = ref 0;;\nfor i= 1 to n do\n\tlet s = List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\n\t\tfor j= 1 to m do \n\t\t\tif (List.nth s (2 * j - 1) = 1) || (List.nth s (2 * j - 2) = 1) then \n\t\t\t\tans:= !ans + 1;\n\t\tdone\ndone;;\nprint_int !ans\n"}, {"source_code": "let read_int() = Scanf.scanf \"%d \" (fun x->x) ;;\nlet rec f = function 0 -> 0 | c -> ( read_int() lor read_int() ) + f (c-1) in print_int @@ f ( read_int() * read_int() )"}, {"source_code": "input_line stdin\n\nlet eval a b =\n if a + b == 0 then 0 else 1 ;;\n\n let rec solve acc =\n let i = Scanf.scanf \"%d %d \" eval in\n try solve (acc + i) with _ -> acc + i ;;\n\nlet ans = solve 0 ;;\n\nPrintf.printf \"%d\\n\" ans ;;"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let m = read_int () in\n\n let awake a b = if a+b > 0 then 1 else 0 in\n let answer = sum 1 n (fun i ->\n sum 1 m (fun j ->\n let a = read_int() in\n let b = read_int() in\n awake a b\n )\n ) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "5b9aed235094de7de36247a3b2a34e0f"} {"nl": {"description": "Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1,\u2009s2,\u2009...,\u2009sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1\u2009\u2264\u2009i\u2009\u2264\u2009n). Help Polycarpus determine the length of the city phone code. ", "input_spec": "The first line of the input contains an integer n (2\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7104) \u2014 the number of Polycarpus's friends. The following n lines contain strings s1,\u2009s2,\u2009...,\u2009sn \u2014 the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.", "output_spec": "Print the number of digits in the city phone code.", "sample_inputs": ["4\n00209\n00219\n00999\n00909", "2\n1\n2", "3\n77012345678999999999\n77012345678901234567\n77012345678998765432"], "sample_outputs": ["2", "0", "12"], "notes": "NoteA prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string \"00209\" has 6 prefixes: \"\" (an empty prefix), \"0\", \"00\", \"002\", \"0020\", \"00209\".In the first sample the city phone code is string \"00\".In the second sample the city phone code is an empty string.In the third sample the city phone code is string \"770123456789\"."}, "positive_code": [{"source_code": "open Array;;\nopen String;;\nlet (|>) x f = f x\nlet identity = fun x -> x\n \nlet flip f y x = f x y\n \nlet readStrLn _ = \n try Some (Scanf.scanf \"%s\\n\" identity)\n with _ -> None\nlet readIntLn _ = Scanf.scanf \"%d\\n\" identity\n \nlet foldCont f a cont = \n let rec fold' a = match cont () with\n None -> a\n | Some x -> fold' (f a x)\n in fold' a\n \nlet _ = readIntLn ()\nlet temp = Scanf.scanf \"%s\\n\" identity\nlet len = length temp;;\nlet f a b = \n let rec f' i = match b.[i] with\n c when c = temp.[i] -> f' (i+1)\n | _ -> temp.[i] <- ' '; i\n in f' 0;;\n(*let main () = *)\nif len = 1 then (print_int 0)\nelse ( len |> flip (foldCont f) readStrLn |> print_int; ());;"}, {"source_code": "let solve codes =\n let rec loop length =\n let num = String.get (List.hd codes) length in\n if List.for_all (fun str -> (String.get str length) = num) codes\n then loop (length+1)\n else length\n in\n loop 0\n\nlet rec input_strings n =\n if n <= 0 then []\n else (Scanf.scanf \" %s\" (fun x -> x)) :: (input_strings (n-1))\n\nlet _ =\n let codes = Scanf.scanf \" %d\" input_strings in\n Printf.printf \"%d\\n\" (solve codes)\n \n"}], "negative_code": [{"source_code": "open Array;;\nopen String;;\nlet (|>) x f = f x\nlet identity = fun x -> x\n \nlet flip f y x = f x y\n \nlet readStrLn _ = \n try Some (Scanf.scanf \"%s\\n\" identity)\n with _ -> None\nlet readIntLn _ = Scanf.scanf \"%d\\n\" identity\n \nlet foldCont f a cont = \n let rec fold' a = match cont () with\n None -> a\n | Some x -> fold' (f a x)\n in fold' a\n \nlet _ = readIntLn ()\nlet temp = Scanf.scanf \"%s\\n\" identity\nlet len = length temp ;;\nlet f a b = \n let rec f' i = match b.[i] with\n c when c = temp.[i] -> f' (i+1)\n | _ -> i\n in f' 0;;\n(*let main () = *)\nif len = 1 then (print_int 0)\nelse ( len |> flip (foldCont f) readStrLn |> print_int; ());;"}], "src_uid": "081b35620952bd32ce6d8ddc756e5c9d"} {"nl": {"description": "When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type \u2014 if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!", "input_spec": "The first line of the input contains three space-separated numbers, n, m and k (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u200918, 0\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009*\u2009(n\u2009-\u20091)) \u2014 the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009n, 0\u2009\u2264\u2009ci\u2009\u2264\u2009109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009k), that xi\u2009=\u2009xj and yi\u2009=\u2009yj.", "output_spec": "In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant.", "sample_inputs": ["2 2 1\n1 1\n2 1 1", "4 3 2\n1 2 3 4\n2 1 5\n3 4 2"], "sample_outputs": ["3", "12"], "notes": "NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5."}, "positive_code": [{"source_code": "let popcount n =\n let rec aux n acc =\n if n == 0\n then acc\n else aux (n lsr 1) (acc + (n land 1))\n in aux n 0\n\nlet (+) = Int64.add\n\nlet () = Scanf.scanf \"%d %d %d\\n\" (fun n m k ->\n (* dp in current state and last eaten dish *)\n let dp = Array.make_matrix (1 lsl n) n (-1L) in\n (* read list of satisfactions *)\n let a = Array.init n (fun i -> Scanf.scanf \"%Ld%_c\" (fun x ->\n dp.(1 lsl i).(i) <- x;\n x))\n (* rules are mappings of (prev,next) -> c *)\n and rules = Array.make_matrix n n 0L\n (* the solution! *)\n and best = ref 0L\n in\n (* populate rules *)\n for i = 1 to k do\n Scanf.scanf \"%d %d %Ld\\n\" (fun x y c ->\n rules.(x - 1).(y - 1) <- c)\n done;\n\n (* loop over all possible states *)\n for state = 1 to (1 lsl n) - 1 do\n (* loop over all possible last-taken dishes *)\n for last = 0 to n - 1 do\n (* are we done? *)\n if dp.(state).(last) != -1L then\n if popcount state == m\n then best := max !best dp.(state).(last)\n else\n (* all next dishes *)\n for next = 0 to n - 1 do\n (* we haven't already eaten this *)\n if state land (1 lsl next) == 0 then\n dp.(state lor (1 lsl next)).(next) <- max dp.(state lor (1 lsl next)).(next)\n (dp.(state).(last) + a.(next) + rules.(last).(next))\n done\n done\n done;\n\n Printf.printf \"%Ld\\n\" !best\n)"}], "negative_code": [{"source_code": "let popcount =\n let k1 = 0x55555555 in\n let k2 = 0x33333333 in\n let k3 = 0x0f0f0f0f in\n (fun x ->\n let x = x - (x lsr 1) land k1 in\n let x = ((x lsr 2) land k2) + (x land k2) in\n let x = (x + (x lsr 4)) land k3 in\n let x = x + x lsr 8 in\n (x + x lsr 16) land 0x3f\n )\n\nlet max (a : float) (b : float) : float = if a >= b then a else b\n\nlet () = Scanf.scanf \"%d %d %d\\n\" (fun n m k ->\n (* dp in current state and last eaten dish *)\n let dp = Array.make_matrix (1 lsl n) n (-1.) in\n (* read list of satisfactions *)\n let a = Array.init n (fun i -> Scanf.scanf \"%f%_c\" (fun x ->\n dp.(1 lsl i).(i) <- x;\n x))\n (* rules are mappings of (prev,next) -> c *)\n and rules = Array.make_matrix n n 0.\n and best = ref 0.\n (* the solution! *)\n in\n (* populate rules *)\n for i = 1 to k do\n Scanf.scanf \"%d %d %f\\n\" (fun x y c ->\n rules.(x - 1).(y - 1) <- c)\n done;\n\n (* loop over all possible states *)\n for state = 1 to (1 lsl n) - 1 do\n (* loop over all possible last-taken dishes *)\n for last = 0 to n - 1 do\n (* are we done? *)\n if dp.(state).(last) != -1. then\n if popcount state = m\n then best := max !best dp.(state).(last)\n else\n (* all next dishes *)\n for next = 0 to n - 1 do\n (* we haven't already eaten this *)\n if state land (1 lsl next) = 0 then\n dp.(state lor (1 lsl next)).(next) <- max dp.(state lor (1 lsl next)).(next)\n (dp.(state).(last) +. a.(next) +. rules.(last).(next))\n done\n done\n done;\n\n Printf.printf \"%.0f\\n\" !best\n)\n"}, {"source_code": "let popcount n =\n let rec aux n acc =\n if n == 0\n then acc\n else aux (n lsr 1) (acc + (n land 1))\n in aux n 0\n\nlet () = Scanf.scanf \"%d %d %d\\n\" (fun n m k ->\n (* dp in current state and last eaten dish *)\n let dp = Array.make_matrix (1 lsl n) n (-1) in\n (* read list of satisfactions *)\n let a = Array.init n (fun i -> Scanf.scanf \"%d%_c\" (fun x ->\n dp.(1 lsl i).(i) <- x;\n x))\n (* rules are mappings of (prev,next) -> c *)\n and rules = Array.make_matrix n n 0\n (* the solution! *)\n and best = ref 0\n in\n (* populate rules *)\n for i = 1 to k do\n Scanf.scanf \"%d %d %d\\n\" (fun x y c ->\n rules.(x - 1).(y - 1) <- c)\n done;\n\n (* loop over all possible states *)\n for state = 1 to (1 lsl n) - 1 do\n (* loop over all possible last-taken dishes *)\n for last = 0 to n - 1 do\n (* are we done? *)\n if dp.(state).(last) != -1 then\n if popcount state == m\n then best := max !best dp.(state).(last)\n else\n (* all next dishes *)\n for next = 0 to n - 1 do\n (* we haven't already eaten this *)\n if state land (1 lsl next) == 0 then\n dp.(state lor (1 lsl next)).(next) <-\n max dp.(state lor (1 lsl next)).(next)\n (dp.(state).(last) + a.(next) + rules.(last).(next))\n done\n done\n done;\n\n print_int !best;\n print_newline ()\n)\n"}], "src_uid": "5b881f1cd74b17358b954299c2742bdf"} {"nl": {"description": "So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal \u2014 their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city \u2014 that's the strategy the flatlanders usually follow when they besiege cities.The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack. Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r\u2009\u2265\u20090) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point. In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range \u2014 as a disk (including the border) with the center at the point where the radar is placed.", "input_spec": "The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|,\u2009|yi|\u2009\u2264\u2009104;\u00a01\u2009\u2264\u2009ri\u2009\u2264\u2009104) \u2014 the city's coordinates and the distance from the city to the flatlanders, correspondingly. It is guaranteed that the cities are located at different points.", "output_spec": "Print a single real number \u2014 the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10\u2009-\u20096.", "sample_inputs": ["0 0 1\n6 0 3", "-10 10 3\n10 -10 3"], "sample_outputs": ["1.000000000000000", "11.142135623730951"], "notes": "NoteThe figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2,\u20090). The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0,\u20090). "}, "positive_code": [{"source_code": "let _ =\n let main () =\n let tri a b c = a, b, c in\n let x1, y1, r1 = Scanf.scanf \" %d %d %d\" tri in\n let x2, y2, r2 = Scanf.scanf \" %d %d %d\" tri in\n let d2 =\n let sq x = x * x in\n let dd = sqrt (float (sq (x2 - x1) + sq (y2 - y1))) in\n let r = (dd -. float (r1 + r2)) /. 2. in\n if r > 0. then r else max ((float (abs (r1 - r2)) -. dd) /. 2.) 0.\n in\n Printf.printf \"%.15f\\n\" d2\n in\n main ()\n"}], "negative_code": [{"source_code": "let _ =\n let main () =\n let tri a b c = a, b, c in\n let x1, y1, r1 = Scanf.scanf \" %d %d %d\" tri in\n let x2, y2, r2 = Scanf.scanf \" %d %d %d\" tri in\n let d2 =\n let sq x = x * x in\n let dd = sqrt (float (sq (x2 - x1) + sq (y2 - y1))) in\n let r = (dd -. float (r1 + r2)) /. 2. in\n if r > 0. then r else (float (abs (r1 - r2)) -. dd) /. 2.\n in\n Printf.printf \"%.15f\\n\" d2\n in\n main ()\n"}, {"source_code": "let _ =\n let main () =\n let tri a b c = a, b, c in\n let x1, y1, r1 = Scanf.scanf \" %d %d %d\" tri in\n let x2, y2, r2 = Scanf.scanf \" %d %d %d\" tri in\n let d2 =\n let sq x = x * x in\n (sqrt (float (sq (x2 - x1) + sq (y2 - y1))) -. float (r1 + r2)) /. 2. \n in\n Printf.printf \"%.15f\\n\" d2\n in\n main ()\n"}], "src_uid": "8996ae454ba3062e47a8aaab7fb1e33b"} {"nl": {"description": "Find an n\u2009\u00d7\u2009n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.", "input_spec": "The only line contains odd integer n (1\u2009\u2264\u2009n\u2009\u2264\u200949).", "output_spec": "Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.", "sample_inputs": ["1", "3"], "sample_outputs": ["1", "2 1 4\n3 5 7\n6 9 8"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let mmod x =\n let r = x mod n in\n if r >= 0\n then r\n else r + n\n in\n let a = Array.make_matrix n n 0 in\n let x = ref (n / 2) in\n let y = ref 0 in\n let _ =\n for i = 1 to n * n do\n if a.(!y).(!x) > 0 then (\n\tx := mmod (!x - 1);\n\ty := mmod (!y + 2);\n );\n a.(!y).(!x) <- i;\n x := mmod (!x + 1);\n y := mmod (!y - 1);\n done;\n in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tPrintf.printf \"%d \" a.(i).(j)\n done;\n Printf.printf \"\\n\"\n done\n\n"}], "negative_code": [], "src_uid": "a7da19d857ca09f052718cb69f2cea57"} {"nl": {"description": "Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers $$$n$$$ pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the $$$i$$$-th from the left sushi as $$$t_i$$$, where $$$t_i = 1$$$ means it is with tuna, and $$$t_i = 2$$$ means it is with eel.Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment $$$[2, 2, 2, 1, 1, 1]$$$ is valid, but subsegment $$$[1, 2, 1, 2, 1, 2]$$$ is not, because both halves contain both types of sushi.Find the length of the longest continuous subsegment of sushi Arkady can buy.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 100\\,000$$$)\u00a0\u2014 the number of pieces of sushi. The second line contains $$$n$$$ integers $$$t_1$$$, $$$t_2$$$, ..., $$$t_n$$$ ($$$t_i = 1$$$, denoting a sushi with tuna or $$$t_i = 2$$$, denoting a sushi with eel), representing the types of sushi from left to right. It is guaranteed that there is at least one piece of sushi of each type. Note that it means that there is at least one valid continuous segment.", "output_spec": "Print a single integer\u00a0\u2014 the maximum length of a valid continuous segment.", "sample_inputs": ["7\n2 2 2 1 1 2 2", "6\n1 2 1 2 1 2", "9\n2 2 1 1 1 2 2 2 2"], "sample_outputs": ["4", "2", "6"], "notes": "NoteIn the first example Arkady can choose the subsegment $$$[2, 2, 1, 1]$$$ or the subsegment $$$[1, 1, 2, 2]$$$ with length $$$4$$$.In the second example there is no way but to choose one of the subsegments $$$[2, 1]$$$ or $$$[1, 2]$$$ with length $$$2$$$.In the third example Arkady's best choice is the subsegment $$$[1, 1, 1, 2, 2, 2]$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\n\nlet rec one_type_seg cur = function\n | x::(y::_ as rest) when x = y -> one_type_seg (cur+1) rest\n | _::rest -> (cur+1) :: one_type_seg 0 rest\n | [] -> []\n\nlet rec max_seg cur = function\n | a::(b::_ as rest) -> max_seg (max cur (2*min a b)) rest\n | _ -> cur\n\nlet () =\n let n = read_int () in\n let a = Array.(init n read_int |> to_list) in\n printf \"%d\\n\" (one_type_seg 0 a |> max_seg 0)\n"}], "negative_code": [], "src_uid": "6477fdad8455f57555f93c021995bb4d"} {"nl": {"description": "Kate has a set $$$S$$$ of $$$n$$$ integers $$$\\{1, \\dots, n\\} $$$. She thinks that imperfection of a subset $$$M \\subseteq S$$$ is equal to the maximum of $$$gcd(a, b)$$$ over all pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are in $$$M$$$ and $$$a \\neq b$$$. Kate is a very neat girl and for each $$$k \\in \\{2, \\dots, n\\}$$$ she wants to find a subset that has the smallest imperfection among all subsets in $$$S$$$ of size $$$k$$$. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size $$$k$$$, will name it $$$I_k$$$. Please, help Kate to find $$$I_2$$$, $$$I_3$$$, ..., $$$I_n$$$.", "input_spec": "The first and only line in the input consists of only one integer $$$n$$$ ($$$2\\le n \\le 5 \\cdot 10^5$$$) \u00a0\u2014 the size of the given set $$$S$$$.", "output_spec": "Output contains only one line that includes $$$n - 1$$$ integers: $$$I_2$$$, $$$I_3$$$, ..., $$$I_n$$$.", "sample_inputs": ["2", "3"], "sample_outputs": ["1", "1 1"], "notes": "NoteFirst sample: answer is 1, because $$$gcd(1, 2) = 1$$$.Second sample: there are subsets of $$$S$$$ with sizes $$$2, 3$$$ with imperfection equal to 1. For example, $$$\\{2,3\\}$$$ and $$$\\{1, 2, 3\\}$$$."}, "positive_code": [{"source_code": "let get_int () =\n Scanf.scanf \"%d \" (fun x -> x)\n;;\n\nlet rec read_int_seq n =\n match n with\n 0 -> []\n | _ -> (get_int ()) :: (read_int_seq (n-1))\n;;\n\nlet rec print_list xs =\n match xs with\n [] -> print_endline \"\"\n | x :: [] -> (Printf.printf \"%d\\n\" x)\n | x :: xs' -> (let _ = Printf.printf \"%d \" x in print_list xs')\n;;\n\nlet rec range a b =\n if a > b then [] else\n a :: (range (a+1) b)\n;;\n\nlet read_case () =\n let n = get_int () in n\n;;\n\nlet rec min_div_from n k =\n if k*k > n then n else\n if n mod k = 0 then k else\n min_div_from n (k+1)\n;;\n\nlet min_div n =\n min_div_from n 2\n;;\n\nlet solve n =\n List.map (fun x -> x / (min_div x)) (range 2 n)\n |> (List.sort (-))\n |> print_list\n;;\n\nlet n = read_case () in\n solve n\n;;\n\n"}], "negative_code": [], "src_uid": "26fe98904d68cf23c5d24aa85dd92120"} {"nl": {"description": "After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant\u2019s sentences, Yash determined a new cipher technique.For a given sentence, the cipher is processed as: Convert all letters of the sentence to lowercase. Reverse each of the words of the sentence individually. Remove all the spaces in the sentence. For example, when this cipher is applied to the sentenceKira is childish and he hates losingthe resulting string isariksihsidlihcdnaehsetahgnisolNow Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910\u2009000)\u00a0\u2014 the length of the ciphered text. The second line consists of n lowercase English letters\u00a0\u2014 the ciphered text t. The third line contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi|\u2009\u2264\u20091\u2009000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1\u2009000\u2009000.", "output_spec": "Print one line \u2014 the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those.", "sample_inputs": ["30\nariksihsidlihcdnaehsetahgnisol\n10\nKira\nhates\nis\nhe\nlosing\ndeath\nchildish\nL\nand\nNote", "12\niherehtolleh\n5\nHI\nHo\nthere\nHeLLo\nhello"], "sample_outputs": ["Kira is childish and he hates losing", "HI there HeLLo"], "notes": "NoteIn sample case 2 there may be multiple accepted outputs, \"HI there HeLLo\" and \"HI there hello\" you may output any of them. "}, "positive_code": [{"source_code": "exception End of int\n\ntype trie = E of bool | N of bool * trie array\n\nlet add w trie =\n let n = String.length w in\n let rec aux i = function\n | E(b) -> if i = n then E(true) else\n (let tab = Array.make 26 (E false) in\n tab.(int_of_char w.[i] - 97) <- aux (i+1) (E false);\n N(b,tab))\n | N(b,tab) -> if i = n then N(true,tab) else\n (tab.(int_of_char w.[i] - 97) <- aux (i+1)\n (tab.(int_of_char w.[i] - 97));\n N(b,tab))\n in ignore (aux 0 trie)\n\nlet main () =\n (let trie = N(false,Array.make 26 (E false)) in\n let hasht = Hashtbl.create 0 in\n let m,w = Scanf.scanf \"%d %s\" (fun i j -> i,j) in\n let n = Scanf.scanf \" %d\" (fun i -> i) in\n for i=1 to n do\n Scanf.scanf \" %s\" (fun s ->\n let s_low = String.lowercase s in\n let m = String.length s_low in\n let rev = String.init m (fun i -> s_low.[m-i-1]) in\n add rev trie;\n Hashtbl.add hasht rev s\n );\n done;\n let tab = Array.make m (-1) in\n let rec aux i last = function\n |E false -> ()\n |E true -> if i = m\n then raise (End(last))\n else if tab.(i) = -1\n then (tab.(i) <- last; aux i i trie)\n |N(false,tab) -> if i < m\n then aux (i+1) last (tab.(int_of_char w.[i] - 97))\n |N(true,tab') -> (if i = m\n then raise (End(last));\n if i < m && tab.(i) = -1\n then (tab.(i) <- last; aux i i trie);\n if i < m\n then aux (i+1) last (tab'.(int_of_char w.[i] - 97)))\n in\n let rec reconst beg en =\n let s = Hashtbl.find hasht (String.sub w beg (en-beg+1)) in\n if beg = 0\n then [s] else s::(reconst (tab.(beg)) (beg - 1))\n in\n try\n aux 0 0 trie; \"\"\n with End last -> String.concat \" \" (List.rev (reconst last (m-1))));;\n\nprint_string (main ())\n"}], "negative_code": [], "src_uid": "5d3fc6a6c4f53d53c38ab4387282a55c"} {"nl": {"description": "Alice and Bob are playing chess on a huge chessboard with dimensions $$$n \\times n$$$. Alice has a single piece left\u00a0\u2014 a queen, located at $$$(a_x, a_y)$$$, while Bob has only the king standing at $$$(b_x, b_y)$$$. Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himself\u00a0\u2014 he needs to march his king to $$$(c_x, c_y)$$$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.Bob will win if he can move his king from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check. Remember that a king can move to any of the $$$8$$$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$3 \\leq n \\leq 1000$$$)\u00a0\u2014 the dimensions of the chessboard. The second line contains two integers $$$a_x$$$ and $$$a_y$$$ ($$$1 \\leq a_x, a_y \\leq n$$$)\u00a0\u2014 the coordinates of Alice's queen. The third line contains two integers $$$b_x$$$ and $$$b_y$$$ ($$$1 \\leq b_x, b_y \\leq n$$$)\u00a0\u2014 the coordinates of Bob's king. The fourth line contains two integers $$$c_x$$$ and $$$c_y$$$ ($$$1 \\leq c_x, c_y \\leq n$$$)\u00a0\u2014 the coordinates of the location that Bob wants to get to. It is guaranteed that Bob's king is currently not in check and the target location is not in check either. Furthermore, the king is not located on the same square as the queen (i.e. $$$a_x \\neq b_x$$$ or $$$a_y \\neq b_y$$$), and the target does coincide neither with the queen's position (i.e. $$$c_x \\neq a_x$$$ or $$$c_y \\neq a_y$$$) nor with the king's position (i.e. $$$c_x \\neq b_x$$$ or $$$c_y \\neq b_y$$$).", "output_spec": "Print \"YES\" (without quotes) if Bob can get from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check, otherwise print \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["8\n4 4\n1 3\n3 1", "8\n4 4\n2 3\n1 6", "8\n3 5\n1 2\n6 1"], "sample_outputs": ["YES", "NO", "NO"], "notes": "NoteIn the diagrams below, the squares controlled by the black queen are marked red, and the target square is marked blue.In the first case, the king can move, for instance, via the squares $$$(2, 3)$$$ and $$$(3, 2)$$$. Note that the direct route through $$$(2, 2)$$$ goes through check. In the second case, the queen watches the fourth rank, and the king has no means of crossing it. In the third case, the queen watches the third file. "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet () =\n\tlet n = get_i64 0 in\n\tlet ax,ay = get_2_i64 0 in\n\tlet bx,by = get_2_i64 0 in\n\tlet cx,cy = get_2_i64 0 in\n\t(\n\t\tif\n\t\t(bx < ax && cx < ax || bx > ax && cx > ax)\n\t\t&&\n\t\t(by < ay && cy < ay || by > ay && cy > ay)\n\tthen (\n\t\tlet dx,dy = labs (bx - ax), labs (by - ay) in\n\t\tif dx = dy then \"NO\" else \"YES\"\n\t) else \"NO\"\n\t)\n\t|> print_endline\n\n\n\n\n"}], "negative_code": [], "src_uid": "c404761a9562ff6034010a553d944324"} {"nl": {"description": "You are given a binary matrix $$$A$$$ of size $$$n \\times n$$$. Let's denote an $$$x$$$-compression of the given matrix as a matrix $$$B$$$ of size $$$\\frac{n}{x} \\times \\frac{n}{x}$$$ such that for every $$$i \\in [1, n], j \\in [1, n]$$$ the condition $$$A[i][j] = B[\\lceil \\frac{i}{x} \\rceil][\\lceil \\frac{j}{x} \\rceil]$$$ is met.Obviously, $$$x$$$-compression is possible only if $$$x$$$ divides $$$n$$$, but this condition is not enough. For example, the following matrix of size $$$2 \\times 2$$$ does not have any $$$2$$$-compression: $$$01$$$ $$$10$$$ For the given matrix $$$A$$$, find maximum $$$x$$$ such that an $$$x$$$-compression of this matrix is possible.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.", "input_spec": "The first line contains one number $$$n$$$ ($$$4 \\le n \\le 5200$$$) \u2014 the number of rows and columns in the matrix $$$A$$$. It is guaranteed that $$$n$$$ is divisible by $$$4$$$. Then the representation of matrix follows. Each of $$$n$$$ next lines contains $$$\\frac{n}{4}$$$ one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from $$$0$$$ to $$$9$$$ or as uppercase Latin letters from $$$A$$$ to $$$F$$$). Binary representation of each of these numbers denotes next $$$4$$$ elements of the matrix in the corresponding row. For example, if the number $$$B$$$ is given, then the corresponding elements are 1011, and if the number is $$$5$$$, then the corresponding elements are 0101. Elements are not separated by whitespaces.", "output_spec": "Print one number: maximum $$$x$$$ such that an $$$x$$$-compression of the given matrix is possible.", "sample_inputs": ["8\nE7\nE7\nE7\n00\n00\nE7\nE7\nE7", "4\n7\nF\nF\nF"], "sample_outputs": ["1", "1"], "notes": "NoteThe first example corresponds to the matrix: $$$11100111$$$ $$$11100111$$$ $$$11100111$$$ $$$00000000$$$ $$$00000000$$$ $$$11100111$$$ $$$11100111$$$ $$$11100111$$$ It is easy to see that the answer on this example is $$$1$$$."}, "positive_code": [{"source_code": "let int_of_hex c = match c with\n| '0' .. '9' -> int_of_char c - int_of_char '0'\n| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10\n| _ -> failwith \"\"\nlet rv f p q = f q p\nlet divisors n = (* O(sqrt n) *)\n let rec f0 i a =\n if i*i > n then a\n else if i*i = n && n mod i = 0 then i::a\n else if n mod i = 0 then f0 (i+1) (i::(n/i)::a)\n else f0 (i+1) a in f0 1 []\n;;\nScanf.(Array.(scanf \" %d\" @@ fun n ->\n let mat = make_matrix n n 0 in\n init n (fun i -> scanf \" %s\" @@ fun s ->\n String.iteri (fun j c ->\n let ih = int_of_hex c in\n mat.(i).(4*j) <- ih land 8 / 8;\n mat.(i).(4*j+1) <- ih land 4 / 4;\n mat.(i).(4*j+2) <- ih land 2 / 2;\n mat.(i).(4*j+3) <- ih land 1;\n ) s\n ) |> ignore;\n (* iter (fun a ->\n iter (fun v ->\n Printf.printf \"%d \" v\n ) a; print_newline ()\n ) mat; *)\n let cml = make_matrix (n+1) (n+1) 0 in\n iteri (fun i a ->\n iteri (fun j _ ->\n cml.(i+1).(j+1) <- cml.(i+1).(j) + mat.(i).(j)\n ) a\n ) mat;\n iteri (fun j a ->\n iteri (fun i _ ->\n cml.(i+1).(j+1) <- cml.(i+1).(j+1) + cml.(i).(j+1)\n ) a\n ) mat;\n (* iter (fun a ->\n iter (fun v ->\n Printf.printf \"%2d \" v\n ) a; print_newline ()\n ) cml; *)\n let get d y x =\n let y,x = y+1,x+1 in\n cml.(y+d-1).(x+d-1) - cml.(y+d-1).(x-1) - cml.(y-1).(x+d-1) + cml.(y-1).(x-1)\n in\n divisors n\n |> List.sort (rv compare)\n |> List.iter (fun d ->\n if d=1 then (\n print_int 1; exit 0;\n );\n let f = ref true in\n init (n/d) (fun y ->\n init (n/d) (fun x ->\n let w = get d (y*d) (x*d) in\n if w=d*d || w=0 then ()\n else f := false\n ) |> ignore\n ) |> ignore;\n if !f then (\n print_int d; exit 0\n )\n )\n));;"}, {"source_code": "\nlet int_of_hex c = match c with\n| '0' .. '9' -> int_of_char c - int_of_char '0'\n| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10\n| _ -> failwith \"\"\nlet rec fix f x = f (fix f) x\nlet gcd = fix (fun f m n ->\n if n=0 then m else f n (m mod n))\n;;\nScanf.(Array.(scanf \" %d\" @@ fun n ->\n let mat = make_matrix n n 0 in\n init n (fun i -> scanf \" %s\" @@ fun s ->\n String.iteri (fun j c ->\n let ih = int_of_hex c in\n mat.(i).(4*j) <- ih land 8 / 8;\n mat.(i).(4*j+1) <- ih land 4 / 4;\n mat.(i).(4*j+2) <- ih land 2 / 2;\n mat.(i).(4*j+3) <- ih land 1;\n ) s\n ) |> ignore;\n let visited = make_matrix n n false in\n let g = ref n in\n let fy y x pt = fix (fun f y ->\n if y>=n || visited.(y).(x) || mat.(y).(x) <> pt then y-1 else f (y+1)) y in\n for i=0 to n-1 do\n for j=0 to n-1 do\n if visited.(i).(j) then ()\n else (\n let pat = mat.(i).(j) in\n let bottom = fy i j pat in\n let finalize x =\n for ii=i to bottom do\n for jj=j to x-1 do\n visited.(ii).(jj) <- true\n done\n done;\n in\n let p,q = fix (fun f (p,q) x ->\n if x>=n then (\n finalize x; (p,q)\n ) else\n let b1 = fy i x pat in\n if b1 <> bottom then (\n finalize x; (p,q)\n ) else f (p,q+1) (x+1)\n ) (bottom+1,1) (j+1) in\n g := gcd !g @@ gcd p q;\n (* Printf.printf \"%2d %2d :: %2d %2d\\n\" i j p q;\n iter (fun b ->\n iter (fun f -> Printf.printf @@ if f then \"t \" else \"_ \") b; print_newline ()\n ) visited *)\n )\n done;\n done;\n print_int @@ !g\n))"}], "negative_code": [{"source_code": "\nlet int_of_hex c = match c with\n| '0' .. '9' -> int_of_char c - int_of_char '0'\n| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10\n| _ -> failwith \"\"\nlet divisors n = (* O(sqrt n) *)\n let rec f0 i a =\n if i*i > n then a\n else if i*i = n && n mod i = 0 then i::a\n else if n mod i = 0 then f0 (i+1) (i::(n/i)::a)\n else f0 (i+1) a in f0 1 []\nlet binary_search ng ok f = let d = if ng < ok then 1 else -1 in\n let rec f0 ng ok =\n if abs (ok - ng) <= 1 then ok\n else let mid = ng + (ok - ng) / 2 in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-d) (ok+d)\n;;\nScanf.(Array.(scanf \" %d\" @@ fun n ->\n let mat = make_matrix n n 0 in\n init n (fun i -> scanf \" %s\" @@ fun s ->\n String.iteri (fun j c ->\n let ih = int_of_hex c in\n mat.(i).(4*j) <- ih land 8 / 8;\n mat.(i).(4*j+1) <- ih land 4 / 4;\n mat.(i).(4*j+2) <- ih land 2 / 2;\n mat.(i).(4*j+3) <- ih land 1;\n ) s\n ) |> ignore;\n (* iter (fun a ->\n iter (fun v ->\n Printf.printf \"%d \" v\n ) a; print_newline ()\n ) mat; *)\n let cml = make_matrix (n+1) (n+1) 0 in\n iteri (fun i a ->\n iteri (fun j _ ->\n cml.(i+1).(j+1) <- cml.(i+1).(j) + mat.(i).(j)\n ) a\n ) mat;\n iteri (fun j a ->\n iteri (fun i _ ->\n cml.(i+1).(j+1) <- cml.(i+1).(j+1) + cml.(i).(j+1)\n ) a\n ) mat;\n (* iter (fun a ->\n iter (fun v ->\n Printf.printf \"%2d \" v\n ) a; print_newline ()\n ) cml; *)\n let get d y x =\n cml.(y+d).(x+d) - cml.(y+d).(x) - cml.(y).(x+d) + cml.(y).(x)\n in\n let divs = divisors n |> List.sort compare |> of_list in\n (* iter (Printf.printf \"%2d; \") divs; print_newline (); *)\n print_int @@ divs.(\n binary_search (length divs-1) 0 (fun i ->\n let d = divs.(i) in\n let f = ref true in\n (* Printf.printf \"%d:\\n\" d; *)\n init (n/d) (fun y ->\n init (n/d) (fun x ->\n let w = get d (y*d) (x*d) in\n (* Printf.printf \" %2d,%2d :: %2d\\n\" (y*d) (x*d) w; *)\n if w=d*d || w=0 then ()\n else f := false\n ) |> ignore\n ) |> ignore; !f\n ))\n));;"}, {"source_code": "let int_of_hex c = match c with\n| '0' .. '9' -> int_of_char c - int_of_char '0'\n| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10\n| _ -> failwith \"\"\nlet divisors n = (* O(sqrt n) *)\n let rec f0 i a =\n if i*i > n then a\n else if i*i = n && n mod i = 0 then i::a\n else if n mod i = 0 then f0 (i+1) (i::(n/i)::a)\n else f0 (i+1) a in f0 1 []\nlet binary_search ng ok f = let d = if ng < ok then 1 else -1 in\n let rec f0 ng ok =\n if abs (ok - ng) <= 1 then ok\n else let mid = ng + (ok - ng) / 2 in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-d) (ok+d)\n;;\nScanf.(Array.(scanf \" %d\" @@ fun n ->\n let mat = make_matrix n n 0 in\n init n (fun i -> scanf \" %s\" @@ fun s ->\n String.iteri (fun j c ->\n let ih = int_of_hex c in\n mat.(i).(4*j) <- ih land 8 / 8;\n mat.(i).(4*j+1) <- ih land 4 / 4;\n mat.(i).(4*j+2) <- ih land 2 / 2;\n mat.(i).(4*j+3) <- ih land 1;\n ) s\n ) |> ignore;\n (* iter (fun a ->\n iter (fun v ->\n Printf.printf \"%d \" v\n ) a; print_newline ()\n ) mat; *)\n let cml = make_matrix (n+1) (n+1) 0 in\n iteri (fun i a ->\n iteri (fun j _ ->\n cml.(i+1).(j+1) <- cml.(i+1).(j) + mat.(i).(j)\n ) a\n ) mat;\n iteri (fun j a ->\n iteri (fun i _ ->\n cml.(i+1).(j+1) <- cml.(i+1).(j+1) + cml.(i).(j+1)\n ) a\n ) mat;\n (* iter (fun a ->\n iter (fun v ->\n Printf.printf \"%2d \" v\n ) a; print_newline ()\n ) cml; *)\n let get d y x =\n cml.(y+d).(x+d) - cml.(y+d).(x) - cml.(y).(x+d) + cml.(y).(x)\n in\n let divs = divisors n |> List.sort compare |> of_list in\n print_int @@ divs.(\n binary_search (length divs-1) 0 (fun i ->\n let d = divs.(i) in\n let f = ref true in\n init (n/d) (fun y ->\n init (n/d) (fun x ->\n let w = get d y x in\n if w=d*d || w=0 then ()\n else f := false\n ) |> ignore\n ) |> ignore; !f\n ))\n))"}, {"source_code": "let int_of_hex c = match c with\n| '0' .. '9' -> int_of_char c - int_of_char '0'\n| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10\n| _ -> failwith \"\"\nlet rec fix f x = f (fix f) x\nlet gcd = fix (fun f m n ->\n if n=0 then m else f n (m mod n))\n;;\nScanf.(Array.(scanf \" %d\" @@ fun n ->\n let mat = make_matrix n n 0 in\n init n (fun i -> scanf \" %s\" @@ fun s ->\n String.iteri (fun j c ->\n let ih = int_of_hex c in\n mat.(i).(4*j) <- ih land 8 / 8;\n mat.(i).(4*j+1) <- ih land 4 / 4;\n mat.(i).(4*j+2) <- ih land 2 / 2;\n mat.(i).(4*j+3) <- ih land 1;\n ) s\n ) |> ignore;\n let visited = make_matrix n n false in\n let g = ref n in\n let rec visit y x c =\n if y >= n || x >= n || visited.(y).(x) || mat.(y).(x) <> c then 0,0\n else (\n visited.(y).(x) <- true;\n let p,q = visit (y+1) x c in\n let r,s = visit y (x+1) c in\n p+r+1,q+s+1\n )\n in\n for i=0 to n-1 do\n for j=0 to n-1 do\n if visited.(i).(j) then ()\n else (\n let p,q = visit i j mat.(i).(j) in\n g := gcd !g @@ gcd p q;\n )\n done;\n done;\n print_int @@ !g\n))"}], "src_uid": "31d95251cd79d889ff9f0a624ef31394"} {"nl": {"description": "You are given a positive decimal number x.Your task is to convert it to the \"simple exponential notation\".Let x\u2009=\u2009a\u00b710b, where 1\u2009\u2264\u2009a\u2009<\u200910, then in general case the \"simple exponential notation\" looks like \"aEb\". If b equals to zero, the part \"Eb\" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.", "input_spec": "The only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types \"float\", \"double\" and other.", "output_spec": "Print the only line \u2014 the \"simple exponential notation\" of the given number x.", "sample_inputs": ["16", "01.23400", ".100", "100."], "sample_outputs": ["1.6E1", "1.234", "1E-1", "1E2"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let (s, e) =\n try\n let i = String.index s '.' in\n let n = String.length s in\n\t(String.sub s 0 i ^ String.sub s (i + 1) (n - i - 1), -(n - i - 1))\n with\n |\tNot_found -> (s, 0)\n in\n let s =\n let n = String.length s in\n let pos = ref 0 in\n while !pos < n && s.[!pos] = '0' do\n\tincr pos\n done;\n String.sub s !pos (n - !pos)\n in\n let (s, e) =\n let n = String.length s in\n let e = ref e in\n let pos = ref n in\n while !pos > 0 && s.[!pos - 1] = '0' do\n\tdecr pos;\n\tincr e;\n done;\n (String.sub s 0 !pos, !e)\n in\n let n = String.length s in\n let e = e + n - 1 in\n if n > 1\n then Printf.printf \"%c.%s\" s.[0] (String.sub s 1 (n - 1))\n else Printf.printf \"%s\" s;\n if e <> 0\n then Printf.printf \"E%d\" e;\n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "b1eebb3928925b84a95b9f1e5a31e4f3"} {"nl": {"description": "A rooted tree is a non-directed connected graph without any cycles with a distinguished vertex, which is called the tree root. Consider the vertices of a rooted tree, that consists of n vertices, numbered from 1 to n. In this problem the tree root is the vertex number 1.Let's represent the length of the shortest by the number of edges path in the tree between vertices v and u as d(v,\u2009u).A parent of vertex v in the rooted tree with the root in vertex r (v\u2009\u2260\u2009r) is vertex pv, such that d(r,\u2009pv)\u2009+\u20091\u2009=\u2009d(r,\u2009v) and d(pv,\u2009v)\u2009=\u20091. For example, on the picture the parent of vertex v\u2009=\u20095 is vertex p5\u2009=\u20092.One day Polycarpus came across a rooted tree, consisting of n vertices. The tree wasn't exactly ordinary: it had strings written on its edges. Polycarpus positioned the tree on the plane so as to make all edges lead from top to bottom if you go from the vertex parent to the vertex (see the picture). For any edge that lead from vertex pv to vertex v (1\u2009<\u2009v\u2009\u2264\u2009n), he knows string sv that is written on it. All strings are written on the edges from top to bottom. For example, on the picture s7=\"ba\". The characters in the strings are numbered starting from 0. An example of Polycarpus's tree (corresponds to the example from the statement) Polycarpus defines the position in this tree as a specific letter on a specific string. The position is written as a pair of integers (v,\u2009x) that means that the position is the x-th letter of the string sv (1\u2009<\u2009v\u2009\u2264\u2009n, 0\u2009\u2264\u2009x\u2009<\u2009|sv|), where |sv| is the length of string sv. For example, the highlighted letters are positions (2,\u20091) and (3,\u20091).Let's consider the pair of positions (v,\u2009x) and (u,\u2009y) in Polycarpus' tree, such that the way from the first position to the second goes down on each step. We will consider that the pair of such positions defines string z. String z consists of all letters on the way from (v,\u2009x) to (u,\u2009y), written in the order of this path. For example, in the picture the highlighted positions define string \"bacaba\".Polycarpus has a string t, he wants to know the number of pairs of positions that define string t. Note that the way from the first position to the second in the pair must go down everywhere. Help him with this challenging tree-string problem!", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of vertices of Polycarpus's tree. Next n\u2009-\u20091 lines contain the tree edges. The i-th of them contains number pi\u2009+\u20091 and string si\u2009+\u20091 (1\u2009\u2264\u2009pi\u2009+\u20091\u2009\u2264\u2009n;\u00a0pi\u2009+\u20091\u2009\u2260\u2009(i\u2009+\u20091)). String si\u2009+\u20091 is non-empty and consists of lowercase English letters. The last line contains string t. String t consists of lowercase English letters, its length is at least 2. It is guaranteed that the input contains at most 3\u00b7105 English letters.", "output_spec": "Print a single integer \u2014 the required number. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["7\n1 ab\n5 bacaba\n1 abacaba\n2 aca\n5 ba\n2 ba\naba", "7\n1 ab\n5 bacaba\n1 abacaba\n2 aca\n5 ba\n2 ba\nbacaba"], "sample_outputs": ["6", "4"], "notes": "NoteIn the first test case string \"aba\" is determined by the pairs of positions: (2, 0) and (5, 0); (5, 2) and (6, 1); (5, 2) and (3, 1); (4, 0) and (4, 2); (4, 4) and (4, 6); (3, 3) and (3, 5).Note that the string is not defined by the pair of positions (7, 1) and (5, 0), as the way between them doesn't always go down."}, "positive_code": [{"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\n(* kmp algorithm. *)\n(* memo.(i) will store the length of the longest prefix of s\n that matches the tail of s1...si *)\nlet kmptable s n = \n let memo = Array.make n 0 in\n for i=1 to (n-1) do\n let rec loop j = \n\tif s.[i] = s.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)\n in memo.(i) <- loop memo.(i-1)\n done;\n memo\n\n(*\n(* returns table.\n table.(i) will store the length of the longest prefix of ms\n that matches the tail of ts0...tsi *)\nlet tailtable ts n ms m = \n let memo = kmptable ms m in\n let table = Array.make n 0 in\n table.(0) <- if ts.[0] = ms.[0] then 1 else 0;\n for i=1 to (n-1) do\n let rec loop j = \n\tif ts.[i] = ms.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)\n in\n\ttable.(i) <- loop (if table.(i-1) < m then table.(i-1) else memo.(m-1))\n done;\n table\n*)\n\nlet solve child n pattern =\n let m = String.length pattern in\n let memo = kmptable pattern m in\n\n let run_kmp s j =\n let n = String.length s in\n let rec outer_loop i count j = if i=n then (j, count) else\n let rec loop j = \n\tif s.[i] = pattern.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)\n in\n let j = loop j in\n let count = if j=m then count+1 else count in\n let j = if j=m then memo.(j-1) else j in\n\touter_loop (i+1) count j\n in\n outer_loop 0 0 j\n in\n \n let rec dfs v j ac = \n(* Printf.printf \"at node %d (j=%d, ac=%d)\\n\" v j ac; *)\n List.fold_left (\n fun ac (w,s) ->\n(*\tPrintf.printf \" edge: (%d, %d) = \\\"%s\\\"\\n\" v w s; *)\n\tlet (j', count) = run_kmp s j in\n\t dfs w j' (ac + count)\n ) ac child.(v)\n in\n dfs 0 0 0\n\nlet () =\n let n = read_int() in\n let child = Array.make n [] in\n for i=1 to n-1 do\n let p = read_int() -1 in\n let s = read_string() in\n\tchild.(p) <- (i,s)::child.(p);\n done;\n\n let pattern = read_string() in\n\n Printf.printf \"%d\\n\" (solve child n pattern)\n"}, {"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\n(* kmp algorithm. *)\n(* memo.(i) will store the length of the longest prefix of s\n that matches the tail of s1...si *)\nlet kmptable s n = \n let memo = Array.make n 0 in\n for i=1 to (n-1) do\n let rec loop j = \n\tif s.[i] = s.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)\n in memo.(i) <- loop memo.(i-1)\n done;\n memo\n\n(*\n(* returns table.\n table.(i) will store the length of the longest prefix of ms\n that matches the tail of ts0...tsi *)\nlet tailtable ts n ms m = \n let memo = kmptable ms m in\n let table = Array.make n 0 in\n table.(0) <- if ts.[0] = ms.[0] then 1 else 0;\n for i=1 to (n-1) do\n let rec loop j = \n\tif ts.[i] = ms.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)\n in\n\ttable.(i) <- loop (if table.(i-1) < m then table.(i-1) else memo.(m-1))\n done;\n table\n*)\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\nlet n2l n = char_of_int ((int_of_char 'a') + n)\n\nlet solve child n pattern =\n let m = String.length pattern in\n let memo = kmptable pattern m in\n let jupdate_array = Array.make_matrix m 26 (-1) in\n\n let rec jupdate c x j = \n if jupdate_array.(j).(x) >= 0 then jupdate_array.(j).(x) else\n let j' = if c = pattern.[j] then j+1 else if j=0 then 0 else jupdate c x memo.(j-1) in\n\tjupdate_array.(j).(x) <- j';\n\tj'\n in\n\n let run_kmp s j =\n let n = String.length s in\n let rec loop i count j = if i=n then (j, count) else\n let j = jupdate s.[i] (l2n s.[i]) j in\n let count = if j=m then count+1 else count in\n let j = if j=m then memo.(j-1) else j in\n\tloop (i+1) count j\n in\n loop 0 0 j\n in\n \n let rec dfs v j ac = \n(* Printf.printf \"at node %d (j=%d, ac=%d)\\n\" v j ac; *)\n List.fold_left (\n fun ac (w,s) ->\n(*\tPrintf.printf \" edge: (%d, %d) = \\\"%s\\\"\\n\" v w s; *)\n\tlet (j', count) = run_kmp s j in\n\t dfs w j' (ac + count)\n ) ac child.(v)\n in\n dfs 0 0 0\n\nlet () =\n let n = read_int() in\n let child = Array.make n [] in\n for i=1 to n-1 do\n let p = read_int() -1 in\n let s = read_string() in\n\tchild.(p) <- (i,s)::child.(p);\n done;\n\n let pattern = read_string() in\n\n Printf.printf \"%d\\n\" (solve child n pattern)\n"}], "negative_code": [], "src_uid": "2e08077d0b49c52586266ddcc12edcb5"} {"nl": {"description": "Mihai has an $$$8 \\times 8$$$ chessboard whose rows are numbered from $$$1$$$ to $$$8$$$ from top to bottom and whose columns are numbered from $$$1$$$ to $$$8$$$ from left to right.Mihai has placed exactly one bishop on the chessboard. The bishop is not placed on the edges of the board. (In other words, the row and column of the bishop are between $$$2$$$ and $$$7$$$, inclusive.)The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. An example of a bishop on a chessboard. The squares it attacks are marked in red. Mihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 36$$$)\u00a0\u2014 the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either '#' or '.', denoting a square under attack and a square not under attack, respectively.", "output_spec": "For each test case, output two integers $$$r$$$ and $$$c$$$ ($$$2 \\leq r, c \\leq 7$$$)\u00a0\u2014 the row and column of the bishop. The input is generated in such a way that there is always exactly one possible location of the bishop that is not on the edge of the board.", "sample_inputs": ["3\n\n\n\n\n.....#..\n\n#...#...\n\n.#.#....\n\n..#.....\n\n.#.#....\n\n#...#...\n\n.....#..\n\n......#.\n\n\n\n\n#.#.....\n\n.#......\n\n#.#.....\n\n...#....\n\n....#...\n\n.....#..\n\n......#.\n\n.......#\n\n\n\n\n.#.....#\n\n..#...#.\n\n...#.#..\n\n....#...\n\n...#.#..\n\n..#...#.\n\n.#.....#\n\n#......."], "sample_outputs": ["4 3\n2 2\n4 5"], "notes": "NoteThe first test case is pictured in the statement. Since the bishop lies in the intersection row $$$4$$$ and column $$$3$$$, the correct output is 4 3."}, "positive_code": [{"source_code": "(*\nhttps://codeforces.com/contest/1681/submission/163367661\nSee also: https://codeforces.com/contest/1681/submission/163367661\n*)\n\nopen Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\n\n(* Main Code file *)\n \nlet () = \n let t = read_int() in\n let n = 8 in\n for t1=1 to t do\n (* printf \"TC %d\\n\" t1; *)\n let rows = Array.init n (fun index -> read_string()) in\n try \n for i=0 to n - 1 do\n let s: string = (Array.get rows i) in \n (* printf \"%d ^%s$\\n\" i s; *)\n for j=1 to n-2 do\n (* printf \"%c \" s.[0]; *)\n (* printf \"> %d %d %c %c %c\\n\" i j\n s.[j - 1] s.[j] s.[j + 1];*)\n if s.[j - 1] == '#' && s.[j] == '.' && s.[j + 1] == '#' then\n let () = (printf \"%d %d\\n\" (i + 2) (j + 1)) in\n raise Exit\n else ()\n done;\n done;\n with Exit -> ()\n done;\n\n"}], "negative_code": [], "src_uid": "b0f968ca75fbea2f11a7e4b9006f136e"} {"nl": {"description": "Alice is visiting New York City. To make the trip fun, Alice will take photos of the city skyline and give the set of photos as a present to Bob. However, she wants to find the set of photos with maximum beauty and she needs your help. There are $$$n$$$ buildings in the city, the $$$i$$$-th of them has positive height $$$h_i$$$. All $$$n$$$ building heights in the city are different. In addition, each building has a beauty value $$$b_i$$$. Note that beauty can be positive or negative, as there are ugly buildings in the city too. A set of photos consists of one or more photos of the buildings in the skyline. Each photo includes one or more buildings in the skyline that form a contiguous segment of indices. Each building needs to be in exactly one photo. This means that if a building does not appear in any photo, or if a building appears in more than one photo, the set of pictures is not valid. The beauty of a photo is equivalent to the beauty $$$b_i$$$ of the shortest building in it. The total beauty of a set of photos is the sum of the beauty of all photos in it. Help Alice to find the maximum beauty a valid set of photos can have. ", "input_spec": "The first line contains an integer $$$n$$$ ($$$1 \\le n \\le 3 \\cdot 10^5$$$), the number of buildings on the skyline. The second line contains $$$n$$$ distinct integers $$$h_1, h_2, \\ldots, h_n$$$ ($$$1 \\le h_i \\le n$$$). The $$$i$$$-th number represents the height of building $$$i$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$-10^9 \\le b_i \\le 10^9$$$). The $$$i$$$-th number represents the beauty of building $$$i$$$.", "output_spec": "Print one number representing the maximum beauty Alice can achieve for a valid set of photos of the skyline. ", "sample_inputs": ["5\n1 2 3 5 4\n1 5 3 2 4", "5\n1 4 3 2 5\n-3 4 -10 2 7", "2\n2 1\n-2 -3", "10\n4 7 3 2 5 1 9 10 6 8\n-4 40 -46 -8 -16 4 -10 41 12 3"], "sample_outputs": ["15", "10", "-3", "96"], "notes": "NoteIn the first example, Alice can achieve maximum beauty by taking five photos, each one containing one building. In the second example, Alice can achieve a maximum beauty of $$$10$$$ by taking four pictures: three just containing one building, on buildings $$$1$$$, $$$2$$$ and $$$5$$$, each photo with beauty $$$-3$$$, $$$4$$$ and $$$7$$$ respectively, and another photo containing building $$$3$$$ and $$$4$$$, with beauty $$$2$$$. In the third example, Alice will just take one picture of the whole city.In the fourth example, Alice can take the following pictures to achieve maximum beauty: photos with just one building on buildings $$$1$$$, $$$2$$$, $$$8$$$, $$$9$$$, and $$$10$$$, and a single photo of buildings $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, and $$$7$$$. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet long x = Int64.of_int x\n\nlet minfty = Int64.of_float (-1e18)\n\nlet make_fenwick_tree n =\n (Array.make (n+1) minfty, n)\n\nlet put_in_tree (a,n) i x =\n(* put x into the fenwick tree at position i, which is currently minfty *)\n let rec loop i = if i>0 then (\n a.(i) <- max a.(i) x;\n loop (i - (i land (-i)))\n ) in\n loop (i+1)\n\nlet range_suffix (a,n) j =\n let rec loop i ac = if i > n then ac else (\n loop (i + (i land (-i))) (max ac a.(i))\n ) in\n loop (j+1) minfty\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let h = Array.init n read_int in\n let b = Array.init n read_long in\n\n let v = Array.make n 0L in\n let s = Array.make n (-1) in\n\n let rec scan li i = if i < n then\n match li with\n | [] -> scan [i] (i+1)\n | hd::t ->\n\tif h.(hd) > h.(i) then scan t i else (\n\t s.(i) <- hd;\n\t scan (i::li) (i+1)\n\t)\n in\n\n scan [] 0;\n\n let ft = make_fenwick_tree n in\n\n v.(0) <- b.(0);\n put_in_tree ft 0 v.(0);\n\n for i=1 to n-1 do\n v.(i) <-\n if s.(i) = -1 then max b.(i) (b.(i) ++ range_suffix ft 0)\n else max v.(s.(i)) (b.(i) ++ range_suffix ft (s.(i)));\n put_in_tree ft i v.(i)\n done;\n\n printf \"%Ld\\n\" v.(n-1)\n"}], "negative_code": [], "src_uid": "c21b78e3a3950446541a2a067f1e4d60"} {"nl": {"description": "Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.", "input_spec": "The first line of input contains two integers n and q (1\u2009\u2264\u2009n,\u2009q\u2009\u2264\u2009300\u2009000)\u00a0\u2014 the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typei\u00a0\u2014 type of the i-th event. If typei\u2009=\u20091 or typei\u2009=\u20092 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1\u2009\u2264\u2009typei\u2009\u2264\u20093,\u20091\u2009\u2264\u2009xi\u2009\u2264\u2009n,\u20091\u2009\u2264\u2009ti\u2009\u2264\u2009q).", "output_spec": "Print the number of unread notifications after each event.", "sample_inputs": ["3 4\n1 3\n1 1\n1 2\n2 3", "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3"], "sample_outputs": ["1\n2\n3\n2", "1\n2\n3\n0\n1\n2"], "notes": "NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let q = read_int () in\n\n let alist = Array.make (n+1) [] in\n let alert = Array.make (q+1) 0 in\n\n let rec loop i t ngen ncleared clearedto =\n if i > 0 then printf \"%d\\n\" (ngen - ncleared);\n if i < q then\n match read_int() with\n\t| 1 ->\n\t let x = read_int () in\n\t alert.(t) <- 1;\n\t alist.(x) <- t :: alist.(x);\n\t loop (i+1) (t+1) (ngen+1) ncleared clearedto\n\t| 2 ->\n\t let x = read_int () in\n\t let nc = List.fold_left (\n\t fun nc t ->\n\t let nc = nc + alert.(t) in\n\t alert.(t) <- 0;\n\t nc\n\t ) 0 alist.(x)\n\t in\n\t alist.(x) <- [];\n\t loop (i+1) t ngen (ncleared + nc) clearedto\n\t| 3 ->\n\t let tt = read_int() in\n\t let cc = ref 0 in\n\t for y = clearedto to tt-1 do\n\t cc := alert.(y) + !cc;\n\t alert.(y) <- 0;\n\t done;\n\t let clearedto = max clearedto tt in\n\t loop (i+1) t ngen (ncleared + !cc) clearedto\n\t| _ -> failwith \"bad input\"\n in\n\n loop 0 0 0 0 0\n"}], "negative_code": [], "src_uid": "a5e724081ad84f88813bb4de23a8230e"} {"nl": {"description": "Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form \"reader entered room\", \"reader left room\". Every reader is assigned a registration number during the registration procedure at the library \u2014 it's a unique integer from 1 to 106. Thus, the system logs events of two forms: \"+ ri\" \u2014 the reader with registration number ri entered the room; \"- ri\" \u2014 the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.", "input_spec": "The first line contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as \"+ ri\" or \"- ri\", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.", "output_spec": "Print a single integer \u2014 the minimum possible capacity of the reading room.", "sample_inputs": ["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"], "sample_outputs": ["3", "2", "1"], "notes": "NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n\n let inc = Array.make n 0 in\n let id = Array.make n 0 in\n \n for i=0 to n-1 do\n inc.(i) <- if read_string() = \"-\" then -1 else 1;\n id.(i) <- read_int()\n done;\n\n let rogue = ref [] in\n\n let h = Hashtbl.create 10 in\n\n for i=0 to n-1 do\n if not (Hashtbl.mem h id.(i)) then (\n Hashtbl.replace h id.(i) true;\n if inc.(i) = -1 then rogue := id.(i) :: !rogue\n )\n done;\n\n let rec make_events ac i = if i=n then List.rev ac else\n make_events (id.(i) :: ac) (i+1)\n in\n\n let events = (!rogue) @ (make_events [] 0) in\n\n let h = Hashtbl.create 10 in\n \n let rec scan ev maxsize =\n match ev with [] -> maxsize\n | id::tail ->\n\tif Hashtbl.mem h id then (\n\t Hashtbl.remove h id;\n\t scan tail maxsize\n\t) else (\n\t Hashtbl.replace h id true;\n\t scan tail (max maxsize (Hashtbl.length h))\n\t)\n in\n\n let answer = scan events 0 in\n\n printf \"%d\\n\" answer;\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let a = Array.make 1_000_000 false in\n let cur = ref 0 and best = ref 0 in\n for i = 1 to n do\n Scanf.scanf \"%c %d\\n\" (fun c x ->\n if c = '-' && not a.(x - 1)\n then incr best\n else begin\n a.(x - 1) <- c = '+';\n if a.(x - 1) then begin\n incr cur;\n best := max !best !cur\n end else decr cur\n end)\n done;\n\n Printf.printf \"%d\\n\" !best)\n"}], "negative_code": [], "src_uid": "6cfd3b0a403212ec68bac1667bce9ef1"} {"nl": {"description": "There are n boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains ai balls, all of which have color i. You have to write a program that will divide all balls into sets such that: each ball belongs to exactly one of the sets, there are no empty sets, there is no set containing two (or more) balls of different colors (each set contains only balls of one color), there are no two sets such that the difference between their sizes is greater than 1. Print the minimum possible number of sets.", "input_spec": "The first line contains one integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009500). The second line contains n integer numbers a1,\u2009a2,\u2009... ,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print one integer number \u2014 the minimum possible number of sets.", "sample_inputs": ["3\n4 7 8", "2\n2 7"], "sample_outputs": ["5", "4"], "notes": "NoteIn the first example the balls can be divided into sets like that: one set with 4 balls of the first color, two sets with 3 and 4 balls, respectively, of the second color, and two sets with 4 balls of the third color."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let isqrt n = int_of_float (sqrt (float_of_int n)) in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a;\n in\n let m = isqrt a.(0) in\n let res = ref 1000000000000000000L in\n let calc k =\n try\n let t = ref 0L in\n\tfor i = 0 to n - 1 do\n\t let q = (a.(i) - 1) / (k + 1) + 1 in\n\t let r = q * (k + 1) - a.(i) in\n\t if q >= r\n\t then t := !t +| Int64.of_int q\n\t else raise Not_found\n\tdone;\n(*Printf.printf \"calc %d %Ld\\n\" k !t;*)\n\tres := min !res !t\n with\n | Not_found -> ()\n in\n for i = 1 to m do\n calc i\n done;\n for i = 1 to m do\n calc (a.(0) / i);\n if a.(0) / i - 1 > 0\n then calc (a.(0) / i - 1);\n done;\n Printf.printf \"%Ld\\n\" !res\n"}], "negative_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let isqrt n = int_of_float (sqrt (float_of_int n)) in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a;\n in\n let m = isqrt a.(0) in\n let res = ref 1000000000000000000L in\n let calc k =\n try\n let t = ref 0L in\n\tfor i = 0 to n - 1 do\n\t let q = a.(i) / k in\n\t let r = a.(i) mod k in\n\t if q >= r\n\t then t := !t +| Int64.of_int q\n\t else raise Not_found\n\tdone;\n(*Printf.printf \"calc %d %Ld\\n\" k !t;*)\n\tres := min !res !t\n with\n | Not_found -> ()\n in\n for i = 1 to m do\n calc i\n done;\n for i = 1 to m do\n calc (a.(0) / i);\n if a.(0) / i - 1 > 0\n then calc (a.(0) / i - 1);\n done;\n Printf.printf \"%Ld\\n\" !res\n"}], "src_uid": "ad5ec7026cbefedca288df14c2bc58e5"} {"nl": {"description": "An array is sorted if it has no inversionsA Young BoyYou are given an array of $$$n$$$ positive integers $$$a_1,a_2,\\ldots,a_n$$$. In one operation you do the following: Choose any integer $$$x$$$. For all $$$i$$$ such that $$$a_i = x$$$, do $$$a_i := 0$$$ (assign $$$0$$$ to $$$a_i$$$). Find the minimum number of operations required to sort the array in non-decreasing order.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$). The second line of each test case contains $$$n$$$ positive integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1 \\le a_i \\le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer\u00a0\u2014 the minimum number of operations required to sort the array in non-decreasing order.", "sample_inputs": ["5\n\n3\n\n3 3 2\n\n4\n\n1 3 1 3\n\n5\n\n4 1 5 3 2\n\n4\n\n2 4 1 2\n\n1\n\n1"], "sample_outputs": ["1\n2\n4\n3\n0"], "notes": "NoteIn the first test case, you can choose $$$x = 3$$$ for the operation, the resulting array is $$$[0, 0, 2]$$$.In the second test case, you can choose $$$x = 1$$$ for the first operation and $$$x = 3$$$ for the second operation, the resulting array is $$$[0, 0, 0, 0]$$$."}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nlet () =\n let t = read_int () in\n\n for _ = 1 to t do\n let n = read_int () in\n let a = read_array read_int n in\n let pos = A.make (n + 1) (-1) in\n A.iteri (fun i x -> pos.(x) <- i) a;\n\n let i = ref (n - 2) in\n while !i >= 0 && a.(!i) <= a.(!i + 1) do i := !i - 1 done;\n let decr_pos = !i + 1 in\n if (decr_pos = 0) then\n pf \"0\\n\"\n else begin\n let diff = Array.make (n + 1) false in\n let cnt = ref 0 in\n let mx = ref 0 in\n i := 0;\n while !i < n do\n mx := max !mx pos.(a.(!i));\n if (not diff.(a.(!i))) then cnt := !cnt + 1;\n diff.(a.(!i)) <- true;\n if !i = !mx && !mx + 1 >= decr_pos then begin\n pf \"%d\\n\" !cnt;\n i := n;\n end;\n i := !i + 1;\n done\n end\n done"}, {"source_code": "let get_num () =\n let rec f acc =\n try\n let c = input_byte stdin in\n if int_of_char '0' <= c && c <= int_of_char '9' then\n f ((acc * 10) + c - int_of_char '0')\n else if acc > 0 then Some acc\n else None\n with End_of_file -> if acc > 0 then Some acc else None\n in\n f 0\n\nmodule Int_Set = Set.Make (struct\n type t = int\n\n let compare = compare\nend)\n\nlet solve_case () =\n match get_num () with\n | Some n ->\n let rec f i set pending prev =\n if i = n then set\n else\n let i = i + 1 in\n match get_num () with\n | Some a ->\n let a = if Int_Set.mem a set then 0 else a in\n if a < prev then\n let set = Int_Set.union set pending in\n f i set (Int_Set.singleton a) a\n else f i set (Int_Set.add a pending) a\n | _ -> exit 1\n in\n let s = f 0 Int_Set.empty Int_Set.empty 0 in\n let s = Int_Set.remove 0 s in\n let fold_f a x = x + 1 in\n let ans = Int_Set.fold fold_f s 0 in\n print_int ans\n | _ -> exit 1\n\nlet () =\n match get_num () with\n | Some t ->\n let rec f i =\n if i = 0 then ()\n else\n let () = solve_case () in\n let () = print_newline () in\n f (i - 1)\n in\n f t\n | _ -> exit 1\n"}], "negative_code": [], "src_uid": "68e830551c1580bb5aff40d7848d968d"} {"nl": {"description": "Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps. Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1,\u2009...,\u20092ak if and only if there exists a non-negative integer x such that 2a1\u2009+\u20092a2\u2009+\u2009...\u2009+\u20092ak\u2009=\u20092x, i. e. the sum of those numbers is a power of two.Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps. ", "input_spec": "The first line of input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106), the number of weights. The second line contains n integers w1,\u2009...,\u2009wn separated by spaces (0\u2009\u2264\u2009wi\u2009\u2264\u2009106 for each 1\u2009\u2264\u2009i\u2009\u2264\u2009n), the powers of two forming the weights values.", "output_spec": "Print the minimum number of steps in a single line.", "sample_inputs": ["5\n1 1 2 3 3", "4\n0 1 2 3"], "sample_outputs": ["2", "4"], "notes": "NoteIn the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two.In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two."}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let w = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n let s = Array.make 2_000_000 false in\n let on = ref 0 in\n\n let rec insert a =\n if s.(a) then begin\n s.(a) <- false;\n decr on;\n insert (a + 1)\n end else begin\n s.(a) <- true;\n incr on\n end\n in\n\n for i = 0 to n - 1 do\n insert w.(i)\n done;\n\n Printf.printf \"%d\\n\" !on)\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let m = 1000030 in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a;\n let b = Array.make m false in\n for i = 0 to n - 1 do\n\tlet pos = ref a.(i) in\n\t while b.(!pos) do\n\t b.(!pos) <- false;\n\t incr pos;\n\t done;\n\t b.(!pos) <- true\n done;\n let res = ref 0 in\n\tfor i = 0 to m - 1 do\n\t if b.(i)\n\t then incr res\n\tdone;\n\tPrintf.printf \"%d\\n\" !res\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet () =\n let m = 1_000_100 in\n let a = Array.make m 0 in\n let n = read_int() in\n for i = 1 to n do\n let x = read_int() in\n a.(x) <- a.(x) + 1\n done;\n let rec go i carry acc =\n if i = m then acc\n else go (i+1) ((carry + a.(i)) / 2) (acc + ((carry + a.(i)) mod 2))\n in\n Printf.printf \"%d\\n\" (go 0 0 0);;\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\nlet maxw = 1000100 in\nlet fr = Array.init (maxw+10) (fun _ -> 0) in\n\nlet rec read_loop i = \n\tif i < n then\n\tbegin\n\t\tlet w = (Scanf.scanf \"%d%_c\" (fun x -> x)) in fr.(w) <- succ fr.(w);\n\t\tread_loop (i+1)\n\tend\nin read_loop 0;\n\nlet rec solve_loop i rem needed_steps = \n\tif i <= maxw then\n\t\tlet total = rem + fr.(i) in\n\t\tsolve_loop (i+1) (total/2) (needed_steps + (total mod 2))\n\telse \n\t\tPrintf.printf \"%d\\n\" needed_steps\nin solve_loop 0 0 0);;\n\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\nlet maxw = 1000100 in\nlet fr = Array.init (maxw+10) (fun _ -> 0) in\n\nlet rec read_loop i = \n\tif i < n then\n\tbegin\n\t\tlet w = (Scanf.scanf \"%d%_c\" (fun x -> x)) in Array.set fr w (succ (Array.get fr w));\n\t\tread_loop (i+1)\n\tend\nin read_loop 0;\n\nlet rec solve_loop i rem needed_steps = \n\tif i <= maxw then\n\t\tlet total = rem + fr.(i) in\n\t\tsolve_loop (i+1) (total/2) (needed_steps + (total mod 2))\n\telse \n\t\tPrintf.printf \"%d\\n\" needed_steps\nin solve_loop 0 0 0);;\n\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n let b = Array.make n 0 in\n let pos = ref 0 in\n b.(0) <- a.(0);\n for i = 1 to n - 1 do\n\tincr pos;\n\tb.(!pos) <- a.(i);\n\twhile !pos > 0 && b.(!pos) = b.(!pos - 1) do\n\t decr pos;\n\t b.(!pos) <- b.(!pos) + 1\n\tdone;\n done;\n Printf.printf \"%d\\n\" (!pos + 1)\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a;\n let b = Array.make n 0 in\n let pos = ref 0 in\n b.(0) <- a.(0);\n for i = 1 to n - 1 do\n\tincr pos;\n\tb.(!pos) <- a.(i);\n\twhile !pos > 0 && b.(!pos) = b.(!pos - 1) do\n\t decr pos;\n\t b.(!pos) <- b.(!pos) + 1\n\tdone;\n done;\n Printf.printf \"%d\\n\" (!pos + 1)\n"}], "src_uid": "089eea1841ef10064647e61094c374fd"} {"nl": {"description": "You are given two binary strings $$$a$$$ and $$$b$$$ of the same length. You can perform the following two operations on the string $$$a$$$: Swap any two bits at indices $$$i$$$ and $$$j$$$ respectively ($$$1 \\le i, j \\le n$$$), the cost of this operation is $$$|i - j|$$$, that is, the absolute difference between $$$i$$$ and $$$j$$$. Select any arbitrary index $$$i$$$ ($$$1 \\le i \\le n$$$) and flip (change $$$0$$$ to $$$1$$$ or $$$1$$$ to $$$0$$$) the bit at this index. The cost of this operation is $$$1$$$. Find the minimum cost to make the string $$$a$$$ equal to $$$b$$$. It is not allowed to modify string $$$b$$$.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^6$$$)\u00a0\u2014 the length of the strings $$$a$$$ and $$$b$$$. The second and third lines contain strings $$$a$$$ and $$$b$$$ respectively. Both strings $$$a$$$ and $$$b$$$ have length $$$n$$$ and contain only '0' and '1'.", "output_spec": "Output the minimum cost to make the string $$$a$$$ equal to $$$b$$$.", "sample_inputs": ["3\n100\n001", "4\n0101\n0011"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first example, one of the optimal solutions is to flip index $$$1$$$ and index $$$3$$$, the string $$$a$$$ changes in the following way: \"100\" $$$\\to$$$ \"000\" $$$\\to$$$ \"001\". The cost is $$$1 + 1 = 2$$$.The other optimal solution is to swap bits and indices $$$1$$$ and $$$3$$$, the string $$$a$$$ changes then \"100\" $$$\\to$$$ \"001\", the cost is also $$$|1 - 3| = 2$$$.In the second example, the optimal solution is to swap bits at indices $$$2$$$ and $$$3$$$, the string $$$a$$$ changes as \"0101\" $$$\\to$$$ \"0011\". The cost is $$$|2 - 3| = 1$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\t\n\tlet repm from_ to_ m_init fbod =\n\t\tlet i,f,m = ref ~|from_,ref true,ref m_init in\n\t\twhile !i <= ~|to_ && !f do\n\t\t\tmatch fbod (~~| !i) !m with\n\t\t\t| `Break -> f := false\n\t\t\t| `Break_m m' -> (f := false; m := m')\n\t\t\t| `Ok m' -> (i := !i +$ 1; m := m')\n\t\tdone; !m\n\tlet (@@@) = (@) let (@) a i = a.(~|i)\nend open MyInt64\nlet () =\n\tlet n = get_i64 0 in\n\tlet s,t = scanf \" %s %s\" (fun u v -> u,v)\n\tin let s,t = char_list_of_string s,char_list_of_string t\n\tin let s,t = Array.of_list s,Array.of_list t\n\tin \n\tlet ans,i = ref 0L,ref 0L\n\tin\n\twhile !i < n do let j = !i in\n\t\tif s @ j <> t @ j then (\n\t\t\tif j+1L < n\n\t\t\t&& s @ j+1L = t @ j && s @ j = t @ j+1L then (\n\t\t\t\t(* adjacent swap : cost = 1 *)\n\t\t\t\ti += 2L\n\t\t\t) else (\n\t\t\t\t(* flip : cost = 1 *)\n\t\t\t\ti += 1L\n\t\t\t);\n\t\t\tans += 1L\n\t\t) else i += 1L\n\tdone;\n\t!ans |> printf \"%Ld\\n\""}], "negative_code": [], "src_uid": "a57555f50985c6c3634de1e7c60553bd"} {"nl": {"description": "Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n\u2009-\u20091). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that: he pointed at the person with index (bi\u2009+\u20091)\u00a0mod\u00a0n either with an elbow or with a nod (x\u00a0mod\u00a0y is the remainder after dividing x by y); if j\u2009\u2265\u20094 and the players who had turns number j\u2009-\u20091, j\u2009-\u20092, j\u2009-\u20093, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice; the turn went to person number (bi\u2009+\u20091)\u00a0mod\u00a0n. The person who was pointed on the last turn did not make any actions.The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.You can assume that in any scenario, there is enough juice for everybody.", "input_spec": "The first line contains a single integer n (4\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns. ", "output_spec": "Print a single integer \u2014 the number of glasses of juice Vasya could have drunk if he had played optimally well.", "sample_inputs": ["4\nabbba", "4\nabbab"], "sample_outputs": ["1", "0"], "notes": "NoteIn both samples Vasya has got two turns \u2014 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like \"abbbb\". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different."}, "positive_code": [{"source_code": "\nlet input_int =\n Scanf.scanf \"%d \" (fun x -> x)\n;;\n\nlet input_string =\n Scanf.scanf \"%s \" (fun x -> x)\n;;\n\nlet solve moves member_count =\n let rec solve_aux i ret =\n if i < String.length moves then begin\n if i >= 3 && moves.[i-1] == moves.[i-2]\n && moves.[i-2] == moves.[i-3] then\n solve_aux (i+member_count) (ret+1)\n else\n solve_aux (i+member_count) ret\n end else ret\n in solve_aux 0 0\n;;\n\nlet member_count = input_int in\nlet moves = input_string in\nPrintf.printf \"%d\\n\" (solve moves member_count);\n\n"}, {"source_code": "(* betaveros's polyglot adventure *)\n\nlet people = int_of_string (read_line ());;\nlet moves = read_line ();;\n\nlet canDrink s i = s.[i-1] == s.[i-2] && s.[i-2] == s.[i-3];;\n\nlet rec addDrinkCount s n i accum =\n\tif i >= String.length s then accum\n\telse addDrinkCount s n (i + n) (\n\t\taccum + if canDrink s i then 1 else 0);;\n\nlet solution = addDrinkCount moves people people 0 in\n\tprint_endline (string_of_int solution);;\n"}], "negative_code": [{"source_code": "\nlet input_int =\n Scanf.scanf \"%d \" (fun x -> x)\n;;\n\nlet input_string =\n Scanf.scanf \"%s \" (fun x -> x)\n;;\n\nlet solve moves member_count =\n let rec solve_aux i ret =\n if i < String.length moves then begin\n if i >= 3 && moves.[i-1] == moves.[i-2]\n && moves.[i-2] == moves.[i-3] then\n solve_aux (i+1) (ret+1)\n else\n solve_aux (i+1) ret\n end else ret\n in solve_aux 0 0\n;;\n\nlet member_count = input_int in\nlet moves = input_string in\nPrintf.printf \"%d\\n\" (solve moves member_count);\n\n"}], "src_uid": "5606799ab5345bb9501fa6535e5abef9"} {"nl": {"description": "You are playing a variation of game 2048. Initially you have a multiset $$$s$$$ of $$$n$$$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from $$$s$$$, remove them from $$$s$$$ and insert the number equal to their sum into $$$s$$$.For example, if $$$s = \\{1, 2, 1, 1, 4, 2, 2\\}$$$ and you choose integers $$$2$$$ and $$$2$$$, then the multiset becomes $$$\\{1, 1, 1, 4, 4, 2\\}$$$.You win if the number $$$2048$$$ belongs to your multiset. For example, if $$$s = \\{1024, 512, 512, 4\\}$$$ you can win as follows: choose $$$512$$$ and $$$512$$$, your multiset turns into $$$\\{1024, 1024, 4\\}$$$. Then choose $$$1024$$$ and $$$1024$$$, your multiset turns into $$$\\{2048, 4\\}$$$ and you win.You have to determine if you can win this game.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$) \u2013 the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \\le n \\le 100$$$) \u2014 the number of elements in multiset. The second line of each query contains $$$n$$$ integers $$$s_1, s_2, \\dots, s_n$$$ ($$$1 \\le s_i \\le 2^{29}$$$) \u2014 the description of the multiset. It is guaranteed that all elements of the multiset are powers of two. ", "output_spec": "For each query print YES if it is possible to obtain the number $$$2048$$$ in your multiset, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).", "sample_inputs": ["6\n4\n1024 512 64 512\n1\n2048\n3\n64 512 2\n2\n4096 4\n7\n2048 2 2048 2048 2048 2048 2048\n2\n2048 4096"], "sample_outputs": ["YES\nYES\nNO\nNO\nYES\nYES"], "notes": "NoteIn the first query you can win as follows: choose $$$512$$$ and $$$512$$$, and $$$s$$$ turns into $$$\\{1024, 64, 1024\\}$$$. Then choose $$$1024$$$ and $$$1024$$$, and $$$s$$$ turns into $$$\\{2048, 64\\}$$$ and you win.In the second query $$$s$$$ contains $$$2048$$$ initially."}, "positive_code": [{"source_code": "let rec insert x = function\n | [] -> [x]\n | y::l when y < x -> y::(insert x l)\n | _ as l -> x::l\n\nlet rec check l =\n match l with\n | [] -> false\n | x::l when x = 2048 -> true\n | y::l when y > 2048 -> false\n | [x] -> x = 2048\n | x::y::l -> if x = y then\n check (insert (y * 2) l)\n else\n check (y::l)\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let _ = int_of_string (input_line stdin) in\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n if check (List.sort compare l) then\n Format.printf \"YES@.\"\n else\n Format.printf \"NO@.\"\n done\n"}], "negative_code": [{"source_code": "let rec check l =\n match l with\n | [] -> false\n | x::l when x = 2048 -> true\n | y::l when y > 2048 -> false\n | [x] -> x = 2048\n | x::y::l -> if x = y then\n check ((y * 2)::l)\n else\n check (y::l)\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let _ = int_of_string (input_line stdin) in\n let l = List.map int_of_string @@ Str.split (Str.regexp \" \") (input_line stdin) in\n if check (List.sort compare l) then\n Format.printf \"YES@.\"\n else\n Format.printf \"NO@.\"\n done\n"}], "src_uid": "b40059fe9cbdb0cc3b64c3e463900849"} {"nl": {"description": "\u00a0\u2014 Do you have a wish? \u00a0\u2014 I want people to stop gifting each other arrays.O_o and Another Young BoyAn array of $$$n$$$ positive integers $$$a_1,a_2,\\ldots,a_n$$$ fell down on you from the skies, along with a positive integer $$$k \\le n$$$.You can apply the following operation at most $$$k$$$ times: Choose an index $$$1 \\le i \\le n$$$ and an integer $$$1 \\le x \\le 10^9$$$. Then do $$$a_i := x$$$ (assign $$$x$$$ to $$$a_i$$$). Then build a complete undirected weighted graph with $$$n$$$ vertices numbered with integers from $$$1$$$ to $$$n$$$, where edge $$$(l, r)$$$ ($$$1 \\le l < r \\le n$$$) has weight $$$\\min(a_{l},a_{l+1},\\ldots,a_{r})$$$.You have to find the maximum possible diameter of the resulting graph after performing at most $$$k$$$ operations.The diameter of a graph is equal to $$$\\max\\limits_{1 \\le u < v \\le n}{\\operatorname{d}(u, v)}$$$, where $$$\\operatorname{d}(u, v)$$$ is the length of the shortest path between vertex $$$u$$$ and vertex $$$v$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\le n \\le 10^5$$$, $$$1 \\le k \\le n$$$). The second line of each test case contains $$$n$$$ positive integers $$$a_1,a_2,\\ldots,a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case print one integer\u00a0\u2014 the maximum possible diameter of the graph after performing at most $$$k$$$ operations.", "sample_inputs": ["6\n\n3 1\n\n2 4 1\n\n3 2\n\n1 9 84\n\n3 1\n\n10 2 6\n\n3 2\n\n179 17 1000000000\n\n2 1\n\n5 9\n\n2 2\n\n4 2"], "sample_outputs": ["4\n168\n10\n1000000000\n9\n1000000000"], "notes": "NoteIn the first test case, one of the optimal arrays is $$$[2,4,5]$$$.The graph built on this array: $$$\\operatorname{d}(1, 2) = \\operatorname{d}(1, 3) = 2$$$ and $$$\\operatorname{d}(2, 3) = 4$$$, so the diameter is equal to $$$\\max(2,2,4) = 4$$$."}, "positive_code": [{"source_code": "type right_link = Sibling of sized_atom | Child of tree\nand atom = { value : int; left_child : tree; right_link : right_link }\nand tree = Empty | Node of sized_atom\nand sized_atom = { atom : atom; size : int }\n\nlet print_tree tree =\n let rec build_floors floors tree rank =\n match tree with\n | Empty -> (floors, rank)\n | Node { atom = node; _ } ->\n let top, below =\n match floors with top :: below -> (top, below) | _ -> ([], [])\n in\n let rec f below atom rank top =\n let below, rank = build_floors below atom.left_child rank in\n let top = (atom.value, rank) :: top in\n let rank = rank + 1 in\n match atom.right_link with\n | Sibling { atom = sibling; _ } -> f below sibling rank top\n | Child child ->\n let below, rank = build_floors below child rank in\n (below, rank, top)\n in\n let below, rank, top = f below node rank top in\n (top :: below, rank)\n in\n let floors, _ = build_floors [] tree 1 in\n let rec f floors =\n match floors with\n | [] -> ()\n | floor :: floors ->\n let floor = List.rev floor in\n let rec g i floor =\n match floor with\n | [] -> ()\n | (value, rank) :: remainder ->\n let (), floor =\n if rank = i then (print_int value, remainder)\n else (print_char ' ', floor)\n in\n g (i + 1) floor\n in\n let () = g 1 floor in\n let () = print_newline () in\n f floors\n in\n\n f floors\n\nlet rec fold tree f acc =\n match tree with\n | Empty -> acc\n | Node { atom; _ } ->\n let rec g atom acc =\n let acc = fold atom.left_child f acc in\n let acc = f atom.value acc in\n match atom.right_link with\n | Sibling { atom; _ } -> g atom acc\n | Child tree -> fold tree f acc\n in\n g atom acc\n\nlet traverse tree f = fold tree f ()\n\ntype excess = ExcessZero | ExcessOne\n\nlet tree_size tree = match tree with Empty -> 0 | Node node -> node.size\n\nlet make_sized atom =\n let size =\n tree_size atom.left_child + 1\n +\n match atom.right_link with\n | Sibling sibling -> sibling.size\n | Child child -> tree_size child\n in\n { atom; size }\n\n(* The index of the first element is zero *)\nlet rec get_nth tree n =\n match tree with\n | Empty -> failwith \"Out of bounds\"\n | Node { atom = node; _ } -> (\n let b = tree_size node.left_child in\n if n < b then get_nth node.left_child n\n else if n = b then node.value\n else\n let n = n - b - 1 in\n match node.right_link with\n | Sibling sibling -> get_nth (Node sibling) n\n | Child tree -> get_nth tree n)\n\nlet raise_left_child node =\n match node.left_child with\n | Empty -> assert false\n | Node { atom = new_node; _ } ->\n let rec f atom =\n match atom.right_link with\n | Child child ->\n let new_sibling = make_sized { node with left_child = child } in\n make_sized { atom with right_link = Sibling new_sibling }\n | Sibling sibling ->\n make_sized { atom with right_link = Sibling (f sibling.atom) }\n in\n f new_node\n\nlet rec width { atom = node; _ } =\n match node.right_link with\n | Sibling sibling -> width sibling + 1\n | Child _ -> 1\n\nlet lower_first_atoms atom size =\n let rec f atom size =\n if size = 0 then (atom, Child atom.atom.left_child)\n else\n match atom.atom.right_link with\n | Child _ -> assert false\n | Sibling sibling ->\n let root, right_link = f sibling (size - 1) in\n (root, Sibling (make_sized { atom.atom with right_link }))\n in\n let root, link = f atom size in\n match link with\n | Child _ -> assert false\n | Sibling node -> make_sized { root.atom with left_child = Node node }\n\nlet rec unflatten_list node child_sizes =\n match child_sizes with\n | [] -> assert false\n | n :: s ->\n let toplevel_node = lower_first_atoms node n in\n let link =\n match toplevel_node.atom.right_link with\n | Child _ -> assert false\n | Sibling sibling -> (\n match s with\n | [] -> Child (Node sibling)\n | _ -> Sibling (unflatten_list sibling s))\n in\n make_sized { toplevel_node.atom with right_link = link }\n\nlet make_higher_if_necessary wide_node =\n let w = width wide_node in\n match w with\n | 1 | 2 -> (wide_node, ExcessZero)\n | 3 | 4 -> (unflatten_list wide_node [ 1 ], ExcessOne)\n | _ -> assert false\n\nlet rec insert_in_node value { atom = node; _ } =\n let rec g atom =\n if value <= atom.value then\n let new_node, excess = insert_full value atom.left_child in\n let atom = { atom with left_child = Node new_node } in\n match excess with\n | ExcessZero -> make_sized atom\n | ExcessOne -> raise_left_child atom\n else\n match atom.right_link with\n | Sibling sibling ->\n make_sized { atom with right_link = Sibling (g sibling.atom) }\n | Child right_child -> (\n let new_node, excess = insert_full value right_child in\n match excess with\n | ExcessZero ->\n make_sized { atom with right_link = Child (Node new_node) }\n | ExcessOne -> make_sized { atom with right_link = Sibling new_node })\n in\n let possibly_too_wide = g node in\n make_higher_if_necessary possibly_too_wide\n\nand insert_full value tree =\n match tree with\n | Empty ->\n ( make_sized { value; left_child = Empty; right_link = Child Empty },\n ExcessOne )\n | Node node -> insert_in_node value node\n\nlet insert value tree =\n let t, _ = insert_full value tree in\n Node t\n\ntype deficit = DeficitZero | DeficitOne\n\nlet rec expand node =\n let new_sibling =\n match node.right_link with\n | Child (Node new_sibling) -> new_sibling\n | Child Empty -> assert false\n | Sibling sibling -> expand sibling.atom\n in\n (* Does not change the size because it's the same subtree on the\n right, its status might just change from right child to sibling. *)\n let center = { node with right_link = Sibling new_sibling } in\n raise_left_child center\n\nlet expand_except_left_child node =\n let sibling =\n match node.right_link with\n | Sibling sibling -> expand sibling.atom\n | Child (Node new_sibling) -> new_sibling\n | Child Empty -> assert false\n in\n make_sized { node with right_link = Sibling sibling }\n\nlet make_higher_if_possible node =\n let w = width node in\n match w with\n | 2 -> (node, DeficitOne)\n | _ ->\n let child_sizes =\n match w with\n | 3 | 4 -> [ 1 ]\n | 5 -> [ 2 ]\n | 6 | 7 -> [ 2; 1 ]\n | _ -> assert false\n in\n (unflatten_list node child_sizes, DeficitZero)\n\nlet handle_left_deficit node =\n let atom = expand_except_left_child node in\n make_higher_if_possible atom\n\nlet handle_right_deficit node =\n let atom = raise_left_child node in\n make_higher_if_possible atom\n\nlet rec extract_min_full node =\n match node.left_child with\n | Empty -> (\n match node.right_link with\n | Sibling sibling -> (Node sibling, DeficitZero, node.value)\n | Child Empty -> (Empty, DeficitOne, node.value)\n | _ -> assert false)\n | Node left_node ->\n let new_child, deficit, min = extract_min_full left_node.atom in\n (* `make_sized` is not necessary I think. *)\n let node = make_sized { node with left_child = new_child } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (node, DeficitZero)\n | DeficitOne -> handle_left_deficit node.atom\n in\n (Node node, deficit, min)\n\nlet extract_min tree =\n match tree with\n | Empty -> failwith \"Called extract_min on a empty tree\"\n | Node node ->\n let tree, _, min = extract_min_full node.atom in\n (tree, min)\n\nlet update_right_with_deficit node f =\n let right =\n match node.right_link with Sibling node -> Node node | Child tree -> tree\n in\n let tree, deficit = f right in\n let tree, deficit =\n match (tree, deficit, node.right_link) with\n | Node sibling, DeficitZero, Sibling _ ->\n (make_sized { node with right_link = Sibling sibling }, DeficitZero)\n | Empty, DeficitZero, Sibling _ -> assert false\n | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->\n (make_sized { node with right_link = Child tree }, DeficitZero)\n | tree, DeficitOne, Child _ ->\n let unbalanced_node = { node with right_link = Child tree } in\n handle_right_deficit unbalanced_node\n in\n\n (tree, deficit)\n\nlet delete_atom node =\n match node.right_link with\n | Sibling right | Child (Node right) ->\n let tree, deficit, min = extract_min_full right.atom in\n let link, deficit =\n match (tree, deficit, node.right_link) with\n | Empty, DeficitZero, _ -> assert false\n | Node new_node, DeficitZero, Sibling _ ->\n (Sibling new_node, DeficitZero)\n | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->\n (Child tree, DeficitZero)\n | tree, DeficitOne, Child _ -> (Child tree, DeficitOne)\n in\n let node = { node with value = min; right_link = link } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (make_sized node, DeficitZero)\n | DeficitOne -> handle_right_deficit node\n in\n (Node node, deficit)\n | Child Empty -> (node.left_child, DeficitOne)\n\nlet rec delete_full value tree =\n match tree with\n | Empty -> (Empty, DeficitZero)\n | Node node -> delete_in_node value node\n\nand delete_in_node value node =\n if value < node.atom.value then\n let tree, deficit = delete_full value node.atom.left_child in\n let node = { node.atom with left_child = tree } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (make_sized node, DeficitZero)\n | DeficitOne -> handle_left_deficit node\n in\n (Node node, deficit)\n else if value = node.atom.value then delete_atom node.atom\n else\n let f = delete_full value in\n let node, deficit = update_right_with_deficit node.atom f in\n (Node node, deficit)\n\nlet delete value tree =\n let tree, _ = delete_full value tree in\n tree\n\nlet get_num () =\n let rec f acc =\n try\n let c = input_byte stdin in\n if int_of_char '0' <= c && c <= int_of_char '9' then\n f ((acc * 10) + c - int_of_char '0')\n else if acc > 0 then Some acc\n else f 0\n with End_of_file -> if acc > 0 then Some acc else None\n in\n f 0\n\nlet get_num () = match get_num () with Some x -> x | None -> exit 1\nlet max_value = 1000000000\nlet half = max_value / 2\n\nlet double x = if x < half then 2 * x else max_value\n\nlet rec print_list list =\n match list with\n | [] -> ()\n | x :: [] ->\n let () = print_int x in\n print_newline ()\n | x :: list ->\n let () = print_int x in\n let () = print_char ' ' in\n print_list list\n\nlet solve_case () =\n let n = get_num () in\n let k = get_num () in\n\n let ans =\n let a0 = get_num () in\n let a1 = get_num () in\n\n let rest, search_tree =\n let rec f i =\n if i >= n then ([], Empty)\n else\n let x = get_num () in\n let rest, search_tree = f (i + 1) in\n (x :: rest, insert (double x) search_tree)\n in\n f 2\n in\n if k = n then max_value\n else\n let search_tree = insert a0 search_tree in\n let search_tree = insert a1 search_tree in\n\n let get_candidate tree = get_nth tree k in\n\n let ans = get_candidate search_tree in\n\n let rec f ans search_tree a0 a1 rest =\n match rest with\n | [] -> ans\n | x :: rest ->\n let search_tree = delete a0 search_tree in\n let search_tree = insert (double a0) search_tree in\n let search_tree = delete (double x) search_tree in\n let search_tree = insert x search_tree in\n let cand = get_candidate search_tree in\n let ans = if ans < cand then cand else ans in\n f ans search_tree a1 x rest\n in\n f ans search_tree a0 a1 rest\n in\n let ans = if max_value < ans then max_value else ans in\n print_int ans\n\nlet run () =\n let t = get_num () in\n let rec f i =\n if i = 0 then ()\n else\n let () = solve_case () in\n let () = print_newline () in\n (f [@tailcall]) (i - 1)\n in\n f t\n\nlet () = run ()\n"}], "negative_code": [{"source_code": "type right_link = Sibling of sized_atom | Child of tree\nand atom = { value : int; left_child : tree; right_link : right_link }\nand tree = Empty | Node of sized_atom\nand sized_atom = { atom : atom; size : int }\n\nlet print_tree tree =\n let rec build_floors floors tree rank =\n match tree with\n | Empty -> (floors, rank)\n | Node { atom = node; _ } ->\n let top, below =\n match floors with top :: below -> (top, below) | _ -> ([], [])\n in\n let rec f below atom rank top =\n let below, rank = build_floors below atom.left_child rank in\n let top = (atom.value, rank) :: top in\n let rank = rank + 1 in\n match atom.right_link with\n | Sibling { atom = sibling; _ } -> f below sibling rank top\n | Child child ->\n let below, rank = build_floors below child rank in\n (below, rank, top)\n in\n let below, rank, top = f below node rank top in\n (top :: below, rank)\n in\n let floors, _ = build_floors [] tree 1 in\n let rec f floors =\n match floors with\n | [] -> ()\n | floor :: floors ->\n let floor = List.rev floor in\n let rec g i floor =\n match floor with\n | [] -> ()\n | (value, rank) :: remainder ->\n let (), floor =\n if rank = i then (print_int value, remainder)\n else (print_char ' ', floor)\n in\n g (i + 1) floor\n in\n let () = g 1 floor in\n let () = print_newline () in\n f floors\n in\n\n f floors\n\nlet rec fold tree f acc =\n match tree with\n | Empty -> acc\n | Node { atom; _ } ->\n let rec g atom acc =\n let acc = fold atom.left_child f acc in\n let acc = f atom.value acc in\n match atom.right_link with\n | Sibling { atom; _ } -> g atom acc\n | Child tree -> fold tree f acc\n in\n g atom acc\n\nlet traverse tree f = fold tree f ()\n\ntype excess = ExcessZero | ExcessOne\n\nlet tree_size tree = match tree with Empty -> 0 | Node node -> node.size\n\nlet make_sized atom =\n let size =\n tree_size atom.left_child + 1\n +\n match atom.right_link with\n | Sibling sibling -> sibling.size\n | Child child -> tree_size child\n in\n { atom; size }\n\n(* The index of the first element is zero *)\nlet rec get_nth tree n =\n match tree with\n | Empty -> failwith \"Out of bounds\"\n | Node { atom = node; _ } -> (\n let b = tree_size node.left_child in\n if n < b then get_nth node.left_child n\n else if n = b then node.value\n else\n let n = n - b - 1 in\n match node.right_link with\n | Sibling sibling -> get_nth (Node sibling) n\n | Child tree -> get_nth tree n)\n\nlet raise_left_child node =\n match node.left_child with\n | Empty -> assert false\n | Node { atom = new_node; _ } ->\n let rec f atom =\n match atom.right_link with\n | Child child ->\n let new_sibling = make_sized { node with left_child = child } in\n make_sized { atom with right_link = Sibling new_sibling }\n | Sibling sibling ->\n make_sized { atom with right_link = Sibling (f sibling.atom) }\n in\n f new_node\n\nlet rec width { atom = node; _ } =\n match node.right_link with\n | Sibling sibling -> width sibling + 1\n | Child _ -> 1\n\nlet lower_first_atoms atom size =\n let rec f atom size =\n if size = 0 then (atom, Child atom.atom.left_child)\n else\n match atom.atom.right_link with\n | Child _ -> assert false\n | Sibling sibling ->\n let root, right_link = f sibling (size - 1) in\n (root, Sibling (make_sized { atom.atom with right_link }))\n in\n let root, link = f atom size in\n match link with\n | Child _ -> assert false\n | Sibling node -> make_sized { root.atom with left_child = Node node }\n\nlet rec unflatten_list node child_sizes =\n match child_sizes with\n | [] -> assert false\n | n :: s ->\n let toplevel_node = lower_first_atoms node n in\n let link =\n match toplevel_node.atom.right_link with\n | Child _ -> assert false\n | Sibling sibling -> (\n match s with\n | [] -> Child (Node sibling)\n | _ -> Sibling (unflatten_list sibling s))\n in\n make_sized { toplevel_node.atom with right_link = link }\n\nlet make_higher_if_necessary wide_node =\n let w = width wide_node in\n match w with\n | 1 | 2 -> (wide_node, ExcessZero)\n | 3 | 4 -> (unflatten_list wide_node [ 1 ], ExcessOne)\n | _ -> assert false\n\nlet rec insert_in_node value { atom = node; _ } =\n let rec g atom =\n if value <= atom.value then\n let new_node, excess = insert_full value atom.left_child in\n let atom = { atom with left_child = Node new_node } in\n match excess with\n | ExcessZero -> make_sized atom\n | ExcessOne -> raise_left_child atom\n else\n match atom.right_link with\n | Sibling sibling ->\n make_sized { atom with right_link = Sibling (g sibling.atom) }\n | Child right_child -> (\n let new_node, excess = insert_full value right_child in\n match excess with\n | ExcessZero ->\n make_sized { atom with right_link = Child (Node new_node) }\n | ExcessOne -> make_sized { atom with right_link = Sibling new_node })\n in\n let possibly_too_wide = g node in\n make_higher_if_necessary possibly_too_wide\n\nand insert_full value tree =\n match tree with\n | Empty ->\n ( make_sized { value; left_child = Empty; right_link = Child Empty },\n ExcessOne )\n | Node node -> insert_in_node value node\n\nlet insert value tree =\n let t, _ = insert_full value tree in\n Node t\n\ntype deficit = DeficitZero | DeficitOne\n\nlet rec expand node =\n let new_sibling =\n match node.right_link with\n | Child (Node new_sibling) -> new_sibling\n | Child Empty -> assert false\n | Sibling sibling -> expand sibling.atom\n in\n (* Does not change the size because it's the same subtree on the\n right, its status might just change from right child to sibling. *)\n let center = { node with right_link = Sibling new_sibling } in\n raise_left_child center\n\nlet expand_except_left_child node =\n let sibling =\n match node.right_link with\n | Sibling sibling -> expand sibling.atom\n | Child (Node new_sibling) -> new_sibling\n | Child Empty -> assert false\n in\n make_sized { node with right_link = Sibling sibling }\n\nlet make_higher_if_possible node =\n let w = width node in\n match w with\n | 2 -> (node, DeficitOne)\n | _ ->\n let child_sizes =\n match w with\n | 3 | 4 -> [ 1 ]\n | 5 -> [ 2 ]\n | 6 | 7 -> [ 2; 1 ]\n | _ -> assert false\n in\n (unflatten_list node child_sizes, DeficitZero)\n\nlet handle_left_deficit node =\n let atom = expand_except_left_child node in\n make_higher_if_possible atom\n\nlet handle_right_deficit node =\n let atom = raise_left_child node in\n make_higher_if_possible atom\n\nlet rec extract_min_full node =\n match node.left_child with\n | Empty -> (\n match node.right_link with\n | Sibling sibling -> (Node sibling, DeficitZero, node.value)\n | Child Empty -> (Empty, DeficitOne, node.value)\n | _ -> assert false)\n | Node left_node ->\n let new_child, deficit, min = extract_min_full left_node.atom in\n (* `make_sized` is not necessary I think. *)\n let node = make_sized { node with left_child = new_child } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (node, DeficitZero)\n | DeficitOne -> handle_left_deficit node.atom\n in\n (Node node, deficit, min)\n\nlet extract_min tree =\n match tree with\n | Empty -> failwith \"Called extract_min on a empty tree\"\n | Node node ->\n let tree, _, min = extract_min_full node.atom in\n (tree, min)\n\nlet update_right_with_deficit node f =\n let right =\n match node.right_link with Sibling node -> Node node | Child tree -> tree\n in\n let tree, deficit = f right in\n let tree, deficit =\n match (tree, deficit, node.right_link) with\n | Node sibling, DeficitZero, Sibling _ ->\n (make_sized { node with right_link = Sibling sibling }, DeficitZero)\n | Empty, DeficitZero, Sibling _ -> assert false\n | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->\n (make_sized { node with right_link = Child tree }, DeficitZero)\n | tree, DeficitOne, Child _ ->\n let unbalanced_node = { node with right_link = Child tree } in\n handle_right_deficit unbalanced_node\n in\n\n (tree, deficit)\n\nlet delete_atom node =\n match node.right_link with\n | Sibling right | Child (Node right) ->\n let tree, deficit, min = extract_min_full right.atom in\n let link, deficit =\n match (tree, deficit, node.right_link) with\n | Empty, DeficitZero, _ -> assert false\n | Node new_node, DeficitZero, Sibling _ ->\n (Sibling new_node, DeficitZero)\n | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->\n (Child tree, DeficitZero)\n | tree, DeficitOne, Child _ -> (Child tree, DeficitOne)\n in\n let node = { node with value = min; right_link = link } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (make_sized node, DeficitZero)\n | DeficitOne -> handle_right_deficit node\n in\n (Node node, deficit)\n | Child Empty -> (node.left_child, DeficitOne)\n\nlet rec delete_full value tree =\n match tree with\n | Empty -> (Empty, DeficitZero)\n | Node node -> delete_in_node value node\n\nand delete_in_node value node =\n if value < node.atom.value then\n let tree, deficit = delete_full value node.atom.left_child in\n let node = { node.atom with left_child = tree } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (make_sized node, DeficitZero)\n | DeficitOne -> handle_left_deficit node\n in\n (Node node, deficit)\n else if value = node.atom.value then delete_atom node.atom\n else\n let f = delete_full value in\n let node, deficit = update_right_with_deficit node.atom f in\n (Node node, deficit)\n\nlet delete value tree =\n let tree, _ = delete_full value tree in\n tree\n\nlet get_num () =\n let rec f acc =\n try\n let c = input_byte stdin in\n if int_of_char '0' <= c && c <= int_of_char '9' then\n f ((acc * 10) + c - int_of_char '0')\n else if acc > 0 then Some acc\n else f 0\n with End_of_file -> if acc > 0 then Some acc else None\n in\n f 0\n\nlet get_num () = match get_num () with Some x -> x | None -> exit 1\nlet max_value = 1000000000\n\nlet rec print_list list =\n match list with\n | [] -> ()\n | x :: [] ->\n let () = print_int x in\n print_newline ()\n | x :: list ->\n let () = print_int x in\n let () = print_char ' ' in\n print_list list\n\nlet solve_case () =\n let n = get_num () in\n let k = get_num () in\n\n let ans =\n let a0 = get_num () in\n let a1 = get_num () in\n\n let rest, search_tree =\n let rec f i =\n if i >= n then ([], Empty)\n else\n let x = get_num () in\n let rest, search_tree = f (i + 1) in\n (x :: rest, insert (2 * x) search_tree)\n in\n f 2\n in\n if k = n then max_value\n else\n let search_tree = insert a0 search_tree in\n let search_tree = insert a1 search_tree in\n\n let get_candidate tree = get_nth tree k in\n\n let ans = get_candidate search_tree in\n\n let rec f ans search_tree a0 a1 rest =\n match rest with\n | [] -> ans\n | x :: rest ->\n let search_tree = delete a0 search_tree in\n let search_tree = insert (2 * a0) search_tree in\n let search_tree = delete (2 * x) search_tree in\n let search_tree = insert x search_tree in\n let cand = get_candidate search_tree in\n let ans = if ans < cand then cand else ans in\n f ans search_tree a1 x rest\n in\n f ans search_tree a0 a1 rest\n in\n let ans = if max_value < ans then max_value else ans in\n print_int ans\n\nlet run () =\n let t = get_num () in\n let rec f i =\n if i = 0 then ()\n else\n let () = solve_case () in\n let () = print_newline () in\n (f [@tailcall]) (i - 1)\n in\n f t\n\nlet () = run ()\n"}, {"source_code": "type right_link = Sibling of sized_atom | Child of tree\nand atom = { value : int; left_child : tree; right_link : right_link }\nand tree = Empty | Node of sized_atom\nand sized_atom = { atom : atom; size : int }\n\nlet print_tree tree =\n let rec build_floors floors tree rank =\n match tree with\n | Empty -> (floors, rank)\n | Node { atom = node; _ } ->\n let top, below =\n match floors with top :: below -> (top, below) | _ -> ([], [])\n in\n let rec f below atom rank top =\n let below, rank = build_floors below atom.left_child rank in\n let top = (atom.value, rank) :: top in\n let rank = rank + 1 in\n match atom.right_link with\n | Sibling { atom = sibling; _ } -> f below sibling rank top\n | Child child ->\n let below, rank = build_floors below child rank in\n (below, rank, top)\n in\n let below, rank, top = f below node rank top in\n (top :: below, rank)\n in\n let floors, _ = build_floors [] tree 1 in\n let rec f floors =\n match floors with\n | [] -> ()\n | floor :: floors ->\n let floor = List.rev floor in\n let rec g i floor =\n match floor with\n | [] -> ()\n | (value, rank) :: remainder ->\n let (), floor =\n if rank = i then (print_int value, remainder)\n else (print_char ' ', floor)\n in\n g (i + 1) floor\n in\n let () = g 1 floor in\n let () = print_newline () in\n f floors\n in\n\n f floors\n\nlet rec fold tree f acc =\n match tree with\n | Empty -> acc\n | Node { atom; _ } ->\n let rec g atom acc =\n let acc = fold atom.left_child f acc in\n let acc = f atom.value acc in\n match atom.right_link with\n | Sibling { atom; _ } -> g atom acc\n | Child tree -> fold tree f acc\n in\n g atom acc\n\nlet traverse tree f = fold tree f ()\n\ntype excess = ExcessZero | ExcessOne\n\nlet tree_size tree = match tree with Empty -> 0 | Node node -> node.size\n\nlet make_sized atom =\n let size =\n tree_size atom.left_child + 1\n +\n match atom.right_link with\n | Sibling sibling -> sibling.size\n | Child child -> tree_size child\n in\n { atom; size }\n\n(* The index of the first element is zero *)\nlet rec get_nth tree n =\n match tree with\n | Empty -> failwith \"Out of bounds\"\n | Node { atom = node; _ } -> (\n let b = tree_size node.left_child in\n if n < b then get_nth node.left_child n\n else if n = b then node.value\n else\n let n = n - b - 1 in\n match node.right_link with\n | Sibling sibling -> get_nth (Node sibling) n\n | Child tree -> get_nth tree n)\n\nlet raise_left_child node =\n match node.left_child with\n | Empty -> assert false\n | Node { atom = new_node; _ } ->\n let rec f atom =\n match atom.right_link with\n | Child child ->\n let new_sibling = make_sized { node with left_child = child } in\n make_sized { atom with right_link = Sibling new_sibling }\n | Sibling sibling ->\n make_sized { atom with right_link = Sibling (f sibling.atom) }\n in\n f new_node\n\nlet rec width { atom = node; _ } =\n match node.right_link with\n | Sibling sibling -> width sibling + 1\n | Child _ -> 1\n\nlet lower_first_atoms atom size =\n let rec f atom size =\n if size = 0 then (atom, Child atom.atom.left_child)\n else\n match atom.atom.right_link with\n | Child _ -> assert false\n | Sibling sibling ->\n let root, right_link = f sibling (size - 1) in\n (root, Sibling (make_sized { atom.atom with right_link }))\n in\n let root, link = f atom size in\n match link with\n | Child _ -> assert false\n | Sibling node -> make_sized { root.atom with left_child = Node node }\n\nlet rec unflatten_list node child_sizes =\n match child_sizes with\n | [] -> assert false\n | n :: s ->\n let toplevel_node = lower_first_atoms node n in\n let link =\n match toplevel_node.atom.right_link with\n | Child _ -> assert false\n | Sibling sibling -> (\n match s with\n | [] -> Child (Node sibling)\n | _ -> Sibling (unflatten_list sibling s))\n in\n make_sized { toplevel_node.atom with right_link = link }\n\nlet make_higher_if_necessary wide_node =\n let w = width wide_node in\n match w with\n | 1 | 2 -> (wide_node, ExcessZero)\n | 3 | 4 -> (unflatten_list wide_node [ 1 ], ExcessOne)\n | _ -> assert false\n\nlet rec insert_in_node value { atom = node; _ } =\n let rec g atom =\n if value <= atom.value then\n let new_node, excess = insert_full value atom.left_child in\n let atom = { atom with left_child = Node new_node } in\n match excess with\n | ExcessZero -> make_sized atom\n | ExcessOne -> raise_left_child atom\n else\n match atom.right_link with\n | Sibling sibling ->\n make_sized { atom with right_link = Sibling (g sibling.atom) }\n | Child right_child -> (\n let new_node, excess = insert_full value right_child in\n match excess with\n | ExcessZero ->\n make_sized { atom with right_link = Child (Node new_node) }\n | ExcessOne -> make_sized { atom with right_link = Sibling new_node })\n in\n let possibly_too_wide = g node in\n make_higher_if_necessary possibly_too_wide\n\nand insert_full value tree =\n match tree with\n | Empty ->\n ( make_sized { value; left_child = Empty; right_link = Child Empty },\n ExcessOne )\n | Node node -> insert_in_node value node\n\nlet insert value tree =\n let t, _ = insert_full value tree in\n Node t\n\ntype deficit = DeficitZero | DeficitOne\n\nlet rec expand node =\n let new_sibling =\n match node.right_link with\n | Child (Node new_sibling) -> new_sibling\n | Child Empty -> assert false\n | Sibling sibling -> expand sibling.atom\n in\n (* Does not change the size because it's the same subtree on the\n right, its status might just change from right child to sibling. *)\n let center = { node with right_link = Sibling new_sibling } in\n raise_left_child center\n\nlet expand_except_left_child node =\n let sibling =\n match node.right_link with\n | Sibling sibling -> expand sibling.atom\n | Child (Node new_sibling) -> new_sibling\n | Child Empty -> assert false\n in\n make_sized { node with right_link = Sibling sibling }\n\nlet make_higher_if_possible node =\n let w = width node in\n match w with\n | 2 -> (node, DeficitOne)\n | _ ->\n let child_sizes =\n match w with\n | 3 | 4 -> [ 1 ]\n | 5 -> [ 2 ]\n | 6 | 7 -> [ 2; 1 ]\n | _ -> assert false\n in\n (unflatten_list node child_sizes, DeficitZero)\n\nlet handle_left_deficit node =\n let atom = expand_except_left_child node in\n make_higher_if_possible atom\n\nlet handle_right_deficit node =\n let atom = raise_left_child node in\n make_higher_if_possible atom\n\nlet rec extract_min_full node =\n match node.left_child with\n | Empty -> (\n match node.right_link with\n | Sibling sibling -> (Node sibling, DeficitZero, node.value)\n | Child Empty -> (Empty, DeficitOne, node.value)\n | _ -> assert false)\n | Node left_node ->\n let new_child, deficit, min = extract_min_full left_node.atom in\n (* `make_sized` is not necessary I think. *)\n let node = make_sized { node with left_child = new_child } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (node, DeficitZero)\n | DeficitOne -> handle_left_deficit node.atom\n in\n (Node node, deficit, min)\n\nlet extract_min tree =\n match tree with\n | Empty -> failwith \"Called extract_min on a empty tree\"\n | Node node ->\n let tree, _, min = extract_min_full node.atom in\n (tree, min)\n\nlet update_right_with_deficit node f =\n let right =\n match node.right_link with Sibling node -> Node node | Child tree -> tree\n in\n let tree, deficit = f right in\n let tree, deficit =\n match (tree, deficit, node.right_link) with\n | Node sibling, DeficitZero, Sibling _ ->\n (make_sized { node with right_link = Sibling sibling }, DeficitZero)\n | Empty, DeficitZero, Sibling _ -> assert false\n | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->\n (make_sized { node with right_link = Child tree }, DeficitZero)\n | tree, DeficitOne, Child _ ->\n let unbalanced_node = { node with right_link = Child tree } in\n handle_right_deficit unbalanced_node\n in\n\n (tree, deficit)\n\nlet delete_atom node =\n match node.right_link with\n | Sibling right | Child (Node right) ->\n let tree, deficit, min = extract_min_full right.atom in\n let link, deficit =\n match (tree, deficit, node.right_link) with\n | Empty, DeficitZero, _ -> assert false\n | Node new_node, DeficitZero, Sibling _ ->\n (Sibling new_node, DeficitZero)\n | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->\n (Child tree, DeficitZero)\n | tree, DeficitOne, Child _ -> (Child tree, DeficitOne)\n in\n let node = { node with value = min; right_link = link } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (make_sized node, DeficitZero)\n | DeficitOne -> handle_right_deficit node\n in\n (Node node, deficit)\n | Child Empty -> (node.left_child, DeficitOne)\n\nlet rec delete_full value tree =\n match tree with\n | Empty -> (Empty, DeficitZero)\n | Node node -> delete_in_node value node\n\nand delete_in_node value node =\n if value < node.atom.value then\n let tree, deficit = delete_full value node.atom.left_child in\n let node = { node.atom with left_child = tree } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (make_sized node, DeficitZero)\n | DeficitOne -> handle_left_deficit node\n in\n (Node node, deficit)\n else if value = node.atom.value then delete_atom node.atom\n else\n let f = delete_full value in\n let node, deficit = update_right_with_deficit node.atom f in\n (Node node, deficit)\n\nlet delete value tree =\n let tree, _ = delete_full value tree in\n tree\n\nlet get_num () =\n let rec f acc =\n try\n let c = input_byte stdin in\n if int_of_char '0' <= c && c <= int_of_char '9' then\n f ((acc * 10) + c - int_of_char '0')\n else if acc > 0 then Some acc\n else f 0\n with End_of_file -> if acc > 0 then Some acc else None\n in\n f 0\n\nlet get_num () = match get_num () with Some x -> x | None -> exit 1\nlet max_value = 1000000000\n\nlet rec print_list list = match list with \n| [] -> ()\n| x::[] -> let () = print_int x in print_newline ()\n| x::list -> let () = print_int x in let () = print_char ' ' in print_list list\n\nlet solve_case () =\n let n = get_num () in\n let k = get_num () in\n\n let ans =\n let a0 = get_num () in\n let a1 = get_num () in\n\n let rest, search_tree =\n let rec f i =\n if i >= n then ([], Empty)\n else\n let x = get_num () in\n let rest, search_tree = f (i + 1) in\n (x :: rest, insert (2 * x) search_tree)\n in\n f 2\n in\n if k = n then max_value\n else\n let search_tree = insert a0 search_tree in\n let search_tree = insert a1 search_tree in\n\n let get_candidate tree = get_nth tree k in\n\n let ans = get_candidate search_tree in\n\n let rec f ans tree a0 a1 rest =\n match rest with\n | [] -> ans\n | x :: rest ->\n let search_tree = delete a0 search_tree in\n let search_tree = insert (2 * a0) search_tree in\n let search_tree = delete (2 * x) search_tree in\n let search_tree = insert x search_tree in\n let cand = get_candidate search_tree in\n let ans =\n if ans < cand then\n cand\n else ans\n in\n f ans search_tree a1 x rest\n in\n f ans search_tree a0 a1 rest\n in\n let ans = if max_value < ans then max_value else ans in\n print_int ans\n\nlet run () =\n let t = get_num () in\n let rec f i =\n if i = 0 then ()\n else\n let () = solve_case () in\n let () = print_newline () in\n (f [@tailcall]) (i - 1)\n in\n f t\n\nlet () = run ()\n"}, {"source_code": "type right_link = Sibling of sized_atom | Child of tree\nand atom = { value : int; left_child : tree; right_link : right_link }\nand tree = Empty | Node of sized_atom\nand sized_atom = { atom : atom; size : int }\n\nlet print_tree tree =\n let rec build_floors floors tree rank =\n match tree with\n | Empty -> (floors, rank)\n | Node { atom = node; _ } ->\n let top, below =\n match floors with top :: below -> (top, below) | _ -> ([], [])\n in\n let rec f below atom rank top =\n let below, rank = build_floors below atom.left_child rank in\n let top = (atom.value, rank) :: top in\n let rank = rank + 1 in\n match atom.right_link with\n | Sibling { atom = sibling; _ } -> f below sibling rank top\n | Child child ->\n let below, rank = build_floors below child rank in\n (below, rank, top)\n in\n let below, rank, top = f below node rank top in\n (top :: below, rank)\n in\n let floors, _ = build_floors [] tree 1 in\n let rec f floors =\n match floors with\n | [] -> ()\n | floor :: floors ->\n let floor = List.rev floor in\n let rec g i floor =\n match floor with\n | [] -> ()\n | (value, rank) :: remainder ->\n let (), floor =\n if rank = i then (print_int value, remainder)\n else (print_char ' ', floor)\n in\n g (i + 1) floor\n in\n let () = g 1 floor in\n let () = print_newline () in\n f floors\n in\n\n f floors\n\nlet rec fold tree f acc =\n match tree with\n | Empty -> acc\n | Node { atom; _ } ->\n let rec g atom acc =\n let acc = fold atom.left_child f acc in\n let acc = f atom.value acc in\n match atom.right_link with\n | Sibling { atom; _ } -> g atom acc\n | Child tree -> fold tree f acc\n in\n g atom acc\n\nlet traverse tree f = fold tree f ()\n\ntype excess = ExcessZero | ExcessOne\n\nlet tree_size tree = match tree with Empty -> 0 | Node node -> node.size\n\nlet make_sized atom =\n let size =\n tree_size atom.left_child + 1\n +\n match atom.right_link with\n | Sibling sibling -> sibling.size\n | Child child -> tree_size child\n in\n { atom; size }\n\n(* The index of the first element is zero *)\nlet rec get_nth tree n =\n match tree with\n | Empty -> failwith \"Out of bounds\"\n | Node { atom = node; _ } -> (\n let b = tree_size node.left_child in\n if n < b then get_nth node.left_child n\n else if n = b then node.value\n else\n let n = n - b - 1 in\n match node.right_link with\n | Sibling sibling -> get_nth (Node sibling) n\n | Child tree -> get_nth tree n)\n\nlet raise_left_child node =\n match node.left_child with\n | Empty -> assert false\n | Node { atom = new_node; _ } ->\n let rec f atom =\n match atom.right_link with\n | Child child ->\n let new_sibling = make_sized { node with left_child = child } in\n make_sized { atom with right_link = Sibling new_sibling }\n | Sibling sibling ->\n make_sized { atom with right_link = Sibling (f sibling.atom) }\n in\n f new_node\n\nlet rec width { atom = node; _ } =\n match node.right_link with\n | Sibling sibling -> width sibling + 1\n | Child _ -> 1\n\nlet lower_first_atoms atom size =\n let rec f atom size =\n if size = 0 then (atom, Child atom.atom.left_child)\n else\n match atom.atom.right_link with\n | Child _ -> assert false\n | Sibling sibling ->\n let root, right_link = f sibling (size - 1) in\n (root, Sibling (make_sized { atom.atom with right_link }))\n in\n let root, link = f atom size in\n match link with\n | Child _ -> assert false\n | Sibling node -> make_sized { root.atom with left_child = Node node }\n\nlet rec unflatten_list node child_sizes =\n match child_sizes with\n | [] -> assert false\n | n :: s ->\n let toplevel_node = lower_first_atoms node n in\n let link =\n match toplevel_node.atom.right_link with\n | Child _ -> assert false\n | Sibling sibling -> (\n match s with\n | [] -> Child (Node sibling)\n | _ -> Sibling (unflatten_list sibling s))\n in\n make_sized { toplevel_node.atom with right_link = link }\n\nlet make_higher_if_necessary wide_node =\n let w = width wide_node in\n match w with\n | 1 | 2 -> (wide_node, ExcessZero)\n | 3 | 4 -> (unflatten_list wide_node [ 1 ], ExcessOne)\n | _ -> assert false\n\nlet rec insert_in_node value { atom = node; _ } =\n let rec g atom =\n if value <= atom.value then\n let new_node, excess = insert_full value atom.left_child in\n let atom = { atom with left_child = Node new_node } in\n match excess with\n | ExcessZero -> make_sized atom\n | ExcessOne -> raise_left_child atom\n else\n match atom.right_link with\n | Sibling sibling ->\n make_sized { atom with right_link = Sibling (g sibling.atom) }\n | Child right_child -> (\n let new_node, excess = insert_full value right_child in\n match excess with\n | ExcessZero ->\n make_sized { atom with right_link = Child (Node new_node) }\n | ExcessOne -> make_sized { atom with right_link = Sibling new_node })\n in\n let possibly_too_wide = g node in\n make_higher_if_necessary possibly_too_wide\n\nand insert_full value tree =\n match tree with\n | Empty ->\n ( make_sized { value; left_child = Empty; right_link = Child Empty },\n ExcessOne )\n | Node node -> insert_in_node value node\n\nlet insert value tree =\n let t, _ = insert_full value tree in\n Node t\n\ntype deficit = DeficitZero | DeficitOne\n\nlet rec expand node =\n let new_sibling =\n match node.right_link with\n | Child (Node new_sibling) -> new_sibling\n | Child Empty -> assert false\n | Sibling sibling -> expand sibling.atom\n in\n (* Does not change the size because it's the same subtree on the\n right, its status might just change from right child to sibling. *)\n let center = { node with right_link = Sibling new_sibling } in\n raise_left_child center\n\nlet expand_except_left_child node =\n let sibling =\n match node.right_link with\n | Sibling sibling -> expand sibling.atom\n | Child (Node new_sibling) -> new_sibling\n | Child Empty -> assert false\n in\n make_sized { node with right_link = Sibling sibling }\n\nlet make_higher_if_possible node =\n let w = width node in\n match w with\n | 2 -> (node, DeficitOne)\n | _ ->\n let child_sizes =\n match w with\n | 3 | 4 -> [ 1 ]\n | 5 -> [ 2 ]\n | 6 | 7 -> [ 2; 1 ]\n | _ -> assert false\n in\n (unflatten_list node child_sizes, DeficitZero)\n\nlet handle_left_deficit node =\n let atom = expand_except_left_child node in\n make_higher_if_possible atom\n\nlet handle_right_deficit node =\n let atom = raise_left_child node in\n make_higher_if_possible atom\n\nlet rec extract_min_full node =\n match node.left_child with\n | Empty -> (\n match node.right_link with\n | Sibling sibling -> (Node sibling, DeficitZero, node.value)\n | Child Empty -> (Empty, DeficitOne, node.value)\n | _ -> assert false)\n | Node left_node ->\n let new_child, deficit, min = extract_min_full left_node.atom in\n (* `make_sized` is not necessary I think. *)\n let node = make_sized { node with left_child = new_child } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (node, DeficitZero)\n | DeficitOne -> handle_left_deficit node.atom\n in\n (Node node, deficit, min)\n\nlet extract_min tree =\n match tree with\n | Empty -> failwith \"Called extract_min on a empty tree\"\n | Node node ->\n let tree, _, min = extract_min_full node.atom in\n (tree, min)\n\nlet update_right_with_deficit node f =\n let right =\n match node.right_link with Sibling node -> Node node | Child tree -> tree\n in\n let tree, deficit = f right in\n let tree, deficit =\n match (tree, deficit, node.right_link) with\n | Node sibling, DeficitZero, Sibling _ ->\n (make_sized { node with right_link = Sibling sibling }, DeficitZero)\n | Empty, DeficitZero, Sibling _ -> assert false\n | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->\n (make_sized { node with right_link = Child tree }, DeficitZero)\n | tree, DeficitOne, Child _ ->\n let unbalanced_node = { node with right_link = Child tree } in\n handle_right_deficit unbalanced_node\n in\n\n (tree, deficit)\n\nlet delete_atom node =\n match node.right_link with\n | Sibling right | Child (Node right) ->\n let tree, deficit, min = extract_min_full right.atom in\n let link, deficit =\n match (tree, deficit, node.right_link) with\n | Empty, DeficitZero, _ -> assert false\n | Node new_node, DeficitZero, Sibling _ ->\n (Sibling new_node, DeficitZero)\n | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->\n (Child tree, DeficitZero)\n | tree, DeficitOne, Child _ -> (Child tree, DeficitOne)\n in\n let node = { node with value = min; right_link = link } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (make_sized node, DeficitZero)\n | DeficitOne -> handle_right_deficit node\n in\n (Node node, deficit)\n | Child Empty -> (node.left_child, DeficitOne)\n\nlet rec delete_full value tree =\n match tree with\n | Empty -> (Empty, DeficitZero)\n | Node node -> delete_in_node value node\n\nand delete_in_node value node =\n if value < node.atom.value then\n let tree, deficit = delete_full value node.atom.left_child in\n let node = { node.atom with left_child = tree } in\n let node, deficit =\n match deficit with\n | DeficitZero -> (make_sized node, DeficitZero)\n | DeficitOne -> handle_left_deficit node\n in\n (Node node, deficit)\n else if value = node.atom.value then delete_atom node.atom\n else\n let f = delete_full value in\n let node, deficit = update_right_with_deficit node.atom f in\n (Node node, deficit)\n\nlet delete value tree =\n let tree, _ = delete_full value tree in\n tree\n\nlet get_num () =\n let rec f acc =\n try\n let c = input_byte stdin in\n if int_of_char '0' <= c && c <= int_of_char '9' then\n f ((acc * 10) + c - int_of_char '0')\n else if acc > 0 then Some acc\n else f 0\n with End_of_file -> if acc > 0 then Some acc else None\n in\n f 0\n\nlet get_num () = match get_num () with Some x -> x | None -> exit 1\nlet max_value = 1000000000\n\nlet solve_case () =\n let n = get_num () in\n let k = get_num () in\n\n let ans =\n let a0 = get_num () in\n let a1 = get_num () in\n\n let rest, search_tree =\n let rec f i =\n if i >= n then ([], Empty)\n else\n let rest, search_tree = f (i + 1) in\n let x = get_num () in\n (x :: rest, insert (2 * x) search_tree)\n in\n f 2\n in\n if k = n then max_value\n else\n let search_tree = insert a0 search_tree in\n let search_tree = insert a1 search_tree in\n\n let get_candidate tree = get_nth tree k in\n\n let ans = get_candidate search_tree in\n\n let rec f ans tree a0 a1 rest =\n match rest with\n | [] -> ans\n | x :: rest ->\n let search_tree = delete a0 search_tree in\n let search_tree = insert (2 * a0) search_tree in\n let search_tree = delete (2 * x) search_tree in\n let search_tree = insert x search_tree in\n let cand = get_candidate search_tree in\n let ans = if ans < cand then cand else ans in\n f ans search_tree a1 x rest\n in\n f ans search_tree a0 a1 rest\n in\n let ans = if max_value < ans then max_value else ans in\n print_int ans\n\nlet run () =\n let t = get_num () in\n let rec f i =\n if i = 0 then ()\n else\n let () = solve_case () in\n let () = print_newline () in\n (f [@tailcall]) (i - 1)\n in\n f t\n\nlet () = run ()\n"}], "src_uid": "d1c2caeec0fe1ac33a6735b03d7c75ce"} {"nl": {"description": "You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 1000$$$) \u2014 the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \\le n \\le 10^{18}$$$).", "output_spec": "Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it.", "sample_inputs": ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"], "sample_outputs": ["0\n4\n6\n6\n-1\n6\n72"], "notes": null}, "positive_code": [{"source_code": "let read_x x_of_string () = read_line () |> Str.(split (regexp \" \")) |> List.map x_of_string;;\nlet read_ints = read_x int_of_string;;\nlet read_int64s = read_x Int64.of_string;;\nlet print_x string_of_x xs = List.map string_of_x xs |> String.concat \" \" |> print_endline;;\nlet print_ints = print_x string_of_int;;\nlet print_int64s = print_x Int64.to_string;;\n\nlet rec solve n =\n 1 +\n let open Int64 in\n if rem n 2L = 0L then\n solve (div n 2L)\n else if rem n 3L = 0L then\n solve (mul 2L (div n 3L))\n else if rem n 5L = 0L then\n solve (mul 4L (div n 5L))\n else if n = 1L then\n -1\n else\n raise Not_found;;\n\nlet [q] = read_ints ();;\nfor _ = 1 to q do\n let [n] = read_int64s () in\n print_ints [try solve n with Not_found -> -1]\ndone;;\n"}], "negative_code": [], "src_uid": "ed5ea0e664aa986ab86e4e6746e8a1bf"} {"nl": {"description": "There are many anime that are about \"love triangles\": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1\u2009000\u2009000\u2009007.", "input_spec": "The first line of input will contain two integers n,\u2009m (3\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 0\u2009\u2264\u2009m\u2009\u2264\u2009100\u2009000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai,\u2009bi,\u2009ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi, ). Each pair of people will be described no more than once.", "output_spec": "Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1\u2009000\u2009000\u2009007. ", "sample_inputs": ["3 0", "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 0", "4 4\n1 2 1\n2 3 1\n3 4 0\n4 1 1"], "sample_outputs": ["4", "1", "0"], "notes": "NoteIn the first sample, the four ways are to: Make everyone love each other Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other."}, "positive_code": [{"source_code": "type relat = Love | Hate\n\nlet flip = function\n | Love -> (fun x -> x)\n | Hate -> not\n\nlet modulus = Int64.of_int 1000000007\n \nlet rec modexp2 = function\n | 0 -> Int64.one\n | n when n mod 2 = 0 -> let k = modexp2 (n/2) in Int64.rem (Int64.mul k k) modulus\n | n -> let k = modexp2 (n/2) in\n Int64.rem (Int64.add (Int64.mul k k) (Int64.mul k k)) modulus\n\nlet _ =\n let n,m = Scanf.scanf \"%d %d \" (fun n m -> n,m) in\n let adjl = Array.init n (fun _ -> []) in\n for i = 1 to m do\n Scanf.scanf \"%d %d %d \" begin fun a b c ->\n adjl.(a-1) <- (b-1, if c = 1 then Love else Hate) :: adjl.(a-1);\n adjl.(b-1) <- (a-1, if c = 1 then Love else Hate) :: adjl.(b-1)\n end\n done;\n let mark = Array.init n (fun _ -> None) in\n let bfs i =\n let q = Queue.create () in\n let visit m j =\n match mark.(j) with\n | Some m' -> if m <> m' then raise Not_found\n | None -> (mark.(j) <- Some m; Queue.push (j, m) q)\n in\n visit true i;\n while not (Queue.is_empty q) do\n let (j, m) = Queue.pop q in\n List.iter (fun (v, rel) -> visit (flip rel m) v) adjl.(j)\n done\n in\n try\n let ctr = ref 0 in\n for i = 0 to n-1 do\n if mark.(i) = None then (bfs i; incr ctr)\n done;\n print_int (Int64.to_int (modexp2 (!ctr - 1)))\n with Not_found -> print_int 0\n \n"}], "negative_code": [{"source_code": "type relat = Love | Hate\n\nlet flip = function\n | Love -> (fun x -> x)\n | Hate -> not\n\nlet modulus = 1000000007\n \nlet rec modexp2 = function\n | 0 -> 1\n | n when n mod 2 = 0 -> let k = modexp2 (n/2) in (k*k) mod modulus\n | n -> let k = modexp2 (n/2) in (2*k*k) mod modulus\n\nlet _ =\n let n,m = Scanf.scanf \"%d %d \" (fun n m -> n,m) in\n let adjl = Array.init n (fun _ -> []) in\n for i = 1 to m do\n Scanf.scanf \"%d %d %d \" begin fun a b c ->\n adjl.(a-1) <- (b-1, if c = 1 then Love else Hate) :: adjl.(a-1);\n adjl.(b-1) <- (a-1, if c = 1 then Love else Hate) :: adjl.(b-1)\n end\n done;\n let mark = Array.init n (fun _ -> None) in\n let bfs i =\n let q = Queue.create () in\n let visit m j =\n match mark.(j) with\n | Some m' -> if m <> m' then raise Not_found\n | None -> (mark.(j) <- Some m; Queue.push (j, m) q)\n in\n visit true i;\n while not (Queue.is_empty q) do\n let (j, m) = Queue.pop q in\n List.iter (fun (v, rel) -> visit (flip rel m) v) adjl.(j)\n done\n in\n try\n let ctr = ref 0 in\n for i = 0 to n-1 do\n if mark.(i) = None then (bfs i; incr ctr)\n done;\n print_int (modexp2 (!ctr - 1))\n with Not_found -> print_int 0\n \n"}, {"source_code": "type relat = Love | Hate\n\nlet flip = function\n | Love -> (fun x -> x)\n | Hate -> not\n\nlet rec modexp2 = function\n | 0 -> 1\n | n when n mod 2 = 0 -> let k = modexp2 (n/2) in k*k\n | n -> let k = modexp2 (n/2) in 2*k*k\n\nlet _ =\n let n,m = Scanf.scanf \"%d %d \" (fun n m -> n,m) in\n let adjl = Array.init n (fun _ -> []) in\n for i = 1 to m do\n Scanf.scanf \"%d %d %d \" begin fun a b c ->\n adjl.(a-1) <- (b-1, if c = 1 then Love else Hate) :: adjl.(a-1);\n adjl.(b-1) <- (a-1, if c = 1 then Love else Hate) :: adjl.(b-1)\n end\n done;\n let mark = Array.init n (fun _ -> None) in\n let bfs i =\n let q = Queue.create () in\n let visit m j =\n match mark.(j) with\n | Some m' -> if m <> m' then raise Not_found\n | None -> (mark.(j) <- Some m; Queue.push (j, m) q)\n in\n visit true i;\n while not (Queue.is_empty q) do\n let (j, m) = Queue.pop q in\n List.iter (fun (v, rel) -> visit (flip rel m) v) adjl.(j)\n done\n in\n try\n let ctr = ref 0 in\n for i = 0 to n-1 do\n if mark.(i) = None then (bfs i; incr ctr)\n done;\n print_int (modexp2 (!ctr - 1))\n with Not_found -> print_int 0\n \n"}, {"source_code": "type relat = Love | Hate\n\nlet flip = function\n | Love -> (fun x -> x)\n | Hate -> not\n\nlet modulus = 1000000007\n \nlet rec modexp2 = function\n | 0 -> 1\n | n when n mod 2 = 0 -> let k = modexp2 (n/2) in (k*k) mod modulus\n | n -> let k = modexp2 (n/2) in 2*k*k mod modulus\n\nlet _ =\n let n,m = Scanf.scanf \"%d %d \" (fun n m -> n,m) in\n let adjl = Array.init n (fun _ -> []) in\n for i = 1 to m do\n Scanf.scanf \"%d %d %d \" begin fun a b c ->\n adjl.(a-1) <- (b-1, if c = 1 then Love else Hate) :: adjl.(a-1);\n adjl.(b-1) <- (a-1, if c = 1 then Love else Hate) :: adjl.(b-1)\n end\n done;\n let mark = Array.init n (fun _ -> None) in\n let bfs i =\n let q = Queue.create () in\n let visit m j =\n match mark.(j) with\n | Some m' -> if m <> m' then raise Not_found\n | None -> (mark.(j) <- Some m; Queue.push (j, m) q)\n in\n visit true i;\n while not (Queue.is_empty q) do\n let (j, m) = Queue.pop q in\n List.iter (fun (v, rel) -> visit (flip rel m) v) adjl.(j)\n done\n in\n try\n let ctr = ref 0 in\n for i = 0 to n-1 do\n if mark.(i) = None then (bfs i; incr ctr)\n done;\n print_int (modexp2 (!ctr - 1))\n with Not_found -> print_int 0\n \n"}], "src_uid": "6a3d6919435e5ba63bb95cd387a11b06"} {"nl": {"description": "You are given a permutation $$$p$$$ of $$$n$$$ elements. A permutation of $$$n$$$ elements is an array of length $$$n$$$ containing each integer from $$$1$$$ to $$$n$$$ exactly once. For example, $$$[1, 2, 3]$$$ and $$$[4, 3, 5, 1, 2]$$$ are permutations, but $$$[1, 2, 4]$$$ and $$$[4, 3, 2, 1, 2]$$$ are not permutations. You should perform $$$q$$$ queries.There are two types of queries: $$$1$$$ $$$x$$$ $$$y$$$ \u2014 swap $$$p_x$$$ and $$$p_y$$$. $$$2$$$ $$$i$$$ $$$k$$$ \u2014 print the number that $$$i$$$ will become if we assign $$$i = p_i$$$ $$$k$$$ times. ", "input_spec": "The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \\le n, q \\le 10^5$$$). The second line contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$. Each of the next $$$q$$$ lines contains three integers. The first integer is $$$t$$$ ($$$1 \\le t \\le 2$$$) \u2014 type of query. If $$$t = 1$$$, then the next two integers are $$$x$$$ and $$$y$$$ ($$$1 \\le x, y \\le n$$$; $$$x \\ne y$$$) \u2014 first-type query. If $$$t = 2$$$, then the next two integers are $$$i$$$ and $$$k$$$ ($$$1 \\le i, k \\le n$$$) \u2014 second-type query. It is guaranteed that there is at least one second-type query.", "output_spec": "For every second-type query, print one integer in a new line \u2014 answer to this query.", "sample_inputs": ["5 4\n5 3 4 2 1\n2 3 1\n2 1 2\n1 1 3\n2 1 2", "5 9\n2 3 5 1 4\n2 3 5\n2 5 5\n2 5 1\n2 5 3\n2 5 4\n1 5 4\n2 5 3\n2 2 5\n2 5 1"], "sample_outputs": ["4\n1\n2", "3\n5\n4\n2\n3\n3\n3\n1"], "notes": "NoteIn the first example $$$p = \\{5, 3, 4, 2, 1\\}$$$. The first query is to print $$$p_3$$$. The answer is $$$4$$$.The second query is to print $$$p_{p_1}$$$. The answer is $$$1$$$.The third query is to swap $$$p_1$$$ and $$$p_3$$$. Now $$$p = \\{4, 3, 5, 2, 1\\}$$$.The fourth query is to print $$$p_{p_1}$$$. The answer is $$$2$$$."}, "positive_code": [{"source_code": "type node = {\n mutable l:node;\n mutable r:node;\n mutable p:node; (* parent *)\n mutable s:int; (* size *)\n mutable key:int;\n}\n\nlet rec null = {l=null; r=null; p=null; s=0; key= -1}\n\nlet isroot n = n.p == null\n\nlet update x = (* assumes x is non-null *)\n x.s <- 1 + x.l.s + x.r.s\n\nlet rot_right p = (* we know that p is a left child *)\n let q = p.p in\n let r = q.p in\n q.l <- p.r;\n if q.l != null then q.l.p <- q;\n p.r <- q;\n q.p <- p;\n p.p <- r;\n if r != null then (\n if r.l == q then r.l <- p \n else if r.r == q then r.r <- p\n );\n update q (* p and r will be updated later *)\n\nlet rot_left p =\n let q = p.p in\n let r = q.p in\n q.r <- p.l;\n if q.r != null then q.r.p <- q;\n p.l <- q;\n q.p <- p;\n p.p <- r;\n if r != null then (\n if r.r == q then r.r <- p \n else if r.l == q then r.l <- p\n );\n update q\n\nlet splay p =\n let rec loop p = if not (isroot p) then\n let q = p.p in\n if isroot q then (\n\tif q.l == p then rot_right p else rot_left p\n ) else (\n\tlet r = q.p in\n\tif r.l == q then (\n\t if q.l == p then (rot_right q; rot_right p) \n\t else (rot_left p; rot_right p)\n\t) else (\n\t if q.r == p then (rot_left q; rot_left p) \n\t else (rot_right p; rot_left p)\t \n\t)\n );\n loop p\n in\n loop p;\n update p\n\nlet join x y =\n (* x and y are tree roots. join them with x to the left of y *)\n (* returns the result *)\n if x == null then y else if y == null then x else\n let rec find_rightmost p =\n\tif p.r == null then p else find_rightmost p.r in\n let z = find_rightmost x in\n splay z;\n z.r <- y;\n y.p <- z;\n update z;\n z\n\nlet split x =\n(* return two trees. The stuff to the left of x,\n and everything from x to the end *)\n splay x;\n let left = x.l in\n if left != null then left.p <- null;\n x.l <- null;\n update x;\n (left,x)\n\nlet find_node_of_rank t r =\n(* t is a tree root, r is the desired rank. r=0 is leftmost *)\n(* splay the node of the required rank *)\n let rec loop x r =\n if x.l.s = r then x\n else if x.l.s > r then loop x.l r\n else loop x.r (r - x.l.s - 1)\n in\n let root = loop t r in\n splay root;\n root\n\nlet rec find_root z old = if isroot z then (z,old)\n else find_root z.p z\n\nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n \nlet bound = 1_000_000\n\nlet () =\n let (n,q) = read_pair() in\n let node = Array.init n (fun i -> {null with s=1; key=i}) in\n let perm = Array.init n (fun i -> read_int() -1) in\n (* 0 based permutation *)\n\n (* build the trees based on the initial permutation *)\n\n(*\n let print_cycles () =\n let mark = Array.make n false in \n let rec print_tree r =\n let rec loop r = \n\tif r == null then () else (\n\t print_tree r.l;\n\t printf \"%d \" (1+r.key);\n\t mark.(r.key) <- true;\n\t print_tree r.r\n\t)\n in\n loop r;\n in\n\n for i=0 to n-1 do\n let i = (fst (find_root node.(i) null)).key in\n if not mark.(i) then (\n\tprintf \"Tree:\";\n\tprint_tree node.(i);\n\tprint_newline()\n )\n done\n in\n*)\n let mark = Array.make n false in\n\n let rec build_tree_for_cycle curr cycle =\n match cycle with [] -> ()\n | h::t ->\n\tlet nxt = node.(h) in\n\tnxt.l <- curr;\n\tif curr != null then curr.p <- nxt;\n\tupdate nxt;\n\tbuild_tree_for_cycle nxt t\n in\n\n for i=0 to n-1 do\n if not mark.(i) then (\n let rec visit_cycle i ac =\n\tif mark.(i) then List.rev ac else (\n\t mark.(i) <- true;\n\t visit_cycle perm.(i) (i::ac)\n\t)\n in\n let cycle = visit_cycle i [] in\n build_tree_for_cycle null cycle\n )\n done;\n\n (* the trees are now initialized *)\n\n let apply_swap_to_trees a b =\n splay a;\n let (b_root,b_below) = find_root b null in\n let a_to_left = a.r == b_below in\n splay b;\n if b_root == a then ( (* same tree *)\n(* printf \"same tree\\n\"; *)\n let (a,b) = if a_to_left then (a,b) else (b,a) in\n(* printf \"Now a=%d b=%d\\n\" (a.key+1) (b.key+1); *)\n (* now a is to the left of b *)\n let (t1,ax) = split a in\n let (t2,bx) = split b in\n ignore (join t1 bx);\n ) else ( (*diff tree*)\n let (t1,ax) = split a in\n let (t2,bx) = split b in\n ignore (join t1 (join bx (join t2 ax)))\n )\n in\n\n let apply_scan_to_tree x k =\n splay x;\n let rx = x.l.s in\n let cyclesize = x.s in\n let ry = (rx + k) mod cyclesize in\n let y = find_node_of_rank x ry in\n y.key\n in\n\n(* print_cycles (); *)\n \n for query = 0 to q-1 do\n match read_int() with\n | 1 -> (*swap*)\n\tlet (x,y) = read_pair() in\n(*\tprintf \"doing swap %d %d\\n\" x y; *)\n\tlet (x,y) = (x-1,y-1) in\n\tlet (px,py) = (perm.(x),perm.(y)) in\n\tperm.(x) <- py;\n\tperm.(y) <- px;\n\tapply_swap_to_trees node.(px) node.(py)\n(*\tprint_cycles() *)\n | 2 -> (*scan*)\n\tlet (x,k) = read_pair() in\n(*\tprintf \"doing scan %d %d\\n\" x k;\t *)\n\tlet x = x-1 in\n\tlet key = apply_scan_to_tree node.(perm.(x)) (k-1) in\n\tprintf \"%d\\n\" (key+1)\n(*\tprint_cycles() *)\n | _ -> failwith \"bad input\"\n done;\n"}], "negative_code": [], "src_uid": "fbe031fe816692046fffe310fbc39f8d"} {"nl": {"description": "There are two rival donut shops.The first shop sells donuts at retail: each donut costs $$$a$$$ dollars.The second shop sells donuts only in bulk: box of $$$b$$$ donuts costs $$$c$$$ dollars. So if you want to buy $$$x$$$ donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them is greater or equal to $$$x$$$.You want to determine two positive integer values: how many donuts can you buy so that they are strictly cheaper in the first shop than in the second shop? how many donuts can you buy so that they are strictly cheaper in the second shop than in the first shop? If any of these values doesn't exist then that value should be equal to $$$-1$$$. If there are multiple possible answers, then print any of them.The printed values should be less or equal to $$$10^9$$$. It can be shown that under the given constraints such values always exist if any values exist at all.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of testcases. Each of the next $$$t$$$ lines contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \\le a \\le 10^9$$$, $$$2 \\le b \\le 10^9$$$, $$$1 \\le c \\le 10^9$$$).", "output_spec": "For each testcase print two positive integers. For both shops print such $$$x$$$ that buying $$$x$$$ donuts in this shop is strictly cheaper than buying $$$x$$$ donuts in the other shop. $$$x$$$ should be greater than $$$0$$$ and less or equal to $$$10^9$$$. If there is no such $$$x$$$, then print $$$-1$$$. If there are multiple answers, then print any of them.", "sample_inputs": ["4\n5 10 4\n4 5 20\n2 2 3\n1000000000 1000000000 1000000000"], "sample_outputs": ["-1 20\n8 -1\n1 2\n-1 1000000000"], "notes": "NoteIn the first testcase buying any number of donuts will be cheaper in the second shop. For example, for $$$3$$$ or $$$5$$$ donuts you'll have to buy a box of $$$10$$$ donuts for $$$4$$$ dollars. $$$3$$$ or $$$5$$$ donuts in the first shop would cost you $$$15$$$ or $$$25$$$ dollars, respectively, however. For $$$20$$$ donuts you'll have to buy two boxes for $$$8$$$ dollars total. Note that $$$3$$$ and $$$5$$$ are also valid answers for the second shop, along with many other answers.In the second testcase buying any number of donuts will be either cheaper in the first shop or the same price. $$$8$$$ donuts cost $$$32$$$ dollars in the first shop and $$$40$$$ dollars in the second shop (because you have to buy two boxes). $$$10$$$ donuts will cost $$$40$$$ dollars in both shops, so $$$10$$$ is not a valid answer for any of the shops.In the third testcase $$$1$$$ donut costs $$$2$$$ and $$$3$$$ dollars, respectively. $$$2$$$ donuts cost $$$4$$$ and $$$3$$$ dollars. Thus, $$$1$$$ is a valid answer for the first shop and $$$2$$$ is a valid answer for the second shop.In the fourth testcase $$$10^9$$$ donuts cost $$$10^{18}$$$ dollars in the first shop and $$$10^9$$$ dollars in the second shop."}, "positive_code": [{"source_code": "let read_ints () =\n let str = read_line () in\n List.map (fun x -> int_of_string x) (Str.split (Str.regexp \" +\") str)\n;;\n\nlet rec main (t : int) =\n if t = 0 then\n ()\n else\n let [a;b;c] = read_ints () in\n (if a < c then print_int 1\n else print_int (-1);\n print_string \" \";\n let a2 = Int64.of_int a in\n let b2 = Int64.of_int b in\n let c2 = Int64.of_int c in\n if (Int64.mul a2 b2) > c2 then\n print_int b\n else\n print_int (-1);\n print_endline \"\";\n main (t-1))\n\n;;\n\nlet n = read_int () in\nmain n\n"}, {"source_code": "(* Codeforces 1373 A Donut Shops train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet shops a b c = \n let n1 = if a < c then Int64.one else Int64.minus_one in\n\t\tlet n2 = if c < (Int64.mul b a) then b else Int64.minus_one in\n\t\t(n1, n2);;\n \nlet do_one () = \n let a = grl () in\n let b = grl () in\n let c = grl () in\n let n1,n2 = shops a b c in\n Printf.printf \"%Ld %Ld\\n\" n1 n2;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [{"source_code": "(* Codeforces 1373 A Donut Shops train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet shops a b c = \n let n1 = if a < c then 1 else -1 in\n\t\tlet n2 = if c < (b * a) then b else -1 in\n\t\t(n1, n2);;\n \nlet do_one () = \n let a = gr () in\n let b = gr () in\n let c = gr () in\n let n1,n2 = shops a b c in\n Printf.printf \"%d %d\\n\" n1 n2;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "src_uid": "002801f26568a1b3524d8754207d32c1"} {"nl": {"description": "Consider a sequence [a1,\u2009a2,\u2009... ,\u2009an]. Define its prefix product sequence .Now given n, find a permutation of [1,\u20092,\u2009...,\u2009n], such that its prefix product sequence is a permutation of [0,\u20091,\u2009...,\u2009n\u2009-\u20091].", "input_spec": "The only input line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105).", "output_spec": "In the first output line, print \"YES\" if such sequence exists, or print \"NO\" if no such sequence exists. If any solution exists, you should output n more lines. i-th line contains only an integer ai. The elements of the sequence should be different positive integers no larger than n. If there are multiple solutions, you are allowed to print any of them.", "sample_inputs": ["7", "6"], "sample_outputs": ["YES\n1\n4\n3\n6\n5\n2\n7", "NO"], "notes": "NoteFor the second sample, there are no valid sequences."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet inverse a p =\n let rec egcd a b =\n (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g *)\n if a = 0 then (0,1,b) else \n let (x,y,g) = egcd (b mod a) a in \n (y-(b/a)*x, x, g)\n in\n let (x,_,_) = egcd a p in\n if x >= 0 then x else x+p\n\nlet isprime n = \n let rec loop i = (i*i > n) || (n mod i <> 0 && loop (i+1)) in\n n >= 2 && loop 2\n\nlet () =\n let n = read_int() in\n\n if n=1 then printf \"YES\\n1\\n\"\n else if n=4 then printf \"YES\\n1 3 2 4\\n\"\n else if not (isprime n) then printf \"NO\\n\"\n else (\n printf \"YES\\n\";\n printf \"1 \";\n for i=1 to n-2 do\n let a = long (inverse i n) in\n let b = long (i+1) in\n printf \"%Ld \" ((a**b) %% (long n))\n done;\n printf \"%d\\n\" n;\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet inverse a p =\n let rec egcd a b =\n (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g *)\n if a = 0 then (0,1,b) else \n let (x,y,g) = egcd (b mod a) a in \n (y-(b/a)*x, x, g)\n in\n let (x,_,_) = egcd a p in\n if x >= 0 then x else x+p\n\nlet isprime n = \n let rec loop i = (i*i > n) || (n mod i <> 0 && loop (i+1)) in\n n >= 2 && loop 2\n\nlet () =\n let n = read_int() in\n\n if n=1 then printf \"YES\\n1\\n\"\n else if not (isprime n) then printf \"NO\\n\"\n else (\n printf \"YES\\n\";\n printf \"1 \";\n for i=1 to n-2 do\n printf \"%d \" (((inverse i n) * (i+1)) mod n)\n done;\n printf \"%d\\n\" n;\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet inverse a p =\n let rec egcd a b =\n (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g *)\n if a = 0 then (0,1,b) else \n let (x,y,g) = egcd (b mod a) a in \n (y-(b/a)*x, x, g)\n in\n let (x,_,_) = egcd a p in\n if x >= 0 then x else x+p\n\nlet isprime n = \n let rec loop i = (i*i > n) || (n mod i <> 0 && loop (i+1)) in\n n >= 2 && loop 2\n\nlet () =\n let n = read_int() in\n\n if n=1 then printf \"YES\\n1\\n\"\n else if not (isprime n) then printf \"NO\\n\"\n else (\n printf \"YES\\n\";\n printf \"1 \";\n for i=1 to n-2 do\n let a = long (inverse i n) in\n let b = long (i+1) in\n printf \"%Ld \" ((a**b) %% (long n))\n done;\n printf \"%d\\n\" n;\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet inverse a p =\n let rec egcd a b =\n (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g *)\n if a = 0 then (0,1,b) else \n let (x,y,g) = egcd (b mod a) a in \n (y-(b/a)*x, x, g)\n in\n let (x,_,_) = egcd a p in\n if x >= 0 then x else x+p\n\nlet isprime n = \n let rec loop i = (i*i > n) || (n mod i <> 0 && loop (i+1)) in\n n >= 2 && loop 2\n\nlet () =\n let n = read_int() in\n\n if not (isprime n) then (\n printf \"NO\\n\"\n ) else (\n printf \"YES\\n\";\n printf \"1 \";\n for i=1 to n-2 do\n printf \"%d \" (((inverse i n) * (i+1)) mod n)\n done;\n printf \"%d\\n\" n;\n )\n"}], "src_uid": "8b61e354ece0242eff539163f76cabde"} {"nl": {"description": "A smile house is created to raise the mood. It has n rooms. Some of the rooms are connected by doors. For each two rooms (number i and j), which are connected by a door, Petya knows their value cij \u2014 the value which is being added to his mood when he moves from room i to room j.Petya wondered whether he can raise his mood infinitely, moving along some cycle? And if he can, then what minimum number of rooms he will need to visit during one period of a cycle?", "input_spec": "The first line contains two positive integers n and m (), where n is the number of rooms, and m is the number of doors in the Smile House. Then follows the description of the doors: m lines each containing four integers i, j, cij \u0438 cji (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n,\u2009i\u2009\u2260\u2009j,\u2009\u2009-\u2009104\u2009\u2264\u2009cij,\u2009cji\u2009\u2264\u2009104). It is guaranteed that no more than one door connects any two rooms. No door connects the room with itself.", "output_spec": "Print the minimum number of rooms that one needs to visit during one traverse of the cycle that can raise mood infinitely. If such cycle does not exist, print number 0.", "sample_inputs": ["4 4\n1 2 -10 3\n1 3 1 -10\n2 4 -10 -1\n3 4 0 -3"], "sample_outputs": ["4"], "notes": "NoteCycle is such a sequence of rooms a1, a2, ..., ak, that a1 is connected with a2, a2 is connected with a3, ..., ak\u2009-\u20091 is connected with ak, ak is connected with a1. Some elements of the sequence can coincide, that is, the cycle should not necessarily be simple. The number of rooms in the cycle is considered as k, the sequence's length. Note that the minimum possible length equals two."}, "positive_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let m = getnum () in\n let es = Array.make_matrix n n 100000000 in\n let _ =\n for i = 0 to n - 1 do\n es.(i).(i) <- 0;\n done;\n for k = 1 to m do\n let i = getnum () - 1 in\n let j = getnum () - 1 in\n let cij = getnum () in\n let cji = getnum () in\n\tes.(i).(j) <- -cij;\n\tes.(j).(i) <- -cji;\n done\n in\n let mmult a b =\n let n = Array.length a in\n let c = Array.make_matrix n n 100000000 in\n for i = 0 to n - 1 do\n\tlet ai = a.(i) in\n\t for k = 0 to n - 1 do\n\t let bk = Array.unsafe_get b k in\n\t for j = n - 1 downto 0 do\n\t\tlet d = Array.unsafe_get ai k + Array.unsafe_get bk j in\n\t\tlet ci = Array.unsafe_get c i in\n\t\t if Array.unsafe_get ci j > d\n\t\t then Array.unsafe_set ci j d\n\t done\n\t done\n done;\n c\n in\n let b = Array.make 10 [| |] in\n let _ =\n b.(1) <- es;\n for i = 2 to 9 do\n b.(i) <- mmult b.(i - 1) b.(i - 1)\n done\n in\n let power n =\n let m = Array.length es in\n let n = ref n in\n let r = ref (Array.make_matrix m m 100000000) in\n let _ =\n for i = 0 to m - 1 do\n\t!r.(i).(i) <- 0\n done\n in\n let bi = ref 1 in\n while !n > 0 do\n\tif !n mod 2 = 1 then (\n\t r := mmult !r b.(!bi)\n\t);\n\tincr bi;\n\tn := !n / 2;\n done;\n !r\n in\n let l = ref (-1) in\n let r = ref (n + 1) in\n while !r - !l > 1 do\n let m = (!l + !r) / 2 in\n let es = power m in\n\t(*Printf.printf \"asd %d\\n\" m;\n\tfor i = 0 to n - 1 do\n\t for j = 0 to n - 1 do\n\t Printf.printf \"%d \" es.(i).(j)\n\t done;\n\t Printf.printf \"\\n\"\n\tdone;*)\n let b = ref false in\n\tfor i = 0 to n - 1 do\n\t if es.(i).(i) < 0\n\t then b := true\n\tdone;\n\tif !b\n\tthen r := m\n\telse l := m\n done;\n if !r <= n\n then Printf.printf \"%d\\n\" !r\n else Printf.printf \"0\\n\"\n\n\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make_matrix n n 100000000 in\n let _ =\n for k = 1 to m do\n let i = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let j = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let cij = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let cji = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tes.(i).(j) <- -cij;\n\tes.(j).(i) <- -cji;\n\tes.(k - 1).(k - 1) <- 0;\n done\n in\n let min (x : int) y = if x <= y then x else y in\n let mmult a b =\n let n = Array.length a in\n let c = Array.make_matrix n n 100000000 in\n for i = 0 to n - 1 do\n\tfor j = 0 to n - 1 do\n\t for k = 0 to n - 1 do\n\t c.(i).(j) <- min c.(i).(j) (a.(i).(k) + b.(k).(j))\n\t done\n\tdone\n done;\n c\n in\n let power b n =\n let m = Array.length b in\n let n = ref n in\n let r = ref (Array.make_matrix m m 100000000) in\n let _ =\n for i = 0 to m - 1 do\n\t!r.(i).(i) <- 0\n done\n in\n let b = ref b in\n while !n > 0 do\n\tif !n mod 2 = 1 then (\n\t r := mmult !r !b\n\t);\n\tb := mmult !b !b;\n\tn := !n / 2;\n done;\n !r\n in\n let l = ref (-1) in\n let r = ref (n + 1) in\n while !r - !l > 1 do\n let m = (!l + !r) / 2 in\n let es = power es m in\n\t(*Printf.printf \"asd %d\\n\" m;\n\tfor i = 0 to n - 1 do\n\t for j = 0 to n - 1 do\n\t Printf.printf \"%d \" es.(i).(j)\n\t done;\n\t Printf.printf \"\\n\"\n\tdone;*)\n let b = ref false in\n\tfor i = 0 to n - 1 do\n\t if es.(i).(i) < 0\n\t then b := true\n\tdone;\n\tif !b\n\tthen r := m\n\telse l := m\n done;\n if !r <= n\n then Printf.printf \"%d\\n\" !r\n else Printf.printf \"0\\n\"\n\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let _ =\n for k = 1 to m do\n let i = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let j = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let cij = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let cji = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tes.(i) <- (j, -cij) :: es.(i);\n\tes.(j) <- (i, -cji) :: es.(j);\n done\n in\n let es = Array.map Array.of_list es in\n let bellman_ford nv =\n let p = Array.make nv (-1) in\n let l = Array.make nv true in\n let w = Array.make nv 0 in\n for k = 1 to nv + 1 do\n\tfor u = 0 to nv - 1 do\n\t if l.(u) then (\n\t for i = 0 to Array.length es.(u) - 1 do\n\t let (v, w') = es.(u).(i) in\n\t\tif w.(u) + w' < w.(v)\n\t\tthen (\n\t\t w.(v) <- w.(u) + w';\n\t\t p.(v) <- u;\n\t\t l.(v) <- true;\n\t\t)\n\t done;\n\t l.(u) <- false;\n\t )\n\tdone\n done;\n p\n in\n let p = bellman_ford n in\n let res = ref (n + 1) in\n let v = Array.make n false in\n for i = 0 to n - 1 do\n if not v.(i) then (\n\tv.(i) <- true;\n\tlet c = ref 1 in\n\tlet u = ref p.(i) in\n\t while !u >= 0 && not v.(!u) do\n\t v.(!u) <- true;\n\t u := p.(!u);\n\t incr c;\n\t done;\n\t if !u = i\n\t then res := min !res !c\n )\n done;\n if !res <= n\n then Printf.printf \"%d\\n\" !res\n else Printf.printf \"0\\n\"\n\n\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make_matrix n n 1000000000 in\n let _ =\n for k = 1 to m do\n let i = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let j = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let cij = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let cji = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tes.(i).(j) <- -cij;\n\tes.(j).(i) <- -cji;\n\tes.(k - 1).(k - 1) <- 0;\n done\n in\n let min (x : int) y = if x <= y then x else y in\n let mmult a b =\n let n = Array.length a in\n let c = Array.make_matrix n n 1000000000 in\n for i = 0 to n - 1 do\n\tfor j = 0 to n - 1 do\n\t for k = 0 to n - 1 do\n\t c.(i).(j) <- min c.(i).(j) (a.(i).(k) + b.(k).(j))\n\t done\n\tdone\n done;\n c\n in\n let power b n =\n let m = Array.length b in\n let n = ref n in\n let r = ref (Array.make_matrix m m 1000000000) in\n let _ =\n for i = 0 to m - 1 do\n\t!r.(i).(i) <- 0\n done\n in\n let b = ref b in\n while !n > 0 do\n\tif !n mod 2 = 1 then (\n\t r := mmult !r !b\n\t);\n\tb := mmult !b !b;\n\tn := !n / 2;\n done;\n !r\n in\n let l = ref (-1) in\n let r = ref (n + 1) in\n while !r - !l > 1 do\n let m = (!l + !r) / 2 in\n let es = power es m in\n\t(*Printf.printf \"asd %d\\n\" m;\n\tfor i = 0 to n - 1 do\n\t for j = 0 to n - 1 do\n\t Printf.printf \"%d \" es.(i).(j)\n\t done;\n\t Printf.printf \"\\n\"\n\tdone;*)\n let b = ref false in\n\tfor i = 0 to n - 1 do\n\t if es.(i).(i) < 0\n\t then b := true\n\tdone;\n\tif !b\n\tthen r := m\n\telse l := m\n done;\n if !r <= n\n then Printf.printf \"%d\\n\" !r\n else Printf.printf \"0\\n\"\n\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make_matrix n n 1000000000 in\n let _ =\n for k = 1 to m do\n let i = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let j = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let cij = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let cji = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tes.(i).(j) <- -cij;\n\tes.(j).(i) <- -cji;\n\tes.(k - 1).(k - 1) <- 0;\n done\n in\n let min (x : int) y = if x <= y then x else y in\n let mmult a b =\n let n = Array.length a in\n let c = Array.make_matrix n n 1000000000 in\n for i = 0 to n - 1 do\n\tfor j = 0 to n - 1 do\n\t for k = 0 to n - 1 do\n\t c.(i).(j) <- min c.(i).(j) (a.(i).(k) + b.(k).(j))\n\t done\n\tdone\n done;\n c\n in\n let power b n =\n let m = Array.length b in\n let n = ref n in\n let r = ref (Array.make_matrix m m 100000000) in\n let _ =\n for i = 0 to m - 1 do\n\t!r.(i).(i) <- 0\n done\n in\n let b = ref b in\n while !n > 0 do\n\tif !n mod 2 = 1 then (\n\t r := mmult !r !b\n\t);\n\tb := mmult !b !b;\n\tn := !n / 2;\n done;\n !r\n in\n let l = ref (-1) in\n let r = ref (n + 1) in\n while !r - !l > 1 do\n let m = (!l + !r) / 2 in\n let es = power es m in\n\t(*Printf.printf \"asd %d\\n\" m;\n\tfor i = 0 to n - 1 do\n\t for j = 0 to n - 1 do\n\t Printf.printf \"%d \" es.(i).(j)\n\t done;\n\t Printf.printf \"\\n\"\n\tdone;*)\n let b = ref false in\n\tfor i = 0 to n - 1 do\n\t if es.(i).(i) < 0\n\t then b := true\n\tdone;\n\tif !b\n\tthen r := m\n\telse l := m\n done;\n if !r <= n\n then Printf.printf \"%d\\n\" !r\n else Printf.printf \"0\\n\"\n\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let _ =\n for k = 1 to m do\n let i = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let j = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let cij = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let cji = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tes.(i) <- (j, -cij) :: es.(i);\n\tes.(j) <- (i, -cji) :: es.(j);\n done\n in\n let es = Array.map Array.of_list es in\n let bellman_ford nv =\n let p = Array.make nv (-1) in\n let l = Array.make nv true in\n let w = Array.make nv 0 in\n for k = 1 to nv do\n\tfor u = 0 to nv - 1 do\n\t if l.(u) then (\n\t for i = 0 to Array.length es.(u) - 1 do\n\t let (v, w') = es.(u).(i) in\n\t\tif w.(u) + w' < w.(v)\n\t\tthen (\n\t\t w.(v) <- w.(u) + w';\n\t\t p.(v) <- u;\n\t\t l.(v) <- true;\n\t\t)\n\t done;\n\t l.(u) <- false;\n\t )\n\tdone\n done;\n p\n in\n let p = bellman_ford n in\n let res = ref (n + 1) in\n let v = Array.make n (-1) in\n let d = Array.make n 0 in\n for i = 0 to n - 1 do\n if v.(i) < 0 then (\n\tv.(i) <- i;\n\td.(i) <- 0;\n\tlet c = ref 1 in\n\tlet u = ref p.(i) in\n\t while !u >= 0 && v.(!u) < 0 do\n\t v.(!u) <- i;\n\t d.(!u) <- !c;\n\t u := p.(!u);\n\t incr c;\n\t done;\n\t if !u >= 0 && v.(!u) = i\n\t then res := min !res (!c - d.(!u))\n )\n done;\n if !res <= n\n then Printf.printf \"%d\\n\" !res\n else Printf.printf \"0\\n\"\n\n\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let es = Array.make n [] in\n let _ =\n for k = 1 to m do\n let i = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let j = Scanf.bscanf sb \"%d \" (fun s -> s) - 1 in\n let cij = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let cji = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\tes.(i) <- (j, -cij) :: es.(i);\n\tes.(j) <- (i, -cji) :: es.(j);\n done\n in\n let es = Array.map Array.of_list es in\n let bellman_ford nv =\n let p = Array.make nv (-1) in\n let l = Array.make nv true in\n let w = Array.make nv 0 in\n for k = 1 to nv do\n\tfor u = 0 to nv - 1 do\n\t if l.(u) then (\n\t for i = 0 to Array.length es.(u) - 1 do\n\t let (v, w') = es.(u).(i) in\n\t\tif w.(u) + w' < w.(v)\n\t\tthen (\n\t\t w.(v) <- w.(u) + w';\n\t\t p.(v) <- u;\n\t\t l.(v) <- true;\n\t\t)\n\t done;\n\t l.(u) <- false;\n\t )\n\tdone\n done;\n p\n in\n let p = bellman_ford n in\n let res = ref (n + 1) in\n let v = Array.make n false in\n for i = 0 to n - 1 do\n if not v.(i) then (\n\tv.(i) <- true;\n\tlet c = ref 1 in\n\tlet u = ref p.(i) in\n\t while !u >= 0 && not v.(!u) do\n\t v.(!u) <- true;\n\t u := p.(!u);\n\t incr c;\n\t done;\n\t if !u = i\n\t then res := min !res !c\n )\n done;\n if !res <= n\n then Printf.printf \"%d\\n\" !res\n else Printf.printf \"0\\n\"\n\n\n\n"}], "src_uid": "85ee2a2349e695aa5300ba789ca4aa94"} {"nl": {"description": "Note that girls in Arpa\u2019s land are really attractive.Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair. There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that: Each person had exactly one type of food, No boy had the same type of food as his girlfriend, Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive. Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.", "input_spec": "The first line contains an integer n (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2009\u2264\u2009\u2009105)\u00a0\u2014 the number of pairs of guests. The i-th of the next n lines contains a pair of integers ai and bi (1\u2009\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009\u20092n)\u00a0\u2014 the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair. ", "output_spec": "If there is no solution, print -1. Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2. If there are multiple solutions, print any of them.", "sample_inputs": ["3\n1 4\n2 5\n3 6"], "sample_outputs": ["1 2\n2 1\n1 2"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n \nlet () = \n let n = read_int () in\n let pair = Array.make (2*n) 0 in\n let pair_index = Array.make n 0 in\n for i=0 to n-1 do\n let (a,b) = read_pair() in\n let (a,b) = (a-1,b-1) in\n pair.(a) <- b;\n pair.(b) <- a;\n pair_index.(i) <- a\n done;\n\n let color = Array.make (2*n) (-1) in\n\n let rec dfs0 v = if color.(v) < 0 then (\n color.(v) <- 0;\n dfs1 pair.(v)\n )\n and dfs1 v = \n color.(v) <- 1;\n dfs0 (v lxor 1)\n in\n\n for v=0 to 2*n-1 do dfs0 v done;\n\n for i=0 to n-1 do\n let a = pair_index.(i) in\n printf \"%d %d\\n\" (1+color.(a)) (1+color.(pair.(a)))\n done\n"}, {"source_code": "let n = read_int () in\nlet nn = 2 * n in\nlet io2chair = Array.make nn 0 and chair2io = Array.make nn 0 in\nfor i = 0 to nn - 1 do\n let chair = Scanf.scanf \"%d \" (fun x -> x - 1) in\n io2chair.(i) <- chair ; chair2io.(chair) <- i\ndone;\nlet out = Array.make nn 0 in\nlet rec fill_cycle i =\n if out.(i) == 0 then (\n out.(i) <- 1;\n let neighbor = chair2io.(io2chair.(i) lxor 1) in\n out.(neighbor) <- 2;\n fill_cycle (neighbor lxor 1)\n ) in\nfor i = 0 to nn - 1 do\n fill_cycle i\ndone;\nArray.iter (Printf.printf \"%d \") out\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n \nlet () = \n let n = read_int () in\n let pair = Array.make (2*n) 0 in\n let pair_index = Array.make n 0 in\n for i=0 to n-1 do\n let (a,b) = read_pair() in\n let (a,b) = (a-1,b-1) in\n pair.(a) <- b;\n pair.(b) <- a;\n pair_index.(i) <- a\n done;\n\n let color = Array.make (2*n) 0 in\n\n let rec dfs1 v = if color.(v) = 0 then (\n color.(v) <- 1;\n dfs2 pair.(v)\n )\n and dfs2 v = \n color.(v) <- 2;\n dfs1 (v lxor 1)\n in\n\n for v=0 to 2*n-1 do dfs1 v done;\n \n for i=0 to n-1 do\n let a = pair_index.(i) in\n printf \"%d %d\\n\" color.(a) color.(pair.(a))\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n \nlet () = \n let n = read_int () in\n let pair = Array.make (2*n) 0 in\n let pair_index = Array.make n 0 in\n for i=0 to n-1 do\n let (a,b) = read_pair() in\n let (a,b) = (a-1,b-1) in\n pair.(a) <- b;\n pair.(b) <- a;\n pair_index.(i) <- a\n done;\n\n let color = Array.make (2*n) (-1) in\n\n let rec dfs0 v = if color.(v) < 0 then (\n color.(v) <- 0;\n dfs1 pair.(v)\n )\n and dfs1 v = \n color.(v) <- 1;\n dfs0 (v lxor 1)\n in\n\n let rec dfs_loop v =\n if v < 2*n then if color.(v) < 0 then dfs0 v else dfs_loop (v+1)\n in\n\n dfs_loop 0;\n\n for i=0 to n-1 do\n let a = pair_index.(i) in\n printf \"%d %d\\n\" (1+color.(a)) (1+color.(pair.(a)))\n done\n"}], "src_uid": "49a78893ea2849aa59647846b4eaba7c"} {"nl": {"description": "Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length x is such a substring of length 2x, that its first half coincides character by character with its second half. Bob started deleting all the repeats from the string. He does it as follows: while it's possible, Bob takes the shortest repeat, if it is not unique, he takes the leftmost one, and deletes its left half and everything that is to the left of this repeat.You're given the string seen by Bob. Find out, what it will look like after Bob deletes all the repeats in the way described above.", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 length of the string. The following line contains n space-separated integer numbers from 0 to 109 inclusive \u2014 numbers that stand for the letters of the string. It's guaranteed that each letter can be met in the string at most 10 times.", "output_spec": "In the first line output the length of the string's part, left after Bob's deletions. In the second line output all the letters (separated by a space) of the string, left after Bob deleted all the repeats in the described way.", "sample_inputs": ["6\n1 2 3 1 2 3", "7\n4 5 6 5 6 7 7"], "sample_outputs": ["3\n1 2 3", "1\n7"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet base = 37\n\nlet () =\n let n = read_int 0 in\n let last = Hashtbl.create n in\n let nxt = Array.make n 0 in\n let a = Array.init n read_int in\n for i = n-1 downto 0 do\n let x = try Hashtbl.find last a.(i)\n with Not_found -> n in\n nxt.(i) <- x;\n Hashtbl.replace last a.(i) i\n done;\n\n let h = Array.make (n+1) 0 in\n let p = Array.make (n+1) 1 in\n for i = 0 to n-1 do\n p.(i+1) <- p.(i) * base;\n h.(i+1) <- h.(i) * base + a.(i)\n done;\n\n let signature i j =\n h.(j) - h.(i) * p.(j-i) in\n let cand = ref [] in\n for i = 0 to n-1 do\n let j = ref i in\n while j := nxt.(!j); !j < n do\n let k = !j*2-i in\n if k <= n && signature i !j = signature !j k then\n cand := (!j-i,i) :: !cand\n done\n done;\n\n let lb = ref 0 in\n cand := List.sort compare !cand;\n List.iter (fun (len,i) ->\n if !lb <= i then\n lb := i+len\n ) !cand;\n Printf.printf \"%d\\n\" (n - !lb);\n for i = !lb to n-1 do\n Printf.printf \"%d%c\" a.(i) (if i = n-1 then '\\n' else ' ')\n done\n"}], "negative_code": [], "src_uid": "7a86885813b1b447468aca5e90910970"} {"nl": {"description": "You are given a line of $$$n$$$ colored squares in a row, numbered from $$$1$$$ to $$$n$$$ from left to right. The $$$i$$$-th square initially has the color $$$c_i$$$.Let's say, that two squares $$$i$$$ and $$$j$$$ belong to the same connected component if $$$c_i = c_j$$$, and $$$c_i = c_k$$$ for all $$$k$$$ satisfying $$$i < k < j$$$. In other words, all squares on the segment from $$$i$$$ to $$$j$$$ should have the same color.For example, the line $$$[3, 3, 3]$$$ has $$$1$$$ connected component, while the line $$$[5, 2, 4, 4]$$$ has $$$3$$$ connected components.The game \"flood fill\" is played on the given line as follows: At the start of the game you pick any starting square (this is not counted as a turn). Then, in each game turn, change the color of the connected component containing the starting square to any other color. Find the minimum number of turns needed for the entire line to be changed into a single color.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 5000$$$)\u00a0\u2014 the number of squares. The second line contains integers $$$c_1, c_2, \\ldots, c_n$$$ ($$$1 \\le c_i \\le 5000$$$)\u00a0\u2014 the initial colors of the squares.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of the turns needed.", "sample_inputs": ["4\n5 2 2 1", "8\n4 5 2 2 1 3 5 5", "1\n4"], "sample_outputs": ["2", "4", "0"], "notes": "NoteIn the first example, a possible way to achieve an optimal answer is to pick square with index $$$2$$$ as the starting square and then play as follows: $$$[5, 2, 2, 1]$$$ $$$[5, 5, 5, 1]$$$ $$$[1, 1, 1, 1]$$$ In the second example, a possible way to achieve an optimal answer is to pick square with index $$$5$$$ as the starting square and then perform recoloring into colors $$$2, 3, 5, 4$$$ in that order.In the third example, the line already consists of one color only."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let n = read_int () in\n let x = Array.init n read_int in (* original input *)\n\n let c = Array.make n 0 in\n\n c.(0) <- x.(0);\n\n let rec compress i j = if j = n then i else (\n if c.(i-1) = x.(j) then compress i (j+1)\n else (\n c.(i) <- x.(j);\n compress (i+1) (j+1)\n )\n ) in\n\n let n = compress 1 1 in\n\n (*\n for i=0 to n-1 do\n printf \"%d \" c.(i)\n done;\n\n print_newline()\n *)\n\n let dp = Array.make_matrix (n+1) (n+1) (-1) in\n\n for j=1 to n do\n dp.(0).(j) <- n-j\n done;\n\n for i=0 to n-1 do\n dp.(i).(n) <- i\n done;\n\n let rec count i j =\n if dp.(i).(j) >= 0 then dp.(i).(j) else\n let answer =\n\tif c.(i-1) = c.(j) then 1 + (count (i-1) (j+1))\n\telse 1 + min (count (i-1) j) (count i (j+1))\n in\n dp.(i).(j) <- answer;\n answer\n in\n\n let answer = minf 0 (n-1) (fun i -> count i (i+1)) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "4ee194d8dc1d25eb8b186603ee71125e"} {"nl": {"description": "Ilya lives in a beautiful city of Chordalsk.There are $$$n$$$ houses on the street Ilya lives, they are numerated from $$$1$$$ to $$$n$$$ from left to right; the distance between every two neighboring houses is equal to $$$1$$$ unit. The neighboring houses are $$$1$$$ and $$$2$$$, $$$2$$$ and $$$3$$$, ..., $$$n-1$$$ and $$$n$$$. The houses $$$n$$$ and $$$1$$$ are not neighboring.The houses are colored in colors $$$c_1, c_2, \\ldots, c_n$$$ so that the $$$i$$$-th house is colored in the color $$$c_i$$$. Everyone knows that Chordalsk is not boring, so there are at least two houses colored in different colors.Ilya wants to select two houses $$$i$$$ and $$$j$$$ so that $$$1 \\leq i < j \\leq n$$$, and they have different colors: $$$c_i \\neq c_j$$$. He will then walk from the house $$$i$$$ to the house $$$j$$$ the distance of $$$(j-i)$$$ units.Ilya loves long walks, so he wants to choose the houses so that the distance between them is the maximum possible.Help Ilya, find this maximum possible distance.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$3 \\leq n \\leq 300\\,000$$$)\u00a0\u2014 the number of cities on the street. The second line contains $$$n$$$ integers $$$c_1, c_2, \\ldots, c_n$$$ ($$$1 \\leq c_i \\leq n$$$)\u00a0\u2014 the colors of the houses. It is guaranteed that there is at least one pair of indices $$$i$$$ and $$$j$$$ so that $$$1 \\leq i < j \\leq n$$$ and $$$c_i \\neq c_j$$$.", "output_spec": "Print a single integer\u00a0\u2014 the maximum possible distance Ilya can walk.", "sample_inputs": ["5\n1 2 3 2 3", "3\n1 2 1", "7\n1 1 3 1 1 1 1"], "sample_outputs": ["4", "1", "4"], "notes": "NoteIn the first example the optimal way is to walk from the first house to the last one, where Ilya can walk the distance of $$$5-1 = 4$$$ units.In the second example the optimal way is to either walk from the first house to the second or from the second to the third. Both these ways have the distance of $$$1$$$ unit.In the third example the optimal way is to walk from the third house to the last one, where Ilya can walk the distance of $$$7-3 = 4$$$ units. "}, "positive_code": [{"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a = Array.init n (fun _i ->\n Scanf.scanf \"%d \" (fun x -> x))\n in\n if a.(0) <> a.(n-1) then Printf.printf \"%d\" (n-1) else begin\n let l = ref 0 in\n while (!l < n-1 && a.(!l) = a.(0)) do incr l; done;\n let r = ref (n-1) in\n while (!r > 0 && a.(!r) = a.(n-1)) do decr r; done;\n let max = ref 0 in\n if !l < n-1 then max := n - 1 - !l;\n if !r > 0 && (!max < !r) then max := !r;\n Printf.printf \"%d\" (!max)\n end;;"}], "negative_code": [{"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a = Array.init n (fun _i ->\n Scanf.scanf \"%d \" (fun x -> x))\n in\n if a.(0) <> a.(n-1) then Printf.printf \"%d\" (n-1) else begin\n let l = ref 0 in\n while (!l < n-1 && a.(!l) = a.(0)) do incr l; done;\n let r = ref (n-1) in\n while (!r > 0 && a.(!r) = a.(n-1)) do decr r; done;\n let max = ref 0 in\n if !l < n-1 then max := !l;\n if !r > 0 && (!max < n-1 - !r) then max := n-1 - !r;\n Printf.printf \"%d\" (!max)\n end;;\n"}], "src_uid": "101fec8d8e169f941e71281048468121"} {"nl": {"description": "Moscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 109.In the evening after the conference, all n scientists decided to go to the cinema. There are m movies in the cinema they came to. Each of the movies is characterized by two distinct numbers\u00a0\u2014 the index of audio language and the index of subtitles language. The scientist, who came to the movie, will be very pleased if he knows the audio language of the movie, will be almost satisfied if he knows the language of subtitles and will be not satisfied if he does not know neither one nor the other (note that the audio language and the subtitles language for each movie are always different). Scientists decided to go together to the same movie. You have to help them choose the movie, such that the number of very pleased scientists is maximum possible. If there are several such movies, select among them one that will maximize the number of almost satisfied scientists.", "input_spec": "The first line of the input contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of scientists. The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the index of a language, which the i-th scientist knows. The third line contains a positive integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of movies in the cinema. The fourth line contains m positive integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bj\u2009\u2264\u2009109), where bj is the index of the audio language of the j-th movie. The fifth line contains m positive integers c1,\u2009c2,\u2009...,\u2009cm (1\u2009\u2264\u2009cj\u2009\u2264\u2009109), where cj is the index of subtitles language of the j-th movie. It is guaranteed that audio languages and subtitles language are different for each movie, that is bj\u2009\u2260\u2009cj. ", "output_spec": "Print the single integer\u00a0\u2014 the index of a movie to which scientists should go. After viewing this movie the number of very pleased scientists should be maximum possible. If in the cinema there are several such movies, you need to choose among them one, after viewing which there will be the maximum possible number of almost satisfied scientists. If there are several possible answers print any of them.", "sample_inputs": ["3\n2 3 2\n2\n3 2\n2 3", "6\n6 3 1 1 3 7\n5\n1 2 3 4 5\n2 3 4 5 1"], "sample_outputs": ["2", "1"], "notes": "NoteIn the first sample, scientists must go to the movie with the index 2, as in such case the 1-th and the 3-rd scientists will be very pleased and the 2-nd scientist will be almost satisfied.In the second test case scientists can go either to the movie with the index 1 or the index 3. After viewing any of these movies exactly two scientists will be very pleased and all the others will be not satisfied. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let m = read_int () in\n let b = Array.init m (fun _ -> read_int()) in\n let c = Array.init m (fun _ -> read_int()) in \n\n let h = Hashtbl.create 10 in\n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n let get t = try Hashtbl.find h t with Not_found -> 0 in\n\n for i=0 to n-1 do\n increment a.(i)\n done;\n\n let eval_movie i = (get b.(i), get c.(i),i) in\n\n let (_,_, besti) = maxf 0 (m-1) eval_movie in\n\n printf \"%d\\n\" (besti+1)\n"}], "negative_code": [], "src_uid": "74ddbcf74988940265985ec8c36bb299"} {"nl": {"description": "There are $$$n$$$ rectangles in a row. You can either turn each rectangle by $$$90$$$ degrees or leave it as it is. If you turn a rectangle, its width will be height, and its height will be width. Notice that you can turn any number of rectangles, you also can turn all or none of them. You can not change the order of the rectangles.Find out if there is a way to make the rectangles go in order of non-ascending height. In other words, after all the turns, a height of every rectangle has to be not greater than the height of the previous rectangle (if it is such). ", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$)\u00a0\u2014 the number of rectangles. Each of the next $$$n$$$ lines contains two integers $$$w_i$$$ and $$$h_i$$$ ($$$1 \\leq w_i, h_i \\leq 10^9$$$)\u00a0\u2014 the width and the height of the $$$i$$$-th rectangle.", "output_spec": "Print \"YES\" (without quotes) if there is a way to make the rectangles go in order of non-ascending height, otherwise print \"NO\". You can print each letter in any case (upper or lower).", "sample_inputs": ["3\n3 4\n4 6\n3 5", "2\n3 4\n5 5"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first test, you can rotate the second and the third rectangles so that the heights will be [4, 4, 3].In the second test, there is no way the second rectangle will be not higher than the first one."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt64 = struct \n\t(* include Int64 *)\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\nend open MyInt64\n\nlet () =\n\tlet n = get_i64 ()\n\tin\n\tlet a = Array.make ~|n (0L,0L)\n\tin\n\tfor i=0 to ~|n-$1 do\n\t\tlet w,h = get_2_i64 ()\n\t\tin a.(i) <- (w,h)\n\tdone;\n\tArray.fold_left (fun (f,u) (w,h) -> \n\t\tlet m = max w h\n\t\tin\n\t\tif u>=m then (f,m) else\n\t\tlet m = min w h\n\t\tin if u>=m then (f,m) else (false,m)\n\t) (true,Int64.max_int) a\n\t|> fst\n\t|> (fun v -> if v then \"YES\" else \"NO\")\n\t|> print_endline"}], "negative_code": [], "src_uid": "162fa942bc6eeb5164b19598da2f8bef"} {"nl": {"description": "Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $$$2 \\cdot n$$$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $$$n$$$ people in each row). Students are numbered from $$$1$$$ to $$$n$$$ in each row in order from left to right. Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all $$$2n$$$ students (there are no additional constraints), and a team can consist of any number of students. Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of students in each row. The second line of the input contains $$$n$$$ integers $$$h_{1, 1}, h_{1, 2}, \\ldots, h_{1, n}$$$ ($$$1 \\le h_{1, i} \\le 10^9$$$), where $$$h_{1, i}$$$ is the height of the $$$i$$$-th student in the first row. The third line of the input contains $$$n$$$ integers $$$h_{2, 1}, h_{2, 2}, \\ldots, h_{2, n}$$$ ($$$1 \\le h_{2, i} \\le 10^9$$$), where $$$h_{2, i}$$$ is the height of the $$$i$$$-th student in the second row.", "output_spec": "Print a single integer \u2014 the maximum possible total height of players in a team Demid can choose.", "sample_inputs": ["5\n9 3 5 7 3\n5 8 1 4 5", "3\n1 2 9\n10 1 1", "1\n7\n4"], "sample_outputs": ["29", "19", "7"], "notes": "NoteIn the first example Demid can choose the following team as follows: In the second example Demid can choose the following team as follows: "}, "positive_code": [{"source_code": "let read_int_list() = read_line() |> Str.(split (regexp \" \")) |> List.map (fun x -> int_of_string x);;\nlet (+!) = Int64.add;;\n\nlet n_student = read_int();;\nlet height_list1 = read_int_list();;\nlet height_list2 = read_int_list();;\n\nlet rec calculate n hl1 hl2 =\n if n == 0\n then (0L, 0L, 0L)\n else\n let (f11, f12, f2) = calculate (n - 1) (List.tl hl1) (List.tl hl2)\n in\n let f01 = (List.hd hl1 |> Int64.of_int) +! (max f12 f2)\n and f02 = (List.hd hl2 |> Int64.of_int) +! (max f11 f2)\n and f1 = max f11 f12\n in\n (f01, f02, f1)\n;;\n\nlet (f01, f02, f1) = calculate n_student height_list1 height_list2;;\nPrintf.printf \"%Ld\\n\" (max f01 f02);"}], "negative_code": [], "src_uid": "667e8938b964d7a24500003f6b89717b"} {"nl": {"description": "If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat. However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat. You have met a cat. Can you figure out whether it's normal or grumpy?", "input_spec": null, "output_spec": null, "sample_inputs": [], "sample_outputs": [], "notes": "NotePlease make sure to use the stream flushing operation after each query in order not to leave part of your output in some buffer."}, "positive_code": [{"source_code": "let str: string list ref = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet n = [\"cool\";\"not bad\";\"great\";\"don't think so\"; \"don't touch me!\";]\n\nlet g = [\"don't even\"; \"are you serious?\" ; \"worse\"; \"terrible\"; \"go die in a hole\"; \"no way\"]\nlet _ =\n let i = ref 0 in\n while !i < 10\n do\n Format.printf \"%d@.\" !i;\n let s = read_line () in\n flush_all ();\n if List.mem s n then\n begin\n Format.printf \"normal@.\";\n exit 0\n end\n else if List.mem s g then\n begin\n Format.printf \"grumpy@.\";\n exit 0\n end\n else\n incr i\n done\n"}, {"source_code": "\nmodule StringSet = Set.Make(String)\n\ntype cat =\n | Normal\n | Grumpy\n\nlet cats = [\n Normal, StringSet.of_list [\n \"great!\";\n \"don't think so\";\n \"nod bad\";\n \"don't touch me\";\n \"cool\"\n ]\n ; Grumpy, StringSet.of_list [\n \"don't even\";\n \"are you serious?\";\n \"go die in a hole\";\n \"no way\";\n \"worse\";\n \"terrible\"\n ]\n]\n\nlet cats_re = [\n Normal, List.map Str.regexp [\n \"cool\";\n \"great\";\n ]\n ; Grumpy, List.map Str.regexp [\n \"die\";\n \"away\";\n \"even\";\n ]\n]\n\nlet find_opt (f: 'a -> bool) (l: 'a list): 'a option =\n try Some (List.find f l) with\n | Not_found -> None\n\nlet determine_heuristic (a: string): cat option =\n (* didn't realize that a simple string find is so hard ... *)\n let str_exist p s =\n try Str.search_forward p s 0; true with\n | Not_found -> false\n in\n match find_opt (fun (_, res) -> List.exists (fun re -> str_exist re a) res) cats_re with\n | None -> None\n | Some (c, _) -> Some c\n\nlet rec determine (i: int): cat =\n if i >= 10\n then Grumpy\n else begin\n i |> string_of_int |> print_endline;\n let reaction = read_line () in\n (* OCaml 4.02.1 has no List.find_opt ... *)\n if reaction = \"no\"\n then i + 1 |> determine\n else\n let found = List.find_all (fun (_, res) -> StringSet.mem reaction res) cats in\n match found with\n | (c, _) :: _ -> c\n | [] -> match determine_heuristic reaction with\n | Some c -> c\n | None -> i + 1 |> determine\n end\n\nlet () =\n (match determine 0 with\n | Normal -> \"normal\"\n | Grumpy -> \"grumpy\") |> print_endline"}], "negative_code": [{"source_code": "let str = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet _ =\n for i = 0 to 9\n do\n Format.printf \"%d@.\" i;\n flush_all ();\n str := read_line ()::!str\n done;\n if result !str then\n Format.printf \"normal@.\"\n else\n Format.printf \"grumpy@.\"\n"}, {"source_code": "let str: string list ref = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet n = [\"cool\";\"not bad\";\"great\";\"don't think so\"; \"don't touch me!\";]\n\nlet _ =\n let i = ref 0 in\n while !i < 10\n do\n Format.printf \"%d@.\" !i;\n let s = read_line () in\n flush_all ();\n if s = \"don't think so\" then\n ignore(1/0)\n else if s = \"don't touch me!\" then\n ignore(1/0)\n else if List.mem s n then\n begin\n Format.printf \"normal@.\";\n exit 0\n end\n else if s = \"no\" then\n incr i\n else\n begin\n Format.printf \"grumpy@.\";\n exit 0\n end\n done\n"}, {"source_code": "let str = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet _ =\n for i = 0 to 9\n do\n Format.printf \"%d@.\" i;\n flush_all ();\n str := read_line ()::!str\n done;\n if result !str then\n Format.printf \"grumpy@.\"\n else\n Format.printf \"grumpy@.\"\n"}, {"source_code": "let str: string list ref = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet n = [\"cool\";\"not bad\";\"great\";\"don't think so\"; \"don't touch me!\";]\n\nlet _ =\n let i = ref 0 in\n while !i < 10\n do\n Format.printf \"%d@.\" !i;\n let s = read_line () in\n flush_all ();\n if List.mem s n then\n begin\n Format.printf \"normal@.\";\n exit 0\n end\n else if s = \"no\" then\n incr i\n else\n begin\n Format.printf \"grumpy@.\";\n exit 0\n end\n done\n"}, {"source_code": "let str: string list ref = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet n = [\"cool\";\"not bad\";\"great\";\"don't think so\"; \"don't touch me!\";]\n\nlet _ =\n let i = ref 0 in\n while !i < 10\n do\n Format.printf \"%d@.\" !i;\n let s = read_line () in\n flush_all ();\n if s = \"don't think so\" then\n begin\n Format.printf \"grumpy@.\";\n exit 0\n end\n else if List.mem s n then\n begin\n Format.printf \"normal@.\";\n exit 0\n end\n else if s = \"no\" then\n incr i\n else\n begin\n Format.printf \"grumpy@.\";\n exit 0\n end\n done\n"}, {"source_code": "let str = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n Str.string_match (Str.regexp cool) s 0\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet _ =\n for i = 0 to 9\n do\n Format.printf \"%d@.\" i;\n flush_all ();\n str := read_line ()::!str\n done;\n if result !str then\n Format.printf \"normal@.\"\n else\n Format.printf \"grumpy@.\"\n"}, {"source_code": "let str = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet _ =\n for i = 0 to 9\n do\n Format.printf \"%d@.\" i;\n flush_all ();\n str := read_line ()::!str\n done;\n if result !str then\n Format.printf \"normal@.\"\n else\n Format.printf \"normal@.\"\n"}, {"source_code": "let str: string list ref = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet n = [\"cool\";\"not bad\";\"great\";\"don't think so\"; \"don't touch me!\";]\n\nlet _ =\n let i = ref 0 in\n while !i < 10\n do\n Format.printf \"%d@.\" !i;\n let s = read_line () in\n flush_all ();\n if s = \"don't touch me!\" then\n begin\n Format.printf \"grumpy@.\";\n exit 0\n end\n else if List.mem s n then\n begin\n Format.printf \"normal@.\";\n exit 0\n end\n else if s = \"no\" then\n incr i\n else\n begin\n Format.printf \"grumpy@.\";\n exit 0\n end\n done\n"}, {"source_code": "\nmodule StringSet = Set.Make(String)\n\ntype cat =\n | Normal\n | Grumpy\n\nlet cats = [\n Normal, StringSet.of_list [\n \"great!\";\n \"don't think so\";\n \"nod bad\";\n \"don't touch me\";\n \"cool\"\n ]\n ; Grumpy, StringSet.of_list [\n \"don't even\";\n \"are you serious?\";\n \"go die in a hole\";\n \"no way\";\n \"worse\";\n \"terrible\"\n ]\n]\n\nlet rec determine (i: int): cat =\n if i >= 10\n then Grumpy\n else begin\n i |> string_of_int |> print_endline;\n let reaction = read_line () in\n (* OCaml 4.02.1 has no List.find_opt ... *)\n let found = List.find_all (fun (_, res) -> StringSet.mem reaction res) cats in\n match found with\n | (c, _) :: _ -> c\n | [] -> i + 1 |> determine\n end\n\nlet () =\n (match determine 0 with\n | Normal -> \"normal\"\n | Grumpy -> \"grumpy\") |> print_endline"}, {"source_code": "\nmodule StringSet = Set.Make(String)\n\ntype cat =\n | Normal\n | Grumpy\n\nlet cats = [\n Normal, StringSet.of_list [\n \"great!\";\n \"don't think so\";\n \"nod bad\";\n \"don't touch me\";\n \"cool\"\n ]\n ; Grumpy, StringSet.of_list [\n \"don't even\";\n \"are you serious?\";\n \"go die in a hole\";\n \"no way\";\n \"worse\";\n \"terrible\"\n ]\n]\n\nlet rec determine (i: int): cat =\n i |> string_of_int |> print_endline;\n let reaction = read_line () in\n (* OCaml 4.02.1 has no List.find_opt ... *)\n let found = List.find_all (fun (_, res) -> StringSet.mem reaction res) cats in\n match found with\n | (c, _) :: _ -> c\n | [] -> i + 1 |> determine\n\nlet () =\n (match determine 0 with\n | Normal -> \"normal\"\n | Grumpy -> \"grumpy\") |> print_endline"}, {"source_code": "let str: string list ref = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet n = [\"cool\";\"not bad\";\"great\";\"don't think so\"; \"don't touch me!\";]\n\nlet _ =\n let i = ref 0 in\n while !i < 10\n do\n Format.printf \"%d@.\" !i;\n let s = read_line () in\n flush_all ();\n ignore(1/0);\n if s = \"don't think so\" then\n ignore(1/0)\n else if s = \"don't touch me!\" then\n ignore(1/0)\n else if List.mem s n then\n begin\n Format.printf \"normal@.\";\n exit 0\n end\n else if s = \"no\" then\n incr i\n else\n begin\n Format.printf \"grumpy@.\";\n exit 0\n end\n done\n"}, {"source_code": "let str: string list ref = ref []\n\nlet cool = \"cool\"\n\nlet mem s =\n s = cool\n\nlet result l =\n List.exists (fun s -> mem s) l\n\nlet n = [\"cool\";\"not bad\";\"great\";\"don't think so\"; \"don't touch me!\";]\n\nlet _ =\n let i = ref 0 in\n while !i < 10\n do\n Format.printf \"%d@.\" !i;\n let s = read_line () in\n flush_all ();\n if s = \"don't think so\" then\n while true do () done\n else if s = \"don't touch me!\" then\n while true do () done\n else if List.mem s n then\n begin\n Format.printf \"normal@.\";\n exit 0\n end\n else if s = \"no\" then\n incr i\n else\n begin\n Format.printf \"grumpy@.\";\n exit 0\n end\n done\n"}], "src_uid": "465eae7567d12a40a05e0f258d963838"} {"nl": {"description": "For an array $$$[b_1, b_2, \\ldots, b_m]$$$ define its number of inversions as the number of pairs $$$(i, j)$$$ of integers such that $$$1 \\le i < j \\le m$$$ and $$$b_i>b_j$$$. Let's call array $$$b$$$ odd if its number of inversions is odd. For example, array $$$[4, 2, 7]$$$ is odd, as its number of inversions is $$$1$$$, while array $$$[2, 1, 4, 3]$$$ isn't, as its number of inversions is $$$2$$$.You are given a permutation $$$[p_1, p_2, \\ldots, p_n]$$$ of integers from $$$1$$$ to $$$n$$$ (each of them appears exactly once in the permutation). You want to split it into several consecutive subarrays (maybe just one), so that the number of the odd subarrays among them is as large as possible. What largest number of these subarrays may be odd?", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$) \u00a0\u2014 the size of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\le p_i \\le n$$$, all $$$p_i$$$ are distinct) \u00a0\u2014 the elements of the permutation. The sum of $$$n$$$ over all test cases doesn't exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each test case output a single integer \u00a0\u2014 the largest possible number of odd subarrays that you can get after splitting the permutation into several consecutive subarrays.", "sample_inputs": ["5\n\n3\n\n1 2 3\n\n4\n\n4 3 2 1\n\n2\n\n1 2\n\n2\n\n2 1\n\n6\n\n4 5 6 1 2 3"], "sample_outputs": ["0\n2\n0\n1\n1"], "notes": "NoteIn the first and third test cases, no matter how we split our permutation, there won't be any odd subarrays.In the second test case, we can split our permutation into subarrays $$$[4, 3], [2, 1]$$$, both of which are odd since their numbers of inversions are $$$1$$$.In the fourth test case, we can split our permutation into a single subarray $$$[2, 1]$$$, which is odd.In the fifth test case, we can split our permutation into subarrays $$$[4, 5], [6, 1, 2, 3]$$$. The first subarray has $$$0$$$ inversions, and the second has $$$3$$$, so it is odd."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f) \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n let rec loop i count = if i >= n-1 then count else (\n if a.(i) > a.(i+1) then loop (i+2) (count+1) else loop (i+1) count\n ) in\n\n printf \"%d\\n\" (loop 0 0)\n done\n"}], "negative_code": [], "src_uid": "80e21bfe08a3ef156d0404d4fe07bccd"} {"nl": {"description": "Polycarpus has been working in the analytic department of the \"F.R.A.U.D.\" company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is negative, then the company suffered losses on the i-th day.Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (ai\u2009<\u20090), he loses his temper and his wrath is terrible.Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.Write a program that, given sequence ai, will print the minimum number of folders.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100), n is the number of days. The second line contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009100), where ai means the company profit on the i-th day. It is possible that the company has no days with the negative ai.", "output_spec": "Print an integer k \u2014 the required minimum number of folders. In the second line print a sequence of integers b1, b2, ..., bk, where bj is the number of day reports in the j-th folder. If there are multiple ways to sort the reports into k days, print any of them.", "sample_inputs": ["11\n1 2 3 -4 -5 -6 5 -5 -6 -7 6", "5\n0 -1 100 -1 0"], "sample_outputs": ["3\n5 3 3", "1\n5"], "notes": "NoteHere goes a way to sort the reports from the first sample into three folders: 1 2 3 -4 -5 | -6 5 -5 | -6 -7 6 In the second sample you can put all five reports in one folder."}, "positive_code": [{"source_code": "(* Codeforces 250A BigOtres done *)\n\nopen String;;\nopen List;;\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\nlet spli s = Str.split (Str.regexp \" \") s;;\nlet printlisti li = List.iter (fun i -> (print_string \" \"; print_int i)) li;;\nlet printarri ai = Array.iter (fun i -> (print_string \" \"; print_int i)) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec nextpap l cnt pap = match l with\n\t| [] -> (l, List.rev pap)\n\t| h :: t ->\n\t\t\tif cnt = 2 && h < 0 then (l, List.rev pap)\n\t\t\telse\n\t\t\t\tlet cnt1 = if h <0 then cnt +1 else cnt in\n\t\t\t\tnextpap t cnt1 (h :: pap);;\n\nlet rec topaps l paps = match l with\n\t| [] -> List.rev paps\n\t| _ ->\n\t\t\tlet ll, pap = nextpap l 0 [] in\n\t\t\ttopaps ll (pap :: paps);;\n\nlet rec prilist l = match l with\n\t| [] -> ()\n\t| h :: t -> begin\n\t\t\t\tprint_int h;\n\t\t\t\tprint_string \" \" ;\n\t\t\t\tprilist t\n\t\t\tend;;\n\nlet main () =\n\tlet n = gr() in\n\tlet l = readlist n [] in\n\tlet paps = topaps l [] in\n\tbegin\n\t\tprint_int (length paps); print_newline();\n\t\tlet papsl = map (fun x -> length x) paps in\n\t\tprilist papsl\n\tend;;\n\nmain();;\n"}], "negative_code": [], "src_uid": "3f320920a023c3bc10ba1525e8c89044"} {"nl": {"description": "You are given a string $$$s$$$, consisting only of characters '0' and '1'.You have to choose a contiguous substring of $$$s$$$ and remove all occurrences of the character, which is a strict minority in it, from the substring.That is, if the amount of '0's in the substring is strictly smaller than the amount of '1's, remove all occurrences of '0' from the substring. If the amount of '1's is strictly smaller than the amount of '0's, remove all occurrences of '1'. If the amounts are the same, do nothing.You have to apply the operation exactly once. What is the maximum amount of characters that can be removed?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The only line of each testcase contains a non-empty string $$$s$$$, consisting only of characters '0' and '1'. The length of $$$s$$$ doesn't exceed $$$2 \\cdot 10^5$$$. The total length of strings $$$s$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the maximum amount of characters that can be removed after applying the operation exactly once.", "sample_inputs": ["4\n01\n1010101010111\n00110001000\n1"], "sample_outputs": ["0\n5\n3\n0"], "notes": "NoteIn the first testcase, you can choose substrings \"0\", \"1\" or \"01\". In \"0\" the amount of '0' is $$$1$$$, the amount of '1' is $$$0$$$. '1' is a strict minority, thus all occurrences of it are removed from the substring. However, since there were $$$0$$$ of them, nothing changes. Same for \"1\". And in \"01\" neither of '0' or '1' is a strict minority. Thus, nothing changes. So there is no way to remove any characters.In the second testcase, you can choose substring \"10101010101\". It contains $$$5$$$ characters '0' and $$$6$$$ characters '1'. '0' is a strict minority. Thus, you can remove all its occurrences. There exist other substrings that produce the same answer.In the third testcase, you can choose substring \"011000100\". It contains $$$6$$$ characters '0' and $$$3$$$ characters '1'. '1' is a strict minority. Thus, you can remove all its occurrences."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet max a b = if a > b then a else b\nlet min a b = if a < b then a else b\n\nlet remove_first s = (String.sub s 1 ((String.length s) - 1))\nlet remove_last s = (String.sub s 0 ((String.length s) - 1))\n\nlet count_remove s = \n let rec run now c0 c1 =\n if now == String.length s then if c0 == c1 then 0 else min c0 c1\n else if (String.get s now) == '0' then run (now + 1) (c0 + 1) c1\n else run (now + 1) c0 (c1 + 1) in\n run 0 0 0\n\nlet find_div7 s = \n let rec find_div7_try k =\n if k == 10 then 0\n else if ((s * 10 + k) mod 7) == 0 then (s * 10 + k)\n else find_div7_try (k + 1) in\n find_div7_try 0\n\nlet rec solve t =\n if t > 0 then (\n let s = read_line() in\n (\n if (String.length s) <= 2 then 0\n else max (max (count_remove (remove_first s)) (count_remove (remove_last s))) (count_remove s)\n )\n |> string_of_int\n |> print_endline;\n solve (t - 1)\n )\n else ()\n\nlet () = \n let t = int_of_string (read_line()) in\n solve t\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet max a b = if a > b then a else b\nlet min a b = if a < b then a else b\n\nlet remove_first s = (String.sub s 1 ((String.length s) - 1))\nlet remove_last s = (String.sub s 0 ((String.length s) - 1))\n\nlet count_remove s = \n let rec run now c0 c1 =\n if now == String.length s then min c0 c1\n else if (String.get s now) == '0' then run (now + 1) (c0 + 1) c1\n else run (now + 1) c0 (c1 + 1) in\n run 0 0 0\n\nlet find_div7 s = \n let rec find_div7_try k =\n if k == 10 then 0\n else if ((s * 10 + k) mod 7) == 0 then (s * 10 + k)\n else find_div7_try (k + 1) in\n find_div7_try 0\n\nlet rec solve t =\n if t > 0 then (\n let s = read_line() in\n (\n if (String.length s) <= 2 then 0\n else max (max (count_remove (remove_first s)) (count_remove (remove_last s))) (count_remove s)\n )\n |> string_of_int\n |> print_endline;\n solve (t - 1)\n )\n else ()\n\nlet () = \n let t = int_of_string (read_line()) in\n solve t\n"}], "src_uid": "62f5798bdcea237c0df9b4cd288b97de"} {"nl": {"description": "During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.You are given a sequence $$$a$$$, consisting of $$$n$$$ distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. First element $$$a_1$$$ becomes the root of the tree. Elements $$$a_2, a_3, \\ldots, a_n$$$ are added one by one. To add element $$$a_i$$$ one needs to traverse the tree starting from the root and using the following rules: The pointer to the current node is set to the root. If $$$a_i$$$ is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. If at some point there is no required child, the new node is created, it is assigned value $$$a_i$$$ and becomes the corresponding child of the current node. ", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 100\\,000$$$)\u00a0\u2014 the length of the sequence $$$a$$$. The second line contains $$$n$$$ distinct integers $$$a_i$$$ ($$$1 \\leq a_i \\leq 10^9$$$)\u00a0\u2014 the sequence $$$a$$$ itself.", "output_spec": "Output $$$n - 1$$$ integers. For all $$$i > 1$$$ print the value written in the node that is the parent of the node with value $$$a_i$$$ in it.", "sample_inputs": ["3\n1 2 3", "5\n4 2 3 1 6"], "sample_outputs": ["1 2", "4 2 2 4"], "notes": null}, "positive_code": [{"source_code": "let n = read_int ()\nlet a = read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string\n\nmodule IntMap = Map.Make(struct type t = int let compare = compare end)\n\ntype node =\n { value : int;\n level : int;\n up : int option;\n left : int option;\n right : int option;\n }\n\nlet new_node value =\n { value;\n left = None;\n right = None;\n level = 0;\n up = None }\n\nlet add_node map value =\n let lefts, _, rights = IntMap.split value map in\n let node = new_node value in\n let attached_left () =\n let _, left = (IntMap.max_binding lefts) in\n map\n |> IntMap.add value { node with left = Some left.value;\n level = left.level + 1;\n up = Some left.value; }\n |> IntMap.add left.value { left with right = Some node.value } in\n let attached_right () =\n let _, right = (IntMap.min_binding rights) in\n map\n |> IntMap.add value { node with right = Some right.value;\n level = right.level + 1;\n up = Some right.value; }\n |> IntMap.add right.value { right with left = Some node.value } in\n match IntMap.is_empty lefts, IntMap.is_empty rights with\n | true, true -> IntMap.singleton value node\n | false, true -> attached_left ()\n | true, false -> attached_right ()\n | false, false ->\n let _, left = (IntMap.max_binding lefts) in\n let _, right = (IntMap.min_binding rights) in\n if right.level > left.level then attached_right() else attached_left()\n\nlet node_map = List.fold_left add_node IntMap.empty a\n\nlet () =\n List.tl a\n |> List.iter (fun x -> let {up = Some y} = IntMap.find x node_map in\n Printf.printf \"%d \" y);\n print_newline ()\n"}, {"source_code": "let n = read_int ()\nlet a = read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string\n\nmodule IntMap = Map.Make(struct type t = int let compare = compare end)\n\ntype node =\n { level : int;\n up : int option;\n }\n\nlet add_node map value =\n let lefts, _, rights = IntMap.split value map in\n let up, {level} = match IntMap.is_empty lefts, IntMap.is_empty rights with\n | true, true -> value, {level = 0; up = None}\n | false, true -> IntMap.max_binding lefts\n | true, false -> IntMap.min_binding rights\n | false, false ->\n let value_left, left = IntMap.max_binding lefts in\n let value_right, right = IntMap.min_binding rights in\n if left.level > right.level\n then value_left, left\n else value_right, right in\n IntMap.add value { level = level + 1; up = Some up; } map\n\nlet node_map = List.fold_left add_node IntMap.empty a\n\nlet () =\n List.tl a\n |> List.iter (fun x -> let {up = Some y} = IntMap.find x node_map in\n Printf.printf \"%d \" y);\n print_newline ()\n"}, {"source_code": "let n = read_int ()\nlet a = read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string\n\nmodule IntMap = Map.Make(struct type t = int let compare = compare end)\n\ntype node =\n { level : int;\n up : int;\n }\n\nlet add_node map value =\n let lefts, _, rights = IntMap.split value map in\n let up, {level} = match IntMap.is_empty lefts, IntMap.is_empty rights with\n | true, true -> value, {level = 0; up = value}\n | false, true -> IntMap.max_binding lefts\n | true, false -> IntMap.min_binding rights\n | false, false ->\n let value_left, left = IntMap.max_binding lefts in\n let value_right, right = IntMap.min_binding rights in\n if left.level > right.level\n then value_left, left\n else value_right, right in\n IntMap.add value { level = level + 1; up; } map\n\nlet node_map = List.fold_left add_node IntMap.empty a\n\nlet () =\n List.tl a\n |> List.iter (fun x -> let {up} = IntMap.find x node_map in\n Printf.printf \"%d \" up);\n print_newline ()\n"}, {"source_code": "(* 2:35 *)\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let seq = Array.init n (fun i -> read_int()) in\n let perm = Array.init n (fun i -> i) in\n\n Array.sort (fun i j -> compare seq.(i) seq.(j)) perm;\n let nseq = Array.make n 0 in\n for i=0 to n-1 do\n nseq.(perm.(i)) <- i\n done;\n\n let next = Array.make n 0 in\n let prev = Array.make n 0 in\n\n for i=0 to n-1 do\n prev.(i) <- i-1;\n next.(i) <- if i = n-1 then -1 else i+1\n done;\n\n let answer = Array.make n 0 in\n\n for i = n-1 downto 1 do\n let togo = nseq.(i) in\n let get k = if k<0 then -1 else perm.(k) in\n answer.(perm.(togo)) <- max (get next.(togo)) (get prev.(togo));\n (* now delete togo from the doubly linked list *)\n let (pj, nj) = (prev.(togo), next.(togo)) in\n if pj >= 0 then next.(pj) <- nj;\n if nj >= 0 then prev.(nj) <- pj;\n done;\n\n for i=1 to n-1 do\n printf \"%d \" seq.(answer.(i))\n done;\n print_newline()\n"}], "negative_code": [{"source_code": "let n = read_int ()\nlet a = read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string\n\nmodule IntMap = Map.Make(struct type t = int let compare = compare end)\n\ntype node =\n { level : int;\n up : int option;\n }\n\nlet add_node map value =\n let lefts, _, rights = IntMap.split value map in\n let up, {level} = match IntMap.is_empty lefts, IntMap.is_empty rights with\n | true, true -> value, {level = 0; up = None}\n | false, true -> IntMap.max_binding lefts\n | true, false -> IntMap.min_binding rights\n | false, false ->\n let value_left, left = IntMap.max_binding lefts in\n let value_right, right = IntMap.min_binding rights in\n if right.level > left.level\n then value_left, left\n else value_right, right in\n IntMap.add value { level = level + 1; up = Some up; } map\n\nlet node_map = List.fold_left add_node IntMap.empty a\n\nlet () =\n List.tl a\n |> List.iter (fun x -> let {up = Some y} = IntMap.find x node_map in\n Printf.printf \"%d \" y);\n print_newline ()\n"}], "src_uid": "d2d21871c068e04469047e959dcf0d09"} {"nl": {"description": "Vasya has a multiset $$$s$$$ consisting of $$$n$$$ integer numbers. Vasya calls some number $$$x$$$ nice if it appears in the multiset exactly once. For example, multiset $$$\\{1, 1, 2, 3, 3, 3, 4\\}$$$ contains nice numbers $$$2$$$ and $$$4$$$.Vasya wants to split multiset $$$s$$$ into two multisets $$$a$$$ and $$$b$$$ (one of which may be empty) in such a way that the quantity of nice numbers in multiset $$$a$$$ would be the same as the quantity of nice numbers in multiset $$$b$$$ (the quantity of numbers to appear exactly once in multiset $$$a$$$ and the quantity of numbers to appear exactly once in multiset $$$b$$$).", "input_spec": "The first line contains a single integer $$$n~(2 \\le n \\le 100)$$$. The second line contains $$$n$$$ integers $$$s_1, s_2, \\dots s_n~(1 \\le s_i \\le 100)$$$ \u2014 the multiset $$$s$$$.", "output_spec": "If there exists no split of $$$s$$$ to satisfy the given requirements, then print \"NO\" in the first line. Otherwise print \"YES\" in the first line. The second line should contain a string, consisting of $$$n$$$ characters. $$$i$$$-th character should be equal to 'A' if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$a$$$ and 'B' if if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$b$$$. Elements are numbered from $$$1$$$ to $$$n$$$ in the order they are given in the input. If there exist multiple solutions, then print any of them.", "sample_inputs": ["4\n3 5 7 1", "3\n3 5 1"], "sample_outputs": ["YES\nBABA", "NO"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let s = Array.init n read_int\n and cnt = Array.make 101 0\n and nice = ref 0\n and swap = ref false in\n for i = 0 to n - 1 do\n cnt.(s.(i)) <- cnt.(s.(i)) + 1;\n if cnt.(s.(i)) = 1 then incr nice\n else if cnt.(s.(i)) = 2 then decr nice\n else if cnt.(s.(i)) = 3 then swap := true\n done;\n if !nice mod 2 = 1 && !swap = false then printf \"NO\\n\"\n else begin\n printf \"YES\\n\";\n let move = ref (!nice / 2) in\n if !nice mod 2 = 0 then swap := false;\n for i = 0 to n - 1 do\n if cnt.(s.(i)) = 1 then\n if !move > 0 then begin\n printf \"B\";\n decr move\n end\n else printf \"A\"\n else if cnt.(s.(i)) >= 3 then\n if !swap then begin\n printf \"B\";\n swap := false\n end\n else printf \"A\"\n else printf \"A\"\n done\n end"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\nlet llen l = i64 @@ List.length l\n\nmodule ISet = Set.Make (Int64)\nmodule IMap = Map.Make (Int64)\nlet () =\n\tlet n = get_i64 0 in\n\tlet a = input_i64_array n in\n\tlet f,z = ref false,ref (-1L) in\n\tlet o,n = Array.fold_left (fun (o,n) v ->\n\t\tif IMap.exists (fun u _ -> u = v) n then (\n\t\t\tlet p = (IMap.find v n) + 1L in\n\t\t\t(* printf \" %Ld\\n\" p; *)\n\t\t\tif p >= 3L then (\n\t\t\t\tf := true;z := v\n\t\t\t); (o,IMap.add v p n)\n\t\t) else if ISet.exists ((=) v) o then (ISet.remove v o,\n\t\t\tIMap.add v 2L n\n\t\t) else (ISet.add v o,n) \n\t) (ISet.empty,IMap.empty) a\n\tin\n\t(* printf \"%Ld\\n\" !z; *)\n\tlet w,x = ISet.elements o |> llen, IMap.bindings n |> llen in\n\t(* printf \"%Ld %Ld\\n\" w x; *)\n\tif w mod 2L = 1L && not !f then (\n\t\tprintf \"NO\\n\"\n\t) else if w mod 2L = 0L then (\n\t\tprintf \"YES\\n\";\n\t\tArray.fold_left (fun m v ->\n\t\t\tif IMap.exists (fun u _ -> u = v) n then (printf \"A\"; m)\n\t\t\telse (printf (if m then \"A\" else \"B\"); (not m))\n\t\t) true a\n\t\t|> ignore;\n\t) else (\n\t\tprintf \"YES\\n\";\n\t\tArray.fold_left (fun (m,q) v ->\n\t\t\tif IMap.exists (fun u _ -> u = v) n then (\n\t\t\t\t(* if q then (printf \"B\";(m,false))\n\t\t\t\telse (printf \"A\"; (m,q)) *)\n\t\t\t\t(* printf \"%Ld %Ld\\n\" v !z; *)\n\t\t\t\tif v = !z then (\n\t\t\t\t\tprintf \"B\"; z := -1L; (m,q);\n\t\t\t\t) else (\n\t\t\t\t\tprintf \"A\"; (m,q)\n\t\t\t\t)\n\t\t\t) else (printf (if m then \"A\" else \"B\"); (not m,q))\n\t\t) (true,true) a\n\t\t|> ignore;\n\t)"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\nlet llen l = i64 @@ List.length l\n\nmodule ISet = Set.Make (Int64)\nmodule IMap = Map.Make (Int64)\nlet () =\n\tlet n = get_i64 0 in\n\tlet a = input_i64_array n in\n\tlet f,z = ref false,ref (-1L) in\n\tlet o,n = Array.fold_left (fun (o,n) v ->\n\t\tif IMap.exists (fun u _ -> u = v) n then (\n\t\t\tlet p = (IMap.find v n) + 1L in\n\t\t\tprintf \" %Ld\\n\" p;\n\t\t\tif p >= 3L then (\n\t\t\t\tf := true;z := v\n\t\t\t); (o,IMap.add v p n)\n\t\t) else if ISet.exists ((=) v) o then (ISet.remove v o,\n\t\t\tIMap.add v 2L n\n\t\t) else (ISet.add v o,n) \n\t) (ISet.empty,IMap.empty) a\n\tin\n\t(* printf \"%Ld\\n\" !z; *)\n\tlet w,x = ISet.elements o |> llen, IMap.bindings n |> llen in\n\t(* printf \"%Ld %Ld\\n\" w x; *)\n\tif w mod 2L = 1L && not !f then (\n\t\tprintf \"NO\\n\"\n\t) else if w mod 2L = 0L then (\n\t\tprintf \"YES\\n\";\n\t\tArray.fold_left (fun m v ->\n\t\t\tif IMap.exists (fun u _ -> u = v) n then (printf \"A\"; m)\n\t\t\telse (printf (if m then \"A\" else \"B\"); (not m))\n\t\t) true a\n\t\t|> ignore;\n\t) else (\n\t\tprintf \"YES\\n\";\n\t\tArray.fold_left (fun (m,q) v ->\n\t\t\tif IMap.exists (fun u _ -> u = v) n then (\n\t\t\t\t(* if q then (printf \"B\";(m,false))\n\t\t\t\telse (printf \"A\"; (m,q)) *)\n\t\t\t\t(* printf \"%Ld %Ld\\n\" v !z; *)\n\t\t\t\tif v = !z then (\n\t\t\t\t\tprintf \"B\"; z := -1L; (m,q);\n\t\t\t\t) else (\n\t\t\t\t\tprintf \"A\"; (m,q)\n\t\t\t\t)\n\t\t\t) else (printf (if m then \"A\" else \"B\"); (not m,q))\n\t\t) (true,true) a\n\t\t|> ignore;\n\t)"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\nlet llen l = i64 @@ List.length l\n\nmodule ISet = Set.Make (Int64)\nlet () =\n\tlet n = get_i64 0 in\n\tlet a = input_i64_array n in\n\tlet o,n = Array.fold_left (fun (o,n) v ->\n\t\tif ISet.exists ((=) v) n then (o,n)\n\t\telse if ISet.exists ((=) v) o then (ISet.remove v o, ISet.add v n)\n\t\telse (ISet.add v o,n) \n\t) (ISet.empty,ISet.empty) a\n\tin\n\tif (ISet.elements o |> llen) mod 2L = 1L then (\n\t\tprintf \"NO\\n\"\n\t) else (\n\t\tprintf \"YES\\n\";\n\t\tArray.fold_left (fun m v ->\n\t\t\tif ISet.exists ((=) v) n then (printf \"A\"; m)\n\t\t\telse (printf (if m then \"A\" else \"B\"); (not m))\n\t\t) true a\n\t\t|> ignore;\n\t)"}], "src_uid": "d126ef6b94e9ab55624cf7f2a96c7ed1"} {"nl": {"description": "During the hypnosis session, Nicholas suddenly remembered a positive integer $$$n$$$, which doesn't contain zeros in decimal notation. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes not prime, that is, either composite or equal to one?For some numbers doing so is impossible: for example, for number $$$53$$$ it's impossible to delete some of its digits to obtain a not prime integer. However, for all $$$n$$$ in the test cases of this problem, it's guaranteed that it's possible to delete some of their digits to obtain a not prime number.Note that you cannot remove all the digits from the number.A prime number is a number that has no divisors except one and itself. A composite is a number that has more than two divisors. $$$1$$$ is neither a prime nor a composite number.", "input_spec": "Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$k$$$ ($$$1 \\le k \\le 50$$$)\u00a0\u2014 the number of digits in the number. The second line of each test case contains a positive integer $$$n$$$, which doesn't contain zeros in decimal notation ($$$10^{k-1} \\le n < 10^{k}$$$). It is guaranteed that it is always possible to remove less than $$$k$$$ digits to make the number not prime. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^4$$$.", "output_spec": "For every test case, print two numbers in two lines. In the first line print the number of digits, that you have left in the number. In the second line print the digits left after all delitions. If there are multiple solutions, print any.", "sample_inputs": ["7\n3\n237\n5\n44444\n3\n221\n2\n35\n3\n773\n1\n4\n30\n626221626221626221626221626221"], "sample_outputs": ["2\n27\n1\n4\n1\n1\n2\n35\n2\n77\n1\n4\n1\n6"], "notes": "NoteIn the first test case, you can't delete $$$2$$$ digits from the number $$$237$$$, as all the numbers $$$2$$$, $$$3$$$, and $$$7$$$ are prime. However, you can delete $$$1$$$ digit, obtaining a number $$$27 = 3^3$$$.In the second test case, you can delete all digits except one, as $$$4 = 2^2$$$ is a composite number."}, "positive_code": [{"source_code": "open Printf\r\nopen Scanf\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_int_char _ = bscanf Scanning.stdin \" %c \" (fun x -> int_of_char x - 48)\r\n\r\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\r\n \r\nlet is_not_prime x = x = 1 || x = 4 || x = 6 || x = 8 || x = 9\r\nlet count l e = List.fold_left (fun acc x -> if x = e then acc + 1 else acc) 0 l\r\nlet contains l e = List.filter (fun x -> x = e) l |> List.length > 0\r\n\r\n\r\nlet () = \r\n let cases = read_int () in\r\n for case = 1 to cases do\r\n let n = read_int () in\r\n let ar = Array.init n (fun _ -> read_int_char ()) in\r\n let a = Array.to_list ar in\r\n (* let () = List.iter (printf \"%d \") a in *)\r\n\r\n let composites = List.filter is_not_prime a in\r\n (if List.length composites <> 0 then \r\n printf \"%d\\n%d\\n\" 1 (List.hd composites)\r\n else\r\n let hd = List.hd a in\r\n let tl = List.tl a in \r\n let res = List.filter (fun x -> x = 2 || x = 5) tl in\r\n if List.length res > 0 then\r\n printf \"%d\\n%d%d\\n\" 2 hd (List.hd res)\r\n else\r\n if count a 2 >= 2 then printf \"%d\\n%d\\n\" 2 22\r\n else if count a 3 >= 2 then printf \"%d\\n%d\\n\" 2 33\r\n else if count a 5 >= 2 then printf \"%d\\n%d\\n\" 2 55\r\n else if count a 7 >= 2 then printf \"%d\\n%d\\n\" 2 77\r\n else \r\n if hd = 2 && contains tl 7 then printf \"%d\\n%d\\n\" 2 27\r\n else if hd = 5 && contains tl 7 then printf \"%d\\n%d\\n\" 2 57\r\n else ()\r\n )\r\n done\r\n"}], "negative_code": [{"source_code": "open Printf\r\nopen Scanf\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\nlet read_int_char _ = bscanf Scanning.stdin \" %c \" (fun x -> int_of_char x - 48)\r\n\r\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\r\n \r\nlet is_not_prime x = x = 1 || x = 4 || x = 6 || x = 8 || x = 9\r\nlet count l e = List.fold_left (fun acc x -> if x = e then acc + 1 else acc) 0 l\r\nlet contains l e = List.filter (fun x -> x = e) l |> List.length > 0\r\n\r\n\r\nlet () = \r\n let cases = read_int () in\r\n let _ = printf \"%d\\n\" cases in \r\n for case = 1 to cases do\r\n let n = read_int () in\r\n let ar = Array.init n (fun _ -> read_int_char ()) in\r\n let a = Array.to_list ar in\r\n (* let () = List.iter (printf \"%d \") a in *)\r\n\r\n let composites = List.filter is_not_prime a in\r\n (if List.length composites <> 0 then \r\n printf \"%d\\n%d\\n\" 1 (List.hd composites)\r\n else\r\n let hd = List.hd a in\r\n let tl = List.tl a in \r\n let res = List.filter (fun x -> x = 2 || x = 5) tl in\r\n if List.length res > 0 then\r\n printf \"%d\\n%d%d\\n\" 2 hd (List.hd res)\r\n else\r\n if count a 2 >= 2 then printf \"%d\\n%d\\n\" 2 22\r\n else if count a 3 >= 2 then printf \"%d\\n%d\\n\" 2 33\r\n else if count a 5 >= 2 then printf \"%d\\n%d\\n\" 2 55\r\n else if count a 7 >= 2 then printf \"%d\\n%d\\n\" 2 77\r\n else \r\n if hd = 2 && contains tl 7 then printf \"%d\\n%d\\n\" 2 27\r\n else if hd = 5 && contains tl 7 then printf \"%d\\n%d\\n\" 2 57\r\n else ()\r\n )\r\n done\r\n"}], "src_uid": "22c0489eec3d8e290fcbcf1aeb3bb66c"} {"nl": {"description": "Let's call the following process a transformation of a sequence of length $$$n$$$.If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of $$$n$$$ integers: the greatest common divisors of all the elements in the sequence before each deletion.You are given an integer sequence $$$1, 2, \\dots, n$$$. Find the lexicographically maximum result of its transformation.A sequence $$$a_1, a_2, \\ldots, a_n$$$ is lexicographically larger than a sequence $$$b_1, b_2, \\ldots, b_n$$$, if there is an index $$$i$$$ such that $$$a_j = b_j$$$ for all $$$j < i$$$, and $$$a_i > b_i$$$.", "input_spec": "The first and only line of input contains one integer $$$n$$$ ($$$1\\le n\\le 10^6$$$).", "output_spec": "Output $$$n$$$ integers \u00a0\u2014 the lexicographically maximum result of the transformation.", "sample_inputs": ["3", "2", "1"], "sample_outputs": ["1 1 3", "1 2", "1"], "notes": "NoteIn the first sample the answer may be achieved this way: Append GCD$$$(1, 2, 3) = 1$$$, remove $$$2$$$. Append GCD$$$(1, 3) = 1$$$, remove $$$1$$$. Append GCD$$$(3) = 3$$$, remove $$$3$$$. We get the sequence $$$[1, 1, 3]$$$ as the result."}, "positive_code": [{"source_code": "let split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nexception Found;;\n\nlet last_big l a =\n let tmp = ref 0 in\n try\n for i = l-1 downto 0 do\n if a.(i) then (tmp := i + 1; raise Found)\n done;\n !tmp\n with Found -> !tmp\n;;\n\nlet n = Scanf.sscanf (read_line ()) \"%i\" (fun n -> n) in\nlet b = Array.make n true in\nlet div = ref 1 in\nlet continue = ref 0 in\nlet last = ref n in\nwhile !continue != n do\n for j = 1 to n do\n if b.(j-1) && j mod (2 * !div) != 0 then begin\n if j = !last && !continue = n - 2 then begin\n Printf.printf \"%i \" !div;\n incr continue;\n Printf.printf \"%i \" !last;\n end else Printf.printf \"%i \" !div;\n incr continue;\n b.(j-1) <- false;\n if j = !last then last := last_big !last b\n end\n done;\n div := 2 * !div;\ndone;\nprint_newline ()\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet n = get_i64 0\nlet nn = \n\tlet r = ref 1L in\n\twhile !r*2L <= n do\n\t\tr *= 2L\n\tdone; !r\nlet f v =\n\tlet r = ref 1L in\n\twhile !r*v <= n do r *= v\n\tdone; !r\nlet () =\n\tif n = 1L then printf \"1\\n\"\n\telse if n = 2L then printf \"1 2\\n\"\n\telse if n = 3L then printf \"1 1 3\\n\"\n\telse\n\tlet p,v = ref n,ref 1L in\n\twhile !p > 0L do\n\t\tif !p >= 4L then (\n\t\t\trep 1L (!p - !p / 2L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L (!p-1L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tprintf \"%Ld\\n\" ((n / !v) * !v);\n\t\t\t(* print_endline \"\";\n\t\t\tprintf \"%Ld\\n\" nn;\n\t\t\tprintf \"%Ld %Ld %Ld\\n\" ((n/2L)*2L) (f !v) ((n / !v) * !v); *)\n\t\t\tp := 0L;\n\t\t)\n\t\t(* let c = !p - !p / 2L in\n\t\tif c >= 2L then (\n\t\t\trep 1L (c) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L c (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tp := 0L\n\t\t) *)\n\tdone;"}], "negative_code": [{"source_code": "\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet n = Scanf.sscanf (read_line ()) \"%i\" (fun n -> n) in\nlet b = Array.make n true in\nlet div = ref 1 in\nlet continue = ref 0 in\nwhile !continue != n do\n for j = 1 to n do\n if b.(j-1) && j mod (2 * !div) != 0 then begin\n b.(j-1) <- false;\n incr continue;\n Printf.printf \"%i \" (if n = 3 && !continue = n then n else !div);\n end\n done;\n div := 2 * !div;\ndone;\nprint_newline ()\n"}, {"source_code": "\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet n = Scanf.sscanf (read_line ()) \"%i\" (fun n -> n) in\nlet b = Array.make n true in\nlet div = ref 1 in\nlet continue = ref true in\nwhile !continue do\n continue := false;\n for j = 1 to n do\n if b.(j-1) then continue := true;\n if b.(j-1) && j mod (2 * !div) != 0 then begin\n b.(j-1) <- false;\n print_int !div;\n end\n done;\n div := 2 * !div;\ndone;\nprint_newline ()\n"}, {"source_code": "let split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet n = Scanf.sscanf (read_line ()) \"%i\" (fun n -> n) in\nlet b = Array.make n true in\nlet div = ref 1 in\nlet continue = ref 0 in\nwhile !continue != n do\n for j = 1 to n do\n if b.(j-1) && j mod (2 * !div) != 0 then begin\n b.(j-1) <- false;\n if j = n && !continue = n - 2 then begin\n Printf.printf \"%i \" !div;\n incr continue;\n Printf.printf \"%i \" n;\n end else Printf.printf \"%i \" !div;\n incr continue;\n end\n done;\n div := 2 * !div;\ndone;\nprint_newline ()\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet n = get_i64 0\nlet () =\n\tif n = 2L then printf \"1 2\\n\"\n\telse if n = 3L then printf \"1 1 3\\n\"\n\telse\n\tlet p,v = ref n,ref 1L in\n\twhile !p > 0L do\n\t\tif !p >= 4L then (\n\t\t\trep 1L (!p - !p / 2L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L (!p-1L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tprintf \"%Ld\\n\" n;\n\t\t\tp := 0L;\n\t\t)\n\t\t(* let c = !p - !p / 2L in\n\t\tif c >= 2L then (\n\t\t\trep 1L (c) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L c (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tp := 0L\n\t\t) *)\n\tdone;\n\n\n(* \nlet n = get_i64 0\nlet mx = i32 n +$ 24\n\nlet prime = Array.make (mx) true\nlet preprocess _ =\n\tprime.(0) <- false;\n\tprime.(1) <- false;\n\trepi 2 mx (fun u ->\n\t\tif prime.(u) then (\n\t\t\trepi (u*$2) mx (fun v ->\n\t\t\t\tprime.(v) <- false;\n\t\t\t\t`Ok\n\t\t\t)\n\t\t);\n\t\t`Ok\n\t)\n\t\nlet () =\n *)\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet n = get_i64 0\nlet () =\n\tif n = 2L then printf \"1 2\\n\"\n\telse if n = 3L then printf \"1 1 3\\n\"\n\telse\n\tlet p,v = ref n,ref 1L in\n\twhile !p > 0L do\n\t\tif !p >= 4L then (\n\t\t\trep 1L (!p - !p / 2L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L (!p-1L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tprintf \"%Ld\\n\" ((n/2L)*2L);\n\t\t\tp := 0L;\n\t\t)\n\t\t(* let c = !p - !p / 2L in\n\t\tif c >= 2L then (\n\t\t\trep 1L (c) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L c (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tp := 0L\n\t\t) *)\n\tdone;"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet n = get_i64 0\nlet nn = \n\tlet r = ref 1L in\n\twhile !r*2L <= n do\n\t\tr *= 2L\n\tdone; !r\nlet () =\n\tif n = 1L then printf \"1\\n\"\n\telse if n = 2L then printf \"1 2\\n\"\n\telse if n = 3L then printf \"1 1 3\\n\"\n\telse\n\tlet p,v = ref n,ref 1L in\n\twhile !p > 0L do\n\t\tif !p >= 4L then (\n\t\t\trep 1L (!p - !p / 2L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L (!p-1L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tprintf \"%Ld\\n\" nn;\n\t\t\tp := 0L;\n\t\t)\n\t\t(* let c = !p - !p / 2L in\n\t\tif c >= 2L then (\n\t\t\trep 1L (c) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L c (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tp := 0L\n\t\t) *)\n\tdone;"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet n = get_i64 0\nlet () =\n\tif n = 1L then printf \"1\\n\"\n\telse if n = 2L then printf \"1 2\\n\"\n\telse if n = 3L then printf \"1 1 3\\n\"\n\telse\n\tlet p,v = ref n,ref 1L in\n\twhile !p > 0L do\n\t\tif !p >= 4L then (\n\t\t\trep 1L (!p - !p / 2L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L (!p-1L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tprintf \"%Ld\\n\" ((n/2L)*2L);\n\t\t\tp := 0L;\n\t\t)\n\t\t(* let c = !p - !p / 2L in\n\t\tif c >= 2L then (\n\t\t\trep 1L (c) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L c (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tp := 0L\n\t\t) *)\n\tdone;\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet n = get_i64 0\nlet () =\n\tif n = 2L then printf \"1 2\\n\"\n\telse if n = 3L then printf \"1 1 3\\n\"\n\telse\n\tlet p,v = ref n,ref 1L in\n\twhile !p > 0L do\n\t\tif !p >= 4L then (\n\t\t\trep 1L (!p - !p / 2L) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L !p (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tp := 0L;\n\t\t)\n\t\t(* let c = !p - !p / 2L in\n\t\tif c >= 2L then (\n\t\t\trep 1L (c) (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tv *= 2L;\n\t\t\tp /= 2L;\n\t\t) else (\n\t\t\trep 1L c (fun _ -> printf \"%Ld \" !v; `Ok);\n\t\t\tp := 0L\n\t\t) *)\n\tdone;"}], "src_uid": "cadff0864835854f4f1e0234f2fd3edf"} {"nl": {"description": "Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Roma's got n positive integers. He wonders, how many of those integers have not more than k lucky digits? Help him, write the program that solves the problem.", "input_spec": "The first line contains two integers n, k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009100). The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the numbers that Roma has. The numbers in the lines are separated by single spaces.", "output_spec": "In a single line print a single integer \u2014 the answer to the problem.", "sample_inputs": ["3 4\n1 2 4", "3 2\n447 44 77"], "sample_outputs": ["3", "2"], "notes": "NoteIn the first sample all numbers contain at most four lucky digits, so the answer is 3.In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2."}, "positive_code": [{"source_code": "let read_one () = Scanf.scanf \" %d\" (fun x -> x)\nlet read_two () = Scanf.scanf \" %d %d\" (fun x y -> (x,y)) \nlet read_three () = Scanf.scanf \" %d %d %d\" (fun x y z -> (x,y,z))\n\nlet read_many n =\n let rec helper i acc =\n if i >= n then List.rev acc\n else Scanf.scanf \" %d\" (fun n -> helper (i+1) (n::acc)) in\n helper 0 []\n\nlet list_iteri f lst = List.fold_left (fun j b -> f j b; j+1) 0 lst\n\nlet rec lucky_enough x k n = \n if n > k then false\n else if x = 0 then true \n else lucky_enough (x / 10) k (if x mod 10 = 4 || x mod 10 = 7 then n+1 else n)\n\nlet main =\n let t = Scanf.scanf \"%d\" (fun t -> t) in\n let k = read_one () in\n let all = read_many t in\n let ans = List.fold_left (fun acc x -> \n if lucky_enough x k 0 then acc + 1 else acc\n ) 0 all in\n Printf.printf \"%d\\n\" ans\n \n"}], "negative_code": [], "src_uid": "6bb26991c9ea70e51a6bda5653de8131"} {"nl": {"description": "While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s. He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length.He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length.", "input_spec": "The first line of input contains string s containing lowercase English letters (1\u2009\u2264\u2009|s|\u2009\u2264\u20091000). The second line contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u20091000).", "output_spec": "Print \"YES\"(without quotes) if he has worn his own back-bag or \"NO\"(without quotes) otherwise.", "sample_inputs": ["saba\n2", "saddastavvat\n2"], "sample_outputs": ["NO", "YES"], "notes": "NotePalindrome is a string reading the same forward and backward.In the second sample, the faxes in his back-bag can be \"saddas\" and \"tavvat\"."}, "positive_code": [{"source_code": "\nlet _ =\n let s = Scanf.scanf \" %s\" (fun s -> s) in\n let k = Scanf.scanf \" %d\" (fun x -> x) in\n try\n let n = String.length s in\n if n mod k <> 0 then raise Not_found;\n let l = n/k in\n for i=0 to k-1 do\n for j = 0 to l-1 do\n if s.[i*l+j] <> s.[i*l+(l-1-j)] then raise Not_found;\n done\n done;\n Printf.printf \"YES\\n\";\n with\n Not_found -> Printf.printf \"NO\\n\";\n"}], "negative_code": [], "src_uid": "43bb8fec6b0636d88ce30f23b61be39f"} {"nl": {"description": "Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,\u2009\u2009-\u20092,\u20091,\u20093,\u2009\u2009-\u20094. Suppose the mother suggested subarrays (1,\u2009\u2009-\u20092), (3,\u2009\u2009-\u20094), (1,\u20093), (1,\u2009\u2009-\u20092,\u20091,\u20093). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1\u00b71\u2009=\u20091 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds (\u2009-\u20092)\u00b71\u2009=\u2009\u2009-\u20092, because he is in one of chosen subarrays, the third flower adds 1\u00b72\u2009=\u20092, because he is in two of chosen subarrays, the fourth flower adds 3\u00b72\u2009=\u20096, because he is in two of chosen subarrays, the fifth flower adds (\u2009-\u20094)\u00b70\u2009=\u20090, because he is in no chosen subarrays. Thus, in total 1\u2009+\u2009(\u2009-\u20092)\u2009+\u20092\u2009+\u20096\u2009+\u20090\u2009=\u20097 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100)\u00a0\u2014 the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moods\u00a0\u2014 n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009100\u2009\u2264\u2009ai\u2009\u2264\u2009100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n) denoting the subarray a[li],\u2009a[li\u2009+\u20091],\u2009...,\u2009a[ri]. Each subarray can encounter more than once.", "output_spec": "Print single integer\u00a0\u2014 the maximum possible value added to the Alyona's happiness.", "sample_inputs": ["5 4\n1 -2 1 3 -4\n1 2\n4 5\n3 4\n1 4", "4 3\n1 2 3 4\n1 3\n2 4\n1 1", "2 2\n-1 -2\n1 1\n1 2"], "sample_outputs": ["7", "16", "0"], "notes": "NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays."}, "positive_code": [{"source_code": "let () =\n Scanf.scanf \"%d %d \" @@ fun n m ->\n let moods = Array.make n 0 in\n for i = 0 to n - 1 do\n Scanf.scanf \"%d \" (Array.set moods i)\n done;\n let value = ref 0 in\n for i = 0 to m - 1 do\n Scanf.scanf \"%d %d \" @@ fun l r ->\n let m = ref 0 in\n for j = l - 1 to r - 1 do\n m := !m + moods.(j)\n done;\n if !m > 0 then value := !value + !m\n done;\n Printf.printf \"%d\\n\" !value\n"}], "negative_code": [], "src_uid": "6d7364048428c70e0e9b76ab1eb8cc34"} {"nl": {"description": "Let's call a string \"s-palindrome\" if it is symmetric about the middle of the string. For example, the string \"oHo\" is \"s-palindrome\", but the string \"aa\" is not. The string \"aa\" is not \"s-palindrome\", because the second half of it is not a mirror reflection of the first half. English alphabet You are given a string s. Check if the string is \"s-palindrome\".", "input_spec": "The only line contains the string s (1\u2009\u2264\u2009|s|\u2009\u2264\u20091000) which consists of only English letters.", "output_spec": "Print \"TAK\" if the string s is \"s-palindrome\" and \"NIE\" otherwise.", "sample_inputs": ["oXoxoXo", "bod", "ER"], "sample_outputs": ["TAK", "TAK", "NIE"], "notes": null}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%s\\n\" (fun s ->\n (* characters that can be the middle of a string *)\n let mid = ['A'; 'H'; 'I'; 'M'; 'O'; 'o'; 'T'; 'U'; 'V'; 'v'; 'W'; 'w'; 'X'; 'x'; 'Y']\n (* mirrored pairs *)\n and pairs = ['b', 'd'; 'd', 'b'; 'p', 'q'; 'q', 'p'] in\n\n let n = String.length s in\n\n print_endline (\n if (n mod 2 = 0 || List.mem s.[n / 2] mid) &&\n Array.fold_left (&&) true (Array.init (n / 2) (fun i ->\n (s.[i] = s.[n - i - 1] && List.mem s.[i] mid) ||\n (List.mem_assoc s.[i] pairs && List.assoc s.[i] pairs = s.[n - i - 1])))\n then \"TAK\" else \"NIE\"))\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let res = ref true in\n let sym =\n function\n | 'A' -> 'A'\n | 'b' -> 'd'\n | 'd' -> 'b'\n | 'H' -> 'H'\n | 'I' -> 'I'\n | 'M' -> 'M'\n | 'O' -> 'O'\n | 'o' -> 'o'\n | 'T' -> 'T'\n | 'U' -> 'U'\n | 'V' -> 'V'\n | 'v' -> 'v'\n | 'W' -> 'W'\n | 'w' -> 'w'\n | 'X' -> 'X'\n | 'x' -> 'x'\n | 'Y' -> 'Y'\n | 'p' -> 'q'\n | 'q' -> 'p'\n | _ -> '\\000'\n in\n for i = 0 to (n - 1) / 2 do\n if s.[i] <> sym s.[n - i - 1]\n then res := false\n done;\n if !res\n then Printf.printf \"TAK\\n\"\n else Printf.printf \"NIE\\n\"\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let res = ref true in\n let sym =\n function\n | 'A' -> 'A'\n | 'b' -> 'd'\n | 'd' -> 'b'\n | 'H' -> 'H'\n | 'I' -> 'I'\n | 'M' -> 'M'\n | 'O' -> 'O'\n | 'o' -> 'o'\n | 'T' -> 'T'\n | 'U' -> 'U'\n | 'V' -> 'V'\n | 'v' -> 'v'\n | 'W' -> 'W'\n | 'w' -> 'w'\n | 'X' -> 'X'\n | 'x' -> 'x'\n | 'Y' -> 'Y'\n | _ -> '\\000'\n in\n for i = 0 to (n - 1) / 2 do\n if s.[i] <> sym s.[n - i - 1]\n then res := false\n done;\n if !res\n then Printf.printf \"TAK\\n\"\n else Printf.printf \"NIE\\n\"\n"}], "src_uid": "bec2349631158b7dbfedcaededf65cc2"} {"nl": {"description": "Alyona has recently bought a miniature fridge that can be represented as a matrix with $$$h$$$ rows and $$$2$$$ columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part. An example of a fridge with $$$h = 7$$$ and two shelves. The shelves are shown in black. The picture corresponds to the first example. Alyona has $$$n$$$ bottles of milk that she wants to put in the fridge. The $$$i$$$-th bottle is $$$a_i$$$ cells tall and $$$1$$$ cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.Alyona is interested in the largest integer $$$k$$$ such that she can put bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. Find this largest $$$k$$$.", "input_spec": "The first line contains two integers $$$n$$$ and $$$h$$$ ($$$1 \\le n \\le 10^3$$$, $$$1 \\le h \\le 10^9$$$)\u00a0\u2014 the number of bottles and the height of the fridge. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \\le a_i \\le h$$$)\u00a0\u2014 the heights of the bottles.", "output_spec": "Print the single integer $$$k$$$\u00a0\u2014 the maximum integer such that Alyona can put the bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. If Alyona can put all bottles in the fridge, print $$$n$$$. It is easy to see that Alyona can always put at least one bottle in the fridge.", "sample_inputs": ["5 7\n2 3 5 4 1", "10 10\n9 1 1 1 1 1 1 1 1 1", "5 10\n3 1 4 2 4"], "sample_outputs": ["3", "4", "5"], "notes": "NoteOne of optimal locations in the first example is shown on the picture in the statement.One of optimal locations in the second example is shown on the picture below. One of optimal locations in the third example is shown on the picture below. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\n\nlet stdin = Scanning.stdin\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x)\n\n\nlet check h a =\n let rec check' i s =\n if i >= Array.length a\n then s <= h\n else check' (i+2) (s++a.(i)) in\n check' 0 0L\n\nlet rec binary_search l r h a =\n if r - l <= 1\n then l\n else\n let m = (l+r)/2 in\n let b = Array.init m (fun i -> a.(i)) in\n Array.sort (fun x y -> Int64.compare y x) b;\n if check h b\n then binary_search m r h a\n else binary_search l m h a\n\nlet () =\n let n,h = bscanf stdin \" %d %Ld\" (fun x y -> (x,y)) in\n let a = Array.init n read_long in\n printf \"%d\\n\" @@ binary_search (-1) (n+1) h a\n"}], "negative_code": [], "src_uid": "2ff0919ee7dfdfb916b23c26fb2caf20"} {"nl": {"description": "When Masha came to math classes today, she saw two integer sequences of length $$$n - 1$$$ on the blackboard. Let's denote the elements of the first sequence as $$$a_i$$$ ($$$0 \\le a_i \\le 3$$$), and the elements of the second sequence as $$$b_i$$$ ($$$0 \\le b_i \\le 3$$$).Masha became interested if or not there is an integer sequence of length $$$n$$$, which elements we will denote as $$$t_i$$$ ($$$0 \\le t_i \\le 3$$$), so that for every $$$i$$$ ($$$1 \\le i \\le n - 1$$$) the following is true: $$$a_i = t_i | t_{i + 1}$$$ (where $$$|$$$ denotes the bitwise OR operation) and $$$b_i = t_i \\& t_{i + 1}$$$ (where $$$\\&$$$ denotes the bitwise AND operation). The question appeared to be too difficult for Masha, so now she asked you to check whether such a sequence $$$t_i$$$ of length $$$n$$$ exists. If it exists, find such a sequence. If there are multiple such sequences, find any of them.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the sequence $$$t_i$$$. The second line contains $$$n - 1$$$ integers $$$a_1, a_2, \\ldots, a_{n-1}$$$ ($$$0 \\le a_i \\le 3$$$)\u00a0\u2014 the first sequence on the blackboard. The third line contains $$$n - 1$$$ integers $$$b_1, b_2, \\ldots, b_{n-1}$$$ ($$$0 \\le b_i \\le 3$$$)\u00a0\u2014 the second sequence on the blackboard.", "output_spec": "In the first line print \"YES\" (without quotes), if there is a sequence $$$t_i$$$ that satisfies the conditions from the statements, and \"NO\" (without quotes), if there is no such sequence. If there is such a sequence, on the second line print $$$n$$$ integers $$$t_1, t_2, \\ldots, t_n$$$ ($$$0 \\le t_i \\le 3$$$)\u00a0\u2014 the sequence that satisfies the statements conditions. If there are multiple answers, print any of them.", "sample_inputs": ["4\n3 3 2\n1 2 0", "3\n1 3\n3 2"], "sample_outputs": ["YES\n1 3 2 0", "NO"], "notes": "NoteIn the first example it's easy to see that the sequence from output satisfies the given conditions: $$$t_1 | t_2 = (01_2) | (11_2) = (11_2) = 3 = a_1$$$ and $$$t_1 \\& t_2 = (01_2) \\& (11_2) = (01_2) = 1 = b_1$$$; $$$t_2 | t_3 = (11_2) | (10_2) = (11_2) = 3 = a_2$$$ and $$$t_2 \\& t_3 = (11_2) \\& (10_2) = (10_2) = 2 = b_2$$$; $$$t_3 | t_4 = (10_2) | (00_2) = (10_2) = 2 = a_3$$$ and $$$t_3 \\& t_4 = (10_2) \\& (00_2) = (00_2) = 0 = b_3$$$. In the second example there is no such sequence."}, "positive_code": [{"source_code": "let rec read_int_seq n stream = \n\tif n = 1 then Scanf.bscanf stream \"%i\" (fun x -> [x]) \n\telse Scanf.bscanf stream \"%i \" (fun x -> x::(read_int_seq (n - 1) stream))\n;;\n\nlet rec into_bits nums = \n\tmatch nums with\n\t| h::t -> (h / 2, h mod 2)::(into_bits t)\n\t| [] -> []\n;;\n\nlet append_to_option head tail =\n\tmatch tail with\n\t| Some t -> Some (head::t)\n\t| None -> None\n;;\n\nlet either f g =\n\tmatch f () with\n\t| Some a -> Some a\n\t| None -> match g () with\n\t\t| Some a -> Some a\n\t\t| None -> None\n;;\n\nlet unwrap op =\n\tmatch op with\n\t| Some a -> a\n\t| None -> failwith \"no value in option\"\n;;\n\nlet contradict_barrier want_to_place hint x =\n\tmatch hint with\n\t| Some a when a = want_to_place -> x\n\t| None -> x\n\t| _ -> None\n;;\n\nlet rec solve nums_a nums_b current_hint_l current_hint_r =\n\tlet infer_l a_bit b_bit a_tail b_tail =\n\t\tlet infer_r l_res next_hint_l =\n\t\t\tmatch (snd a_bit, snd b_bit, current_hint_r) with\n\t\t\t| (0, 0, _) -> contradict_barrier 0 current_hint_r (append_to_option (l_res, 0) (solve a_tail b_tail next_hint_l (Some 0)))\n\t\t\t| (1, 1, _) -> contradict_barrier 1 current_hint_r (append_to_option (l_res, 1) (solve a_tail b_tail next_hint_l (Some 1)))\n\t\t\t| (1, 0, Some 0) -> append_to_option (l_res, 0) (solve a_tail b_tail next_hint_l (Some 1))\n\t\t\t| (1, 0, Some 1) -> append_to_option (l_res, 1) (solve a_tail b_tail next_hint_l (Some 0))\n\t\t\t| (1, 0, None) -> either (fun () -> append_to_option (l_res, 0) (solve a_tail b_tail next_hint_l (Some 1))) (fun () -> append_to_option (l_res, 1) (solve a_tail b_tail next_hint_l (Some 0)))\n\t\t\t| (0, 1, _) -> None\n\t\t\t| _ -> failwith \"corrupt data\"\n\t\tin\n\t\tmatch (fst a_bit, fst b_bit, current_hint_l) with\n\t\t| (0, 0, _) -> contradict_barrier 0 current_hint_l (infer_r 0 (Some 0))\n\t\t| (1, 1, _) -> contradict_barrier 1 current_hint_l (infer_r 1 (Some 1))\n\t\t| (1, 0, Some 0) -> infer_r 0 (Some 1)\n\t\t| (1, 0, Some 1) -> infer_r 1 (Some 0)\n\t\t| (1, 0, None) -> either (fun () -> infer_r 0 (Some 1)) (fun () -> infer_r 1 (Some 0))\n\t\t| (0, 1, _) -> None\n\t\t| _ -> failwith \"corrupt data\"\n\tin \n\tmatch (nums_a, nums_b) with\n\t| (h1::t1, h2::t2) -> infer_l h1 h2 t1 t2\n\t| _ -> Some [(unwrap current_hint_l, unwrap current_hint_r)]\n;;\n\nlet n = read_int();;\nlet input_len = n - 1;;\nlet nums_a = read_line();;\nlet nums_b = read_line();;\nlet nums_a = read_int_seq input_len (Scanf.Scanning.from_string nums_a);;\nlet nums_b = read_int_seq input_len (Scanf.Scanning.from_string nums_b);;\nlet nums_a = into_bits nums_a;;\nlet nums_b = into_bits nums_b;;\n\nlet solution = solve nums_a nums_b None None;;\nmatch solution with\n\t| Some solution -> (Printf.printf \"YES\\n\"; List.iter (fun (x, y) -> Printf.printf \"%i \" (2*x + y)) solution)\n\t| None -> Printf.printf \"NO\\n\"\n;;"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64,ist = Int64.(to_int,of_int,to_string)\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* io *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\t(* imperative *)\n\tlet rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done\n\tlet repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done\n\tlet repm f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m\n\tlet repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done\n\tlet repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done\n\tlet repim f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m\n\t(* debug *)\n\tlet dump_list f ls = string_of_list f ls |> print_endline\n\tlet dump_array f a = string_of_array f a |> print_endline\nend open Lib\n\nopen I64_infix\nlet () =\n\tlet tbl = Hashtbl.create ~random:true 10014 in\n\trep 0L 3L (fun t ->\n\t\trep 0L 3L (fun a ->\n\t\t\trep 0L 3L (fun b ->\n\t\t\t\tlet ls = ref (-1L) in\n\t\t\t\trep 0L 3L (fun tt ->\n\t\t\t\t\tif a = t lor tt && b = t land tt then ls := tt\n\t\t\t\t);\n\t\t\t\tif !ls >= 0L then Hashtbl.add tbl (t,a,b) @@ !ls\n\t\t\t\t\n\t\t\t)\n\t\t)\n\t);\n\tlet n = get_i64 0 in\n\tlet a = input_i64_array (n-1L) in\n\tlet b = input_i64_array (n-1L) in\n\tlet t = Array.make (i32 n) 0L in\n\trep 0L 3L (fun t0 ->\n\t\tt.(0) <- t0;\n\t\tlet f = ref true in\n\t\trepf 1L (n-1L) (fun i ->\n\t\t\tlet i = i32 i in\n\t\t\ttry\n\t\t\t\tt.(i) <- Hashtbl.find tbl (t.(i-$1),a.(i-$1),b.(i-$1));\n\t\t\t\t`Ok\n\t\t\twith | Not_found -> (\n\t\t\t\tf := false; `Break\n\t\t\t)\n\t\t);\n\t\tif !f then (\n\t\t\tprintf \"YES\\n\";\n\t\t\tdump_array Int64.to_string t; exit 0\n\t\t)\n\t);\n\tprintf \"NO\\n\";\n"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64,ist = Int64.(to_int,of_int,to_string)\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* io *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\t(* imperative *)\n\tlet rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done\n\tlet repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done\n\tlet repm f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m\n\tlet repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done\n\tlet repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done\n\tlet repim f t m0 fbod =\n\t\tlet i,c,m = ref f,ref true,ref m0 in\n\t\twhile !i<=t && !c do match fbod !m !i with\n\t\t| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m\n\t(* debug *)\n\tlet dump_list f ls = string_of_list f ls |> print_endline\n\tlet dump_array f a = string_of_array f a |> print_endline\nend open Lib\n\nopen I64_infix\nlet undef = -77L\nlet () =\n\tlet tbl = Hashtbl.create ~random:true 10014 in\n\trep 0L 3L (fun t ->\n\t\trep 0L 3L (fun a ->\n\t\t\trep 0L 3L (fun b ->\n\t\t\t\tlet ls = ref (-1L) in\n\t\t\t\trep 0L 3L (fun tt ->\n\t\t\t\t\tif a = t lor tt && b = t land tt then ls := tt\n\t\t\t\t);\n\t\t\t\tif !ls >= 0L then Hashtbl.add tbl (t,a,b) @@ !ls\n\t\t\t\telse Hashtbl.add tbl (t,a,b) undef\n\t\t\t)\n\t\t)\n\t);\n\tlet n = get_i64 0 in\n\tlet a = input_i64_array (n-1L) in\n\tlet b = input_i64_array (n-1L) in\n\tlet t = Array.make (i32 n) 0L in\n\trep 0L 3L (fun t0 ->\n\t\tt.(0) <- t0;\n\t\tlet f = ref true in\n\t\trepf 1L (n-1L) (fun i ->\n\t\t\tlet i = i32 i in\n\t\t\tlet v = Hashtbl.find tbl (t.(i-$1),a.(i-$1),b.(i-$1))\n\t\t\tin if v = undef then (f := false; `Break)\n\t\t\telse (t.(i) <- v; `Ok)\n\t\t);\n\t\tif !f then (\n\t\t\tprintf \"YES\\n\";\n\t\t\tdump_array Int64.to_string t; exit 0\n\t\t)\n\t);\n\tprintf \"NO\\n\";\n"}], "negative_code": [{"source_code": "let rec read_int_seq n stream = \n\tif n = 1 then Scanf.bscanf stream \"%i\" (fun x -> [x]) \n\telse Scanf.bscanf stream \"%i \" (fun x -> x::(read_int_seq (n - 1) stream))\n;;\n\nlet rec into_bits nums = \n\tmatch nums with\n\t| h::t -> (h / 2, h mod 2)::(into_bits t)\n\t| [] -> []\n;;\n\nlet append_to_option head tail =\n\tmatch tail with\n\t| Some t -> Some (head::t)\n\t| None -> None\n;;\n\nlet either f g =\n\tmatch f () with\n\t| Some a -> Some a\n\t| None -> match g () with\n\t\t| Some a -> Some a\n\t\t| None -> None\n;;\n\nlet unwrap op =\n\tmatch op with\n\t| Some a -> a\n\t| None -> failwith \"no value in option\"\n;;\n\nlet rec solve nums_a nums_b current_hint_l current_hint_r =\n\tlet infer_l a_bit b_bit a_tail b_tail =\n\t\tlet infer_r l_res next_hint_l =\n\t\t\tmatch (snd a_bit, snd b_bit, current_hint_r) with\n\t\t\t| (0, 0, _) -> append_to_option (l_res, 0) (solve a_tail b_tail next_hint_l (Some 0))\n\t\t\t| (1, 1, _) -> append_to_option (l_res, 1) (solve a_tail b_tail next_hint_l (Some 1))\n\t\t\t| (1, 0, Some 0) -> append_to_option (l_res, 0) (solve a_tail b_tail next_hint_l (Some 1))\n\t\t\t| (1, 0, Some 1) -> append_to_option (l_res, 1) (solve a_tail b_tail next_hint_l (Some 0))\n\t\t\t| (1, 0, None) -> either (fun () -> append_to_option (l_res, 0) (solve a_tail b_tail next_hint_l (Some 1))) (fun () -> append_to_option (l_res, 1) (solve a_tail b_tail next_hint_l (Some 0)))\n\t\t\t| (0, 1, _) -> None\n\t\t\t| _ -> failwith \"corrupt data\"\n\t\tin\n\t\tmatch (fst a_bit, fst b_bit, current_hint_l) with\n\t\t| (0, 0, _) -> infer_r 0 (Some 0)\n\t\t| (1, 1, _) -> infer_r 1 (Some 1)\n\t\t| (1, 0, Some 0) -> infer_r 0 (Some 1)\n\t\t| (1, 0, Some 1) -> infer_r 1 (Some 0)\n\t\t| (1, 0, None) -> either (fun () -> infer_r 0 (Some 1)) (fun () -> infer_r 1 (Some 0))\n\t\t| (0, 1, _) -> None\n\t\t| _ -> failwith \"corrupt data\"\n\tin \n\tmatch (nums_a, nums_b) with\n\t| (h1::t1, h2::t2) -> infer_l h1 h2 t1 t2\n\t| _ -> Some [(unwrap current_hint_l, unwrap current_hint_r)]\n;;\n\nlet n = read_int();;\nlet input_len = n - 1;;\nlet nums_a = read_line();;\nlet nums_b = read_line();;\nlet nums_a = read_int_seq input_len (Scanf.Scanning.from_string nums_a);;\nlet nums_b = read_int_seq input_len (Scanf.Scanning.from_string nums_b);;\nlet nums_a = into_bits nums_a;;\nlet nums_b = into_bits nums_b;;\n\nlet solution = solve nums_a nums_b None None;;\nmatch solution with\n\t| Some solution -> (Printf.printf \"YES\\n\"; List.iter (fun (x, y) -> Printf.printf \"%i \" (2*x + y)) solution)\n\t| None -> Printf.printf \"NO\\n\"\n;;"}], "src_uid": "ac21483a33e7bcb031b1f8f62e39d60f"} {"nl": {"description": "Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a \"plus\") and negative (a \"minus\"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100000) \u2014 the number of magnets. Then n lines follow. The i-th line (1\u2009\u2264\u2009i\u2009\u2264\u2009n) contains either characters \"01\", if Mike put the i-th magnet in the \"plus-minus\" position, or characters \"10\", if Mike put the magnet in the \"minus-plus\" position.", "output_spec": "On the single line of the output print the number of groups of magnets.", "sample_inputs": ["6\n10\n10\n10\n01\n10\n10", "4\n01\n01\n10\n10"], "sample_outputs": ["3", "2"], "notes": "NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets."}, "positive_code": [{"source_code": "let solve () = \n let n = Pervasives.read_int () in\n let rec loop i last count = \n if i <= n\n then\n let current = Pervasives.read_line () in\n if String.compare current last = 0\n then\n loop (i + 1) last count\n else\n loop (i + 1) current (count + 1)\n else\n count\n in loop 2 (Pervasives.read_line ()) 1\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve ())"}, {"source_code": "let n = int_of_string (read_line ()) in\nlet g = Array.init n (fun i -> int_of_string (read_line ())) |> Array.to_list in\nprint_int (List.fold_left (fun (b,c) a -> (a, c + if a != b then 1 else 0)) (List.hd g, 1) (List.tl g) |> snd)\n\n"}, {"source_code": "let n = read_int () in\nlet g = ref 1 in\nlet l = ref '2' in\nfor i = 1 to n do\n match read_line () with\n \"01\" -> if !l = '0' then g := !g + 1; l := '1'\n | \"10\" -> if !l = '1' then g := !g + 1; l := '0'\ndone ;\nprint_int !g ; print_newline () ;;\n"}], "negative_code": [], "src_uid": "6c52df7ea24671102e4c0eee19dc6bba"} {"nl": {"description": "The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times.", "input_spec": "The only line of the input contains a pair of integers n (1000\u2009\u2264\u2009n\u2009\u2264\u200910\u00a0000) and t (0\u2009\u2264\u2009t\u2009\u2264\u20092\u00a0000\u00a0000\u00a0000)\u00a0\u2014 the number of transistors in the initial time and the number of seconds passed since the initial time.", "output_spec": "Output one number \u2014 the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10\u2009-\u20096.", "sample_inputs": ["1000 1000000"], "sample_outputs": ["1011.060722383550382782399454922040"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let res = float_of_int n *. 1.000000011 ** t in\n Printf.printf \"%.6f\\n\" res\n"}], "negative_code": [], "src_uid": "36ad784f23bd1e8e579052642a6e9244"} {"nl": {"description": "You are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters.Your task is to add spaces to the text by the following rules: if there is no punctuation mark between two words, then they should be separated by exactly one space there should be no spaces before each punctuation mark there should be exactly one space after each punctuation mark It is guaranteed that there is at least one word between any two punctuation marks. The text begins and ends with a Latin letter.", "input_spec": "The input data contains of a single non-empty line \u2014 the text whose length is no more than 10000 characters.", "output_spec": "Print the text, edited according to the rules. In this problem you should follow the output format very strictly. For example, extra space at the end of the output line is considered as wrong answer. Note that a newline character at the end of the line doesn't matter.", "sample_inputs": ["galileo galilei was an italian physicist ,mathematician,astronomer", "galileo was born in pisa"], "sample_outputs": ["galileo galilei was an italian physicist, mathematician, astronomer", "galileo was born in pisa"], "notes": null}, "positive_code": [{"source_code": "type state =\n | Start\n | Word of Buffer.t\n | Mark\n\nlet _ =\n let s = input_line stdin in\n let s = s ^ \" \" in\n let n = String.length s in\n let state = ref Start in\n for i = 0 to n - 1 do\n let c = s.[i] in\n\tmatch c with\n\t | 'a'..'z' -> (\n\t match !state with\n\t\t| Start ->\n\t\t let b = Buffer.create 10 in\n\t\t Buffer.add_char b c;\n\t\t state := Word b\n\t\t| Word b ->\n\t\t Buffer.add_char b c\n\t\t| Mark ->\n\t\t output_char stdout ' ';\n\t\t let b = Buffer.create 10 in\n\t\t Buffer.add_char b c;\n\t\t state := Word b\n\t )\n\t | '.' | ',' | '!' | '?' -> (\n\t match !state with\n\t\t| Start ->\n\t\t output_char stdout c;\n\t\t state := Mark\n\t\t| Word b ->\n\t\t output_string stdout (Buffer.contents b);\n\t\t output_char stdout c;\n\t\t state := Mark;\n\t\t| Mark ->\n\t\t output_char stdout c;\n\t )\n\t | ' ' -> (\n\t match !state with\n\t\t| Start -> ()\n\t\t| Word b ->\n\t\t output_string stdout (Buffer.contents b);\n\t\t state := Mark\n\t\t| Mark -> ()\n\t )\n\t | _ -> assert false\n done\n"}, {"source_code": "type state =\n | Start\n | Word of Buffer.t\n | Mark\n\nlet _ =\n let s = input_line stdin in\n let s = s ^ \" \" in\n let n = String.length s in\n let state = ref Start in\n for i = 0 to n - 1 do\n let c = s.[i] in\n\tmatch c with\n\t | 'a'..'z' -> (\n\t match !state with\n\t\t| Start ->\n\t\t let b = Buffer.create 10 in\n\t\t Buffer.add_char b c;\n\t\t state := Word b\n\t\t| Word b ->\n\t\t Buffer.add_char b c\n\t\t| Mark ->\n\t\t output_char stdout ' ';\n\t\t let b = Buffer.create 10 in\n\t\t Buffer.add_char b c;\n\t\t state := Word b\n\t )\n\t | '.' | ',' | '!' | '?' -> (\n\t match !state with\n\t\t| Start ->\n\t\t output_char stdout c;\n\t\t state := Mark\n\t\t| Word b ->\n\t\t output_string stdout (Buffer.contents b);\n\t\t output_char stdout c;\n\t\t state := Mark;\n\t\t| Mark ->\n\t\t output_char stdout c;\n\t )\n\t | ' ' -> (\n\t match !state with\n\t\t| Start -> ()\n\t\t| Word b ->\n\t\t output_string stdout (Buffer.contents b);\n\t\t state := Mark\n\t\t| Mark -> ()\n\t )\n\t | _ -> assert false\n done\n"}], "negative_code": [], "src_uid": "8c26daa1eed2078af3b32737da0a0f84"} {"nl": {"description": "New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $$$h$$$ hours and $$$m$$$ minutes, where $$$0 \\le hh < 24$$$ and $$$0 \\le mm < 60$$$. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $$$0$$$ hours and $$$0$$$ minutes.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1439$$$) \u2014 the number of test cases. The following $$$t$$$ lines describe test cases. The $$$i$$$-th line contains the time as two integers $$$h$$$ and $$$m$$$ ($$$0 \\le h < 24$$$, $$$0 \\le m < 60$$$). It is guaranteed that this time is not a midnight, i.e. the following two conditions can't be met at the same time: $$$h=0$$$ and $$$m=0$$$. It is guaranteed that both $$$h$$$ and $$$m$$$ are given without leading zeros.", "output_spec": "For each test case, print the answer on it \u2014 the number of minutes before the New Year.", "sample_inputs": ["5\n23 55\n23 0\n0 1\n4 20\n23 59"], "sample_outputs": ["5\n60\n1439\n1180\n1"], "notes": null}, "positive_code": [{"source_code": "let f h m =\n (60 * (23 - h)) + (60 - m)\n\nlet () =\n let n = read_int () in\n for i = 1 to n do\n let t = Scanf.scanf \"%d %d\\n\" f in\n Printf.printf \"%d\\n\" t\n done\n"}], "negative_code": [], "src_uid": "f4982de28aca7080342eb1d0ff87734c"} {"nl": {"description": "On the number line there are $$$m$$$ points, $$$i$$$-th of which has integer coordinate $$$x_i$$$ and integer weight $$$w_i$$$. The coordinates of all points are different, and the points are numbered from $$$1$$$ to $$$m$$$.A sequence of $$$n$$$ segments $$$[l_1, r_1], [l_2, r_2], \\dots, [l_n, r_n]$$$ is called system of nested segments if for each pair $$$i, j$$$ ($$$1 \\le i < j \\le n$$$) the condition $$$l_i < l_j < r_j < r_i$$$ is satisfied. In other words, the second segment is strictly inside the first one, the third segment is strictly inside the second one, and so on.For a given number $$$n$$$, find a system of nested segments such that: both ends of each segment are one of $$$m$$$ given points; the sum of the weights $$$2\\cdot n$$$ of the points used as ends of the segments is minimal. For example, let $$$m = 8$$$. The given points are marked in the picture, their weights are marked in red, their coordinates are marked in blue. Make a system of three nested segments: weight of the first segment: $$$1 + 1 = 2$$$ weight of the second segment: $$$10 + (-1) = 9$$$ weight of the third segment: $$$3 + (-2) = 1$$$ sum of the weights of all the segments in the system: $$$2 + 9 + 1 = 12$$$ System of three nested segments ", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014the number of input test cases. An empty line is written before each test case. The first line of each test case contains two positive integers $$$n$$$ ($$$1 \\le n \\le 10^5$$$) and $$$m$$$ ($$$2 \\cdot n \\le m \\le 2 \\cdot 10^5$$$). The next $$$m$$$ lines contain pairs of integers $$$x_i$$$ ($$$-10^9 \\le x_i \\le 10^9$$$) and $$$w_i$$$ ($$$-10^4 \\le w_i \\le 10^4$$$) \u2014 coordinate and weight of point number $$$i$$$ ($$$1 \\le i \\le m$$$) respectively. All $$$x_i$$$ are different. It is guaranteed that the sum of $$$m$$$ values over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output $$$n + 1$$$ lines: in the first of them, output the weight of the composed system, and in the next $$$n$$$ lines output exactly two numbers \u00a0\u2014 the indices of the points which are the endpoints of the $$$i$$$-th segment ($$$1 \\le i \\le n$$$). The order in which you output the endpoints of a segment is not important \u2014 you can output the index of the left endpoint first and then the number of the right endpoint, or the other way around. If there are several ways to make a system of nested segments with minimal weight, output any of them.", "sample_inputs": ["3\n\n3 8\n0 10\n-2 1\n4 10\n11 20\n7 -1\n9 1\n2 3\n5 -2\n\n3 6\n-1 2\n1 3\n3 -1\n2 4\n4 0\n8 2\n\n2 5\n5 -1\n3 -2\n1 0\n-2 0\n-5 -3"], "sample_outputs": ["12\n2 6\n5 1\n7 8\n\n10\n1 6\n5 2\n3 4\n\n-6\n5 1\n4 2"], "notes": "NoteThe first test case coincides with the example from the condition. It can be shown that the weight of the composed system is minimal.The second test case has only $$$6$$$ points, so you need to use each of them to compose $$$3$$$ segments."}, "positive_code": [{"source_code": "let rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n \r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n \r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n \r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n \r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n \r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n \r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n \r\nlet rec fusion2 p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt y x -> x::(fusion2 q1 p2)\r\n | _,x::q2 -> x::(fusion2 p1 q2)\r\n;;\r\n \r\nlet rec tri_fusion2 p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion2 (tri_fusion2 a) (tri_fusion2 b)\r\n;;\r\n \r\n \r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n \r\nlet rec prend_pet len l = match l with\r\n |[]->[],Int64.zero\r\n |p::q when len = 0 -> [] , Int64.zero\r\n |p::q -> let m,l,k = p in let a,b = (prend_pet (len-1) q) in p::a,(Int64.add (Int64.of_int l) b)\r\n \r\n \r\n;;\r\n \r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((a,b,j))::(!liste)\r\n done;\r\n let banned, total = prend_pet (nsegs*2) (tri_fusion2 !liste)in\r\n print_endline (Int64.to_string (total)) ;\r\n let casentbon = tri_fusion (banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}], "negative_code": [{"source_code": "let rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet rec fusion2 p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt y x -> x::(fusion2 q1 p2)\r\n | _,x::q2 -> x::(fusion2 p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion2 p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion2 (tri_fusion2 a) (tri_fusion2 b)\r\n;;\r\n\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\nlet rec prend_pet len l = match l with\r\n |[]->[],Int64.zero\r\n |p::q when len = 0 -> [] , Int64.zero\r\n |p::q -> let m,l,k = p in let a,b = (prend_pet (len-1) q) in p::a,(Int64.add (Int64.of_int l) b)\r\n \r\n \r\n;;\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((a,b,j))::(!liste)\r\n done;\r\n let banned, total = prend_pet (nsegs*2) (tri_fusion2 !liste)in\r\n print_endline (string_of_int (Int64.to_int total)) ;\r\n let casentbon = tri_fusion (banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}, {"source_code": "(*absisse,poids,id*) \r\n\r\nlet rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet rec fusion2 p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt y x -> x::(fusion2 q1 p2)\r\n | _,x::q2 -> x::(fusion2 p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion2 p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion2 (tri_fusion2 a) (tri_fusion2 b)\r\n;;\r\n\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\nlet rec prend_pet len l = match l with\r\n |[]->[],0\r\n |p::q when len = 0 -> [] , 0\r\n |p::q -> let m,l,k = p in let a,b = (prend_pet (len-1) q) in p::a,l+b\r\n \r\n \r\n;;\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((a,b,j))::(!liste)\r\n done;\r\n let banned, total = prend_pet (nsegs*2) (tri_fusion2 !liste)in\r\n print_endline (string_of_int total) ;\r\n let casentbon = tri_fusion (banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}, {"source_code": "(*absisse,poids,id*) \r\n\r\nlet rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet rec fusion2 p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt y x -> x::(fusion2 q1 p2)\r\n | _,x::q2 -> x::(fusion2 p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion2 p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion2 (tri_fusion2 a) (tri_fusion2 b)\r\n;;\r\n\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\nlet rec prend_pet len l = match l with\r\n |[]->[],0\r\n |p::q when len = 0 -> [] , 0\r\n |p::q -> let a,b = (prend_pet (len-1) q) in p::a,1+b\r\n \r\n \r\n;;\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((a,b,j))::(!liste)\r\n done;\r\n let banned, total = prend_pet (nsegs*2) (tri_fusion2 !liste)in\r\n print_endline (string_of_int total) ;\r\n let casentbon = tri_fusion (banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}, {"source_code": "(*absisse,poids,id*) \r\n\r\nlet rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet min l banned = \r\n let rec aux m l banned = match l with\r\n |[]->m\r\n |p::q -> aux (if gt m p && not(appartient p banned) then p else m) q banned\r\n in aux (999999,99999999,9999999) l banned \r\n;;\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((b,a,j))::(!liste)\r\n done;\r\n let banned= ref [] in\r\n for j = 0 to nsegs *2 -1 do \r\n let temp = min (!liste) (!banned) in\r\n banned := (temp)::(!banned) ;\r\n done;\r\n let total = somme (!banned) in\r\n print_endline (string_of_int total) ;\r\n let casentbon = tri_fusion (!banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}, {"source_code": "(*absisse,poids,id*) \r\n\r\nlet rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet min l banned = \r\n let rec aux m l banned = match l with\r\n |[]->m\r\n |p::q -> aux (if gt m p && not(appartient p banned) then p else m) q banned\r\n in aux (999999,99999999,9999999) l banned \r\n;;\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((b,a,j))::(!liste)\r\n done;\r\n let banned= ref [] in\r\n for j = 0 to nsegs *2 -1 do \r\n let temp = min (!liste) (!banned) in\r\n banned := (temp)::(!banned) ;\r\n done;\r\n let total = somme (!banned) in\r\n print_endline (string_of_int total) ;\r\n let casentbon = tri_fusion (!banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}, {"source_code": "(*absisse,poids,id*) \r\n\r\nlet rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet min l banned = \r\n let rec aux m l banned = match l with\r\n |[]->m\r\n |p::q -> aux (if gt m p && not(appartient p banned) then p else m) q banned\r\n in aux (999999,99999999,9999999) l banned \r\n;;\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((b,a,j))::(!liste)\r\n done;\r\n let banned= ref [] in\r\n for j = 0 to nsegs *2 -1 do \r\n let temp = min (!liste) (!banned) in\r\n banned := (temp)::(!banned) ;\r\n done;\r\n let total = somme (!banned) in\r\n print_endline (string_of_int total) ;\r\n let casentbon = tri_fusion (!banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}, {"source_code": "(*poids,absisse*) \r\n\r\nlet rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n\r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet min l banned = \r\n let rec aux m l banned = match l with\r\n |[]->m\r\n |p::q -> aux (if gt m p && not(appartient p banned) then p else m) q banned\r\n in aux (999999,99999999,9999999) l banned \r\n;;\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((b,a,j))::(!liste)\r\n done;\r\n let banned= ref [] in\r\n for j = 0 to nsegs *2 -1 do \r\n let temp = min (!liste) (!banned) in\r\n let mm,ll,kk = temp in\r\n banned := (temp)::(!banned) ;\r\n done;\r\n let total = somme (!banned) in\r\n print_endline (string_of_int total) ;\r\n let casentbon = tri_fusion (!banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}, {"source_code": "(*poids,absisse*) \r\n\r\nlet rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n\r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet min l banned = \r\n let rec aux m l banned = match l with\r\n |[]->m\r\n |p::q -> aux (if gt m p && not(appartient p banned) then p else m) q banned\r\n in aux (999999,99999999,9999999) l banned \r\n;;\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((b,a,i))::(!liste)\r\n done;\r\n let banned= ref [] in\r\n for j = 0 to nsegs *2 -1 do \r\n let temp = min (!liste) (!banned) in\r\n let mm,ll,kk = temp in\r\n banned := (temp)::(!banned) ;\r\n done;\r\n let total = somme (!banned) in\r\n print_endline (string_of_int total) ;\r\n let casentbon = tri_fusion (!banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}, {"source_code": "(*poids,absisse*) \r\n\r\nlet rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n\r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet min l banned = \r\n let rec aux m l banned = match l with\r\n |[]->m\r\n |p::q -> aux (if gt m p && not(appartient p banned) then p else m) q banned\r\n in aux (999999,99999999,9999999) l banned \r\n;;\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((b,a,i))::(!liste)\r\n done;\r\n let banned= ref [] in\r\n for j = 1 to nsegs *2 do \r\n let temp = min (!liste) (!banned) in\r\n let mm,ll,kk = temp in\r\n prerr_endline (string_of_int(mm)) ;\r\n prerr_endline (string_of_int(ll)) ;\r\n prerr_endline (string_of_int(kk)) ;\r\n banned := (temp)::(!banned) ;\r\n done;\r\n let total = somme (!banned) in\r\n print_endline (string_of_int total) ;\r\n let casentbon = tri_fusion (!banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}, {"source_code": "(*poids,absisse*) \r\n\r\nlet rec somme l = match l with \r\n |[]-> 0\r\n |p::q -> let a,b,c = p in b + somme q\r\n;; \r\n\r\nlet gt a b = let q,s,d = a in let w,x,c = b in s>x ;;\r\n\r\nlet gt2 a b = let q,s,d = a in let w,x,c = b in q>w ;;\r\n\r\nlet rec fission q=match q with\r\n | [] | [_] -> q, []\r\n | x::y::p -> let a,b=fission p in x::a, y::b\r\n;;\r\n\r\nlet rec fusion p1 p2=match p1, p2 with\r\n | [],_ -> p2\r\n | _, [] -> p1\r\n | x::q1, y::_ when gt2 y x -> x::(fusion q1 p2)\r\n | _,x::q2 -> x::(fusion p1 q2)\r\n;;\r\n\r\nlet rec tri_fusion p=match p with\r\n | [] | [_] -> p\r\n | _ -> let a,b=fission p in fusion (tri_fusion a) (tri_fusion b)\r\n;;\r\n\r\nlet rec appartient x liste = match liste with\r\n |[]->false\r\n |p::q -> if p = x then true else appartient x q\r\n;; \r\n\r\nlet min l banned = \r\n let rec aux m l banned = match l with\r\n |[]->m\r\n |p::q -> aux (if gt m p && not(appartient p banned) then p else m) q banned\r\n in aux (999999,99999999,9999999) l banned \r\n;;\r\n\r\nlet rec finish l1 l2 nsegs = match l1,l2 with \r\n |_ when nsegs <= 0 -> ()\r\n | p::q, r::s -> let a,b,c = p in let d,e,f = r in\r\n print_endline (string_of_int(c)^\" \"^string_of_int(f)) ; finish q s (nsegs-1)\r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in \r\nlet fjdskq = input_line stdin in\r\nfor i = 0 to n-1 do\r\n let nsegs, npairs = Scanf.sscanf(input_line stdin)\" %d %d\"(fun nsegs npairs->nsegs, npairs) in\r\n let liste = ref [] in\r\n for j = 1 to npairs do\r\n let a,b = Scanf.sscanf(input_line stdin)\" %d %d\"(fun a b -> a,b) in\r\n liste := ((b,a,i))::(!liste)\r\n done;\r\n let banned= ref [] in\r\n for j = 0 to nsegs *2 -1 do \r\n let temp = min (!liste) (!banned) in\r\n let mm,ll,kk = temp in\r\n prerr_endline (string_of_int(mm)) ;\r\n prerr_endline (string_of_int(ll)) ;\r\n prerr_endline (string_of_int(kk)) ;\r\n banned := (temp)::(!banned) ;\r\n done;\r\n let total = somme (!banned) in\r\n print_endline (string_of_int total) ;\r\n let casentbon = tri_fusion (!banned) in\r\n let bbb = List.rev casentbon in\r\n finish casentbon bbb nsegs;\r\n if (i<> n-1) then (let fjdskljfq = input_line stdin in () );\r\ndone;;"}], "src_uid": "bfb2831c319400d4a62890e6ea20d045"} {"nl": {"description": "Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3\u2009\u00d7\u20095 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3\u2009\u00d7\u20095 table is 15\u2009+\u20098\u2009+\u20093\u2009=\u200926.", "input_spec": "The first line of the input contains a single integer x (1\u2009\u2264\u2009x\u2009\u2264\u20091018)\u00a0\u2014 the number of squares inside the tables Spongebob is interested in.", "output_spec": "First print a single integer k\u00a0\u2014 the number of tables with exactly x distinct squares inside. Then print k pairs of integers describing the tables. Print the pairs in the order of increasing n, and in case of equality\u00a0\u2014 in the order of increasing m.", "sample_inputs": ["26", "2", "8"], "sample_outputs": ["6\n1 26\n2 9\n3 5\n5 3\n9 2\n26 1", "2\n1 2\n2 1", "4\n1 8\n2 3\n3 2\n8 1"], "notes": "NoteIn a 1\u2009\u00d7\u20092 table there are 2 1\u2009\u00d7\u20091 squares. So, 2 distinct squares in total. In a 2\u2009\u00d7\u20093 table there are 6 1\u2009\u00d7\u20091 squares and 2 2\u2009\u00d7\u20092 squares. That is equal to 8 squares in total. "}, "positive_code": [{"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\n\nopen Printf\nopen Scanf\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet () = \n let x = read_long () in\n\n let pyramid n =\n ((n--1L) ** n ** (n++n--1L)) // 6L\n in\n\n let rec find_max_n i = if pyramid i >= x then i -- 1L else find_max_n (i++1L) in\n\n let maxn = find_max_n 1L in\n\n let test n = \n let denom n = (n ** (n++1L)) // 2L in\n let numerator n x =\n x -- (pyramid n) ++ (n**n**(n -- 1L))//2L\n in\n let num = numerator n x in\n let den = denom n in\n let m = num // den in\n if m < n || m ** den <> num then None else Some m\n in\n\n let rec list_solutions n ac = if n>maxn then ac else\n match test n with\n\t| None -> list_solutions (n++1L) ac\n\t| Some m -> list_solutions (n++1L) ((n,m)::ac)\n in\n\n let l1 = list_solutions 1L [] in\n\n let (lastn,lastm) = List.hd l1 in\n\n let l2 = List.map (fun (n,m) -> (m,n)) l1 in\n\n let answer = if lastn <> lastm\n then (List.rev l1) @ l2\n else (List.rev (List.tl l1)) @ l2\n in\n\n printf \"%d\\n\" (List.length answer);\n\n List.iter (fun (n,m) -> printf \"%Ld %Ld\\n\" n m) answer\n"}], "negative_code": [{"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\n\nopen Printf\nopen Scanf\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet () = \n let x = read_long () in\n\n let pyramid n =\n ((n--1L) ** n ** (n++n--1L)) // 6L\n in\n\n let rec find_max_n i = if pyramid i >= x then i -- 1L else find_max_n (i++1L) in\n\n let maxn = find_max_n 1L in\n\n printf \"%Ld\\n\" maxn;\n\n let test n = \n let denom n = (n ** (n++1L)) // 2L in\n let numerator n x =\n x -- (pyramid n) ++ (n**n**(n -- 1L))//2L\n in\n let num = numerator n x in\n let den = denom n in\n let m = num // den in\n if m < n || m ** den <> num then None else Some m\n in\n\n let rec list_solutions n ac = if n>maxn then ac else\n match test n with\n\t| None -> list_solutions (n++1L) ac\n\t| Some m -> list_solutions (n++1L) ((n,m)::ac)\n in\n\n let l1 = list_solutions 1L [] in\n\n let (lastn,lastm) = List.hd l1 in\n\n let l2 = List.map (fun (n,m) -> (m,n)) l1 in\n\n let answer = if lastn <> lastm\n then (List.rev l1) @ l2\n else (List.rev (List.tl l1)) @ l2\n in\n\n printf \"%d\\n\" (List.length answer);\n\n List.iter (fun (n,m) -> printf \"%Ld %Ld\\n\" n m) answer\n"}], "src_uid": "5891432c43cfee35a212ad92d7da2a64"} {"nl": {"description": "Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters \"a\", \"e\", \"i\", \"o\", \"u\" are considered vowels.Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k\u2009=\u20091, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k\u2009=\u20092, they do not rhyme (ommit\u2009\u2260\u2009ermit).Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): Clerihew (aabb); Alternating (abab); Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20092500, 1\u2009\u2264\u2009k\u2009\u2264\u20095)\u00a0\u2014 the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.", "output_spec": "Print the rhyme scheme of the poem as \"aabb\", \"abab\", \"abba\", \"aaaa\"; or \"NO\" if the poem does not belong to any of the above mentioned schemes.", "sample_inputs": ["1 1\nday\nmay\nsun\nfun", "1 1\nday\nmay\ngray\nway", "2 1\na\na\na\na\na\na\ne\ne", "2 1\nday\nmay\nsun\nfun\ntest\nhill\nfest\nthrill"], "sample_outputs": ["aabb", "aaaa", "aabb", "NO"], "notes": "NoteIn the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is \"NO\"."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet n = read_int()\nlet k = read_int()\n\nlet is_vowel c = match c with 'a' | 'e' | 'i' | 'o' | 'u' -> true | _ -> false\n\nlet rec vowel_place s kk i =\n if i<0 || kk<=0 then None\n else if (is_vowel s.[i]) then \n if (kk=1) then Some i else vowel_place s (kk-1) (i-1)\n else vowel_place s kk (i-1)\n\nlet rec tail_equals s t ls lt i j = \n if i>=ls then true else s.[i] = t.[j] && (tail_equals s t ls lt (i+1) (j+1))\n\nlet smatch s t kk = \n let vp ss = vowel_place ss kk ((String.length ss)-1) in\n let ls = String.length s in\n let lt = String.length t in\n let a = vp s in\n let b = vp t in\n match (a,b) with \n | (None, _) | (_, None) -> false\n | (Some i, Some j) ->\n\t if (ls-i)<>(lt-j) then false else tail_equals s t ls lt i j\n\nlet schemes = ref 15\n\nlet () = \n for i=0 to n-1 do\n let l1 = read_string() in\n let l2 = read_string() in\n let l3 = read_string() in\n let l4 = read_string() in\n match (smatch l1 l2 k, smatch l1 l3 k, smatch l1 l4 k, smatch l2 l3 k, smatch l2 l4 k, smatch l3 l4 k) with\n\t| (true, true, true, true, true, true) -> () (* aaaa *)\n\t| (true, false, false, false, false, true) -> (* aabb *) schemes := !schemes land 4\n\t| (false, true, false, false, true, false) -> (* abab *) schemes := !schemes land 2\n\t| (false, false, true, true, false, false) -> (* abba *) schemes := !schemes land 1\n\t| _ -> schemes := 0\n done\n\n;;\nmatch !schemes with \n | 15 -> Printf.printf \"aaaa\\n\"\n | 4 -> Printf.printf \"aabb\\n\"\n | 2 -> Printf.printf \"abab\\n\"\n | 1 -> Printf.printf \"abba\\n\"\n | _ -> Printf.printf \"NO\\n\"\n"}], "negative_code": [], "src_uid": "a17bac596b1f060209534cbffdf0f40e"} {"nl": {"description": "Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!A restaurant called \"Dijkstra's Place\" has started thinking about optimizing the booking system. There are n booking requests received by now. Each request is characterized by two numbers: ci and pi \u2014 the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.We know that for each request, all ci people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.Unfortunately, there only are k tables in the restaurant. For each table, we know ri \u2014 the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of requests from visitors. Then n lines follow. Each line contains two integers: ci,\u2009pi (1\u2009\u2264\u2009ci,\u2009pi\u2009\u2264\u20091000) \u2014 the size of the group of visitors who will come by the i-th request and the total sum of money they will pay when they visit the restaurant, correspondingly. The next line contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u20091000) \u2014 the number of tables in the restaurant. The last line contains k space-separated integers: r1,\u2009r2,\u2009...,\u2009rk (1\u2009\u2264\u2009ri\u2009\u2264\u20091000) \u2014 the maximum number of people that can sit at each table.", "output_spec": "In the first line print two integers: m,\u2009s \u2014 the number of accepted requests and the total money you get from these requests, correspondingly. Then print m lines \u2014 each line must contain two space-separated integers: the number of the accepted request and the number of the table to seat people who come via this request. The requests and the tables are consecutively numbered starting from 1 in the order in which they are given in the input. If there are multiple optimal answers, print any of them.", "sample_inputs": ["3\n10 50\n2 100\n5 30\n3\n4 6 9"], "sample_outputs": ["2 130\n2 1\n3 2"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int();;\nlet r=ref n;;\nlet req=Array.make (n+1) (0,0,0);;\nfor i=1 to n do\n let a=read_int() and b=read_int() in\n req.(i)<-(a,b,i)\ndone;;\nlet k=read_int();;\nlet tab=Array.make (k+1) (0,0);;\nfor i=1 to k do\n tab.(i)<-(read_int(),i)\ndone;;\n\nlet rec list_of_tab vec i j=\nif i=j then [vec.(i)] else vec.(i)::(list_of_tab vec (i+1) j);;\n\nlet rec inserer v i=function\n|[]->[(v,i)]\n|(h,j)::t->if v<=h then (v,i)::(h,j)::t else (h,j)::(inserer v i t);;\n\nlet rec tri=function\n|[]->[]\n|(h,j)::t->inserer h j (tri t);;\n\nlet rec inserer2 c p i=function\n|[]->[(c,p,i)]\n|(c1,p1,j)::t->if (p>p1) then (c,p,i)::(c1,p1,j)::t else if (p=p1)&&(c<=c1) then (c,p,i)::(c1,p1,j)::t else (c1,p1,j)::(inserer2 c p i t);;\n\nlet rec tri2=function\n|[]->[]\n|(c,p,i)::t->inserer2 c p i (tri2 t);;\n\nlet lreq=tri2(list_of_tab req 1 n);;\nlet ltab=tri(list_of_tab tab 1 k);;\n\nlet final=ref [];;\n\nlet rec faire c p i=function\n|[]->r:= !r-1;(0,[])\n|(h,j)::t->if c<=h then (final:= (i,j)::( !final);(p,t)) else let (p1,t1)=faire c p i t in (p1,(h,j)::t1);;\n\nlet rec make l2=function\n|[]->0\n|(c,p,i)::t->let (a,b)=faire c p i l2 in a+make b t;;\n\nlet score=make ltab lreq;;\nprint_int !r;;\nprint_string \" \";;\nprint_int score;;\n\nlet rec print_list=function\n|[]->()\n|(i,j)::t->print_list t;print_newline();print_int i;print_string \" \";print_int j;;\n\nprint_list !final;;"}], "negative_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int();;\nlet r=ref n;;\nlet req=Array.make (n+1) (0,0,0);;\nfor i=1 to n do\n let a=read_int() and b=read_int() in\n req.(i)<-(a,b,i)\ndone;;\nlet k=read_int();;\nlet tab=Array.make (k+1) (0,0);;\nfor i=1 to k do\n tab.(i)<-(read_int(),i)\ndone;;\n\nlet rec list_of_tab vec i j=\nif i=j then [vec.(i)] else vec.(i)::(list_of_tab vec (i+1) j);;\n\nlet rec inserer v i=function\n|[]->[(v,i)]\n|(h,j)::t->if v<=h then (v,i)::(h,j)::t else (h,j)::(inserer v i t);;\n\nlet rec tri=function\n|[]->[]\n|(h,j)::t->inserer h j (tri t);;\n\nlet rec inserer2 c p i=function\n|[]->[(c,p,i)]\n|(c1,p1,j)::t->if (p>=p1)&&(c<=c1) then (c,p,i)::(c1,p1,j)::t else (c1,p1,j)::(inserer2 c p i t);;\n\nlet rec tri2=function\n|[]->[]\n|(c,p,i)::t->inserer2 c p i (tri2 t);;\n\nlet lreq=tri2(list_of_tab req 1 n);;\nlet ltab=tri(list_of_tab tab 1 k);;\n\nlet final=ref [];;\n\nlet rec faire c p i=function\n|[]->r:= !r-1;(0,[])\n|(h,j)::t->if c<=h then (final:= (i,j)::( !final);(p,t)) else let (p1,t1)=faire c p i t in (p1,(h,j)::t1);;\n\nlet rec make l2=function\n|[]->0\n|(c,p,i)::t->let (a,b)=faire c p i l2 in a+make b t;;\n\nlet score=make ltab lreq;;\nprint_int !r;;\nprint_string \" \";;\nprint_int score;;\n\nlet rec print_list=function\n|[]->()\n|(i,j)::t->print_list t;print_newline();print_int i;print_string \" \";print_int j;;\n\nprint_list !final;;"}], "src_uid": "ac4e4aca1146d7ad706c4ea12c90caf6"} {"nl": {"description": "Your working week consists of $$$n$$$ days numbered from $$$1$$$ to $$$n$$$, after day $$$n$$$ goes day $$$1$$$ again. And $$$3$$$ of them are days off. One of the days off is the last day, day $$$n$$$. You have to decide when the other two are.Choosing days off, you pursue two goals: No two days should go one after the other. Note that you can't make day $$$1$$$ a day off because it follows day $$$n$$$. Working segments framed by days off should be as dissimilar as possible in duration. More specifically, if the segments are of size $$$l_1$$$, $$$l_2$$$, and $$$l_3$$$ days long, you want to maximize $$$\\min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|)$$$. Output the maximum value of $$$\\min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|)$$$ that can be obtained.", "input_spec": "The first line of the input contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. The description of test cases follows. The only line of each test case contains the integer $$$n$$$ ($$$6 \\le n \\le 10^9$$$).", "output_spec": "For each test case, output one integer \u2014 the maximum possible obtained value.", "sample_inputs": ["3\n\n6\n\n10\n\n1033"], "sample_outputs": ["0\n1\n342"], "notes": "NoteIn the image below you can see the example solutions for the first two test cases. Chosen days off are shown in purple. Working segments are underlined in green.In test case $$$1$$$, the only options for days off are days $$$2$$$, $$$3$$$, and $$$4$$$ (because $$$1$$$ and $$$5$$$ are next to day $$$n$$$). So the only way to place them without selecting neighboring days is to choose days $$$2$$$ and $$$4$$$. Thus, $$$l_1 = l_2 = l_3 = 1$$$, and the answer $$$\\min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|) = 0$$$. For test case $$$2$$$, one possible way to choose days off is shown. The working segments have the lengths of $$$2$$$, $$$1$$$, and $$$4$$$ days. So the minimum difference is $$$1 = \\min(1, 3, 2) = \\min(|2 - 1|, |1 - 4|, |4 - 2|)$$$. It can be shown that there is no way to make it larger. "}, "positive_code": [{"source_code": "open Printf\r\nopen Scanf\r\n\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\n\r\n\r\nlet () = \r\n let t = read_int () in\r\n for ct = 1 to t do\r\n let x = read_int () in\r\n let y = if x > 6 then (x - 3) / 3 - 1 else 0 in\r\n printf \"%d\\n\" y\r\n done;\r\n"}], "negative_code": [{"source_code": "open Printf\r\nopen Scanf\r\n\r\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\r\n\r\n\r\nlet () = \r\n let t = read_int () in\r\n for ct = 1 to t do\r\n let x = read_int () in\r\n let y = if x > 6 then (x - 4) / 3 - 1 else 0 in\r\n printf \"%d\\n\" y\r\n done;\r\n"}], "src_uid": "0690e2df87f60e5be34505d9e2817032"} {"nl": {"description": "Codeforces separates its users into $$$4$$$ divisions by their rating: For Division 1: $$$1900 \\leq \\mathrm{rating}$$$ For Division 2: $$$1600 \\leq \\mathrm{rating} \\leq 1899$$$ For Division 3: $$$1400 \\leq \\mathrm{rating} \\leq 1599$$$ For Division 4: $$$\\mathrm{rating} \\leq 1399$$$ Given a $$$\\mathrm{rating}$$$, print in which division the $$$\\mathrm{rating}$$$ belongs.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of testcases. The description of each test consists of one line containing one integer $$$\\mathrm{rating}$$$ ($$$-5000 \\leq \\mathrm{rating} \\leq 5000$$$).", "output_spec": "For each test case, output a single line containing the correct division in the format \"Division X\", where $$$X$$$ is an integer between $$$1$$$ and $$$4$$$ representing the division for the corresponding rating.", "sample_inputs": ["7\n-789\n1299\n1300\n1399\n1400\n1679\n2300"], "sample_outputs": ["Division 4\nDivision 4\nDivision 4\nDivision 4\nDivision 3\nDivision 2\nDivision 1"], "notes": "NoteFor test cases $$$1-4$$$, the corresponding ratings are $$$-789$$$, $$$1299$$$, $$$1300$$$, $$$1399$$$, so all of them are in division $$$4$$$.For the fifth test case, the corresponding rating is $$$1400$$$, so it is in division $$$3$$$.For the sixth test case, the corresponding rating is $$$1679$$$, so it is in division $$$2$$$.For the seventh test case, the corresponding rating is $$$2300$$$, so it is in division $$$1$$$."}, "positive_code": [{"source_code": "let getInt () = Scanf.scanf \" %d\" (fun i -> i);;\r\nlet f((x: int)) = \r\nif x >= 1900 then 1\r\nelse if x >= 1600 then 2\r\nelse if x >= 1400 then 3\r\nelse 4;;\r\n\r\nlet main() = \r\n let t = getInt() in\r\n for i = 1 to t do \r\n let x = getInt() in print_endline(\"Division \" ^ string_of_int(f(x)))\r\n done;;\r\n\r\nmain();;\r\n\r\n\r\n"}, {"source_code": "let id x = x\n\nlet div_of_rating rating =\n let ns =\n match rating with\n | r when r <= 1399 -> \"4\"\n | r when r <= 1599 -> \"3\"\n | r when r <= 1899 -> \"2\"\n | _ -> \"1\"\n in\n \"Division \" ^ ns\n\nlet solve () =\n let t = Scanf.scanf \"%d\\n\" id in\n let () =\n for i = 1 to t do\n let r = Scanf.scanf \"%d\\n\" (fun x -> x) in\n print_endline (div_of_rating r)\n done\n in\n ()\n\nlet main = solve ()\n"}], "negative_code": [], "src_uid": "020c7b64688736ecc5e97d17df2c2605"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots , a_n$$$ and two integers $$$m$$$ and $$$k$$$.You can choose some subarray $$$a_l, a_{l+1}, \\dots, a_{r-1}, a_r$$$. The cost of subarray $$$a_l, a_{l+1}, \\dots, a_{r-1}, a_r$$$ is equal to $$$\\sum\\limits_{i=l}^{r} a_i - k \\lceil \\frac{r - l + 1}{m} \\rceil$$$, where $$$\\lceil x \\rceil$$$ is the least integer greater than or equal to $$$x$$$. The cost of empty subarray is equal to zero.For example, if $$$m = 3$$$, $$$k = 10$$$ and $$$a = [2, -4, 15, -3, 4, 8, 3]$$$, then the cost of some subarrays are: $$$a_3 \\dots a_3: 15 - k \\lceil \\frac{1}{3} \\rceil = 15 - 10 = 5$$$; $$$a_3 \\dots a_4: (15 - 3) - k \\lceil \\frac{2}{3} \\rceil = 12 - 10 = 2$$$; $$$a_3 \\dots a_5: (15 - 3 + 4) - k \\lceil \\frac{3}{3} \\rceil = 16 - 10 = 6$$$; $$$a_3 \\dots a_6: (15 - 3 + 4 + 8) - k \\lceil \\frac{4}{3} \\rceil = 24 - 20 = 4$$$; $$$a_3 \\dots a_7: (15 - 3 + 4 + 8 + 3) - k \\lceil \\frac{5}{3} \\rceil = 27 - 20 = 7$$$. Your task is to find the maximum cost of some subarray (possibly empty) of array $$$a$$$.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \\le n \\le 3 \\cdot 10^5, 1 \\le m \\le 10, 1 \\le k \\le 10^9$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$-10^9 \\le a_i \\le 10^9$$$).", "output_spec": "Print the maximum cost of some subarray of array $$$a$$$.", "sample_inputs": ["7 3 10\n2 -4 15 -3 4 8 3", "5 2 1000\n-13 -4 -9 -20 -11"], "sample_outputs": ["7", "0"], "notes": null}, "positive_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\nlet readInt64 () = Scanf.scanf \" %Ld\" (fun x -> x)\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\nlet (%%) = Int64.rem\n\nlet solve n m k a =\n let open Int64 in\n let byMod = Array.make m (of_int n ** of_float 1e11) in\n byMod.(0) <- 0L;\n let sum = ref 0L in\n let ans = ref 0L in\n for i=0 to n-1 do\n sum := !sum ++ of_int m ** a.(i) -- of_int k;\n let r = (i+1) mod m in\n for l=0 to m-1 do\n let d = (r-l+m) mod m in\n let adjust = if d = 0 then 0L else of_int k ** of_int (m - d) in\n ans := max !ans (!sum -- byMod.(l) -- adjust);\n done;\n byMod.(r) <- min byMod.(r) !sum;\n done;\n !ans // of_int m\n\n(*\nlet solveSlow n m k a =\n let open Int64 in\n let ans = ref 0L in\n for l=0 to n-1 do\n for r=l+1 to n do\n let rec go sum i = if i >= r then sum else go (sum ++ a.(i)) (i + 1) in\n let sum = go 0L l in\n let ok = (m > 0) in\n if not ok then Printf.eprintf \"%d %d %d\\n\" n m k;\n assert ok;\n let cur = sum -- of_int k ** (of_int (r - l + m-1) // of_int m) in\n ans := max !ans cur\n done\n done;\n !ans\n*)\n\nlet cfMain () =\n let n = readInt () in\n let m = readInt () in\n let k = readInt () in\n let a = Array.init n (fun _ -> readInt64 ()) in\n Printf.printf \"%Ld\\n\" (solve n m k a)\n\n(* let () =\n let x = solve 7 3 10 (Array.map Int64.of_int [|7;3;10;2;-4;15;-3;4;8;3|]) in Printf.printf \"%Ld\\n\" x *)\n\n(*\nlet tenToNine = int_of_float 1e9\nlet test =\n QCheck.Test.make ~count:1000 ~name:\"fast = slow\"\n QCheck.(triple (1 -- 10) (1 -- tenToNine) (array_of_size (gen (1 -- 100)) ((-tenToNine) -- tenToNine)))\n (fun (m, k, a) ->\n let a = Array.map Int64.of_int a in\n let n = Array.length a in\n QCheck.assume (n > 0);\n QCheck.assume (m > 0);\n QCheck.assume (k > 0);\n solve n m k a = solveSlow n m k a)\n\nlet testMain () = QCheck.Test.check_exn test\n*)\n\n(* let () =\n let (n, m, k, a) = (1, 4, 333333335, [|333333335L|]) in\n let x = solve n m k a in\n let y = solveSlow n m k a in\n Printf.printf \"%Ld %Ld\\n\" x y *)\n\nlet () = cfMain ()\n"}], "negative_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\nlet readInt64 () = Scanf.scanf \" %Ld\" (fun x -> x)\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\nlet (%%) = Int64.rem\n\nlet solve n m k a =\n let open Int64 in\n let byMod = Array.make m 0L in\n let sum = ref 0L in\n let ans = ref 0L in\n for i=0 to n-1 do\n sum := !sum ++ of_int m ** a.(i) -- of_int k;\n let r = (i+1) mod m in\n for l=0 to m-1 do\n let d = (r-l+m) mod m in\n let adjust = if d = 0 then 0 else k*(m - d) in\n ans := max !ans (!sum -- byMod.(l) -- of_int adjust);\n done;\n byMod.(r) <- min byMod.(r) !sum;\n done;\n !ans // of_int m\n\nlet main () =\n let n = readInt () in\n let m = readInt () in\n let k = readInt () in\n let a = Array.init n (fun _ -> readInt64 ()) in\n Printf.printf \"%Ld\\n\" (solve n m k a)\n\nlet () = main ()\n\n(* let () =\n let x = solve 7 3 10 (Array.map Int64.of_int [|7;3;10;2;-4;15;-3;4;8;3|]) in () *)\n"}, {"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\nlet readInt64 () = Scanf.scanf \" %Ld\" (fun x -> x)\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\nlet (%%) = Int64.rem\n\nlet solve n m k a =\n let open Int64 in\n let byMod = Array.make m (of_int n ** of_float 1e9) in\n let sum = ref 0L in\n let ans = ref 0L in\n for i=0 to n-1 do\n sum := !sum ++ of_int m ** a.(i) -- of_int k;\n let r = (i+1) mod m in\n for l=0 to m-1 do\n let d = (r-l+m) mod m in\n let adjust = if d = 0 then 0 else k*(m - d) in\n ans := max !ans (!sum -- byMod.(l) -- of_int adjust);\n done;\n byMod.(r) <- min byMod.(r) !sum;\n done;\n !ans // of_int m\n\n(*\nlet solveSlow n m k a =\n let open Int64 in\n let ans = ref 0L in\n for l=0 to n-1 do\n for r=l+1 to n do\n let rec go sum i = if i >= r then sum else go (sum ++ a.(i)) (i + 1) in\n let sum = go 0L l in\n let cur = sum -- of_int k ** (of_int (r - l + m-1) // of_int m) in\n ans := max !ans cur\n done\n done;\n !ans\n*)\n\nlet cfMain () =\n let n = readInt () in\n let m = readInt () in\n let k = readInt () in\n let a = Array.init n (fun _ -> readInt64 ()) in\n Printf.printf \"%Ld\\n\" (solve n m k a)\n\n(* let () =\n let x = solve 7 3 10 (Array.map Int64.of_int [|7;3;10;2;-4;15;-3;4;8;3|]) in Printf.printf \"%Ld\\n\" x *)\n\n(*\nlet tenToNine = int_of_float 1e9\nlet test =\n QCheck.Test.make ~count:1000 ~name:\"fast = slow\"\n QCheck.(triple (1 -- 10) (1 -- tenToNine) (array_of_size (gen (1 -- 100)) ((-tenToNine) -- tenToNine)))\n (fun (m, k, a) ->\n let a = Array.map Int64.of_int a in\n let n = Array.length a in\n solve n m k a = solveSlow n m k a)\n\nlet testMain () = QCheck.Test.check_exn test\n*)\n\n(* let () = let x = solve 1 2 2 [|2L|] in Printf.printf \"%Ld\\n\" x *)\n\nlet () = cfMain ()\n"}], "src_uid": "529aed80a647d181f08d2c26bb14d65d"} {"nl": {"description": "A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each row. Laurenty lives in the very last house of the second row. The only shop in town is placed in the first house of the first row.The first and second rows are separated with the main avenue of the city. The adjacent houses of one row are separated by streets.Each crosswalk of a street or an avenue has some traffic lights. In order to cross the street, you need to press a button on the traffic light, wait for a while for the green light and cross the street. Different traffic lights can have different waiting time.The traffic light on the crosswalk from the j-th house of the i-th row to the (j\u2009+\u20091)-th house of the same row has waiting time equal to aij (1\u2009\u2264\u2009i\u2009\u2264\u20092,\u20091\u2009\u2264\u2009j\u2009\u2264\u2009n\u2009-\u20091). For the traffic light on the crossing from the j-th house of one row to the j-th house of another row the waiting time equals bj (1\u2009\u2264\u2009j\u2009\u2264\u2009n). The city doesn't have any other crossings.The boy wants to get to the store, buy the products and go back. The main avenue of the city is wide enough, so the boy wants to cross it exactly once on the way to the store and exactly once on the way back home. The boy would get bored if he had to walk the same way again, so he wants the way home to be different from the way to the store in at least one crossing. Figure to the first sample. Help Laurenty determine the minimum total time he needs to wait at the crossroads.", "input_spec": "The first line of the input contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of houses in each row. Each of the next two lines contains n\u2009-\u20091 space-separated integer \u2014 values aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009100). The last line contains n space-separated integers bj (1\u2009\u2264\u2009bj\u2009\u2264\u2009100).", "output_spec": "Print a single integer \u2014 the least total time Laurenty needs to wait at the crossroads, given that he crosses the avenue only once both on his way to the store and on his way back home.", "sample_inputs": ["4\n1 2 3\n3 2 1\n3 2 2 3", "3\n1 2\n3 3\n2 1 3", "2\n1\n1\n1 1"], "sample_outputs": ["12", "11", "4"], "notes": "NoteThe first sample is shown on the figure above. In the second sample, Laurenty's path can look as follows: Laurenty crosses the avenue, the waiting time is 3; Laurenty uses the second crossing in the first row, the waiting time is 2; Laurenty uses the first crossing in the first row, the waiting time is 1; Laurenty uses the first crossing in the first row, the waiting time is 1; Laurenty crosses the avenue, the waiting time is 1; Laurenty uses the second crossing in the second row, the waiting time is 3. In total we get that the answer equals 11.In the last sample Laurenty visits all the crossings, so the answer is 4."}, "positive_code": [{"source_code": "let n= read_int () and ans = ref max_int;;\nlet a= Array.append\n\t[|( Array.of_list (List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ()))))|]\n [|( Array.of_list (List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ()))))|];;\nlet b= Array.of_list (List.map(int_of_string) (Str.split (Str.regexp \" \") (read_line ())));;\nlet f1= Array.create n 0 and f2= Array.create n 0;;\nfor i= 1 to n - 1 do Array.set f1 i (f1.(i - 1) + a.(1).(i - 1)) done;;\nfor i= n - 2 downto 0 do Array.set f2 i (f2.(i + 1) + a.(0).(i)) done;;\nfor i= 0 to n - 1 do for j= 0 to n - 1 do if i <> j then\n\tans:= min !ans (f1.(i) + b.(i) + f2.(i) + f2.(j) + f1.(j) + b.(j))\ndone done;;\nprint_int !ans;;\n"}, {"source_code": "let a = ref [] in\nlet b = ref [] in\nlet c = ref [] in\nlet n = read_int () in\n\t(let l = Scanf.Scanning.from_string (read_line ()) in\n\tfor j = 1 to n-1 do\n\t\ttry let k = Scanf.bscanf l \"%d \" (fun x -> x) in a := k::(!a) with _ -> \n\t\tlet k = Scanf.bscanf l \"%d\" (fun x -> x) in a := k::(!a)\n\tdone);\n\t(let l = Scanf.Scanning.from_string (read_line ()) in\n\tfor j = 1 to n-1 do\n\t\ttry let k = Scanf.bscanf l \"%d \" (fun x -> x) in b := k::(!b) with _ ->\n\t\tlet k = Scanf.bscanf l \"%d\" (fun x -> x) in b := k::(!b)\n\tdone);\n\t(let l = Scanf.Scanning.from_string (read_line ()) in\n\tfor j = 1 to n do\n\t\ttry let k = Scanf.bscanf l \"%d \" (fun x -> x) in c := k::(!c) with _ ->\n\t\tlet k = Scanf.bscanf l \"%d\" (fun x -> x) in c := k::(!c)\n\tdone);\n\nlet al = List.rev (!a) in\nlet bl = List.rev (!b) in\nlet cl = List.rev (!c) in\n\nlet rec trav i where st =\n\tmatch where with\n\t\ttrue ->\n\t\t\tlet k2 = trav i false (2::st) in\n\t\t\tif i = n-1 then ((fst k2) + List.nth cl i, snd k2)\n\t\t\telse\n\t\t\t\tlet k1 = trav (i+1) true (0::st) in\n\t\t\t\tlet i2 = List.nth cl i in\t\n\t\t\t\tlet t = min (fst k1 + List.nth al i) (fst k2 + i2) in\n\t\t\t\tif t = (i2 + fst k2) then (t, snd k2) \n\t\t\t\telse (t, snd k1)\n\t\t| false -> \n\t\t\tif i = n-1 then (0, st)\n\t\t\telse let k2 = trav (i+1) false (1::st) in\n\t\t\t(fst k2 + (List.nth bl i), snd k2)\n\tin\t\t\t\nlet (stv, stl) = trav 0 true [] in\nlet st = List.rev stl in\n\nlet rec trav2 i where ed w =\n\tmatch where with\n\t\tfalse ->\n\t\t\tlet k2 = trav2 i true (2::ed) 2 in\n\t\t\tif i = 0 then ((fst k2) + List.nth cl i, snd k2)\n\t\t\telse\n\t\t\t\tlet k1 = trav2 (i-1) false (1::ed) 1 in\n\t\t\t\tlet i2 = List.nth cl i in\t\n\t\t\t\tlet t = min (fst k1 + List.nth bl (i-1)) (fst k2 + i2) in\n\t\t\t\tif t = (i2 + fst k2) then (t, snd k2) \n\t\t\t\telse (t, snd k1)\n\t\t| true -> \n\t\t\tif i = 0 then\n\t\t\t\t(let bb = ed <> st in\n\t\t\t\tif bb then (0, ed) else (99999999, ed))\n\t\t\telse let k2 = trav2 (i-1) true (0::ed) 0 in\n\t\t\t(fst k2 + (List.nth al (i-1)), snd k2)\n\tin\nlet (edv, edl) = trav2 (n-1) false [] 2 in\n\nprint_int (stv + edv);;\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let read _ = Scanf.scanf \"%d%_c\" (fun x -> x) in\n\n let a1 = Array.init (n - 1) read\n and a2 = Array.init (n - 1) read\n and b = Array.init n read in\n\n (* calculate cumulative sum of a1\n * and reverse cumulative sum of a2 *)\n let s1 = Array.of_list (List.rev (Array.fold_left (fun (hd::_ as acc) x -> (x + hd) :: acc) [0] a1))\n and s2 = Array.of_list (Array.fold_right (fun x (hd::_ as acc) -> (x + hd) :: acc) a2 [0]) in\n\n let best = ref (-1) in\n\n (* first crossing *)\n for i = 0 to n - 2 do\n (* second crossing *)\n for j = i + 1 to n - 1 do\n let sum = s1.(i) + s2.(j) + s1.(j) + s2.(i) + b.(i) + b.(j) in\n if !best = (-1) || sum < !best\n then best := sum\n done\n done;\n\n Printf.printf \"%d\\n\" !best)\n"}], "negative_code": [], "src_uid": "e3e0625914fdc08950601248b1278f7d"} {"nl": {"description": "Smart Beaver became interested in drawing. He draws suns. However, at some point, Smart Beaver realized that simply drawing suns is boring. So he decided to design a program that will process his drawings. You are given a picture drawn by the beaver. It will have two colors: one for the background and one for the suns in the image. Your task will be to count the number of suns in the image and for each of them to count the number of rays.Sun is arbitrarily rotated ellipse with rays. Ray is a segment which connects point on boundary of the ellipse with some point outside ellipse. An image where all suns are circles. An image where all suns are ellipses, their axes are parallel to the coordinate axes. An image where all suns are rotated ellipses. It is guaranteed that: No two suns have common points. The rays\u2019 width is 3 pixels. The lengths of the ellipsis suns\u2019 axes will lie between 40 and 200 pixels. No two rays intersect. The lengths of all rays will lie between 10 and 30 pixels. ", "input_spec": "The first line contains two integers h and w \u2014 the height and width of the image (1\u2009\u2264\u2009h,\u2009w\u2009\u2264\u20091600). Next h lines will contain w space-separated integers each. They describe Smart Beaver\u2019s picture. Each number equals either a 0 (the image background), or a 1 (the sun color). The input limits for scoring 30 points are (subproblem F1): All suns on the image are circles. The input limits for scoring 70 points are (subproblems F1+F2): All suns on the image are ellipses with axes parallel to the coordinate axes. The input limits for scoring 100 points are (subproblems F1+F2+F3): All suns on the image are ellipses, they can be arbitrarily rotated. ", "output_spec": "The first line must contain a single number k \u2014 the number of suns on the beaver\u2019s image. The second line must contain exactly k space-separated integers, corresponding to the number of rays on each sun. The numbers of the second line must be sorted in the increasing order.", "sample_inputs": [], "sample_outputs": [], "notes": "NoteFor each complexity level you are suggested a sample in the initial data. You can download the samples at http://www.abbyy.ru/sun.zip."}, "positive_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w 0 in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n let idx = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif used.(i).(j) = 0 then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif used.(y).(x) = 0 then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- !idx;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t incr idx;\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- !idx;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 4 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h &&\n\t\t\t (x' - x) * (x' - x) + (y' - y) * (y' - y) <= d * d\n\t\t\t then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if used.(y').(x') = !idx\n\t\t\t then incr s;\n\t\t\t if used.(y').(x') = !idx && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && float_of_int !s *. 6.5 < float_of_int !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w 0 in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n let idx = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif used.(i).(j) = 0 then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif used.(y).(x) = 0 then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- !idx;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t incr idx;\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- !idx;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 4 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if used.(y').(x') = !idx\n\t\t\t then incr s;\n\t\t\t if used.(y').(x') = !idx && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 4 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w 0 in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n let idx = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif used.(i).(j) = 0 then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif used.(y).(x) = 0 then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- !idx;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t incr idx;\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- !idx;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 4 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if used.(y').(x') = !idx\n\t\t\t then incr s;\n\t\t\t if used.(y').(x') = !idx && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 4 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}], "negative_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w 0 in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n let idx = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif used.(i).(j) = 0 then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif used.(y).(x) = 0 then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- !idx;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t incr idx;\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- !idx;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 4 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if used.(y').(x') = !idx\n\t\t\t then incr s;\n\t\t\t if used.(y').(x') = !idx && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 4 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w 0 in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n let idx = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif used.(i).(j) = 0 then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif used.(y).(x) = 0 then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- !idx;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t incr idx;\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- !idx;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 4 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if used.(y').(x') = !idx\n\t\t\t then incr s;\n\t\t\t if used.(y').(x') = !idx && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && float_of_int !s *. 3.5 < float_of_int !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w false in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif not used.(i).(j) then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- true;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\tlet mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)\n\t in\n\t let ps = ref [] in\n\t let d = 5 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if a.(y').(x') <> 0\n\t\t\t then incr s;\n\t\t\t if a.(y').(x') <> 0 && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 3 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w 0 in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n let idx = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif used.(i).(j) = 0 then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif used.(y).(x) = 0 then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- !idx;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t incr idx;\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- !idx;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 5 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if used.(y').(x') = !idx\n\t\t\t then incr s;\n\t\t\t if used.(y').(x') = !idx && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 4 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w 0 in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n let idx = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif used.(i).(j) = 0 then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif used.(y).(x) = 0 then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- !idx;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t incr idx;\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- !idx;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 3 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if used.(y').(x') = !idx\n\t\t\t then incr s;\n\t\t\t if used.(y').(x') = !idx && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 4 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w false in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif not used.(i).(j) then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- true;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\tlet mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)\n\t in\n\t let ps = ref [] in\n\t let d = 5 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if a.(y').(x') <> 0\n\t\t\t then incr s;\n\t\t\t if a.(y').(x') <> 0 && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 3 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w false in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif not used.(i).(j) then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- true;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 5 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if a.(y').(x') <> 0\n\t\t\t then incr s;\n\t\t\t if a.(y').(x') <> 0 && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 4 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w false in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif not used.(i).(j) then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- true;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 5 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if a.(y').(x') <> 0\n\t\t\t then incr s;\n\t\t\t if a.(y').(x') <> 0 && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 3 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w false in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif not used.(i).(j) then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- true;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\tlet mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)\n\t in\n\t let ps = ref [] in\n\t let d = 5 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if a.(y').(x') <> 0\n\t\t\t then incr s;\n\t\t\t if a.(y').(x') <> 0 && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 3 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w false in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif not used.(i).(j) then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif not used.(y).(x) then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- true;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- true;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 6 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if a.(y').(x') <> 0\n\t\t\t then incr s;\n\t\t\t if a.(y').(x') <> 0 && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 4 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let sqr x = x *. x in\n let h = getnum () in\n let w = getnum () in\n let a = Array.make_matrix h w 0 in\n let () =\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\ta.(i).(j) <- getnum ()\n done\n done\n in\n let cand = Array.make_matrix h w false in\n let res = ref 0 in\n let rays = ref [] in\n let used = Array.make_matrix h w 0 in\n let stack = Array.make (h * w) (0, 0) in\n let pos = ref 0 in\n let idx = ref 0 in\n (*let a' = Array.make_matrix n n 0 in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n\tlet b = ref 0 in\n\t for i' = -f to f do\n\t for j' = -f to f do\n\t let x = j + j'\n\t and y = i + i' in\n\t\tif x >= 0 && y >= 0 && x < n && y < n\n\t\tthen b := !b + a.(y).(x)\n\t done\n\t done;\n\t if float_of_int !b > float_of_int ((2 * f + 1) * (2 * f + 1)) *. 0.4\n\t then a'.(i).(j) <- 1\n done\n done;\n for i = 0 to n - 1 do\n a.(i) <- a'.(i)\n done;*)\n for i = 0 to h - 1 do\n for j = 0 to w - 1 do\n\tif used.(i).(j) = 0 then (\n\t if a.(i).(j) <> 0 then (\n\t let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in\n\t let border = ref [] in\n\t let mx = ref 0 in\n\t let my = ref 0 in\n\t let cnt = ref 0 in\n\t let rec dfs () =\n\t if !pos > 0 then (\n\t\tdecr pos;\n\t\tlet (x, y) = stack.(!pos) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t incr cnt;\n\t\t for i = 0 to 3 do\n\t\t let (dx, dy) = d.(i) in\n\t\t let x = x + dx\n\t\t and y = y + dy in\n\t\t if x >= 0 && y >= 0 && x < w && y < h &&\n\t\t\ta.(y).(x) > 0\n\t\t then (\n\t\t\tif used.(y).(x) = 0 then (\n\t\t\t stack.(!pos) <- (x, y);\n\t\t\t incr pos;\n\t\t\t used.(y).(x) <- !idx;\n\t\t\t)\n\t\t ) else (\n\t\t\tborder := (x, y) :: !border\n\t\t )\n\t\t done;\n\t\t dfs ()\n\t )\n\t in\n\t incr idx;\n\t pos := 0;\n\t stack.(!pos) <- (j, i);\n\t incr pos;\n\t used.(i).(j) <- !idx;\n\t dfs ();\n\t let border = Array.of_list !border in\n\t let l = Array.length border in\n\t let (mx, my) =\n\t\t(*let mx = ref 0 in\n\t\tlet my = ref 0 in\n\t\t for i = 0 to l - 1 do\n\t\t let (x, y) = border.(i) in\n\t\t mx := !mx + x;\n\t\t my := !my + y;\n\t\t done;\n\t\t (float_of_int !mx /. float_of_int l,\n\t\t float_of_int !my /. float_of_int l)*)\n\t\t(float_of_int !mx /. float_of_int !cnt,\n\t\t float_of_int !my /. float_of_int !cnt)\n\t in\n\t let ps = ref [] in\n\t let d = 6 in\n\t let () =\n\t\tArray.iter\n\t\t (fun (x, y) ->\n\t\t let b = ref true in\n\t\t let dist = \n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t in\n\t\t let s = ref 0 in\n\t\t let t = ref 0 in\n\t\t for y' = y - d to y + d do\n\t\t\t for x' = x - d to x + d do\n\t\t\t incr t;\n\t\t\t if x' >= 0 && y' >= 0 && x' < w && y' < h then (\n\t\t\t let dist' = \n\t\t\t let x = float_of_int x'\n\t\t\t and y = float_of_int y' in\n\t\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t\t in\n\t\t\t if cand.(y').(x')\n\t\t\t then b := false;\n\t\t\t if used.(y').(x') = !idx\n\t\t\t then incr s;\n\t\t\t if used.(y').(x') = !idx && dist' > dist\n\t\t\t then b := false;\n\t\t\t )\n\t\t\t done\n\t\t done;\n\t\t if !b && !s * 4 < !t then (\n\t\t\t cand.(y).(x) <- true;\n\t\t\t ps := (x, y) :: !ps;\n\t\t\t (*Printf.printf \"asd %d %d %d %d\\n\" x y !s !t;*)\n\t\t )\n\t\t ) border\n\t in\n\t\trays := (List.length !ps) :: !rays;\n\t\tincr res;\n\t\t(*let d =\n\t\t Array.map\n\t\t (fun (x, y) ->\n\t\t let x = float_of_int x\n\t\t and y = float_of_int y in\n\t\t\t sqrt (sqr (x -. mx) +. sqr (y -. my))\n\t\t ) border\n\t\tin\n\t\tlet r =\n\t\t let r = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t r := !r +. d.(i)\n\t\t done;\n\t\t !r /. float_of_int l\n\t\tin\n\t\tlet sr =\n\t\t let sr = ref 0.0 in\n\t\t for i = 0 to l - 1 do\n\t\t sr := !sr +. sqr (d.(i) -. r)\n\t\t done;\n\t\t !sr /. float_of_int l\n\t\tin\n\t\t if sr /. r < 0.03\n\t\t then incr resc\n\t\t else incr ress;\n\t\t (*Printf.printf \"asd %f %f %f %f\\t%f %d\\n\"\n\t\t mx my r sr (sr /. r) l*)\n\t\t*)\n\t )\n\t)\n done\n done;\n let rays = List.sort compare !rays in\n Printf.printf \"%d\\n\" !res;\n List.iter (Printf.printf \"%d \") rays;\n Printf.printf \"\\n\"\n\n \n"}], "src_uid": "71f9a86f8af6a99ba010d5c55f74d63a"} {"nl": {"description": "The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits.Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number ri \u2014 the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to ri, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (x1,\u2009y1) and (x2,\u2009y2) is Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place.The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.", "input_spec": "The first input line contains coordinates of two opposite table corners xa, ya, xb, yb (xa\u2009\u2260\u2009xb,\u2009ya\u2009\u2260\u2009yb). The second line contains integer n \u2014 the number of radiators (1\u2009\u2264\u2009n\u2009\u2264\u2009103). Then n lines contain the heaters' coordinates as \"xi yi ri\", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1\u2009\u2264\u2009ri\u2009\u2264\u20091000. Several radiators can be located at the same point.", "output_spec": "Print the only number \u2014 the number of blankets you should bring.", "sample_inputs": ["2 5 4 2\n3\n3 1 2\n5 3 1\n1 3 2", "5 2 6 3\n2\n6 2 2\n6 5 3"], "sample_outputs": ["4", "0"], "notes": "NoteIn the first sample the generals are sitting at points: (2,\u20092), (2,\u20093), (2,\u20094), (2,\u20095), (3,\u20092), (3,\u20095), (4,\u20092), (4,\u20093), (4,\u20094), (4,\u20095). Among them, 4 generals are located outside the heating range. They are the generals at points: (2,\u20095), (3,\u20095), (4,\u20094), (4,\u20095).In the second sample the generals are sitting at points: (5,\u20092), (5,\u20093), (6,\u20092), (6,\u20093). All of them are located inside the heating range."}, "positive_code": [{"source_code": "(* codeforces 103. Danny Sleator *)\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \nlet read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet () =\n let xa = read_int() in\n let ya = read_int() in\n let xb = read_int() in\n let yb = read_int() in\n let n = read_int() in\n let rad = Array.make n (0,0,0) in\n let () = for i=0 to n-1 do\n let x = read_int() in\n let y = read_int() in\n let r = read_int() in\n rad.(i) <- (x,y,r)\n done in\n\n let (xa,ya,xb,yb)= (min xa xb, min ya yb, max xa xb, max ya yb) in\n\n let sq x = x*x in\n\n let count = ref 0 in\n for x = xa to xb do\n for y = ya to yb do\n\tif x=xa || x=xb || y=ya || y=yb then \n\t let rec gcov i = if i=n then false else \n\t let (xr,yr,r) = rad.(i) in\n\t if (sq r) >= (sq (x-xr)) + (sq (y-yr)) then true else gcov (i+1)\n\t in\n\t if not (gcov 0) then count := !count +1 else ()\n\telse ()\n done\n done;\n \n Printf.printf \"%d\\n\" !count;\n"}], "negative_code": [], "src_uid": "9e7fdc3261d312e7578da7f14c259e43"} {"nl": {"description": "Many years ago Berland was a small country where only $$$n$$$ people lived. Each person had some savings: the $$$i$$$-th one had $$$a_i$$$ burles.The government considered a person as wealthy if he had at least $$$x$$$ burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that: the government chooses some subset of people (maybe all of them); the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list $$$[5, 1, 2, 1]$$$: if the government chose the $$$1$$$-st and the $$$3$$$-rd persons then it, at first, will take all $$$5 + 2 = 7$$$ burles and after that will return $$$3.5$$$ burles to the chosen people. As a result, the savings will become $$$[3.5, 1, 3.5, 1]$$$.A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.", "input_spec": "The first line contains single integer $$$T$$$ ($$$1 \\le T \\le 1000$$$) \u2014 the number of test cases. Next $$$2T$$$ lines contain the test cases \u2014 two lines per test case. The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 10^5$$$, $$$1 \\le x \\le 10^9$$$) \u2014 the number of people and the minimum amount of money to be considered as wealthy. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) \u2014 the initial savings of each person. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$.", "output_spec": "Print $$$T$$$ integers \u2014 one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.", "sample_inputs": ["4\n4 3\n5 1 2 1\n4 10\n11 9 11 9\n2 5\n4 3\n3 7\n9 4 9"], "sample_outputs": ["2\n4\n0\n3"], "notes": "NoteThe first test case is described in the statement.In the second test case, the government, for example, could carry out two reforms: $$$[\\underline{11}, \\underline{9}, 11, 9] \\rightarrow [10, 10, \\underline{11}, \\underline{9}] \\rightarrow [10, 10, 10, 10]$$$.In the third test case, the government couldn't make even one person wealthy.In the fourth test case, the government could choose all people to carry out a reform: $$$[\\underline{9}, \\underline{4}, \\underline{9}] \\rightarrow [7\\frac{1}{3}, 7\\frac{1}{3}, 7\\frac{1}{3}]$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let n = read_int () in\n let x = read_long() in\n let a = Array.init n read_long in\n Array.sort (fun a b -> compare b a) a;\n let rec loop j ac = (* ac = a0+a(j-1) *)\n if j=n then n else\n\tlet ac = a.(j) ++ ac in (* ac = a0 + ... + aj *)\n\tif ac < x ** (long (j+1)) then j else loop (j+1) ac\n in\n printf \"%d\\n\" (loop 0 0L)\n done\n"}], "negative_code": [], "src_uid": "51f922bb2c51f50b5c3b55725dd7766e"} {"nl": {"description": "A new e-mail service \"Berlandesk\" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.", "input_spec": "The first line contains number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The following n lines contain the requests to the system. Each request is a non-empty line, and consists of not more than 32 characters, which are all lowercase Latin letters.", "output_spec": "Print n lines, which are system responses to the requests: OK in case of successful registration, or a prompt with a new name, if the requested name is already taken.", "sample_inputs": ["4\nabacaba\nacaba\nabacaba\nacab", "6\nfirst\nfirst\nsecond\nsecond\nthird\nthird"], "sample_outputs": ["OK\nOK\nabacaba1\nOK", "OK\nfirst1\nOK\nsecond1\nOK\nthird1"], "notes": null}, "positive_code": [{"source_code": "let acceptable = \"OK\\n\"\n\nlet processName name table =\n if Hashtbl.mem table name\n then let currFreeNum = Hashtbl.find table name in\n begin\n Hashtbl.replace table name (currFreeNum + 1);\n Printf.sprintf \"%s%d\\n\" name currFreeNum\n end\n else \n begin\n Hashtbl.add table name 1;\n acceptable\n end\n\nlet () =\n let numNames = Scanf.sscanf (read_line ()) \"%d\" (fun x -> x) in\n let table = Hashtbl.create numNames in\n for i = 1 to numNames do\n let currName = read_line () in\n print_string (processName currName table)\n done\n"}, {"source_code": "let num = read_int () in\n let hbl = Hashtbl.create (num / 8) in\n for tot = 1 to num do\n let uc = read_line () in\n let i = try Hashtbl.find hbl uc with Not_found -> 0 in\n if i <> 0 then (print_string uc; print_int i; print_newline ()) else (print_endline \"OK\");\n Hashtbl.replace hbl uc (i + 1)\n done\n \n "}, {"source_code": "open Hashtbl;;\n\nlet regs = read_int ();;\n\nlet users = Hashtbl.create 0;;\n\nfor i = 1 to regs do\n\tlet name = read_line () in\n\tif Hashtbl.mem users name then begin\n\t\tlet x = Hashtbl.find users name + 1 in\n\t\tlet _ = print_string (name ^ (string_of_int x) ^ \"\\n\") in\n\t\tHashtbl.replace users name x\n\t\t\n\tend else begin\n\t\tHashtbl.add users name 0;\n\t\tprint_string \"OK\\n\"\n\tend\ndone;\n"}, {"source_code": "let () =\n let n = read_int () in\n let h = Hashtbl.create n in\n for i = 1 to n do\n let s = read_line () in\n let x = try Hashtbl.find h s with _ -> 0 in\n Hashtbl.replace h s (x+1);\n if x = 0 then\n print_endline \"OK\"\n else\n Printf.printf \"%s%d\\n\" s x\n done\n"}, {"source_code": "let n = read_int ();; let users = Hashtbl.create 1000;; for i = 1 to n do let name = read_line () in if Hashtbl.mem users name then begin let _ = print_endline (name ^ (string_of_int (Hashtbl.find users name +1)) ^ \"\\n\") in Hashtbl.replace users name (Hashtbl.find users name+1) end else begin let _ = print_string \"OK\\n\" in Hashtbl.add users name 0 end done; "}, {"source_code": "open Printf\nopen String\n\nmodule type DICTIONARY =\nsig\n type key = string\n type 'a dict\n exception NotFound\n\n val make : unit -> 'a dict\n val insert : 'a dict -> key -> 'a -> 'a dict\n val lookup : 'a dict -> key -> 'a\n val map : ('a -> 'b) -> 'a dict -> 'b dict\nend\n\n(* implemented with association list *)\nmodule AssocList : DICTIONARY =\nstruct\n type key = string\n type 'a dict = (key * 'a) list\n exception NotFound\n \n let make () : 'a dict = []\n let insert (d : 'a dict) (k : key) (x : 'a) : 'a dict = (k, x) :: d\n let rec lookup (d : 'a dict) (k : key) : 'a =\n match d with\n | [] -> raise NotFound\n | (k', x) :: rest ->\n if k = k' then x\n else lookup rest k\n let map (f : 'a -> 'b) (d : 'a dict) =\n List.map (fun (k, a) -> (k, f a)) d\nend\n\n(* implemented with higher-order function *)\nmodule FunctionDict : DICTIONARY =\nstruct\n type key = string\n type 'a dict = string -> 'a\n exception NotFound\n \n let make () = fun _ -> raise NotFound\n let lookup (d : 'a dict) (key : string) : 'a = d key\n let insert (d : 'a dict) (k : key) (x : 'a) : 'a dict = \n fun k' -> if k = k' then x else d k'\n let map (f : 'a -> 'b) (d : 'a dict) = fun k -> f (d k)\nend \n\n(* a better association list verion *)\nmodule SortedAssocList : DICTIONARY =\nstruct\n type key = string\n type 'a dict = (key * 'a) list\n exception NotFound\n \n let make() : 'a dict = []\n let rec insert (d : 'a dict) (k : key) (x : 'a) : 'a dict =\n match d with\n | [] -> (k, x) :: []\n | (k', x') :: rest ->\n match String.compare k k' with\n 1 -> (k', x') :: (insert rest k x)\n | 0 -> (k, x) :: rest\n | -1 -> (k, x) :: (k', x') :: rest\n | _ -> failwith \"Impossible\"\n\n let rec lookup (d : 'a dict) (k : key) : 'a =\n match d with\n [] -> raise NotFound\n | (k', x) :: rest ->\n match String.compare k k' with\n 0 -> x\n | -1 -> raise NotFound\n | 1 -> lookup rest k\n | _ -> failwith \"Impossible\"\n\n let map (f : 'a -> 'b) (d : 'a dict) =\n List.map (fun (k,a) -> (k, f a)) d\nend\n\n(* implemented with binary tree, logn loopup *)\nmodule AssocTree : DICTIONARY =\nstruct\n type key = string\n type 'a dict = Empty | Node of key * 'a * 'a dict * 'a dict\n exception NotFound\n\n\n let make() : 'a dict = Empty\n\n let rec insert (d : 'a dict) (k : key) (x : 'a) : 'a dict =\n match d with\n Empty -> Node (k, x, Empty, Empty)\n | Node (k', x', l, r) ->\n match String.compare k k' with\n 0 -> Node(k, x, l, r)\n | -1 -> Node(k', x', insert l k x, r)\n | 1 -> Node(k', x', l, insert r k x)\n | _ -> failwith \"Impossible\"\n\n let rec lookup (d : 'a dict) (k : key) : 'a =\n match d with\n Empty -> raise NotFound\n | Node(k', x, l, r) ->\n match String.compare k k' with\n 0 -> x\n | -1 -> lookup l k\n | 1 -> lookup r k\n | _ -> failwith \"Impossible\"\n\n let rec map (f : 'a -> 'b) (d : 'a dict) =\n match d with\n Empty -> Empty\n | Node (k, x, l, r) -> Node (k, f x, map f l, map f r)\nend\n\nlet tree = AssocTree.make ()\n \nlet n = Scanf.scanf \"%d \" (fun x -> x)\n\nlet myprint s i =\n let t = s^(string_of_int i) in\n printf \"%s\\n\" t\n\nlet rec loop tr ii =\n if ii = 0 then\n ()\n else\n begin\n let open AssocTree in\n let s = Scanf.scanf \"%s \" (fun x -> x) in\n try\n let x = lookup tr s in\n myprint s (x+1); loop (insert tr s (x+1)) (ii-1) \n with\n NotFound -> printf \"OK\\n\"; loop (insert tr s 0) (ii-1)\n end \n \n let () = loop tree n\n \n"}, {"source_code": "let solve n =\n let tbl = Hashtbl.create 100000 in\n for i = 1 to n do\n let query = Scanf.scanf \" %s\" (fun x -> x) in\n if Hashtbl.mem tbl query\n then\n begin\n\tlet v = Hashtbl.find tbl query in\n\tHashtbl.add tbl query (v+1);\t\n\tPrintf.printf \"%s%d\\n\" query v;\n end\n else\n begin\n\tHashtbl.add tbl query 1;\n\tPrintf.printf \"OK\\n\";\n end\n done\n\nlet _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n solve n\n \n\n"}], "negative_code": [], "src_uid": "24098df9c12d9704391949c9ff529c98"} {"nl": {"description": "It's Petya's birthday party and his friends have presented him a brand new \"Electrician-$$$n$$$\" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.Construction set \"Electrician-$$$n$$$\" consists of $$$2n - 1$$$ wires and $$$2n$$$ light bulbs. Each bulb has its own unique index that is an integer from $$$1$$$ to $$$2n$$$, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed $$$2i$$$ and $$$2i - 1$$$ turn on if the chain connecting them consists of exactly $$$d_i$$$ wires. Moreover, the following important condition holds: the value of $$$d_i$$$ is never greater than $$$n$$$.Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.", "input_spec": "The first line of the input contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 100\\,000$$$)\u00a0\u2014 the parameter of a construction set that defines the number of bulbs and the number of wires. Next line contains $$$n$$$ integers $$$d_1, d_2, \\ldots, d_n$$$ ($$$1 \\leq d_i \\leq n$$$), where $$$d_i$$$ stands for the number of wires the chain between bulbs $$$2i$$$ and $$$2i - 1$$$ should consist of.", "output_spec": "Print $$$2n - 1$$$ lines. The $$$i$$$-th of them should contain two distinct integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \\leq a_i, b_i \\leq 2n$$$, $$$a_i \\ne b_i$$$)\u00a0\u2014 indices of bulbs connected by a wire. If there are several possible valid answer you can print any of them.", "sample_inputs": ["3\n2 2 2", "4\n2 2 2 1", "6\n2 2 2 2 2 2", "2\n1 1"], "sample_outputs": ["1 6\n2 6\n3 5\n3 6\n4 5", "1 6\n1 7\n2 6\n3 5\n3 6\n4 5\n7 8", "1 3\n2 3\n3 5\n4 5\n5 7\n6 7\n7 12\n8 12\n9 11\n9 12\n10 11", "1 2\n1 4\n3 4"], "notes": "Note Answer for the first sample test. Answer for the second sample test. "}, "positive_code": [{"source_code": "let iteri_if action cond lst =\n let rec go i lst = \n match lst with\n | [] -> ()\n | x :: rest -> (if cond i x then action i x else ()) ; go (i + 1) rest\n in go 0 lst\n\nlet ans =\n let n = read_int() in\n let s = read_line() in\n let words = Str.split_delim (Str.regexp \" \") s in\n let ds = List.map int_of_string words in\n let prs = Array.make n (0, 0) in\n List.iteri (fun i k -> prs.(i) <- (k, i)) ds;\n Array.fast_sort (fun x y -> - (compare x y)) prs;\n let par = Array.make (n * 2 + 1) 0 in\n let lst = Array.make (n * 2) 0 in\n Array.iteri (fun i (_,k) -> lst.(i) <- 2 * k + 1) prs;\n let cur = ref n in\n Array.iteri (fun i (d,k) ->\n if d + i = !cur then\n (lst.(!cur) <- 2*k+2;\n cur := !cur + 1)\n else\n par.(2*k+2) <- lst.(d + i - 1)\n ) prs;\n for i = 1 to !cur-1 do\n par.(lst.(i)) <- lst.(i-1)\n done;\n iteri_if (fun i j -> Printf.printf \"%d %d\\n\" i j)\n (fun i j -> j <> 0) (Array.to_list par)\n"}, {"source_code": "(* Petya and Construction Set\n * https://codeforces.com/contest/1214/problem/E *)\n\nlet ans =\n let n = read_int() in\n let ds = read_line()\n |> Str.split_delim (Str.regexp \" \")\n |> List.map int_of_string in\n let prs = Array.make n (0, 0) in\n List.iteri (fun i k -> prs.(i) <- (k, i)) ds;\n Array.fast_sort (fun x y -> - (compare x y)) prs;\n let par = Array.make (n * 2 + 1) 0 in\n let lst = Array.make (n * 2) 0 in\n Array.iteri (fun i (_,k) -> lst.(i) <- 2 * k + 1) prs;\n let cur = ref n in\n let rec iter i cur =\n if i = n then cur\n else\n let (d, k) = prs.(i) in\n let ncur =\n if d + i = cur then\n (lst.(cur) <- 2*k+2;\n cur + 1)\n else (par.(2*k+2) <- lst.(d + i - 1);\n cur) in\n iter (i+1) ncur in\n let cur = iter 0 n in\n (* Array.iteri (fun i (d,k) ->\n * if d + i = !cur then\n * (lst.(!cur) <- 2*k+2;\n * cur := !cur + 1)\n * else\n * par.(2*k+2) <- lst.(d + i - 1)\n * ) prs; *)\n for i = 1 to cur - 1 do\n par.(lst.(i)) <- lst.(i-1)\n done;\n Array.iteri\n (fun i j -> if j = 0 then () else Printf.printf \"%d %d\\n\" i j) par\n"}, {"source_code": "(* let iteri_if action cond seq =\n * let rec go i seq = \n * match seq with\n * | Seq.Nil -> ()\n * | Seq.Cons (x, rest) -> (if cond i x then action i x else ()) ; go (i + 1) (rest ())\n * in go 0 seq *)\n\nlet arr_iteri_if action cond arr =\n let rec go i =\n match i with\n | k when k = Array.length arr -> ()\n | _ -> (if cond i arr.(i) then action i arr.(i) else ()) ; go (i + 1) \n in go 0\n\nlet ans =\n let n = read_int() in\n let s = read_line() in\n let words = Str.split_delim (Str.regexp \" \") s in\n let ds = List.map int_of_string words in\n let prs = Array.make n (0, 0) in\n List.iteri (fun i k -> prs.(i) <- (k, i)) ds;\n Array.fast_sort (fun x y -> - (compare x y)) prs;\n let par = Array.make (n * 2 + 1) 0 in\n let lst = Array.make (n * 2) 0 in\n Array.iteri (fun i (_,k) -> lst.(i) <- 2 * k + 1) prs;\n let cur = ref n in\n Array.iteri (fun i (d,k) ->\n if d + i = !cur then\n (lst.(!cur) <- 2*k+2;\n cur := !cur + 1)\n else\n par.(2*k+2) <- lst.(d + i - 1)\n ) prs;\n for i = 1 to !cur-1 do\n par.(lst.(i)) <- lst.(i-1)\n done;\n arr_iteri_if (fun i j -> Printf.printf \"%d %d\\n\" i j)\n (fun i j -> j <> 0) par\n"}, {"source_code": "let ans =\n let n = read_int() in\n let s = read_line() in\n let words = Str.split_delim (Str.regexp \" \") s in\n let ds = List.map int_of_string words in\n let prs = Array.make n (0, 0) in\n List.iteri (fun i k -> prs.(i) <- (k, i)) ds;\n Array.fast_sort (fun x y -> - (compare x y)) prs;\n let par = Array.make (n * 2 + 1) 0 in\n let lst = Array.make (n * 2) 0 in\n Array.iteri (fun i (_,k) -> lst.(i) <- 2 * k + 1) prs;\n let cur = ref n in\n for i = 0 to n-1 do\n let (d, k) = prs.(i) in\n if d + i = !cur then\n (lst.(!cur) <- 2*k+2;\n cur := !cur + 1)\n else\n par.(2*k+2) <- lst.(d + i - 1)\n done;\n for i = 1 to !cur-1 do\n par.(lst.(i)) <- lst.(i-1)\n done;\n for i = 1 to n * 2 do\n if par.(i) = 0 then\n ()\n else\n Printf.printf \"%d %d\\n\" i par.(i)\n done \n"}], "negative_code": [{"source_code": "(* Petya and Construction Set\n * https://codeforces.com/contest/1214/problem/E *)\n\nlet ans =\n let n = read_int() in\n let ds = read_line()\n |> Str.split_delim (Str.regexp \" \")\n |> List.map int_of_string in\n let prs = Array.make n (0, 0) in\n List.iteri (fun i k -> prs.(i) <- (k, i)) ds;\n Array.fast_sort (fun x y -> - (compare x y)) prs;\n let par = Array.make (n * 2 + 1) 0 in\n let lst = Array.make (n * 2) 0 in\n Array.iteri (fun i (_,k) -> lst.(i) <- 2 * k + 1) prs;\n let cur = ref n in\n let rec iter i cur =\n if i = n then ()\n else\n let (d, k) = prs.(i) in\n let ncur = \n if d + i = cur then\n (lst.(cur) <- 2*k+2;\n cur + 1)\n else (par.(2*k+2) <- lst.(d + i - 1);\n cur) in\n iter (i+1) ncur in\n iter 0 n;\n (* Array.iteri (fun i (d,k) ->\n * if d + i = !cur then\n * (lst.(!cur) <- 2*k+2;\n * cur := !cur + 1)\n * else\n * par.(2*k+2) <- lst.(d + i - 1)\n * ) prs; *)\n for i = 1 to !cur-1 do\n par.(lst.(i)) <- lst.(i-1)\n done;\n Array.iteri\n (fun i j -> if j = 0 then () else Printf.printf \"%d %d\\n\" i j) par\n"}, {"source_code": "(* #load \"str.cma\" *)\n\nlet () =\n let n = read_int() in\n let s = read_line() in\n let words = Str.split_delim (Str.regexp \" \") s in\n let ds = List.map int_of_string words in\n print_int (List.fold_left (+) 0 ds)\n"}], "src_uid": "61bb5f2b315eddf2e658e3f54d8f43b8"} {"nl": {"description": "Sereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai,\u2009bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091000) \u2014 the description of the i-th bottle.", "output_spec": "In a single line print a single integer \u2014 the answer to the problem.", "sample_inputs": ["4\n1 1\n2 2\n3 3\n4 4", "4\n1 2\n2 3\n3 4\n4 1"], "sample_outputs": ["4", "0"], "notes": null}, "positive_code": [{"source_code": "\nlet () =\n let (@@) f x = f x in\n let (|>) x f = f x in\n let open List in\n let split = Str.split @@ Str.regexp_string \" \" in\n let n = read_int () in\n let bottles = Array.make n (0, 0) in\n for i = 0 to n - 1 do\n read_line () |> split |> map int_of_string |> fun l_pair ->\n bottles.(i) <- hd l_pair, hd @@ tl l_pair;\n done;\n let can_open i j = i <> j && snd bottles.(j) = fst bottles.(i) in\n let answer = ref 0 in\n for i = 0 to n - 1 do\n try\n for j = 0 to n - 1 do\n if can_open i j then raise Exit\n done;\n incr answer\n with Exit -> ()\n done;\n print_endline @@ string_of_int !answer\n\n"}], "negative_code": [], "src_uid": "84bd49becca69e126606d5a2f764dd91"} {"nl": {"description": "Alice and Bob are playing a game with strings. There will be $$$t$$$ rounds in the game. In each round, there will be a string $$$s$$$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $$$s$$$.More formally, if there was a string $$$s = s_1s_2 \\ldots s_k$$$ the player can choose a substring $$$s_ls_{l+1} \\ldots s_{r-1}s_r$$$ with length of corresponding parity and remove it. After that the string will become $$$s = s_1 \\ldots s_{l-1}s_{r+1} \\ldots s_k$$$.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $$$\\texttt{a}$$$ is $$$1$$$, the value of $$$\\texttt{b}$$$ is $$$2$$$, the value of $$$\\texttt{c}$$$ is $$$3$$$, $$$\\ldots$$$, and the value of $$$\\texttt{z}$$$ is $$$26$$$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.", "input_spec": "The first line of input contains a single integer $$$t$$$ ($$$1\\leq t\\leq 5\\cdot 10^4$$$) denoting the number of rounds. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\\leq |s|\\leq 2\\cdot 10^5$$$) consisting of lowercase English letters, denoting the string used for the round. Here $$$|s|$$$ denotes the length of the string $$$s$$$. It is guaranteed that the sum of $$$|s|$$$ over all rounds does not exceed $$$2\\cdot 10^5$$$.", "output_spec": "For each round, print a single line containing a string and an integer. If Alice wins the round, the string must be \"Alice\". If Bob wins the round, the string must be \"Bob\". The integer must be the difference between their scores assuming both players play optimally.", "sample_inputs": ["5\n\naba\n\nabc\n\ncba\n\nn\n\ncodeforces"], "sample_outputs": ["Alice 2\nAlice 4\nAlice 4\nBob 14\nAlice 93"], "notes": "NoteFor the first round, $$$\\texttt{\"aba\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"}{\\color{red}{\\texttt{ab}}}\\texttt{a\"}\\xrightarrow{} \\texttt{\"a\"}\\xrightarrow{\\texttt{Bob}}\\texttt{\"}{\\color{red}{\\texttt{a}}}\\texttt{\"}\\xrightarrow{}\\texttt{\"\"}$$$. Alice's total score is $$$1+2=3$$$. Bob's total score is $$$1$$$.For the second round, $$$\\texttt{\"abc\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"a}{\\color{red}{\\texttt{bc}}}\\texttt{\"}\\xrightarrow{} \\texttt{\"a\"}\\xrightarrow{\\texttt{Bob}}\\texttt{\"}{\\color{red}{\\texttt{a}}}\\texttt{\"}\\xrightarrow{}\\texttt{\"\"}$$$. Alice's total score is $$$2+3=5$$$. Bob's total score is $$$1$$$.For the third round, $$$\\texttt{\"cba\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"}{\\color{red}{\\texttt{cb}}}\\texttt{a\"}\\xrightarrow{} \\texttt{\"a\"}\\xrightarrow{\\texttt{Bob}}\\texttt{\"}{\\color{red}{\\texttt{a}}}\\texttt{\"}\\xrightarrow{}\\texttt{\"\"}$$$. Alice's total score is $$$3+2=5$$$. Bob's total score is $$$1$$$.For the fourth round, $$$\\texttt{\"n\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"n\"}\\xrightarrow{} \\texttt{\"n\"}\\xrightarrow{\\texttt{Bob}}\\texttt{\"}{\\color{red}{\\texttt{n}}}\\texttt{\"}\\xrightarrow{}\\texttt{\"\"}$$$. Alice's total score is $$$0$$$. Bob's total score is $$$14$$$.For the fifth round, $$$\\texttt{\"codeforces\"}\\xrightarrow{\\texttt{Alice}}\\texttt{\"}{\\color{red}{\\texttt{codeforces}}}\\texttt{\"}\\xrightarrow{} \\texttt{\"\"}$$$. Alice's total score is $$$3+15+4+5+6+15+18+3+5+19=93$$$. Bob's total score is $$$0$$$."}, "positive_code": [{"source_code": "let n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let a = input_line stdin in\r\n if String.length a = 1 then (let b = Char.code (a.[0]) -96 in print_endline (\"Bob \"^(string_of_int b)))\r\n else ( if String.length a mod 2 = 0 then (let count = ref 0 in\r\n for i = 0 to String.length a - 1 do\r\n count := !count + Char.code (a.[i]) - 96 ;\r\n done;\r\n print_endline (\"Alice \"^ (string_of_int (!count )))) \r\n else begin\r\n let count = ref 0 in\r\n for i = 1 to String.length a - 2 do\r\n count := !count + Char.code (a.[i]) - 96 ;\r\n done;\r\n let b = Char.code (a.[0]) -96 in\r\n let c = Char.code (a.[ String.length a - 1]) -96 in\r\n let d = (max b c) - (min b c) in\r\n print_endline (\"Alice \"^ (string_of_int (!count +d )));\r\n end)\r\ndone;;\r\n "}], "negative_code": [], "src_uid": "8f02891aa9d2fcd1963df3a4028aa5c0"} {"nl": {"description": "Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.", "output_spec": "In a single line print the answer to the problem \u2014 the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.", "sample_inputs": ["2\n?ab\n??b", "2\na\nb", "1\n?a?b"], "sample_outputs": ["xab", "?", "cacb"], "notes": "NoteConsider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on."}, "positive_code": [{"source_code": "let n=read_int();;\nlet tab=Array.make (n+1) \"\";;\nfor i=1 to n do\n tab.(i)<-read_line()\ndone;;\nlet m=String.length(tab.(1));;\nlet vec=Array.make m ' ';;\nfor j=0 to m-1 do\n vec.(j)<-tab.(1).[j]\ndone;;\nfor i=2 to n do\n for j=0 to m-1 do\n if vec.(j)='?' then vec.(j)<-tab.(i).[j]\n else if tab.(i).[j]='?' then ()\n else if tab.(i).[j]<>vec.(j) then vec.(j)<-'!'\n done\ndone;;\n\nlet sol=tab.(1);;\nfor j=0 to m-1 do\n if vec.(j)='?' then sol.[j]<-'a'\n else if vec.(j)='!' then sol.[j]<-'?'\n else sol.[j]<-vec.(j)\ndone;;\nprint_string sol;;\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet read_int () = scanf \" %d \" (fun x -> x) in\nlet read_string () = scanf \" %s \" (fun x -> x) in\n\nlet n = read_int () in\nlet a = Array.init n (fun x -> (read_string ())) in\nlet m = String.length a.(0) in\n\nlet res = String.make m 'A' in\n\nlet upd i c =\n if c <> '?' then\n if res.[i] = 'A' || res.[i] = c then\n res.[i] <- c\n else\n res.[i] <- '?' in\n\nArray.iter (String.iteri upd) a;\nprintf \"%s\\n\" (String.lowercase res);;\n\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n \"\" in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%s \" (fun s -> s)\n done;\n in\n let k = String.length a.(0) in\n let res = String.make k 'x' in\n for i = 0 to k - 1 do\n let c = ref '?' in\n\tfor j = 0 to n - 1 do\n\t if !c = '?' && a.(j).[i] <> '?' then (\n\t c := a.(j).[i];\n\t res.[i] <- !c;\n\t ) else if !c <> '?' && a.(j).[i] <> '?' && a.(j).[i] <> !c then (\n\t res.[i] <- '?'\n\t )\n\tdone\n done;\n Printf.printf \"%s\\n\" res;\n"}], "negative_code": [], "src_uid": "a51d2e6e321d7db67687a594a2b85e47"} {"nl": {"description": "Nick had received an awesome array of integers $$$a=[a_1, a_2, \\dots, a_n]$$$ as a gift for his $$$5$$$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $$$a_1 \\cdot a_2 \\cdot \\dots a_n$$$ of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index $$$i$$$ ($$$1 \\le i \\le n$$$) and do $$$a_i := -a_i - 1$$$.For example, he can change array $$$[3, -1, -4, 1]$$$ to an array $$$[-4, -1, 3, 1]$$$ after applying this operation to elements with indices $$$i=1$$$ and $$$i=3$$$. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements $$$a_1 \\cdot a_2 \\cdot \\dots a_n$$$ which can be received using only this operation in some order.If there are multiple answers, print any of them.", "input_spec": "The first line contains integer $$$n$$$ ($$$1 \\leq n \\leq 10^{5}$$$)\u00a0\u2014 number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^{6} \\leq a_i \\leq 10^{6}$$$)\u00a0\u2014 elements of the array", "output_spec": "Print $$$n$$$ numbers\u00a0\u2014 elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array. If there are multiple answers, print any of them.", "sample_inputs": ["4\n2 2 2 2", "1\n0", "3\n-3 -3 2"], "sample_outputs": ["-3 -3 -3 -3", "0", "-3 -3 2"], "notes": null}, "positive_code": [{"source_code": "let (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\n\n\nlet () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a =\n Array.init n (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x))\n |> Array.mapi (fun i x -> (if 0L <= x then 0L -- x -- 1L else x), i)\n in\n if n mod 2 = 0 then\n Array.iter (fun (x, _) -> Printf.printf \"%Ld \" x) a\n else\n let min, min_idx =\n Array.fold_left\n (fun (min, min_idx) (x, i) ->\n if x < min then x, i else min, min_idx\n ) a.(0) a\n in\n a.(min_idx) <- 0L -- fst a.(min_idx) -- 1L, min_idx;\n Array.iter (fun (x, _) -> Printf.printf \"%Ld \" x) a\n;;\n"}], "negative_code": [{"source_code": "let (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\n\n\nlet () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a =\n Array.init n (fun _ -> Scanf.scanf \"%Ld \" (fun x -> x))\n |> Array.mapi (fun i x -> (if 0L <= x then 0L -- x -- 1L else x), i)\n in\n if n mod 2 = 0 then\n Array.iter (fun (x, _) -> Printf.printf \"%Ld \" x) a\n else\n let max, max_idx =\n Array.fold_left\n (fun (max, max_idx) (x, i) ->\n if max < x then x, i else max, max_idx\n ) a.(0) a\n in\n a.(max_idx) <- 0L -- fst a.(max_idx) -- 1L, max_idx;\n Array.iter (fun (x, _) -> Printf.printf \"%Ld \" x) a\n;;\n"}, {"source_code": "let () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let a =\n Array.init n (fun _ -> Scanf.scanf \"%d \" (fun x -> x))\n |> Array.mapi (fun i x -> (if 0 <= x then - x - 1 else x), i)\n in\n if n mod 2 = 0 then\n Array.iter (fun (x, _) -> Printf.printf \"%d \" x) a\n else\n let max, max_idx =\n Array.fold_left\n (fun (max, max_idx) (x, i) ->\n if max < x then x, i else max, max_idx\n ) a.(0) a\n in\n a.(max_idx) <- - fst a.(max_idx) - 1, max_idx;\n Array.iter (fun (x, _) -> Printf.printf \"%d \" x) a\n;;\n"}], "src_uid": "b0561fee6236f0720f737ca41e20e382"} {"nl": {"description": "Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n\u2009-\u20091 and 0 to m\u2009-\u20091 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.", "input_spec": "The first line contains two integer n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100). The second line contains integer b (0\u2009\u2264\u2009b\u2009\u2264\u2009n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1,\u2009x2,\u2009...,\u2009xb (0\u2009\u2264\u2009xi\u2009<\u2009n), denoting the list of indices of happy boys. The third line conatins integer g (0\u2009\u2264\u2009g\u2009\u2264\u2009m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1,\u2009y2,\u2009... ,\u2009yg (0\u2009\u2264\u2009yj\u2009<\u2009m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.", "output_spec": "If Drazil can make all his friends become happy by this plan, print \"Yes\". Otherwise, print \"No\".", "sample_inputs": ["2 3\n0\n1 0", "2 4\n1 0\n1 2", "2 3\n1 0\n1 1"], "sample_outputs": ["Yes", "No", "Yes"], "notes": "NoteBy we define the remainder of integer division of i by k.In first sample case: On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day. On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day. On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day. On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy. On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment. "}, "positive_code": [{"source_code": "(* start 6:35 done 6:42 *)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let (n,m) = read_pair () in\n let boy = Array.make n false in\n let girl = Array.make m false in\n let b = read_int () in\n for i=0 to b-1 do\n boy.(read_int()) <- true;\n done;\n let g = read_int() in\n for i=0 to g-1 do\n girl.(read_int()) <- true;\n done;\n\n for i=0 to n*m*(1 + min m n) do\n let x = boy.(i mod n) || girl.(i mod m) in\n boy.(i mod n) <- x;\n girl.(i mod m) <- x;\n done;\n\n if (forall 0 (n-1) (fun i -> boy.(i))) && (forall 0 (m-1) (fun i -> girl.(i)))\n then printf \"Yes\\n\" else printf \"No\\n\";\n\n"}], "negative_code": [{"source_code": "(* start 6:35 *)\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let (n,m) = read_pair () in\n let boy = Array.make n false in\n let girl = Array.make m false in\n let b = read_int () in\n for i=0 to b-1 do\n boy.(read_int()) <- true;\n done;\n let g = read_int() in\n for i=0 to g-1 do\n girl.(read_int()) <- true;\n done;\n\n for i=0 to n*m do\n let x = boy.(i mod n) || girl.(i mod m) in\n boy.(i mod n) <- x;\n girl.(i mod m) <- x;\n done;\n\n if (forall 0 (n-1) (fun i -> boy.(i))) && (forall 0 (m-1) (fun i -> girl.(i)))\n then printf \"Yes\\n\" else printf \"No\\n\";\n\n"}], "src_uid": "65efbc0a1ad82436100eea7a2378d4c2"} {"nl": {"description": "Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.Everybody knows that the World history encompasses exactly n events: the i-th event had continued from the year ai to the year bi inclusive (ai\u2009<\u2009bi). Polycarpus easily learned the dates when each of n events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event j includes an event i if aj\u2009<\u2009ai and bi\u2009<\u2009bj. Your task is simpler: find the number of events that are included in some other event.", "input_spec": "The first input line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) which represents the number of events. Next n lines contain descriptions of the historical events, one event per line. The i\u2009+\u20091 line contains two integers ai and bi (1\u2009\u2264\u2009ai\u2009<\u2009bi\u2009\u2264\u2009109) \u2014 the beginning and the end of the i-th event. No two events start or finish in the same year, that is, ai\u2009\u2260\u2009aj,\u2009ai\u2009\u2260\u2009bj,\u2009bi\u2009\u2260\u2009aj,\u2009bi\u2009\u2260\u2009bj for all i, j (where i\u2009\u2260\u2009j). Events are given in arbitrary order.", "output_spec": "Print the only integer \u2014 the answer to the problem.", "sample_inputs": ["5\n1 10\n2 9\n3 8\n4 7\n5 6", "5\n1 100\n2 50\n51 99\n52 98\n10 60", "1\n1 1000000000"], "sample_outputs": ["4", "4", "0"], "notes": "NoteIn the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third \u2014 in the second and the second \u2014 in the first.In the second example all events except the first one are contained in the first.In the third example only one event, so the answer is 0."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet read_pair () = let a = read_int () in (a , read_int ());;\n\nmodule Pair_set = struct\n type t = int*int\n let compare = compare\nend;;\n\nmodule Mytest = Set.Make (Pair_set);;\n\nlet n = read_int ();;\n\nlet data = Array.init n (fun i -> read_pair ());;\nArray.sort compare data;;\n\nlet ans = ref 0 and _end = ref (-1) in \n for i = 0 to (n-1) do\n let first , second = data.(i) in\n if second < !_end then ans := !ans + 1\n else _end := second\n done;\n Printf.printf \"%d\\n\" !ans;;\n\n\n"}, {"source_code": "(*************** Ocaml stdio functions **********************)\nlet stdin_stream = Stream.of_channel stdin;;\nlet stdout_buffer = Buffer.create 65536;;\nlet rec gi() =\n match Stream.next stdin_stream with\n '-' -> - (ri 0)\n | '+' -> ri 0\n | '0'..'9' as c -> ri ((int_of_char c) - 48)\n | _ -> gi ()\nand ri x =\n match Stream.next stdin_stream with\n '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))\n | _ -> x\n;;\nlet flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;\nlet putchar c =\n if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();\n Buffer.add_char stdout_buffer c;;\nlet rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;\nlet pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));;\nlet pa a = let n = Array.length a in Array.iteri (fun i j -> pi j; putchar (if i == (n-1) then '\\n' else ' ')) a;;\n(*************** Ocaml solution ******************************)\nopen Array\nlet main() =\n let n = gi() in\n let a = init n (fun i -> let ai = gi () in let bi = gi () in (ai, bi)) in\n let cmp a b = compare (fst a) (fst b) in\n stable_sort cmp a;\n let mx = ref 0 in\n let s = ref 0 in\n for i = 0 to (n-1) do\n let b = snd a.(i) in\n s := (!s) + (if b > (!mx) then 0 else 1);\n mx := max (!mx) b\n done;\n Printf.printf \"%d\\n\" (!s)\n ;;\nmain();;\nflushout ()"}, {"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\nlet _ =\n let n = getnum () in\n let c = Array.make n (0, 0) in\n for i = 0 to n - 1 do\n let a = getnum () in\n let b = getnum () in\n\tc.(i) <- (a, b)\n done;\n Array.sort compare c;\n let latest = ref 0 in\n let res = ref 0 in\n for i = 0 to n - 1 do\n\tlet (_a, b) = c.(i) in\n\t if b < !latest\n\t then incr res;\n\t latest := max !latest b\n done;\n output_string stdout (string_of_int !res);\n output_char stdout '\\n';\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet n = read_int()\n\nlet p = Array.make n (0,0)\n\nlet contained (a,b) s = \n let (l,_,_) = Pset.split (a,b) s in\n if Pset.is_empty l then false else\n let (ai,bi) = Pset.max_elt l in b < bi\n\nlet () =\n for i=0 to n-1 do\n let a = read_int() in\n let b = read_int() in\n p.(i) <- (a,b)\n done;\n Array.sort (fun (a,b) (c,d) -> compare (d-c) (b-a)) p;\n\n let s = ref Pset.empty in\n let count = ref 0 in\n for i=0 to n-1 do\n if not (contained p.(i) !s) then s := Pset.add p.(i) !s\n else count := !count + 1;\n done;\n \n Printf.printf \"%d\\n\" !count\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\n\nlet read_pair () = let a = read_int () in (a , read_int ());;\n\nlet n = read_int ();;\n\nlet events = Array.init (2*n) (fun i -> (read_int (),if i land 1 = 0 then 0 else 1));;\n\nlet compare x y = let a , b = x in let c , d = y in if a = c then 0 else if a > c then 1 else -1;;\n\nArray.sort compare events;;\n\nlet ans = ref 0;;\n\nlet () = \n let cnt = ref 0 in\n for i = 0 to (2*n-1) do\n let first , second = events.(i) in \n if second = 1 then begin\n cnt := !cnt - 1;\n if !cnt > 0 then ans := !ans + 1\n else () end\n else cnt := !cnt + 1\n done;;\n\nPrintf.printf \"%d\\n\" !ans;;\n \n"}], "src_uid": "dfb1479ffa17489095b6bf1921758f7e"} {"nl": {"description": "Shakespeare is a widely known esoteric programming language in which programs look like plays by Shakespeare, and numbers are given by combinations of ornate epithets. In this problem we will have a closer look at the way the numbers are described in Shakespeare.Each constant in Shakespeare is created from non-negative powers of 2 using arithmetic operations. For simplicity we'll allow only addition and subtraction and will look for a representation of the given number which requires a minimal number of operations.You are given an integer n. You have to represent it as n\u2009=\u2009a1\u2009+\u2009a2\u2009+\u2009...\u2009+\u2009am, where each of ai is a non-negative power of 2, possibly multiplied by -1. Find a representation which minimizes the value of m.", "input_spec": "The only line of input contains a positive integer n, written as its binary notation. The length of the notation is at most 106. The first digit of the notation is guaranteed to be 1.", "output_spec": "Output the required minimal m. After it output m lines. Each line has to be formatted as \"+2^x\" or \"-2^x\", where x is the power coefficient of the corresponding term. The order of the lines doesn't matter.", "sample_inputs": ["1111", "1010011"], "sample_outputs": ["2\n+2^4\n-2^0", "4\n+2^0\n+2^1\n+2^4\n+2^6"], "notes": null}, "positive_code": [{"source_code": "let s = read_line()\nlet n = String.length s\n\nlet neg = Array.make (n+1) 0\nlet pos = Array.make (n+1) 0\n\nlet bit i = if i>=n then 0 else (int_of_char s.[n-i-1]) - (int_of_char '0')\n\nlet nl = ref []\nlet pl = ref []\n\nlet _ = \n if bit 0 = 1 then (\n pos.(0) <- 1;\n neg.(0) <- 1;\n nl := [-2*n]; (* bit zero is turned on *)\n pl := [ 2*n];\n ) else neg.(0) <- n+1\n\nlet _ =\n for i=1 to n do\n match bit i with \n | 0 ->\n\t if neg.(i-1)+1 < pos.(i-1) then (\n\t pos.(i) <- neg.(i-1)+1;\n\t pl := i::!nl;\n\t ) else \n\t pos.(i) <- pos.(i-1);\n\t neg.(i) <- neg.(i-1)+1;\n\t nl := (-i)::!nl;\n | 1 ->\n\t if pos.(i-1)+1 < neg.(i-1) then (\n\t neg.(i) <- pos.(i-1) + 1;\n\t nl := (-i)::!pl\n\t ) else\n\t neg.(i) <- neg.(i-1);\n\t pos.(i) <- pos.(i-1)+1;\n\t pl := i::!pl;\n | _ -> failwith \"bad bit\"\n done\n\nlet rec print_soln = function [] -> ()\n | h::t -> if h<0 then (\n print_string \"-2^\";\n print_int ((-h) mod (2*n));\n print_char '\\n'\n ) else (\n print_string \"+2^\";\n print_int (h mod (2*n));\n print_char '\\n'\n );\n print_soln t\n;;\n\nPrintf.printf \"%d\\n\" (List.length !pl);\nprint_soln !pl\n"}], "negative_code": [{"source_code": "let read_string () = \n Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet s = read_string()\nlet n = String.length s\n\nlet neg = Array.make (n+1) 0\nlet pos = Array.make (n+1) 0\n\nlet bit i = if i>=n then 0 else (int_of_char s.[n-i-1]) - (int_of_char '0')\n\nlet nl = ref []\nlet pl = ref []\n\nlet _ = \n if bit 0 = 1 then (\n pos.(0) <- 1;\n neg.(0) <- 1;\n nl := [-2*n]; (* bit zero is turned on *)\n pl := [ 2*n];\n ) else neg.(0) <- n+1\n\nlet _ =\n for i=1 to n do\n match bit i with \n | 0 ->\n\t if neg.(i-1)+1 < pos.(i-1) then (\n\t pos.(i) <- neg.(i-1)+1;\n\t pl := i::!nl;\n\t ) else \n\t pos.(i) <- pos.(i-1);\n\t neg.(i) <- neg.(i-1)+1;\n\t nl := (-i)::!nl;\n | 1 ->\n\t if pos.(i-1)+1 < neg.(i-1) then (\n\t neg.(i) <- pos.(i-1) + 1;\n\t nl := (-i)::!pl\n\t ) else\n\t neg.(i) <- neg.(i-1);\n\t pos.(i) <- pos.(i-1)+1;\n\t pl := i::!pl;\n | _ -> failwith \"bad bit\"\n done\n\nlet rec print_soln = function [] -> ()\n | h::t -> if h<0 then \n Printf.printf \"-2^%d\\n\" ((-h) mod (2*n))\n else \n Printf.printf \"+2^%d\\n\" (h mod (2*n));\n print_soln t\n;;\n\nprint_soln !pl\n"}], "src_uid": "212eaa6132f64db29c326cc02b298d52"} {"nl": {"description": "Vladik had started reading a complicated book about algorithms containing n pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation P\u2009=\u2009[p1,\u2009p2,\u2009...,\u2009pn], where pi denotes the number of page that should be read i-th in turn.Sometimes Vladik\u2019s mom sorted some subsegment of permutation P from position l to position r inclusive, because she loves the order. For every of such sorting Vladik knows number x\u00a0\u2014 what index of page in permutation he should read. He is wondered if the page, which he will read after sorting, has changed. In other words, has px changed? After every sorting Vladik return permutation to initial state, so you can assume that each sorting is independent from each other.", "input_spec": "First line contains two space-separated integers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009104)\u00a0\u2014 length of permutation and number of times Vladik's mom sorted some subsegment of the book. Second line contains n space-separated integers p1,\u2009p2,\u2009...,\u2009pn (1\u2009\u2264\u2009pi\u2009\u2264\u2009n)\u00a0\u2014 permutation P. Note that elements in permutation are distinct. Each of the next m lines contains three space-separated integers li, ri, xi (1\u2009\u2264\u2009li\u2009\u2264\u2009xi\u2009\u2264\u2009ri\u2009\u2264\u2009n)\u00a0\u2014 left and right borders of sorted subsegment in i-th sorting and position that is interesting to Vladik.", "output_spec": "For each mom\u2019s sorting on it\u2019s own line print \"Yes\", if page which is interesting to Vladik hasn't changed, or \"No\" otherwise.", "sample_inputs": ["5 5\n5 4 3 2 1\n1 5 3\n1 3 1\n2 4 3\n4 4 4\n2 5 3", "6 5\n1 4 3 2 5 6\n2 4 3\n1 6 2\n4 5 4\n1 3 3\n2 6 3"], "sample_outputs": ["Yes\nNo\nYes\nYes\nNo", "Yes\nNo\nYes\nNo\nYes"], "notes": "NoteExplanation of first test case: [1,\u20092,\u20093,\u20094,\u20095]\u00a0\u2014 permutation after sorting, 3-rd element hasn\u2019t changed, so answer is \"Yes\". [3,\u20094,\u20095,\u20092,\u20091]\u00a0\u2014 permutation after sorting, 1-st element has changed, so answer is \"No\". [5,\u20092,\u20093,\u20094,\u20091]\u00a0\u2014 permutation after sorting, 3-rd element hasn\u2019t changed, so answer is \"Yes\". [5,\u20094,\u20093,\u20092,\u20091]\u00a0\u2014 permutation after sorting, 4-th element hasn\u2019t changed, so answer is \"Yes\". [5,\u20091,\u20092,\u20093,\u20094]\u00a0\u2014 permutation after sorting, 3-rd element has changed, so answer is \"No\". "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read3 _ = bscanf Scanning.stdib \" %d %d %d \" (fun x y z -> (x,y,z)) \nlet () = \n let n = read_int () in\n let m = read_int () in\n let p = Array.init (n+1) (fun i -> if i=0 then 0 else read_int()) in\n let query = Array.init m read3 in\n\n let count_smaller l r x =\n let count_range i j v =\n let c = ref 0 in\n for k=i to j do\n\tif p.(k) < v then c := !c + 1\n done;\n !c\n in\n\n let r1 = r-l+1 in\n let r2 = l-1 + (n-r) in\n if r1 <= r2 then count_range l r p.(x)\n else p.(x) - 1 - ((count_range 1 (l-1) p.(x)) + (count_range (r+1) n p.(x)))\n in\n\n for i=0 to m-1 do\n let (l,r,x) = query.(i) in\n if count_smaller l r x = x-l then printf \"Yes\\n\" else printf \"No\\n\"\n done\n"}], "negative_code": [], "src_uid": "44162a97e574594ac0e598368e8e4e14"} {"nl": {"description": "Little Petya likes to play a lot. Most of all he likes to play a game \u00abHoles\u00bb. This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i\u2009+\u2009ai, then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.", "input_spec": "The first line contains two integers N and M (1\u2009\u2264\u2009N\u2009\u2264\u2009105, 1\u2009\u2264\u2009M\u2009\u2264\u2009105) \u2014 the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N \u2014 initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a 0 a b 1 a a b N", "output_spec": "For each move of the type 1 output two space-separated numbers on a separate line \u2014 the number of the last hole the ball visited before leaving the row and the number of jumps it made.", "sample_inputs": ["8 5\n1 1 1 1 1 2 8 2\n1 1\n0 1 3\n1 1\n0 3 4\n1 2"], "sample_outputs": ["8 7\n8 5\n7 3"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\ntype node = {mutable p: int; mutable d: int; ch: int array; mutable size: int}\n\nclass link_cut_tree n_ = object (self)\n val n = n_\n val a = Array.init (n_+1) (fun i ->\n {p=0; d=2; ch=Array.make 2 0; size=if i = 0 then 0 else 1}\n )\n\n method private pull x =\n a.(x).size <- a.(a.(x).ch.(0)).size + a.(a.(x).ch.(1)).size + 1\n\n method private join x d y =\n if d < 2 then\n a.(x).ch.(d) <- y;\n a.(y).p <- x;\n a.(y).d <- d\n\n method private zag x =\n let y = a.(x).p\n and d = a.(x).d in\n self#join y d a.(x).ch.(1-d);\n self#join a.(y).p a.(y).d x;\n self#join x (1-d) y;\n self#pull y\n\n method private splay x =\n let rec go _ =\n let y = a.(x).p in\n if y <> 0 && a.(x).d < 2 then (\n if a.(y).p <> 0 && a.(y).d < 2 then\n self#zag (if a.(x).d = a.(y).d then y else x);\n self#zag x;\n go ()\n )\n in\n go ();\n self#pull x\n\n method private access x =\n let rec go x y =\n if x <> 0 then (\n self#splay x;\n a.(a.(x).ch.(1)).d <- 2;\n self#join x 1 y;\n go a.(x).p x\n )\n in\n go x 0\n\n method get_root x =\n self#access x;\n self#splay x;\n let rec go x =\n if a.(x).ch.(0) = 0 then\n x\n else\n go a.(x).ch.(0)\n in\n let r = go x in\n self#splay r;\n r\n\n method get_dep x =\n self#access x;\n self#splay x;\n a.(a.(x).ch.(0)).size\n\n method link x y =\n (* self#access y; not necessary if no reverse *)\n self#splay y;\n a.(y).p <- x;\n a.(y).d <- 2;\n self#splay y\n\n method cut x =\n self#access x;\n self#splay x;\n a.(a.(x).ch.(0)).p <- 0;\n a.(a.(x).ch.(0)).d <- 2;\n a.(x).ch.(0) <- 0\n\n method dump =\n for i = 0 to n do\n Printf.printf \"%d: p=%d d=%d l=%d r=%d size=%d\\n\" i a.(i).p a.(i).d\n a.(i).ch.(0) a.(i).ch.(1) a.(i).size\n done\nend\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let t = new link_cut_tree n in\n for i = 1 to n do\n let x = read_int 0 in\n if i+x <= n then\n t#link (i+x) i\n done;\n for i = 1 to m do\n if read_int 0 = 0 then (\n let x = read_int 0 in\n let y = read_int 0 in\n t#cut x;\n t#link (if x+y > n then 0 else x+y) x\n ) else\n let x = read_int 0 in\n Printf.printf \"%d %d\\n\" (t#get_root x) (t#get_dep x + 1)\n done\n"}], "negative_code": [], "src_uid": "72e62f8dab43725ae5f4dd4d73d3d626"} {"nl": {"description": "Today Pari and Arya are playing a game called Remainders.Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value . There are n ancient numbers c1,\u2009c2,\u2009...,\u2009cn and Pari has to tell Arya if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value for any positive integer x?Note, that means the remainder of x after dividing it by y.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n,\u2009 k\u2009\u2264\u20091\u2009000\u2009000)\u00a0\u2014 the number of ancient integers and value k that is chosen by Pari. The second line contains n integers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u20091\u2009000\u2009000).", "output_spec": "Print \"Yes\" (without quotes) if Arya has a winning strategy independent of value of x, or \"No\" (without quotes) otherwise.", "sample_inputs": ["4 5\n2 3 5 12", "2 7\n2 3"], "sample_outputs": ["Yes", "No"], "notes": "NoteIn the first sample, Arya can understand because 5 is one of the ancient numbers.In the second sample, Arya can't be sure what is. For example 1 and 7 have the same remainders after dividing by 2 and 3, but they differ in remainders after dividing by 7."}, "positive_code": [{"source_code": "let rec gcd x y =\n if y == 0 then\n x\n else\n gcd y (x mod y)\n\nlet () =\n match read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string with\n | [n; k] ->\n let c = read_line () |> Str.(split (regexp \" \")) |> List.map int_of_string in\n print_endline (\n if List.(fold_left gcd k (map (fun ci -> k / gcd k ci) c)) == 1 then\n \"Yes\"\n else\n \"No\"\n )\n | _ -> assert false\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet factor n = (* factor n into a list of prime powers *)\n let rec loop n p pow ac =\n let ac' = if pow>1 then (pow::ac) else ac in\n if n=1 then ac'\n else if n mod p = 0 then loop (n/p) p (pow*p) ac\n else loop n (p+1) 1 ac'\n in\n List.rev (loop n 2 1 [])\n \nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f) \n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let k = read_int () in\n let c = Array.init n (fun _ -> read_int()) in\n\n let factors = factor k in\n\n let answer = List.exists (fun p ->\n forall 0 (n-1) (fun i -> c.(i) mod p <> 0)\n ) factors in\n \n if answer then printf \"No\\n\" else printf \"Yes\\n\"\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet factor n = \n let rec loop n p ac = \n if n=1 then ac\n else if p*p > n then (n::ac)\n else if n mod p = 0 then loop (n/p) p (p::ac)\n else loop n (p+1) ac\n in\n List.rev (loop n 2 [])\n \nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f) \n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let k = read_int () in\n let c = Array.init n (fun _ -> read_int()) in\n\n let factors = List.sort_uniq compare (factor k) in\n\n let answer = List.exists (fun p ->\n forall 0 (n-1) (fun i -> c.(i) mod p <> 0)\n ) factors in\n \n if answer then printf \"No\\n\" else printf \"Yes\\n\"\n"}], "src_uid": "e72fa6f8a31c34fd3ca0ce3a3873ff50"} {"nl": {"description": "Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n\u2009-\u20091 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0\u2009\u2264\u2009degreei\u2009\u2264\u2009n\u2009-\u20091, 0\u2009\u2264\u2009si\u2009<\u2009216), separated by a space.", "output_spec": "In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0\u2009\u2264\u2009a\u2009\u2264\u2009n\u2009-\u20091, 0\u2009\u2264\u2009b\u2009\u2264\u2009n\u2009-\u20091), corresponding to edge (a,\u2009b). Edges can be printed in any order; vertices of the edge can also be printed in any order.", "sample_inputs": ["3\n2 3\n1 0\n1 0", "2\n1 1\n1 0"], "sample_outputs": ["2\n1 0\n2 0", "1\n0 1"], "notes": "NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as \"^\", and in Pascal \u2014 as \"xor\"."}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let s = Stack.create () in\n let e = ref [] in\n let a = Array.init n (fun i ->\n let d, x = Scanf.scanf \"%d %d\\n\" (fun d s -> (d, s)) in\n if d = 1 then Stack.push i s;\n (d, x)\n ) in\n while not (Stack.is_empty s) do\n let i = Stack.pop s in\n let d', j = a.(i) in\n if d' = 1 then begin\n e := (i, j) :: !e;\n let d, x = a.(j) in\n a.(j) <- (d - 1, x lxor i);\n if d = 2 then Stack.push j s\n end\n done;\n Printf.printf \"%d\\n\" (List.length !e);\n List.iter (fun (a, b) -> Printf.printf \"%d %d\\n\" a b) !e\n)\n"}, {"source_code": "type el = {\n i : int; (* node index *)\n mutable d : int; (* node degree *)\n mutable s : int; (* xor sum of neighbours *)\n}\n\nmodule H : sig\n type t\n val make : int -> t\n val add : t -> el -> unit\n val dec : t -> int -> unit\n val is_empty : t -> bool\n val pop : t -> el\n val get : t -> int -> el * int\nend = struct\n type t = {\n mutable len : int;\n arr : el array;\n rev : int array;\n }\n\n let is_empty h = h.len = 0\n\n let make n = {\n len = 0;\n arr = Array.make n { i = -1; d = 0; s = 0 };\n rev = Array.make n 0;\n }\n\n let get h i =\n let j = h.rev.(i) in\n (h.arr.(j), j)\n\n let swap h i j =\n let e = h.arr.(i)\n and f = h.arr.(j) in\n h.arr.(i) <- f;\n h.arr.(j) <- e;\n h.rev.(e.i) <- j;\n h.rev.(f.i) <- i\n\n let rec dec h i =\n if i = 0 then ()\n else begin\n (* get parent *)\n let p = (i - 1) / 2 in\n (* if the child has smaller degree than parent *)\n if h.arr.(p).d > h.arr.(i).d then begin\n swap h i p;\n dec h p\n end\n end\n\n let rec inc h i =\n let l = 2 * i + 1\n and r = 2 * i + 2 in\n\n (* no children *)\n if l >= h.len then ()\n\n (* only left child *)\n else if r >= h.len then begin\n if h.arr.(i).d > h.arr.(l).d then begin\n swap h i l;\n inc h l\n end\n end\n\n (* both children *)\n else begin\n if h.arr.(i).d > h.arr.(l).d then\n (* right child is smallest *)\n if h.arr.(l).d > h.arr.(r).d then begin\n swap h i r;\n inc h r\n (* left child is smallest *)\n end else begin\n swap h i l;\n inc h l\n end\n (* right child is smaller *)\n else if h.arr.(i).d > h.arr.(r).d then begin\n swap h i r;\n inc h r\n end\n end\n\n let add h e =\n (* insert the element at the end of the heap *)\n h.arr.(h.len) <- e;\n h.rev.(e.i) <- h.len;\n\n (* bubble up to enforce the heap constraint *)\n dec h h.len;\n h.len <- h.len + 1\n\n let pop h =\n let e = h.arr.(0) in\n h.len <- h.len - 1;\n\n (* move the last element to the top *)\n swap h 0 h.len;\n\n (* bubble down *)\n inc h 0;\n\n (* return the element *)\n e\nend\n\nlet () = Scanf.scanf \"%d\\n\" (fun n ->\n let nodes = H.make n in\n let edges = ref [] in\n\n (* read nodes and populate the heap *)\n for i = 0 to n - 1 do\n let d, s = Scanf.scanf \"%d %d\\n\" (fun d s -> (d, s)) in\n let el = { i; d; s } in\n H.add nodes el\n done;\n\n while not (H.is_empty nodes) do\n let e = H.pop nodes in\n match e.d with\n | 0 -> () (* isolated node; no edges *)\n\n | 1 -> (* leaf node, add edge to list *)\n edges := (e.i, e.s) :: !edges;\n let f, j = H.get nodes e.s in\n f.s <- f.s lxor e.i;\n f.d <- f.d - 1;\n H.dec nodes j;\n\n | _ -> failwith \"Cycle detected\"\n done;\n\n Printf.printf \"%d\\n\" (List.length !edges);\n List.iter (fun (a, b) -> Printf.printf \"%d %d\\n\" a b) !edges\n)\n"}], "negative_code": [], "src_uid": "14ad30e33bf8cad492e665b0a486008e"} {"nl": {"description": "Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price \u2014 their owners are ready to pay Bob if he buys their useless apparatus. Bob can \u00abbuy\u00bb any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009m\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai (\u2009-\u20091000\u2009\u2264\u2009ai\u2009\u2264\u20091000) \u2014 prices of the TV sets. ", "output_spec": "Output the only number \u2014 the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.", "sample_inputs": ["5 3\n-6 0 35 -2 4", "4 2\n7 0 0 -7"], "sample_outputs": ["8", "7"], "notes": null}, "positive_code": [{"source_code": "let rec input_tv = function\n | 0 -> []\n | i -> (Scanf.scanf \" %d\" (fun x -> x)) :: input_tv (i-1)\n\nlet solve n m =\n let tv = List.sort compare (input_tv n) in\n let rec loop i tv =\n match i with\n | 0 -> 0\n | i ->\n let current = List.hd tv in\n if current > 0 then 0\n else current + (loop (i-1) (List.tl tv))\n in\n -(loop m tv)\n\nlet _ =\n Printf.printf \"%d\\n\" (Scanf.scanf \" %d %d\" solve)\n \n"}], "negative_code": [{"source_code": "let rec input_tv = function\n | 0 -> []\n | i -> (Scanf.scanf \" %d\" (fun x -> x)) :: input_tv (i-1)\n\nlet solve n m =\n let tv = List.sort compare (input_tv n) in\n let rec loop i tv =\n match i with\n | 0 -> 0\n | i ->\n (List.hd tv) + (loop (i-1) (List.tl tv))\n in\n -(loop m tv)\n\nlet _ =\n Printf.printf \"%d\\n\" (Scanf.scanf \" %d %d\" solve)\n \n"}], "src_uid": "9a56288d8bd4e4e7ef3329e102f745a5"} {"nl": {"description": "You are given an integer $$$n$$$. You have to change the minimum number of digits in it in such a way that the resulting number does not have any leading zeroes and is divisible by $$$7$$$.If there are multiple ways to do it, print any of them. If the given number is already divisible by $$$7$$$, leave it unchanged.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 990$$$) \u2014 the number of test cases. Then the test cases follow, each test case consists of one line containing one integer $$$n$$$ ($$$10 \\le n \\le 999$$$).", "output_spec": "For each test case, print one integer without any leading zeroes \u2014 the result of your changes (i.\u2009e. the integer that is divisible by $$$7$$$ and can be obtained by changing the minimum possible number of digits in $$$n$$$). If there are multiple ways to apply changes, print any resulting number. If the given number is already divisible by $$$7$$$, just print it.", "sample_inputs": ["3\n42\n23\n377"], "sample_outputs": ["42\n28\n777"], "notes": "NoteIn the first test case of the example, $$$42$$$ is already divisible by $$$7$$$, so there's no need to change it.In the second test case of the example, there are multiple answers \u2014 $$$28$$$, $$$21$$$ or $$$63$$$.In the third test case of the example, other possible answers are $$$357$$$, $$$371$$$ and $$$378$$$. Note that you cannot print $$$077$$$ or $$$77$$$."}, "positive_code": [{"source_code": "open Printf\r\nopen Scanf\r\n\r\n\r\nlet solve_one = (\r\n)\r\n\r\nlet remove_last s = (String.sub s 0 ((String.length s) - 1))\r\n\r\nlet find_div7 s = \r\n let rec find_div7_try k =\r\n if k == 10 then 0\r\n else if ((s * 10 + k) mod 7) == 0 then (s * 10 + k)\r\n else find_div7_try (k + 1) in\r\n find_div7_try 0\r\n\r\nlet rec solve t =\r\n if t > 0 then (\r\n let s = read_line() in\r\n let v = int_of_string s in\r\n (\r\n if v mod 7 == 0 then v\r\n else find_div7 (int_of_string (remove_last s))\r\n )\r\n |> string_of_int\r\n |> print_endline;\r\n solve (t - 1)\r\n )\r\n else ()\r\n\r\nlet () = \r\n let t = int_of_string (read_line()) in\r\n solve t\r\n"}, {"source_code": "Scanf.scanf \"%d\" (fun t ->\n for i = 1 to t do\n Printf.printf \"%d\\n\" (\n Scanf.scanf \" %d\" (fun n ->\n if n mod 7 = 0 then n else\n let n2 = n / 10 * 10 in\n let rec loop i =\n if (n2 + i) mod 7 = 0 then n2 + i else loop (i + 1)\n in\n loop 0\n )\n )\n done\n)\n"}], "negative_code": [{"source_code": "open Printf\r\nopen Scanf\r\n\r\n\r\nlet solve_one = (\r\n)\r\n\r\nlet remove_last s = (String.sub s 0 ((String.length s) - 1))\r\n\r\nlet find_div7 s = \r\n let rec find_div7_try k =\r\n if k == 10 then 0\r\n else if ((s * 10 + k) mod 7) == 0 then (s * 10 + k)\r\n else find_div7_try (k + 1) in\r\n find_div7_try 0\r\n\r\nlet rec solve t =\r\n if t > 0 then (\r\n let s = read_line() in\r\n print_endline (string_of_int (find_div7 (int_of_string (remove_last s))));\r\n solve (t - 1)\r\n )\r\n else ()\r\n\r\nlet () = \r\n let t = int_of_string (read_line()) in\r\n solve t\r\n"}], "src_uid": "128372d890f632494e59e81287abd85a"} {"nl": {"description": "You are given an array $$$a$$$ of $$$n$$$ integers. Find the number of pairs $$$(i, j)$$$ ($$$1 \\le i < j \\le n$$$) where the sum of $$$a_i + a_j$$$ is greater than or equal to $$$l$$$ and less than or equal to $$$r$$$ (that is, $$$l \\le a_i + a_j \\le r$$$).For example, if $$$n = 3$$$, $$$a = [5, 1, 2]$$$, $$$l = 4$$$ and $$$r = 7$$$, then two pairs are suitable: $$$i=1$$$ and $$$j=2$$$ ($$$4 \\le 5 + 1 \\le 7$$$); $$$i=1$$$ and $$$j=3$$$ ($$$4 \\le 5 + 2 \\le 7$$$). ", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n, l, r$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$1 \\le l \\le r \\le 10^9$$$)\u00a0\u2014 the length of the array and the limits on the sum in the pair. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ overall test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, output a single integer\u00a0\u2014 the number of index pairs $$$(i, j)$$$ ($$$i < j$$$), such that $$$l \\le a_i + a_j \\le r$$$.", "sample_inputs": ["4\n3 4 7\n5 1 2\n5 5 8\n5 1 2 4 3\n4 100 1000\n1 1 1 1\n5 9 13\n2 5 5 1 1"], "sample_outputs": ["2\n7\n0\n1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int () in\n let l = read_long () in\n let r = read_long () in\n let a = Array.init n read_long in\n Array.sort compare a;\n\n let rec scan i v w count = if i=n then count else (\n let rec loopv v = if v <= 0 then v else (\n\tif a.(i) ++ a.(v-1) >= l then loopv (v-1) else v\n ) in\n let v = loopv v in\n\n let rec loopw w = if w < 0 then w else (\n\tif a.(i) ++ a.(w) > r then loopw (w-1) else w\n ) in\n let w = loopw w in\n if a.(i) ++ a.(v) < l then scan (i+1) v w count\n else if w < 0 then count else (\n\tlet count = count ++ (long (max (w-v+1) 0)) in\n\tscan (i+1) v w count\n )\n ) in\n\n let count = scan 0 (n-1) (n-1) 0L in\n let diag = sum 0 (n-1) (fun i -> if a.(i) ++ a.(i) <= r && a.(i) ++ a.(i) >= l then 1 else 0) in\n let answer = (count -- (long diag))//2L in\n printf \"%Ld\\n\" answer\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int () in\n let l = read_long () in\n let r = read_long () in\n let a = Array.init n read_long in\n Array.sort compare a;\n\n let findv i =\n (* return Some v if a.(i) + a.(v) >= l and v is the smallest such index.\n\t None if there is no such index *)\n let rec bsearch lo hi =\n (* know that a.(i) + a.(hi) >= l and a.(i) + a.(lo) < l *)\n\tif hi = lo+1 then hi else\n\t let m = (lo+hi)/2 in\n\t if a.(i) ++ a.(m) < l then bsearch m hi else bsearch lo m\n in\n if a.(i) ++ a.(n-1) < l then None\n else if a.(i) ++ a.(0) >= l then Some 0\n else Some (bsearch 0 (n-1))\n in\n\n let findw i =\n (* return Some v if a.(i) + a.(v) <= r and v is the largest such index.\n\t None if there is no such index *)\n let rec bsearch lo hi =\n (* know that a.(i) + a.(hi) > r and a.(i) + a.(lo) <= r *)\n\tif hi = lo+1 then lo else\n\t let m = (lo+hi)/2 in\n\t if a.(i) ++ a.(m) <= r then bsearch m hi else bsearch lo m\n in\n if a.(i) ++ a.(0) > r then None\n else if a.(i) ++ a.(n-1) <= r then Some (n-1)\n else Some (bsearch 0 (n-1))\n in\n\n let count = sum 0 (n-1) (fun i ->\n match (findv i, findw i) with\n\t| (None, _) | (_, None) -> 0\n\t| (Some v, Some w) -> max (w-v+1) 0\n ) in\n\n if n <= 1 then printf \"0\\n\" else (\n let diag = sum 0 (n-1) (fun i -> if a.(i) ++ a.(i) <= r && a.(i) ++ a.(i) >= l then 1 else 0) in\n let answer = (count - diag)/2 in\n printf \"%d\\n\" answer\n )\n done\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int () in\n let l = read_long () in\n let r = read_long () in\n let a = Array.init n read_long in\n Array.sort compare a;\n\n let findv i =\n (* return Some v if a.(i) + a.(v) >= l and v is the smallest such index.\n\t None if there is no such index *)\n let rec bsearch lo hi =\n (* know that a.(i) + a.(hi) >= l and a.(i) + a.(lo) < l *)\n\tif hi = lo+1 then hi else\n\t let m = (lo+hi)/2 in\n\t if a.(i) ++ a.(m) < l then bsearch m hi else bsearch lo m\n in\n if a.(i) ++ a.(n-1) < l then None\n else if a.(i) ++ a.(0) >= l then Some 0\n else Some (bsearch 0 (n-1))\n in\n\n let findw i =\n (* return Some v if a.(i) + a.(v) <= r and v is the largest such index.\n\t None if there is no such index *)\n let rec bsearch lo hi =\n (* know that a.(i) + a.(hi) >= r and a.(i) + a.(lo) < r *)\n\tif hi = lo+1 then hi else\n\t let m = (lo+hi)/2 in\n\t if a.(i) ++ a.(m) < r then bsearch m hi else bsearch lo m\n in\n if a.(i) ++ a.(0) > r then None\n else if a.(i) ++ a.(n-1) <= r then Some (n-1)\n else Some (bsearch 0 (n-1))\n in\n\n let count = sum 0 (n-1) (fun i ->\n match (findv i, findw i) with\n\t| (None, _) | (_, None) -> 0\n\t| (Some v, Some w) -> max (w-v+1) 0\n ) in\n\n if n <= 1 then printf \"0\\n\" else (\n let diag = sum 0 (n-1) (fun i -> if a.(i) ++ a.(i) <= r && a.(i) ++ a.(i) >= l then 1 else 0) in\n \n let answer = (count - diag)/2 in\n printf \"%d\\n\" answer\n )\n done\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0 \n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int () in\n let l = read_long () in\n let r = read_long () in\n let a = Array.init n read_long in\n Array.sort compare a;\n\n let rec scan i v w count = if i=n then count else (\n let rec loopv v = if v <= 0 then v else (\n\tif a.(i) ++ a.(v-1) >= l then loopv (v-1) else v\n ) in\n let v = loopv v in\n\n let rec loopw w = if w < 0 then w else (\n\tif a.(i) ++ a.(w) > r then loopw (w-1) else w\n ) in\n let w = loopw w in\n if a.(i) ++ a.(v) < l then scan (i+1) v w count\n else if w < 0 then count else (\n\tlet count = count + max (w-v+1) 0 in\n\tscan (i+1) v w count\n )\n ) in\n\n let count = scan 0 (n-1) (n-1) 0 in\n let diag = sum 0 (n-1) (fun i -> if a.(i) ++ a.(i) <= r && a.(i) ++ a.(i) >= l then 1 else 0) in\n let answer = (count - diag)/2 in\n printf \"%d\\n\" answer\n done\n"}], "src_uid": "2f12b2bb23497119bb70ca0839991d68"} {"nl": {"description": "Luyi has n circles on the plane. The i-th circle is centered at (xi,\u2009yi). At the time zero circles start to grow simultaneously. In other words, the radius of each circle at time t (t\u2009>\u20090) is equal to t. The circles are drawn as black discs on an infinite white plane. So at each moment the plane consists of several black and white regions. Note that the circles may overlap while growing. We define a hole as a closed, connected white region. For instance, the figure contains two holes shown by red border. During growing some holes may be created and it is easy to see that each created hole will disappear eventually. Luyi asks you to find moment of time such that the last hole disappears. In other words, you should find the first moment such that no hole can be seen after that.", "input_spec": "The first line of the input contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Each of the next n lines contains two integers xi and yi (\u2009-\u2009104\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009104), indicating the location of i-th circle. It's guaranteed that no two circles are centered at the same point.", "output_spec": "Print the moment where the last hole disappears. If there exists no moment in which we can find holes print -1. The answer will be considered correct if the absolute or relative error does not exceed 10\u2009-\u20094.", "sample_inputs": ["3\n0 0\n1 1\n2 2", "4\n0 0\n0 2\n2 2\n2 0", "4\n0 1\n0 -1\n-2 0\n4 0"], "sample_outputs": ["-1", "1.414214", "2.125000"], "notes": null}, "positive_code": [{"source_code": "let ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\n(* http://www.cs.cmu.edu/~quake/robust.html *)\n\nlet sq x = x ** x\n\nlet det ((a,b,c),(d,e,f),(g,h,i)) = \n a**(e**i -- f**h) -- b**(d**i -- f**g) ++ c**(d**h -- e**g)\n\n(* This returns 0 if the four points are on the same circle.\n It returns >0 if going around the circle in the direction\n a --> b --> c then d is on the side of the circle pointed\n to by my left hand. It returns >0 otherwise. It's a fourth\n degree function in the given coordinates. *)\n\nlet incircle (ax,ay) (bx,by) (cx,cy) (dx,dy) = \n let row ax dx ay dy = \n let a = ax -- dx in\n let b = ay -- dy in\n (a, b, (sq a) ++ (sq b))\n in\n det (row ax dx ay dy, row bx dx by dy, row cx dx cy dy)\n\nlet (---) (x1,y1) (x2,y2) = (x1--x2, y1--y2);;\nlet (+++) (x1,y1) (x2,y2) = (x1++x2, y1++y2);;\nlet cross (x1,y1) (x2,y2) = (x1**y2) -- (y1**x2);;\nlet dot (x1,y1) (x2,y2) = (x1**x2) ++ (y1**y2);;\n\n(* radius of a circle given three points from\n http://en.wikipedia.org/wiki/Circumscribed_circle *)\n\nlet length (x,y) = \n let (x,y) = (Int64.to_float x, Int64.to_float y) in\n sqrt (x*.x +. y*.y)\n\nlet radius a b c = \n let a = a --- c in\n let b = b --- c in\n (length a) *. (length b) *. (length (a --- b)) /. \n (2.0 *. (abs_float (Int64.to_float (cross a b))))\n\n(* this returns >0 if c on the left side of a-->b, <0 if on the right, and 0 if on. *)\nlet leftside a b c = cross (a---c) (b---c)\n\n\n(* The following function takes a list of points as input, and returns true\n if it's smooth, that is, if none of the angles as we walk around the points\n subsumes more than half of the circle *)\nlet smooth_set a = \n let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) in\n let sum i j f = fold i j (fun i a -> (f i) +. a) 0.0 in\n let float_of_array a n =\n Array.init n (fun i -> let (xi, yi) = a.(i) in (Int64.to_float xi, Int64.to_float yi))\n in\n\n let a = Array.of_list a in\n let n = Array.length a in\n let af = float_of_array a n in\n let cx = (sum 0 (n-1) (fun i -> fst af.(i))) /. (float n) in\n let cy = (sum 0 (n-1) (fun i -> snd af.(i))) /. (float n) in\n let ang = Array.init n (fun i -> (atan2 ((fst af.(i) -. cx)) ((snd af.(i)) -. cy), i)) in\n let () = Array.sort compare ang in\n\n let rec loop i = i=n || (\n let j1 = snd ang.(i) in\n let j2 = snd (ang.((i+1) mod n)) in\n let j3 = snd (ang.((i+2) mod n)) in\n let v1 = a.(j3) --- a.(j1) in\n let v2 = a.(j2) --- a.(j3) in\n dot v1 v2 < 0L && loop (i+1)\n ) in\n loop 0\n\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = Scanf.bscanf Scanf.Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_pair _ = let u = read_long() in (u, read_long())\n\nlet print_smooth_set s = \n Printf.printf \"smooth set: \";\n List.iter (fun (x,y) -> Printf.printf \"(%Ld,%Ld) \" x y) s;\n print_newline()\n\nlet () = \n let n = read_int() in\n let c = Array.init n read_pair in\n \n let bestr = ref (-1.0) in\n \n for i=0 to n-1 do\n for j=0 to n-1 do\n\tif i <> j then (\n\t let prev = ref (-1) in\n\t for k=0 to n-1 do\n\t if k <> i && k <> j && (leftside c.(i) c.(j) c.(k) > 0L) then (\n\t\tif !prev = -1 || (incircle c.(i) c.(j) c.(!prev) c.(k)) > 0L then prev := k\n\t )\n\t done;\n\t if !prev >0 then (\n\t let bad = ref false in\n\t let onlist = ref [] in\n\t\tfor k=0 to n-1 do\n\t\t let cval = incircle c.(i) c.(j) c.(!prev) c.(k) in\n\t\t if cval = 0L then onlist := c.(k) :: !onlist\n\t\t else if cval > 0L then bad := true\n\t\tdone;\n\t\tif (not !bad) && (smooth_set !onlist) then (\n(*\t\t print_smooth_set !onlist; *)\n\t\t let r = radius c.(i) c.(j) c.(!prev) in\n\t\t bestr := max r !bestr\n\t\t)\n\t )\n\t)\n done\n done;\n \n if !bestr < 0.0 then Printf.printf \"-1\\n\" else Printf.printf \"%.6f\\n\" !bestr\n"}, {"source_code": "(* O(n^2) Delaunay triangulation algorithm *)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\n(* http://www.cs.cmu.edu/~quake/robust.html *)\n\n(* This returns 0 if the four points are on the same circle.\n It returns >0 if going around the circle in the direction\n a --> b --> c then d is on the side of the circle pointed\n to by my left hand. It returns >0 otherwise. It's a fourth\n degree function in the given coordinates. *)\n\nlet (---) (x1,y1) (x2,y2) = (x1--x2, y1--y2);;\nlet (+++) (x1,y1) (x2,y2) = (x1++x2, y1++y2);;\nlet cross (x1,y1) (x2,y2) = (x1**y2) -- (y1**x2);;\nlet dot (x1,y1) (x2,y2) = (x1**x2) ++ (y1**y2);;\nlet sq x = x ** x\nlet length (x,y) = \n let (x,y) = (Int64.to_float x, Int64.to_float y) in\n sqrt (x*.x +. y*.y)\n\nlet incircle (ax,ay) (bx,by) (cx,cy) (dx,dy) = \n let det ((a,b,c),(d,e,f),(g,h,i)) = \n a**(e**i -- f**h) -- b**(d**i -- f**g) ++ c**(d**h -- e**g)\n in\n\n let row ax dx ay dy = \n let a = ax -- dx in\n let b = ay -- dy in\n (a, b, (sq a) ++ (sq b))\n in\n det (row ax dx ay dy, row bx dx by dy, row cx dx cy dy)\n\n(* radius of a circle given three points from\n http://en.wikipedia.org/wiki/Circumscribed_circle *)\n\nlet radius a b c = \n let a = a --- c in\n let b = b --- c in\n (length a) *. (length b) *. (length (a --- b)) /. \n (2.0 *. (abs_float (Int64.to_float (cross a b))))\n\n(* this returns >0 if c on the left side of a-->b, <0 if on the right, and 0 if on. *)\nlet leftside a b c = cross (a---c) (b---c)\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\n(* takes as input an array of p of n points, and computes\n the Delaunay triangulation of them *)\nlet delaunay p n = \n\n let len2 (px,py) (qx,qy) = (sq (px--qx)) ++ (sq (py--qy)) in\n\n let rec closest (i,j) (bi,bj) dist = \n if j=n then (bi,bj) else\n let d = len2 p.(i) p.(j) in\n let next = if i+1j vector\n with the normalized j-->k vector, and sort it in decreasing order. *)\n let v = Array.make (nv-2) (0.0, 0) in\n let rec loadv k li = match li with [] -> () | h::li ->\n let a = p.(j) --- p.(i) in\n let b = p.(h) --- p.(j) in\n let dp = (Int64.to_float (dot a b)) /. (length b) in\n\tv.(k) <- (dp, h);\n\tloadv (k+1) li\n in\n loadv 0 face;\n Array.sort (fun a b -> compare b a) v;\n Array.init nv (fun k -> if k=0 then i else if k=1 then j else snd v.(k-2))\n in\n\n let rec loop (completed,todo) ac =\n match todo with \n | [] -> ac\n | (i,j)::todo ->\n\t if Pset.mem (i,j) completed then loop (completed,todo) ac else\n\t let rec findface ac k = if k=n then ac else \n\t if k = i || k = j || (leftside p.(i) p.(j) p.(k) <= 0L) then findface ac (k+1) else \n\t\tif ac = [] then findface [k] (k+1) else \n\t\t let ic = incircle p.(i) p.(j) p.(List.hd ac) p.(k) in\n\t\t if ic > 0L then findface [k] (k+1)\n\t\t else if ic = 0L then findface (k::ac) (k+1)\n\t\t else findface ac (k+1)\n\t in\n\t let face = findface [] 0 in\n\n\t if face = [] then loop (Pset.add (i,j) completed, todo) ac (* convex hull edge *)\n\t else (\n\t\tlet nv = 2 + (List.length face) in\n\t\tlet v = order_face i j face nv in\n\t\tlet rec process_face k (s,t) = if k = nv then (s,t) else\n\t\t let l = (k+1) mod nv in\n\t\t let s = Pset.add (v.(k), v.(l)) s in\n\t\t let t = (v.(l), v.(k)) :: t in\n\t\t process_face (k+1) (s,t)\n\t\tin\n\t\t loop (process_face 0 (completed,todo)) (v::ac)\n\t )\n in \n loop (Pset.empty, [(bi,bj); (bj,bi)]) []\n\n(*----------------------------------------------------------------------*)\n\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = Scanf.bscanf Scanf.Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_pair _ = let u = read_long() in (u, read_long())\n\nlet () = \n let n = read_int() in\n let p = Array.init n read_pair in\n\n (* The following function takes an array of indices on a circle as input,\n and returns true if it's smooth, that is, if the polygon strictly \n contains the center. *)\n let smooth_set a n = \n let rec loop i = i=n || (\n let j1 = a.(i) in\n let j2 = a.((i+1) mod n) in\n let j3 = a.((i+2) mod n) in\n let v1 = p.(j3) --- p.(j1) in\n let v2 = p.(j2) --- p.(j3) in\n\tdot v1 v2 < 0L && loop (i+1)\n ) in\n loop 0\n in\n\n let rec loop bestr f = match f with [] -> bestr\n | a::f -> \n\tlet nv = Array.length a in\n\tlet bestr = if smooth_set a nv then \n\t max bestr (radius p.(a.(0)) p.(a.(1)) p.(a.(2))) else bestr\n\tin\n\t loop bestr f\n in\n let bestr = loop (-1.0) (delaunay p n) in\n if bestr < 0.0 then Printf.printf \"-1\\n\" else Printf.printf \"%.6f\\n\" bestr\n"}], "negative_code": [], "src_uid": "8b1129d61855e558e4153e9c07427ffd"} {"nl": {"description": "There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a,\u2009b).Each of the three horses can paint the special cards. If you show an (a,\u2009b) card to the gray horse, then the horse can paint a new (a\u2009+\u20091,\u2009b\u2009+\u20091) card. If you show an (a,\u2009b) card, such that a and b are even integers, to the white horse, then the horse can paint a new card. If you show two cards (a,\u2009b) and (b,\u2009c) to the gray-and-white horse, then he can paint a new (a,\u2009c) card.Polycarpus really wants to get n special cards (1,\u2009a1), (1,\u2009a2), ..., (1,\u2009an). For that he is going to the horse land. He can take exactly one (x,\u2009y) card to the horse land, such that 1\u2009\u2264\u2009x\u2009<\u2009y\u2009\u2264\u2009m. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards?Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires.", "input_spec": "The first line contains two integers n,\u2009m (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20092\u2009\u2264\u2009m\u2009\u2264\u2009109). The second line contains the sequence of integers a1,\u2009a2,\u2009...,\u2009an (2\u2009\u2264\u2009ai\u2009\u2264\u2009109). Note, that the numbers in the sequence can coincide. The numbers in the lines are separated by single spaces.", "output_spec": "Print a single integer \u2014 the answer to the problem. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["1 6\n2", "1 6\n7", "2 10\n13 7"], "sample_outputs": ["11", "14", "36"], "notes": null}, "positive_code": [{"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec show_int_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_int x; print_string \" \"; show_int_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if y = 0 then x else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet calc x =\n let m = Int64.of_int m in\n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (Int64.add acc (Int64.sub m x)) (Int64.add x x) in\n aux (Int64.zero) (Int64.of_int x)\n\nlet get_dvsr () = \n let up = iof (sqrt (foi d)) in\n let rec aux n acc = \n\tif n > up then acc\n\telse \n\t if d mod n = 0 then \n\t\tif n * n <> d then aux (n + 1) (n :: (d/n) :: acc)\n\t\telse aux (n + 1) (n :: acc)\n\t else \n\t\taux (n + 1) acc\n in\n aux 1 []\n\nlet () =\n Printf.printf \"%Ld\" ( \n\tList.filter (fun x -> x mod 2 = 1) (get_dvsr () )\n\t\t\t\t\t\t |> List.fold_left (fun acc y -> Int64.add acc (calc y)) Int64.zero)\n\t\n\n\n \n"}, {"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec show_int_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_int x; print_string \" \"; show_int_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if y = 0 then x else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet calc x =\n let m = Int64.of_int m in\n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (Int64.add acc (Int64.sub m x)) (Int64.add x x) in\n aux (Int64.zero) (Int64.of_int x)\n\nlet get_dvsr () = \n let up = iof (sqrt (foi d)) in\n let rec aux n acc = \n\tif n > up then acc\n\telse \n\t if d mod n = 0 then \n\t\tif n * n <> d then aux (n + 1) (n :: (d/n) :: acc)\n\t\telse aux (n + 1) (n :: acc)\n\t else \n\t\taux (n + 1) acc\n in\n aux 1 []\n\nlet () =\n List.filter (fun x -> x mod 2 = 1) (get_dvsr () )\n\t|> List.fold_left (fun acc y -> Int64.add acc (calc y)) Int64.zero\n\t|> Printf.printf \"%Ld\"\n\t\n\n\n \n"}, {"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec show_int_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_int x; print_string \" \"; show_int_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if x mod y = 0 then y else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet calc x =\n let m = Int64.of_int m in\n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (Int64.add acc (Int64.sub m x)) (Int64.add x x) in\n aux (Int64.zero) (Int64.of_int x)\n\nlet get_dvsr () = \n let up = iof (sqrt (foi d)) in\n let rec aux n acc = \n\tif n > up then acc\n\telse \n\t if d mod n = 0 then \n\t\tif n * n <> d then aux (n + 1) (n :: (d/n) :: acc)\n\t\telse aux (n + 1) (n :: acc)\n\t else \n\t\taux (n + 1) acc\n in\n aux 1 []\n\nlet () =\n List.filter (fun x -> x mod 2 = 1) (get_dvsr () )\n\t|> List.fold_left (fun acc y -> Int64.add acc (calc y)) Int64.zero\n\t|> Printf.printf \"%Ld\"\n\t\n\n\n \n"}, {"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec show_int_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_int x; print_string \" \"; show_int_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if x mod y = 0 then y else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n(* let () = \n print_newline(); print_int n; print_newline (); print_int m; print_newline()\n*)\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet chk y = \n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (acc + m - x) (2 * x) in\n aux 0 y\n\nlet calc x =\n let m = Int64.of_int m in\n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (Int64.add acc (Int64.sub m x)) (Int64.add x x) in\n aux (Int64.zero) (Int64.of_int x)\n\nlet get_dvsr () = \n let up = iof (sqrt (foi d)) in\n let rec aux n acc = \n\tif n > up then acc\n\telse \n\t if d mod n = 0 then \n\t\tif n * n <> d then aux (n + 1) (n :: (d/n) :: acc)\n\t\telse aux (n + 1) (n :: acc)\n\t else \n\t\taux (n + 1) acc\n in\n aux 1 []\n\nlet () =\n Printf.printf \"%Ld\" ( \n\tList.filter (fun x -> x mod 2 = 1) (get_dvsr () )\n\t\t\t\t\t\t |> List.map calc\n\t\t\t\t\t\t |> List.fold_left (fun x y -> Int64.add x y) Int64.zero) \n\t\n\n\n \n"}], "negative_code": [{"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if x mod y = 0 then y else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n(* let () = \n print_newline(); print_int n; print_newline (); print_int m; print_newline()\n*)\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet chk y = \n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (acc + m - x) (2 * x) in\n aux 0 y\n\nlet calc x = \n let mm = Int64.of_int (min m 800000000) in\n let rec aux acc x = \n\tif x >= mm then acc\n\telse aux (Int64.add acc (Int64.sub mm x)) (Int64.add x x) in\n aux (Int64.zero) (Int64.of_int x)\n\n\nlet () =\n Printf.printf \"%Ld\" (List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)\n\t|> List.map calc \n\t|> List.fold_left (fun x y -> Int64.add x y) Int64.zero) \n\t\n\n\n \n"}, {"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if x mod y = 0 then y else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n(* let () = \n print_newline(); print_int n; print_newline (); print_int m; print_newline()\n*)\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet chk y = \n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (acc + m - x) (2 * x) in\n aux 0 y\n\nlet calc x = \n let mm = min m 500000011 in\n let rec aux acc x = \n\tif x >= mm then acc\n\telse aux (acc +. foi (mm - x)) (2 * x) in\n aux 0. x\n\n\nlet () =\n Printf.printf \"%.0f\" (List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)\n\t|> List.map calc \n\t|> List.fold_left (+.) 0.) \n\t\n\n\n \n"}, {"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if x mod y = 0 then y else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n(* let () = \n print_newline(); print_int n; print_newline (); print_int m; print_newline()\n*)\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet chk y = \n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (acc + m - x) (2 * x) in\n aux 0 y\n\nlet calc x = \n let mm = min m 1000011 in\n let rec aux acc x = \n\tif x >= mm then acc\n\telse aux (acc + mm - x) (2 * x) in\n aux 0 x\n\n\nlet () =\n List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)\n\t|> List.map calc \n\t|> List.fold_left (+) 0 \n\t|> print_int\n\n\n \n"}, {"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if x mod y = 0 then y else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n(* let () = \n print_newline(); print_int n; print_newline (); print_int m; print_newline()\n*)\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet chk y = \n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (acc + m - x) (2 * x) in\n aux 0 y\n\nlet calc x = \n let mm = min m 10011 in\n let rec aux acc x = \n\tif x >= mm then acc\n\telse aux (acc + mm - x) (2 * x) in\n aux 0 x\n\n\nlet () =\n List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)\n\t|> List.map calc \n\t|> List.fold_left (+) 0 \n\t|> print_int\n\n\n \n"}, {"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if x mod y = 0 then y else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n(* let () = \n print_newline(); print_int n; print_newline (); print_int m; print_newline()\n*)\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet chk y = \n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (acc + m - x) (2 * x) in\n aux 0 y\n\nlet calc x = \n let mm = min m 100000011 in\n let rec aux acc x = \n\tif x >= mm then acc\n\telse aux (acc + mm - x) (2 * x) in\n aux 0 x\n\n\nlet () =\n List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)\n\t|> List.map calc \n\t|> List.fold_left (+) 0 \n\t|> print_int\n\n\n \n"}, {"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if x mod y = 0 then y else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n(* let () = \n print_newline(); print_int n; print_newline (); print_int m; print_newline()\n*)\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet chk y = \n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (acc + m - x) (2 * x) in\n aux 0 y\n\nlet calc x = \n let mm = min m 500000011 in\n let rec aux acc x = \n\tif x >= mm then acc\n\telse aux (acc + mm - x) (2 * x) in\n aux 0 x\n\n\nlet () =\n List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)\n\t|> List.map calc \n\t|> List.fold_left (+) 0 \n\t|> print_int\n\n\n \n"}, {"source_code": "let ( |> ) x f = f x\nlet ( <| ) f x = f x\n\nlet foi = float_of_int\nlet iof = int_of_float\n\nlet next_int () = Scanf.scanf \"%d%c\" (fun x _ -> x)\nlet next_flt () = Scanf.scanf \"%f%c\" (fun x _ -> x)\n\nlet seq n = \n let rec aux n acc = \n\tif n = 0 then acc\n\telse aux (n-1) (n :: acc) in\n aux n []\n\nlet rec show_flt_list x = \n match x with\n\t [] -> print_newline ()\n\t| x::xs -> print_float x; print_string \" \"; show_flt_list xs\n\nlet rec loop n f acc = \n if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)\n\nlet rec gcd x y = \n if x mod y = 0 then y else gcd y (x mod y)\n;;\n\nlet n = next_int () \nlet m = next_int () \n\n(* let () = \n print_newline(); print_int n; print_newline (); print_int m; print_newline()\n*)\n\nlet a = loop n (fun _ -> (next_int()) - 1) []\nlet d = List.fold_left gcd (List.hd a) a\n\nlet chk y = \n let rec aux acc x = \n\tif x >= m then acc\n\telse aux (acc + m - x) (2 * x) in\n aux 0 y\n\nlet calc x = \n let mm = min m 100011 in\n let rec aux acc x = \n\tif x >= mm then acc\n\telse aux (acc + mm - x) (2 * x) in\n aux 0 x\n\n\nlet () =\n List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)\n\t|> List.map calc \n\t|> List.fold_left (+) 0 \n\t|> print_int\n\n\n \n"}], "src_uid": "189a8a9a6e99ed52bda9a5773bf2621b"} {"nl": {"description": "City X consists of n vertical and n horizontal infinite roads, forming n\u2009\u00d7\u2009n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.Road repairs are planned for n2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.According to the schedule of road works tell in which days at least one road will be asphalted.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 the number of vertical and horizontal roads in the city. Next n2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers hi,\u2009vi (1\u2009\u2264\u2009hi,\u2009vi\u2009\u2264\u2009n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the hi-th horizontal and vi-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.", "output_spec": "In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.", "sample_inputs": ["2\n1 1\n1 2\n2 1\n2 2", "1\n1 1"], "sample_outputs": ["1 4", "1"], "notes": "NoteIn the sample the brigade acts like that: On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road; On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything; On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything; On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet () = \n let n = read_int() in\n let arrv : bool array = Array.create n false in\n let arrh : bool array = Array.create n false in\n for i = 1 to n*n do\n let h, v = scanf \"%d %d\\n\" (fun x y -> x, y) in\n if not (arrh.(h-1) || arrv.(v-1)) then begin\n arrh.(h-1) <- true;\n arrv.(v-1) <- true;\n printf \"%d \" i\n end;\n printf \"\\n%!\"\ndone\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let h = Array.make n false\n and v = Array.make n false in\n for i = 1 to n*n do\n Scanf.scanf \"%d %d\\n\" (fun x y ->\n if not (h.(x - 1) || v.(y - 1)) then begin\n h.(x - 1) <- true;\n v.(y - 1) <- true;\n Printf.printf \"%d \" i\n end)\n done)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet () = \n let n = read_int () in\n let vert : bool array = Array.create n false in\n let horz : bool array = Array.create n false in\n for i = 1 to n * n do\n let h, v = scanf \"%d %d\\n\" (fun x y -> x - 1, y - 1) in\n if not (horz.(h) || vert.(v)) then begin\n horz.(h) <- true;\n vert.(v) <- true;\n printf \"%d \" i\n end;\n printf \"\\n%!\"\n done\n\n \n"}], "negative_code": [], "src_uid": "c611808e636d9307e6df9ee0e706310b"} {"nl": {"description": "There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately. In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct). In the first contest, the participant on the 100-th place scored $$$a$$$ points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least $$$b$$$ points in the second contest.Similarly, for the second contest, the participant on the 100-th place has $$$c$$$ points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least $$$d$$$ points in the first contest.After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place.Given integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, please help the jury determine the smallest possible value of the cutoff score.", "input_spec": "You need to process $$$t$$$ test cases. The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 3025$$$)\u00a0\u2014 the number of test cases. Then descriptions of $$$t$$$ test cases follow. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \\le a,\\,b,\\,c,\\,d \\le 9$$$; $$$d \\leq a$$$; $$$b \\leq c$$$). One can show that for any test case satisfying the constraints above, there is at least one olympiad scenario possible.", "output_spec": "For each test case print a single integer\u00a0\u2014 the smallest possible cutoff score in some olympiad scenario satisfying the given information.", "sample_inputs": ["2\n1 2 2 1\n4 8 9 2"], "sample_outputs": ["3\n12"], "notes": "NoteFor the first test case, consider the following olympiad scenario: there are $$$101$$$ participants in the elimination stage, each having $$$1$$$ point for the first contest and $$$2$$$ points for the second contest. Hence the total score of the participant on the 100-th place is $$$3$$$.For the second test case, consider the following olympiad scenario: there are $$$50$$$ participants with points $$$5$$$ and $$$9$$$ for the first and second contest respectively; $$$50$$$ participants with points $$$4$$$ and $$$8$$$ for the first and second contest respectively; and $$$50$$$ participants with points $$$2$$$ and $$$9$$$ for the first and second contest respectively. Hence the total point score of the participant on the 100-th place is $$$12$$$."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let t = read_int () in\n let solve a b c d =\n max (a + b) (d + c)\n in\n for i = 1 to t do\n let a = read_int () in\n let b = read_int () in\n let c = read_int () in\n let d = read_int () in\n Printf.printf \"%d\\n\" (solve a b c d)\n done\n"}], "negative_code": [], "src_uid": "a60321dd9ada279c007415f28775099b"} {"nl": {"description": "Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L\u2009-\u2009R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of columns. The next n lines contain the pairs of integers li and ri (1\u2009\u2264\u2009li,\u2009ri\u2009\u2264\u2009500)\u00a0\u2014 the number of soldiers in the i-th column which start to march from the left or the right leg respectively.", "output_spec": "Print single integer k\u00a0\u2014 the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.", "sample_inputs": ["3\n5 6\n8 9\n10 3", "2\n6 5\n5 6", "6\n5 9\n1 3\n4 8\n4 5\n23 54\n12 32"], "sample_outputs": ["3", "1", "0"], "notes": "NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5\u2009+\u20098\u2009+\u200910\u2009=\u200923, and from the right leg\u00a0\u2014 6\u2009+\u20099\u2009+\u20093\u2009=\u200918. In this case the beauty of the parade will equal |23\u2009-\u200918|\u2009=\u20095.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5\u2009+\u20098\u2009+\u20093\u2009=\u200916, and who march from the right leg\u00a0\u2014 6\u2009+\u20099\u2009+\u200910\u2009=\u200925. In this case the beauty equals |16\u2009-\u200925|\u2009=\u20099.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let rec loop\n neg_max neg_max_index neg_sum\n pos_max pos_max_index pos_sum i =\n if i > n then\n begin\n if (pos_max - neg_sum) > (pos_sum - neg_max) then pos_max_index\n else neg_max_index\n end\n else\n begin\n let l = read_int () and r = read_int () in\n let diff = l - r in\n if diff < 0 then\n begin\n if (diff < neg_max) then\n loop\n diff i (neg_sum + diff)\n pos_max pos_max_index pos_sum\n (i + 1)\n else\n loop\n neg_max neg_max_index (neg_sum + diff)\n pos_max pos_max_index pos_sum (i + 1)\n end\n else if diff > 0 then\n begin\n if (diff > pos_max) then\n loop\n neg_max neg_max_index neg_sum\n diff i (pos_sum + diff) (i + 1)\n else\n loop\n neg_max neg_max_index neg_sum\n pos_max pos_max_index (pos_sum + diff)\n (i + 1)\n end\n else\n loop\n neg_max neg_max_index neg_sum\n pos_max pos_max_index pos_sum (i + 1)\n end\n in\n loop 0 0 0 0 0 0 1 |> Printf.printf \"%d\"\n"}, {"source_code": "let solve n ds =\n let beauty = List.fold_left ( + ) 0 ds in\n let rec loop best index i = function\n | [] -> index\n | d :: ds ->\n let b = abs (beauty - 2 * d) in\n if b > best then\n loop b i (i - 1) ds\n else\n loop best index (i - 1) ds\n in loop (abs beauty) 0 n ds\n\nlet () =\n Scanf.scanf \"%d \" @@ fun n ->\n let ds =\n let rec loop acc = function\n | 0 -> acc\n | n ->\n let d = Scanf.scanf \"%d %d\\n\" @@ ( - ) in\n loop (d :: acc) (n - 1)\n in loop [] n in\n solve n ds |> string_of_int |> print_endline\n"}], "negative_code": [], "src_uid": "2be73aa00a13be5274cf840ecd3befcb"} {"nl": {"description": "Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \\cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, \"abc\" $$$\\cdot~2~=$$$ \"abcabc\", \"a\" $$$\\cdot~5~=$$$ \"aaaaa\".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \\cdot x = a$$$. For example, \"abababab\" is divisible by \"ab\", but is not divisible by \"ababab\" or \"aa\".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 2000$$$) \u2014 the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \\le |s|, |t| \\le 20$$$). Each character in each of these strings is either 'a' or 'b'.", "output_spec": "For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.", "sample_inputs": ["3\nbaba\nba\naa\naaa\naba\nab"], "sample_outputs": ["baba\naaaaaa\n-1"], "notes": "NoteIn the first test case, \"baba\" = \"baba\" $$$\\cdot~1~=$$$ \"ba\" $$$\\cdot~2$$$.In the second test case, \"aaaaaa\" = \"aa\" $$$\\cdot~3~=$$$ \"aaa\" $$$\\cdot~2$$$."}, "positive_code": [{"source_code": "open Str\nopen Big_int\nopen Num\n\nlet multitest = true\n\nmodule Shortcuts = struct\n let loop n f = for i = 0 to n - 1 do f i; done\n\nend\n\nmodule Helper = struct\n open Shortcuts\n\n let read_s () = Scanf.scanf \"%s\\n\" (fun x -> x)\n\n let read_int ?endl () =\n match endl with\n | None -> Scanf.scanf \"%d \" (fun x -> x)\n | Some () -> Scanf.scanf \"%d\\n\" (fun x -> x)\n\n let read_array n =\n let a = Array.make n 0 in\n loop (n-1) (fun i -> a.(i) <- read_int ());\n a.(n-1) <- read_int ~endl:() ();\n a\n\nend\n\nmodule Ext = struct\n module List = struct\n let rec make n x =\n if (n <= 0) then []\n else x :: make (n-1) x\n\n end\n\nend\n\nmodule Alg = struct\n let rec gcd x y =\n if y <> 0 then (gcd y (x mod y))\n else (abs x)\n\n let lcm x y =\n if x = 0 || y = 0 then 0\n else abs (x * y) / (gcd x y)\n\nend\n\nlet solve _ =\n let open Shortcuts in\n let open Helper in\n let open Printf in\n let open Ext in\n let open Alg in\n (* ***** Solution code here ***** *)\n let s = read_s () in\n let t = read_s () in\n let sl = String.length s in\n let tl = String.length t in\n let lcm = lcm sl tl in\n let ss = String.concat \"\" (List.make (lcm / sl) s) in\n let tt = String.concat \"\" (List.make (lcm / tl) t) in\n if (ss = tt) then printf \"%s\\n\" ss\n else printf \"-1\\n\";\n (* ***** ******************* ***** *)\n;;\n\nlet () =\n let open Helper in\n let open Shortcuts in\n let t = if multitest then read_int ~endl:() () else 1 in\n loop t solve;;\n"}], "negative_code": [], "src_uid": "710c7211d23cf8c01fae0b476a889276"} {"nl": {"description": "New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n\u2009-\u20091 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n\u2009-\u20091. Let's define d(u,\u2009v) as total length of roads on the path between city u and city v.As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1.Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1\u2009\u2264\u2009k\u2009\u2264\u20093) Santa will take charge of the warehouse in city ck.It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1,\u2009c2)\u2009+\u2009d(c2,\u2009c3)\u2009+\u2009d(c3,\u2009c1) dollars. Santas are too busy to find the best place, so they decided to choose c1,\u2009c2,\u2009c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network.However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.", "input_spec": "The first line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cities in Tree World. Next n\u2009-\u20091 lines describe the roads. The i-th line of them (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091) contains three space-separated integers ai, bi, li (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi, 1\u2009\u2264\u2009li\u2009\u2264\u2009103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009105) \u2014 the number of road length changes. Next q lines describe the length changes. The j-th line of them (1\u2009\u2264\u2009j\u2009\u2264\u2009q) contains two space-separated integers rj, wj (1\u2009\u2264\u2009rj\u2009\u2264\u2009n\u2009-\u20091, 1\u2009\u2264\u2009wj\u2009\u2264\u2009103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times.", "output_spec": "Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["3\n2 3 5\n1 3 3\n5\n1 4\n2 2\n1 2\n2 1\n1 1", "6\n1 5 3\n5 3 2\n6 1 7\n1 4 4\n5 2 3\n5\n1 2\n2 1\n3 5\n4 1\n5 2"], "sample_outputs": ["14.0000000000\n12.0000000000\n8.0000000000\n6.0000000000\n4.0000000000", "19.6000000000\n18.6000000000\n16.6000000000\n13.6000000000\n12.6000000000"], "notes": "NoteConsider the first sample. There are 6 triples: (1,\u20092,\u20093),\u2009(1,\u20093,\u20092),\u2009(2,\u20091,\u20093),\u2009(2,\u20093,\u20091),\u2009(3,\u20091,\u20092),\u2009(3,\u20092,\u20091). Because n\u2009=\u20093, the cost needed to build the network is always d(1,\u20092)\u2009+\u2009d(2,\u20093)\u2009+\u2009d(3,\u20091) for all the triples. So, the expected cost equals to d(1,\u20092)\u2009+\u2009d(2,\u20093)\u2009+\u2009d(3,\u20091)."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n\n let tree = Array.make n [] in\n let len = Array.make (n-1) 0.0 in\n let size = Array.make n 0 in\n let coeff = Array.make (n-1) 0.0 in\n let edge = Array.make (n-1) (0,0) in\n\n for i=0 to n-2 do\n let a = read_int()-1 in\n let b = read_int()-1 in\n let l = read_int() in\n tree.(a) <- b::tree.(a);\n tree.(b) <- a::tree.(b);\n edge.(i) <- (a,b);\n len.(i) <- float l;\n done;\n\n let q = read_int() in\n\n let changes = Array.make q (0, 0.0) in\n\n for i=0 to q-1 do\n let r = read_int() -1 in\n let w = read_int() in\n changes.(i) <- (r, float w)\n done;\n\n let rec dfs u p =\n size.(u) <- List.fold_left (fun t v -> \n if v = p then t else t + (dfs v u)\n ) 1 tree.(u);\n size.(u)\n in\n \n if dfs 0 (-1) <> n then failwith \"bad dfs\";\n\n for e = 0 to n-2 do\n let (a,b) = edge.(e) in\n let se = float (min size.(a) size.(b)) in\n let fn = float n in\n coeff.(e) <- 2.0 *. (se *. (fn -. se)) /. (fn *. (fn -. 1.0))\n done;\n\n let exp_pair_dist = ref 0.0 in\n\n exp_pair_dist := sum 0 (n-2) (fun e -> len.(e) *. coeff.(e));\n\n for i=0 to q-1 do\n let (e,newweight) = changes.(i) in\n exp_pair_dist := !exp_pair_dist +. (newweight -. len.(e)) *. coeff.(e);\n len.(e) <- newweight;\n printf \"%.10f\\n\" (3.0 *. !exp_pair_dist)\n done;\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n\n let tree = Array.make n [] in\n let len = Array.make (n-1) 0.0 in\n let size = Array.make n 0 in\n let coeff = Array.make (n-1) 0.0 in\n let edge = Array.make (n-1) (0,0) in\n\n for i=0 to n-2 do\n let a = read_int()-1 in\n let b = read_int()-1 in\n let l = read_int() in\n tree.(a) <- b::tree.(a);\n tree.(b) <- a::tree.(b);\n edge.(i) <- (a,b);\n len.(i) <- float l;\n done;\n\n let q = read_int() in\n\n let changes = Array.make q (0, 0.0) in\n\n for i=0 to q-1 do\n let r = read_int() -1 in\n let w = read_int() in\n changes.(i) <- (r, float w)\n done;\n\n let rec dfs u p =\n size.(u) <- List.fold_left (fun t v -> \n if v = p then t else t + (dfs v u)\n ) 1 tree.(u);\n size.(u)\n in\n \n if dfs 0 (-1) <> n then failwith \"bad dfs\";\n\n for e = 0 to n-2 do\n let (a,b) = edge.(e) in\n let se = min size.(a) size.(b) in\n coeff.(e) <- 2.0 *. (float (se * (n - se))) /. (float (n * (n-1)))\n done;\n\n let exp_pair_dist = ref 0.0 in\n\n exp_pair_dist := sum 0 (n-2) (fun e -> len.(e) *. coeff.(e));\n\n for i=0 to q-1 do\n let (e,newweight) = changes.(i) in\n exp_pair_dist := !exp_pair_dist +. (newweight -. len.(e)) *. coeff.(e);\n len.(e) <- newweight;\n printf \"%.10f\\n\" (3.0 *. !exp_pair_dist)\n done;\n"}], "src_uid": "38388446f5c265f77124132caa3ce4d2"} {"nl": {"description": "A flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.Determine the maximum possible number of large bouquets Vasya can make. ", "input_spec": "The first line contains a single positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of initial bouquets. The second line contains a sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009106) \u2014 the number of flowers in each of the initial bouquets.", "output_spec": "Print the maximum number of large bouquets Vasya can make. ", "sample_inputs": ["5\n2 3 4 2 7", "6\n2 2 6 8 6 12", "3\n11 4 10"], "sample_outputs": ["2", "0", "1"], "notes": "NoteIn the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme. In the second example it is not possible to form a single bouquet with odd number of flowers.In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11\u2009+\u20094\u2009+\u200910\u2009=\u200925."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\nlet (%%) = Int64.rem\nlet landl = Int64.logand\nlet lorl = Int64.logor\nlet lnotl = Int64.lognot\nlet lxorl = Int64.logxor\nlet lsll = Int64.shift_left\nlet lsrl = Int64.shift_right_logical\nlet long = Int64.of_int\nlet succl = Int64.succ\nlet predl = Int64.pred\n\nlet read_int _ = scanf \" %d \" (fun x -> x)\nlet read_long _ = scanf \" %Ld \" (fun x -> x)\nlet read_str _ = scanf \" %s \" (fun x -> x)\nlet read_double _ = scanf \" %f \" (fun x -> x)\n\nlet m = 1_000_000_007L\n\nlet rec gcd a b = if b = 0L then a else gcd b (a %% b)\n\nlet rec mod_pow a = function\n | 0L -> 1L\n | b -> (if b %% 2L = 0L then 1L else a) ** mod_pow (a ** a %% m) (b//2L) %% m\n\n\nlet () =\n let n = read_int () in\n let a = Array.(init n read_int |> to_list) in\n let oddc = List.(a |> filter (fun x -> x mod 2 == 1) |> length) in\n let m = min oddc (n-oddc) in\n printf \"%d\\n\" @@ (oddc-m) / 3 + m\n"}], "negative_code": [], "src_uid": "61e6fd68d7568c599204130b102ea389"} {"nl": {"description": "You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings \"AB\" and \"BA\" (the substrings can go in any order).", "input_spec": "The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.", "output_spec": "Print \"YES\" (without the quotes), if string s contains two non-overlapping substrings \"AB\" and \"BA\", and \"NO\" otherwise.", "sample_inputs": ["ABA", "BACFAB", "AXBYBXA"], "sample_outputs": ["NO", "YES", "NO"], "notes": "NoteIn the first sample test, despite the fact that there are substrings \"AB\" and \"BA\", their occurrences overlap, so the answer is \"NO\".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring \"AB\" nor substring \"BA\"."}, "positive_code": [{"source_code": "let input () = Pervasives.read_line ()\nlet print str = Pervasives.print_endline str\n\nlet find a b str l = \n let rec loop i prev sawAB sawBA =\n if i < l\n then\n if sawAB = false\n then\n if str.[i] = b && prev = a\n then\n loop (i + 1) 'Z' true sawBA\n else\n loop (i + 1) str.[i] sawAB sawBA\n else\n if str.[i] = a && prev = b\n then\n true\n else\n loop (i + 1) str.[i] sawAB sawBA\n else\n false\n in loop 0 'Z' false false\n\nlet solve str = \n let l = String.length str in\n let result = \n (if (find 'A' 'B' str l) || (find 'B' 'A' str l)\n then\n \"YES\"\n else\n \"NO\")\n in print result\n \nlet () = solve (input ())"}], "negative_code": [{"source_code": "let input () = Pervasives.read_line ()\nlet print str = Pervasives.print_endline str\n\nlet find a b str l = \n let rec loop i prev sawAB sawBA =\n if i < l\n then\n if sawAB = false || sawBA = false\n then\n if str.[i] = b && prev = a && sawAB = false\n then \n loop (i + 1) 'Z' true sawBA\n else\n if str.[i] = a && prev = b && sawBA = false\n then\n loop (i + 1) 'Z' sawAB true\n else\n loop (i + 1) str.[i] sawAB sawBA\n else\n true\n else\n if sawAB && sawBA \n then\n true\n else\n false\n in loop 1 str.[0] false false\n\nlet solve str = \n let l = String.length str in\n let result = \n (if (find 'A' 'B' str l) || (find 'B' 'A' str l)\n then\n \"YES\"\n else\n \"NO\")\n in print result\n \nlet () = solve (input ())"}], "src_uid": "33f7c85e47bd6c83ab694a834fa728a2"} {"nl": {"description": "Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $$$s = s_1 s_2 \\dots s_n$$$ of length $$$n$$$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.In a move, a player must choose an index $$$i$$$ ($$$1 \\leq i \\leq n$$$) that has not been chosen before, and change $$$s_i$$$ to any other lowercase English letter $$$c$$$ that $$$c \\neq s_i$$$.When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \\ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. ", "input_spec": "Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u00a0\u2014 the number of test cases. Description of the test cases follows. The only line of each test case contains a single string $$$s$$$ ($$$1 \\leq |s| \\leq 50$$$) consisting of lowercase English letters.", "output_spec": "For each test case, print the final string in a single line.", "sample_inputs": ["3\na\nbbbb\naz"], "sample_outputs": ["b\nazaz\nby"], "notes": "NoteIn the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\n \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let s = read_string() in\n let n = String.length s in\n for i=0 to n-1 do\n if i mod 2 = 0 then (\n\tif s.[i] = 'a' then printf \"b\" else printf \"a\"\n ) else (\n\tif s.[i] = 'z' then printf \"y\" else printf \"z\"\n )\t\n done;\n print_newline()\n done\n"}], "negative_code": [], "src_uid": "c02357c4d959e300f970f66f9b3107eb"} {"nl": {"description": "The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2\u2009\u00d7\u20092 square, such that from the four letters of this square you can make word \"face\". You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.", "input_spec": "The first line contains two space-separated integers, n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950) \u2014 the height and the width of the image, respectively. Next n lines define the image. Each line contains m lowercase Latin letters.", "output_spec": "In the single line print the number of faces on the image.", "sample_inputs": ["4 4\nxxxx\nxfax\nxcex\nxxxx", "4 2\nxx\ncf\nae\nxx", "2 3\nfac\ncef", "1 4\nface"], "sample_outputs": ["1", "1", "2", "0"], "notes": "NoteIn the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column: In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.In the third sample two faces are shown: In the fourth sample the image has no faces on it."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet read_pair () = let u = read_int () in (u, read_int ())\n\nlet () =\n let (n, m) = read_pair () in\n let board = Array.init n (fun _ -> read_string ()) in\n\n let count = ref 0 in\n\n let is_face l = \n let l = List.sort compare l in \n l = ['a'; 'c'; 'e'; 'f']\n in \n\n for i=0 to n-2 do\n for j = 0 to m-2 do\n if is_face [board.(i).[j]; board.(i+1).[j]; board.(i).[j+1]; board.(i+1).[j+1] ]\n then count := !count + 1\n done\n done;\n\n printf \"%d\\n\" !count"}, {"source_code": "(* iterate all 2x2 square *)\nopen Scanf\nopen Printf\nlet read_int() = bscanf Scanning.stdib \" %d \" (fun x->x)\nlet read_string() = bscanf Scanning.stdib \" %s \" (fun x->x)\n\nlet () =\n let n = read_int() in\n let m = read_int() in\n let img = Array.init n (fun _-> read_string()) in\n let ci c = int_of_char c in\n let face = 1 lsl (ci 'f') + 1 lsl (ci 'a') + 1 lsl (ci 'c') + 1 lsl (ci 'e') in\n let is_face a b c d = 1 lsl (ci a) + 1 lsl (ci b) + 1 lsl (ci c) + 1 lsl (ci d) == face in \n let count = ref 0 in\n for i=0 to n-2 do\n\tfor j=0 to m-2 do\n\t if is_face img.(i).[j] img.(i).[j+1] img.(i+1).[j] img.(i+1).[j+1] then\n\t\tcount := !count + 1\n\tdone\n done;\n\tprintf \"%d\\n\" !count\n\t \n\n \n"}, {"source_code": "let ok mat =\n\tlet compt = ref 0 in\n\tfor i=0 to Array.length mat - 2 do\n\tfor j=0 to String.length (mat.(0)) - 2 do\n\t\tif List.sort compare [(mat.(i)).[j];(mat.(i+1)).[j];(mat.(i)).[j+1];(mat.(i+1)).[j+1]] = ['a';'c';'e';'f']\n\t\t\tthen incr compt;\n\tdone;\n\tdone;\n\t!compt\n\nlet () =\n\tlet n = Scanf.scanf \"%d %d \" (fun i _ -> i) in\n\tlet tab = Array.init n (fun i -> Scanf.scanf \" %s\" (fun j -> j)) in\n\t\tPrintf.printf \"%d\" (ok tab)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let (n,m) = read_pair () in\n let board = Array.init n (fun _ -> read_string()) in\n\n let count = ref 0 in\n\n let is_face l =\n let l = List.sort compare l in\n l = ['a';'c';'e';'f']\n in\n\n for i=0 to n-2 do\n for j=0 to m-2 do\n if is_face [board.(i).[j]; board.(i+1).[j]; board.(i).[j+1]; board.(i+1).[j+1] ]\n then count := !count + 1\n done\n done;\n\n printf \"%d\\n\" !count\n"}], "negative_code": [], "src_uid": "742e4e6ca047da5f5ebe5d854d6a2024"} {"nl": {"description": "You've got two rectangular tables with sizes na\u2009\u00d7\u2009ma and nb\u2009\u00d7\u2009mb cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the i-th row and the j-th column, as ai,\u2009j; we will define the element of the second table, located at the intersection of the i-th row and the j-th column, as bi,\u2009j. We will call the pair of integers (x,\u2009y) a shift of the second table relative to the first one. We'll call the overlap factor of the shift (x,\u2009y) value:where the variables i,\u2009j take only such values, in which the expression ai,\u2009j\u00b7bi\u2009+\u2009x,\u2009j\u2009+\u2009y makes sense. More formally, inequalities 1\u2009\u2264\u2009i\u2009\u2264\u2009na,\u20091\u2009\u2264\u2009j\u2009\u2264\u2009ma,\u20091\u2009\u2264\u2009i\u2009+\u2009x\u2009\u2264\u2009nb,\u20091\u2009\u2264\u2009j\u2009+\u2009y\u2009\u2264\u2009mb must hold. If there are no values of variables i,\u2009j, that satisfy the given inequalities, the value of the sum is considered equal to 0. Your task is to find the shift with the maximum overlap factor among all possible shifts.", "input_spec": "The first line contains two space-separated integers na,\u2009ma (1\u2009\u2264\u2009na,\u2009ma\u2009\u2264\u200950) \u2014 the number of rows and columns in the first table. Then na lines contain ma characters each \u2014 the elements of the first table. Each character is either a \"0\", or a \"1\". The next line contains two space-separated integers nb,\u2009mb (1\u2009\u2264\u2009nb,\u2009mb\u2009\u2264\u200950) \u2014 the number of rows and columns in the second table. Then follow the elements of the second table in the format, similar to the first table. It is guaranteed that the first table has at least one number \"1\". It is guaranteed that the second table has at least one number \"1\".", "output_spec": "Print two space-separated integers x,\u2009y (|x|,\u2009|y|\u2009\u2264\u2009109) \u2014 a shift with maximum overlap factor. If there are multiple solutions, print any of them.", "sample_inputs": ["3 2\n01\n10\n00\n2 3\n001\n111", "3 3\n000\n010\n000\n1 1\n1"], "sample_outputs": ["0 1", "-1 -1"], "notes": null}, "positive_code": [{"source_code": "let main = \n let (na, ma) = Scanf.scanf \"%d %d \" (fun a b -> (a,b)) in\n let a = Array.make na \"\" in\n for i = 0 to na-1 do\n a.(i) <- Scanf.scanf \"%s \" (fun s -> s);\n done;\n let (nb, mb) = Scanf.scanf \"%d %d \" (fun a b -> (a,b)) in\n let b = Array.make nb \"\" in\n for i = 0 to nb-1 do\n b.(i) <- Scanf.scanf \"%s \" (fun s -> s);\n done;\n \n let find_sum y x =\n let sum = ref 0 in\n for i = 0 to na-1 do\n for j = 0 to ma -1 do\n\tif i >= 0 && i <= na -1 && j >= 0 && j <= ma - 1 &&\n\t y+i >= 0 && y + i <= nb - 1 && x+j >= 0 && x+j <= mb - 1 then begin\n\t if a.(i).[j] = '1' && b.(y+i).[x+j] = '1' then incr sum\n\t end\n done;\n done;\n !sum in\n\n let m = ref 0 in\n let mxy = ref (0,0) in\n for i = (-na) + 1 to nb - 1 do\n for j = (-ma) + 1 to mb - 1 do\n let s = find_sum i j in\n if s > !m then begin\n\tm := s;\n\tmxy := (i,j);\n end\n done;\n done; \n let (x,y) = !mxy in\n Printf.printf \"%d %d\\n\" x y\n"}], "negative_code": [], "src_uid": "8abdf3aa47fb3ec715693f6388d62a55"} {"nl": {"description": "Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second \u2014 from a2 to b2What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.", "input_spec": "The first line of the input file contains integers n and x0 (1\u2009\u2264\u2009n\u2009\u2264\u2009100; 0\u2009\u2264\u2009x0\u2009\u2264\u20091000). The following n lines contain pairs of integers ai,\u2009bi (0\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091000; ai\u2009\u2260\u2009bi).", "output_spec": "Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.", "sample_inputs": ["3 3\n0 7\n14 2\n4 6"], "sample_outputs": ["1"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let x0 = read_int 0 in\n let l = ref 0 and r = ref 1000 in\n for i = 1 to n do\n let a = read_int 0 in\n let b = read_int 0 in\n let a,b = min a b, max a b in\n l := max !l a;\n r := min !r b\n done;\n Printf.printf \"%d\\n\" (if !l > !r then\n -1\n else if x0 < !l then\n !l-x0\n else if !r < x0 then\n x0- !r\n else\n 0)\n"}], "negative_code": [], "src_uid": "3c066bad8ee6298b318bf0f4521c7c45"} {"nl": {"description": "The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vector is 1 or \u2009-\u20091 and any two vectors are orthogonal. Just as a reminder, two vectors in n-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is: .Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for 2k vectors in 2k-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?", "input_spec": "The only line of the input contains a single integer k (0\u2009\u2264\u2009k\u2009\u2264\u20099).", "output_spec": "Print 2k lines consisting of 2k characters each. The j-th character of the i-th line must be equal to '\u2009*\u2009' if the j-th coordinate of the i-th vector is equal to \u2009-\u20091, and must be equal to '\u2009+\u2009' if it's equal to \u2009+\u20091. It's guaranteed that the answer always exists. If there are many correct answers, print any.", "sample_inputs": ["2"], "sample_outputs": ["++**\n+*+*\n++++\n+**+"], "notes": "NoteConsider all scalar products in example: Vectors 1 and 2: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009-\u20091)\u2009=\u20090 Vectors 1 and 3: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 Vectors 1 and 4: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 Vectors 2 and 3: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 Vectors 2 and 4: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009-\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 Vectors 3 and 4: (\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009-\u20091)\u2009+\u2009(\u2009+\u20091)\u00b7(\u2009+\u20091)\u2009=\u20090 "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let k = read_int() in\n\n let v = Array.make (k+1) [||] in\n\n for i=0 to k do\n let d = 1 lsl i in\n v.(i) <- Array.make_matrix d d 0\n done;\n\n for i=1 to k do\n let d = 1 lsl i in\n let d' = d/2 in \n for j = 0 to d-1 do\n for l = 0 to d-1 do\n\tv.(i).(j).(l) <- v.(i-1).(j mod d').(l mod d');\n\tif j >= d' && l >= d' then v.(i).(j).(l) <- 1 - v.(i).(j).(l)\n done\n done\n done;\n\n let d = 1 lsl k in\n\n for j=0 to d-1 do\n for l=0 to d-1 do\n printf \"%c\" (if v.(k).(j).(l) = 0 then '*' else '+')\n done;\n print_newline()\n done\n"}], "negative_code": [], "src_uid": "4e25d49e8a50dacc1cfcc9413ee83db6"} {"nl": {"description": "Jack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or \u2014 horror of horrors! \u2014 stops for a while. For example, if Jack uses the sequence 'right, left, break', when the sergeant yells: 'Left! Right! Left! Right! Left! Right!', Jack first makes a step with the right foot, then one with the left foot, then he is confused and stops for a moment, then again - this time according to the order - starts with the right foot, then uses the left foot, then - to the sergeant's irritation - he stops to catch his breath, to incorrectly start with the right foot again... Marching this way, Jack will make the step that he is supposed to in the given moment in only one third of cases.When the officers convinced him he should do something about it, Jack decided to modify the basic sequence of steps that he repeats. However, in order not to get too tired, he has decided that the only thing he'll do is adding any number of breaks in any positions of the original sequence (a break corresponds to stopping for the duration of one step). Of course, Jack can't make a step on the same foot twice in a row, if there is no pause between these steps. It is, however, not impossible that the sequence of steps he used so far is incorrect (it would explain a lot, actually).Help Private Jack! Given the sequence of steps he keeps repeating, calculate the maximal percentage of time that he can spend marching correctly after adding some breaks to his scheme.", "input_spec": "The first line of input contains a sequence consisting only of characters 'L', 'R' and 'X', where 'L' corresponds to a step with the left foot, 'R' \u2014 with the right foot, and 'X' \u2014 to a break. The length of the sequence will not exceed 106.", "output_spec": "Output the maximum percentage of time that Jack can spend marching correctly, rounded down to exactly six digits after the decimal point.", "sample_inputs": ["X", "LXRR"], "sample_outputs": ["0.000000", "50.000000"], "notes": "NoteIn the second example, if we add two breaks to receive LXXRXR, Jack will march: LXXRXRLXXRXRL... instead of LRLRLRLRLRLRL... and will make the correct step in half the cases. If we didn't add any breaks, the sequence would be incorrect \u2014 Jack can't step on his right foot twice in a row."}, "positive_code": [{"source_code": "open Int64\n\nlet f a n =\n let rec go i p q f pair =\n if i >= n then\n p,q,f,pair\n else if a.[i] = 'X' then\n go (i+1) p (q+1) f pair\n else if a.[i] = (if q mod 2 = 0 then 'L' else 'R') then\n go (i+1) (p+1) (q+1) 0 pair\n else\n go (i+1) (p+1) (q+2) (1-f) (pair+f)\n in\n let p,q,f,pair = go 0 0 0 0 0 in\n let q,pair = if q mod 2 = 1 then q+1,pair+f else q,pair in\n let p,q = if p*2 > q then p-pair,q-pair*2 else p,q in\n div (mul (of_int p) 100000000L) (of_int q)\n\nlet () =\n let a = read_line () in\n let n = String.length a in\n let b = String.make (n*2) '.' in\n let m = ref 0 in\n for i = 0 to n-1 do\n if i > 0 && a.[i] = a.[i-1] && a.[i] != 'X' then (\n b.[!m] <- 'X';\n incr m;\n );\n b.[!m] <- a.[i];\n incr m\n done;\n let ans = if b.[0] = b.[!m-1] && b.[0] != 'X' then (\n b.[!m] <- 'X';\n max (f (b^\"X\") (!m+1)) (f (\"X\"^b) (!m+1))\n ) else\n f b !m\n in\n Printf.printf \"%Ld.%06Ld\\n\" (div ans 1000000L) (rem ans 1000000L)\n"}], "negative_code": [{"source_code": "open Int64\n\nlet f a n =\n let rec go i p q f pair =\n if i >= n then\n p,q,f,pair\n else if a.[i] = 'X' then\n go (i+1) p (q+1) f pair\n else if a.[i] = (if q mod 2 = 0 then 'L' else 'R') then\n go (i+1) (p+1) (q+1) 0 pair\n else\n go (i+1) (p+1) (q+2) (1-f) (pair+f)\n in\n let p,q,f,pair = go 0 0 0 0 0 in\n let q,pair = if q mod 2 = 1 then q+1,pair+f else q,pair in\n let p,q = if p*2 > q then p-pair,q-pair*2 else p,q in\n div (mul (of_int p) 100000000L) (of_int q)\n\nlet () =\n let a = read_line () in\n let n = String.length a in\n let b = String.make (n*2) '.' in\n let m = ref 0 in\n for i = 0 to n-1 do\n if i > 0 && a.[i] = a.[i-1] && a.[i] != 'X' then (\n b.[!m] <- 'X';\n incr m;\n );\n b.[!m] <- a.[i];\n incr m\n done;\n let ans = if b.[0] = b.[!m-1] && b.[0] != 'X' then\n max (f (b^\"X\") (!m+1)) (f (\"X\"^b) (!m+1))\n else\n f b !m\n in\n Printf.printf \"%Ld.%06Ld\\n\" (div ans 1000000L) (rem ans 1000000L)\n"}, {"source_code": "open Int64\n\nlet f a n =\n let rec go i p q f pair =\n if i >= n then\n p,q,f,pair\n else if a.[i] = 'X' then\n go (i+1) p (q+1) f pair\n else if a.[i] = (if q mod 2 = 0 then 'L' else 'R') then\n go (i+1) (p+1) (q+1) 0 pair\n else\n go (i+1) (p+1) (q+2) (1-f) (pair+f)\n in\n let p,q,f,pair = go 0 0 0 0 0 in\n let q,pair = if q mod 2 = 1 then q+1,pair+f else q,pair in\n let p,q = if p*2 > q then p-pair,q-pair else p,q in\n div (mul (of_int p) 100000000L) (of_int q)\n\nlet () =\n let a = read_line () in\n let n = String.length a in\n let b = String.make (n*2) '.' in\n let m = ref 0 in\n for i = 0 to n-1 do\n if i > 0 && a.[i] = a.[i-1] && a.[i] != 'X' then (\n b.[!m] <- 'X';\n incr m;\n );\n b.[!m] <- a.[i];\n incr m\n done;\n let ans = if b.[0] = b.[!m-1] && b.[0] != 'X' then\n max (f (b^\"X\") (!m+1)) (f (\"X\"^b) (!m+1))\n else\n f b !m\n in\n Printf.printf \"%Ld.%06Ld\\n\" (div ans 1000000L) (rem ans 1000000L)\n"}], "src_uid": "4931c42108f487b81b702db3617f0af6"} {"nl": {"description": "You are standing at the point $$$0$$$ on a coordinate line. Your goal is to reach the point $$$n$$$. In one minute, you can move by $$$2$$$ or by $$$3$$$ to the left or to the right (i.\u2009e., if your current coordinate is $$$x$$$, it can become $$$x-3$$$, $$$x-2$$$, $$$x+2$$$ or $$$x+3$$$). Note that the new coordinate can become negative.Your task is to find the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ lines describing the test cases follow. The $$$i$$$-th of these lines contains one integer $$$n$$$ ($$$1 \\le n \\le 10^9$$$) \u2014 the goal of the $$$i$$$-th test case.", "output_spec": "For each test case, print one integer \u2014 the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$ for the corresponding test case.", "sample_inputs": ["4\n\n1\n\n3\n\n4\n\n12"], "sample_outputs": ["2\n1\n2\n4"], "notes": null}, "positive_code": [{"source_code": "let rec loop t =\r\n if t > 0 then\r\n let n = read_int() in\r\n print_int ( if n > 3 then\r\n (n + 2) / 3\r\n else\r\n 1 + (if n = 1 then 1 else 0));\r\n print_newline ();\r\n loop (t-1)\r\n else ()\r\n;;\r\n\r\nloop (read_int ());;\r\n"}], "negative_code": [], "src_uid": "208e285502bed3015b30ef10a351fd6d"} {"nl": {"description": "There are $$$n$$$ students numerated from $$$1$$$ to $$$n$$$. The level of the $$$i$$$-th student is $$$a_i$$$. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than $$$x$$$.For example, if $$$x = 4$$$, then the group with levels $$$[1, 10, 8, 4, 4]$$$ is stable (because $$$4 - 1 \\le x$$$, $$$4 - 4 \\le x$$$, $$$8 - 4 \\le x$$$, $$$10 - 8 \\le x$$$), while the group with levels $$$[2, 10, 10, 7]$$$ is not stable ($$$7 - 2 = 5 > x$$$).Apart from the $$$n$$$ given students, teachers can invite at most $$$k$$$ additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).For example, if there are two students with levels $$$1$$$ and $$$5$$$; $$$x = 2$$$; and $$$k \\ge 1$$$, then you can invite a new student with level $$$3$$$ and put all the students in one stable group.", "input_spec": "The first line contains three integers $$$n$$$, $$$k$$$, $$$x$$$ ($$$1 \\le n \\le 200\\,000$$$, $$$0 \\le k \\le 10^{18}$$$, $$$1 \\le x \\le 10^{18}$$$)\u00a0\u2014 the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference. The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^{18}$$$)\u00a0\u2014 the students levels.", "output_spec": "In the only line print a single integer: the minimum number of stable groups you can split the students into.", "sample_inputs": ["8 2 3\n1 1 5 8 12 13 20 22", "13 0 37\n20 20 80 70 70 70 420 5 1 5 1 60 90"], "sample_outputs": ["2", "3"], "notes": "NoteIn the first example you can invite two students with levels $$$2$$$ and $$$11$$$. Then you can split the students into two stable groups: $$$[1, 1, 2, 5, 8, 11, 12, 13]$$$, $$$[20, 22]$$$. In the second example you are not allowed to invite new students, so you need $$$3$$$ groups: $$$[1, 1, 5, 5, 20, 20]$$$ $$$[60, 70, 70, 70, 80, 90]$$$ $$$[420]$$$ "}, "positive_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x)\r\nlet scan_lint () = Scanf.scanf \" %Ld\" (fun x -> x)\r\nlet n = scan_int()\r\nlet k = ref (scan_lint())\r\nlet x = scan_lint()\r\n\r\nlet () =\r\n let a = Array.make n 0L in\r\n for i = 0 to n - 1 do\r\n a.(i) <- scan_lint()\r\n done;\r\n Array.sort compare a;\r\n let d = Array.make (n - 1) 0L in\r\n for i = 0 to n - 2 do\r\n d.(i) <- Int64.sub a.(i + 1) a.(i)\r\n done;\r\n Array.sort compare d;\r\n let ans = ref n in\r\n for i = 0 to Array.length d - 1 do\r\n if d.(i) <= x then\r\n ans := !ans - 1\r\n else if !k > 0L then\r\n let di = Int64.sub d.(i) 1L in\r\n let c = Int64.div di x in\r\n let ok = !k >= c in\r\n if ok then k := (Int64.sub !k c);\r\n if ok then ans := !ans - 1;\r\n done;\r\n Printf.printf \"%d\\n\" !ans;;"}, {"source_code": "open Int64;;\r\nopen Array;;\r\nlet da x = ();;\r\nlet is_digit c = \r\n if (int_of_char c) >= (int_of_char '0') \r\n then if (int_of_char c) <= (int_of_char '9') then true\r\n else false\r\n else false;;\r\nlet digit c = (int_of_char c) - (int_of_char '0');;\r\nlet digitInt64 c = of_int(digit c);;\r\nlet readLine() = input_line stdin;;\r\nlet print_number x = print_string (to_string x ^ \" \");;\r\nlet print_char c = print_string (Char.escaped c);;\r\nlet readChar() = \r\n let s = Bytes.create 1 in\r\n let () = da (input stdin s 0 1) in \r\n Bytes.get s 0;;\r\nlet readLong() =\r\n let number = ref 0L in\r\n let () = \r\n let quit_loop = ref false in\r\n while not !quit_loop do\r\n let c = readChar() in\r\n if is_digit c then \r\n number := add (mul !number 10L) (digitInt64 c)\r\n else\r\n quit_loop := true\r\n done in \r\n !number;;\r\n \r\n \r\n \r\nlet merge a b =\r\n let n = length a in\r\n let m = length b in\r\n let ret = make (n+m) 0L in\r\n let i = ref 0 in\r\n let j = ref 0 in\r\n let who = ref false in\r\n let ptr = ref 0 in\r\n while !ptr < (n+m) do\r\n let () = \r\n if !i < n then \r\n if !j < m then who := a.(!i) < b.(!j) \r\n else who := true\r\n else who := false in\r\n let () = \r\n if !who = true then ret.(!ptr) <- a.(!i)\r\n else ret.(!ptr) <- b.(!j) in\r\n let () = \r\n if !who = true then i := !i + 1\r\n else j := !j + 1 in\r\n ptr := !ptr + 1\r\n done; \r\n ret;; \r\nlet rec merge_sort a = \r\n if (length a) = 1 then a\r\n else \r\n let l = init ((length a + 1) / 2) (fun i -> a.(i)) in\r\n let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in\r\n merge (merge_sort l) (merge_sort r);;\r\nlet n = readLong() in\r\nlet k = ref (readLong()) in\r\nlet x = readLong() in\r\nlet a = Array.init (to_int n) (fun i -> readLong()) in\r\nif n = 1L then print_number n \r\nelse\r\n let sorted = merge_sort a in\r\n let cost = make (to_int n-1) 0L in\r\n let () = \r\n for i = 1 to (length a - 1) do\r\n let () = cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x) in\r\n if cost.(i-1) < 0L then cost.(i-1) <- 0L\r\n done in\r\n let sorted_cost = merge_sort cost in\r\n let answer = ref 1L in\r\n let () = \r\n for i = 0 to (length cost - 1) do\r\n if !k >= sorted_cost.(i) then\r\n k := Int64.sub !k sorted_cost.(i)\r\n else\r\n answer := Int64.add !answer 1L\r\n done in\r\n print_number !answer;;"}, {"source_code": "open Int64;;\r\nopen Array;;\r\nlet merge a b =\r\n let n = length a in\r\n let m = length b in\r\n let ret = make (n+m) 0L in\r\n let i = ref 0 in\r\n let j = ref 0 in\r\n let who = ref false in\r\n let ptr = ref 0 in\r\n while !ptr < (n+m) do\r\n let () = \r\n if !i < n then \r\n if !j < m then who := a.(!i) < b.(!j) \r\n else who := true\r\n else who := false in\r\n let () = \r\n if !who = true then ret.(!ptr) <- a.(!i)\r\n else ret.(!ptr) <- b.(!j) in\r\n let () = \r\n if !who = true then i := !i + 1\r\n else j := !j + 1 in\r\n ptr := !ptr + 1\r\n done; \r\n ret;; \r\nlet rec merge_sort a = \r\n if (length a) = 1 then a\r\n else \r\n let l = init ((length a + 1) / 2) (fun i -> a.(i)) in\r\n let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in\r\n merge (merge_sort l) (merge_sort r);;\r\nlet readLong () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet print_number x = print_string (to_string x);;\r\nlet n = readLong() in\r\nlet k = ref (readLong()) in\r\nlet x = readLong() in\r\nlet a = Array.init (to_int n) (fun i -> readLong()) in\r\nif n = 1L then print_number n \r\nelse\r\n let sorted = merge_sort a in\r\n let cost = make (to_int n-1) 0L in\r\n let () = \r\n for i = 1 to (length a - 1) do\r\n let () = cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x) in\r\n if cost.(i-1) < 0L then cost.(i-1) <- 0L\r\n done in\r\n let sorted_cost = merge_sort cost in\r\n let answer = ref 1L in\r\n let () = \r\n for i = 0 to (length cost - 1) do\r\n if !k >= sorted_cost.(i) then\r\n k := Int64.sub !k sorted_cost.(i)\r\n else\r\n answer := Int64.add !answer 1L\r\n done in\r\n print_number !answer;;"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x)\r\nlet scan_lint () = Scanf.scanf \" %Ld\" (fun x -> x)\r\nlet n = scan_int()\r\nlet k = ref (scan_lint())\r\nlet x = scan_lint()\r\n\r\nlet () =\r\n let a = Array.make n 0L in\r\n for i = 0 to n - 1 do\r\n a.(i) <- scan_lint()\r\n done;\r\n let b = List.sort compare (Array.to_list a) in\r\n let d = Array.make (n - 1) 0L in\r\n for i = 1 to n - 2 do\r\n d.(i) <- Int64.sub (List.nth b i) (List.nth b (i - 1))\r\n done;\r\n let d = List.sort compare (Array.to_list d) in\r\n let ans = ref n in\r\n for i = 0 to List.length d - 1 do\r\n if (List.nth d i) <= x then\r\n ans := !ans - 1\r\n else if !k > 0L then\r\n let di = Int64.sub (List.nth d i) 1L in\r\n let c = Int64.div di x in\r\n let ok = !k >= c in\r\n if ok then k := (Int64.sub !k c);\r\n if ok then ans := !ans - 1;\r\n done;\r\n Printf.printf \"%d\\n\" !ans;;"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x)\r\nlet scan_lint () = Scanf.scanf \" %Ld\" (fun x -> x)\r\nlet rec init n =\r\n if n = 0 then []\r\n else scan_lint() :: (init (n - 1))\r\nlet rec cal_diff l pos =\r\n if pos = List.length l then []\r\n else if pos = 0 then\r\n cal_diff l (pos + 1)\r\n else Int64.sub (List.nth l pos) (List.nth l (pos - 1)) :: cal_diff l (pos + 1)\r\nlet get_diff l = let sl = List.fast_sort compare l in List.sort compare (cal_diff sl 0)\r\nlet n = scan_int()\r\nlet k = ref (scan_lint())\r\nlet x = scan_lint()\r\nlet d = get_diff (init n)\r\n\r\nlet () =\r\n let ans = ref n in\r\n for i = 0 to List.length d - 1 do\r\n if (List.nth d i) <= x then\r\n ans := !ans - 1\r\n else\r\n let c = Int64.div (List.nth d i) x in\r\n let ok = !k >= c in\r\n if ok then k := (Int64.sub !k c);\r\n if ok then ans := !ans - 1;\r\n done;\r\n Printf.printf \"%d\\n\" !ans;;"}, {"source_code": "\r\nopen Int64;;\r\nopen Array;;\r\nlet size = 1000;;\r\nlet s = Bytes.create size;;\r\nlet pos = ref 0;;\r\nlet ptr = ref 0;;\r\nlet read cnt = \r\n if !pos + cnt < size then\r\n let () = pos := !pos + (input stdin s !pos cnt) in\r\n true\r\n else\r\n false;;\r\nlet restart() =\r\n let () = \r\n for i = 1 to !pos - !ptr do\r\n Bytes.set s (i - 1) (Bytes.get s (i + !ptr)) \r\n done in\r\n let () = \r\n pos := !pos - !ptr in\r\n ptr := 0;;\r\nlet da x = ();;\r\nlet is_digit c = \r\n if (int_of_char c) >= (int_of_char '0') \r\n then if (int_of_char c) <= (int_of_char '9') then true\r\n else false\r\n else false;;\r\nlet digit c = (int_of_char c) - (int_of_char '0');;\r\nlet digitInt64 c = of_int(digit c);;\r\nlet readLine() = input_line stdin;;\r\nlet print_number x = print_string (to_string x ^ \" \");;\r\nlet print_char c = print_string (Char.escaped c);;\r\nlet check_reader() = \r\n let () = \r\n if !pos < size then da (read (size - !pos - 1)) in\r\n if !ptr >= 980 then restart();;\r\nlet skip() = \r\n let () = check_reader() in\r\n let quit_loop = ref false in\r\n while not !quit_loop do\r\n let c = Bytes.get s !ptr in\r\n let () = \r\n if is_digit c then quit_loop := true\r\n else ptr := !ptr + 1 in check_reader()\r\n done;;\r\nlet readLong() =\r\n let () = skip() in\r\n let quit_loop = ref false in \r\n let number = ref 0L in\r\n let () = \r\n while not !quit_loop do\r\n let c = Bytes.get s !ptr in\r\n if is_digit c then \r\n let () = number := add (mul !number 10L) (digitInt64 c) in\r\n ptr := !ptr + 1\r\n else\r\n quit_loop := true\r\n done in\r\n !number;;\r\nlet merge a b =\r\n let n = length a in\r\n let m = length b in\r\n let ret = make (n+m) 0L in\r\n let i = ref 0 in\r\n let j = ref 0 in\r\n let who = ref false in\r\n let ptr = ref 0 in\r\n while !ptr < (n+m) do\r\n let () = \r\n if !i < n then \r\n if !j < m then who := a.(!i) < b.(!j) \r\n else who := true\r\n else who := false in\r\n let () = \r\n if !who = true then ret.(!ptr) <- a.(!i)\r\n else ret.(!ptr) <- b.(!j) in\r\n let () = \r\n if !who = true then i := !i + 1\r\n else j := !j + 1 in\r\n ptr := !ptr + 1\r\n done; \r\n ret;; \r\nlet rec merge_sort a = \r\n if (length a) = 1 then a\r\n else \r\n let l = init ((length a + 1) / 2) (fun i -> a.(i)) in\r\n let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in\r\n merge (merge_sort l) (merge_sort r);;\r\nlet n = readLong() in\r\nlet k = ref (readLong()) in\r\nlet x = readLong() in\r\nlet a = Array.init (to_int n) (fun i -> readLong()) in\r\nif n = 1L then print_number n \r\nelse\r\n let sorted = merge_sort a in\r\n let cost = make (to_int n-1) 0L in\r\n let () = \r\n for i = 1 to (length a - 1) do\r\n let () = cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x) in\r\n if cost.(i-1) < 0L then cost.(i-1) <- 0L\r\n done in\r\n let sorted_cost = merge_sort cost in\r\n let answer = ref 1L in\r\n let () = \r\n for i = 0 to (length cost - 1) do\r\n if !k >= sorted_cost.(i) then\r\n k := Int64.sub !k sorted_cost.(i)\r\n else\r\n answer := Int64.add !answer 1L\r\n done in\r\n print_number !answer;;"}, {"source_code": "\r\nopen Int64;;\r\nopen Array;;\r\nlet size = 1000;;\r\nlet s = Bytes.create size;;\r\nlet pos = ref 0;;\r\nlet ptr = ref 0;;\r\nlet read cnt = \r\n if !pos + cnt < size then\r\n let nums = (input stdin s !pos cnt) in\r\n let () = pos := !pos + nums in\r\n true\r\n else\r\n false;;\r\nlet restart() =\r\n let () = \r\n for i = 1 to !pos - !ptr do\r\n Bytes.set s (i - 1) (Bytes.get s (i + !ptr)) \r\n done in\r\n let () = \r\n pos := !pos - !ptr in\r\n ptr := 0;;\r\nlet da x = ();;\r\nlet is_digit c = \r\n if (int_of_char c) >= (int_of_char '0') \r\n then if (int_of_char c) <= (int_of_char '9') then true\r\n else false\r\n else false;;\r\nlet digit c = (int_of_char c) - (int_of_char '0');;\r\nlet digitInt64 c = of_int(digit c);;\r\nlet readLine() = input_line stdin;;\r\nlet print_number x = print_string (to_string x ^ \" \");;\r\nlet print_char c = print_string (Char.escaped c);;\r\nlet check_reader() = \r\n let () = \r\n if !pos < size then da (read (size - !pos - 1)) in\r\n if !ptr >= 980 then restart();;\r\nlet skip() = \r\n let quit_loop = ref false in\r\n while not !quit_loop do\r\n let c = Bytes.get s !ptr in\r\n if is_digit c then quit_loop := true\r\n else ptr := !ptr + 1\r\n done;;\r\nlet readInt() = \r\n let () = check_reader() in\r\n let () = skip() in\r\n let quit_loop = ref false in \r\n let number = ref 0 in\r\n let () = \r\n while not !quit_loop do\r\n let c = Bytes.get s !ptr in\r\n if is_digit c then \r\n let () = number := !number * 10 + (digit c) in\r\n ptr := !ptr + 1\r\n else\r\n quit_loop := true\r\n done in\r\n !number;;\r\nlet readLong() =\r\n let () = check_reader() in\r\n let () = skip() in\r\n let quit_loop = ref false in \r\n let number = ref 0L in\r\n let () = \r\n while not !quit_loop do\r\n let c = Bytes.get s !ptr in\r\n if is_digit c then \r\n let () = number := add (mul !number 10L) (digitInt64 c) in\r\n ptr := !ptr + 1\r\n else\r\n quit_loop := true\r\n done in\r\n !number;;\r\nlet merge a b =\r\n let n = length a in\r\n let m = length b in\r\n let ret = make (n+m) 0L in\r\n let i = ref 0 in\r\n let j = ref 0 in\r\n let who = ref false in\r\n let ptr = ref 0 in\r\n while !ptr < (n+m) do\r\n let () = \r\n if !i < n then \r\n if !j < m then who := a.(!i) < b.(!j) \r\n else who := true\r\n else who := false in\r\n let () = \r\n if !who = true then ret.(!ptr) <- a.(!i)\r\n else ret.(!ptr) <- b.(!j) in\r\n let () = \r\n if !who = true then i := !i + 1\r\n else j := !j + 1 in\r\n ptr := !ptr + 1\r\n done; \r\n ret;; \r\nlet rec merge_sort a = \r\n if (length a) = 1 then a\r\n else \r\n let l = init ((length a + 1) / 2) (fun i -> a.(i)) in\r\n let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in\r\n merge (merge_sort l) (merge_sort r);;\r\nlet n = readLong() in\r\nlet k = ref (readLong()) in\r\nlet x = readLong() in\r\nlet a = Array.init (to_int n) (fun i -> readLong()) in\r\nif n = 1L then print_number n \r\nelse\r\n let sorted = merge_sort a in\r\n let cost = make (to_int n-1) 0L in\r\n let () = \r\n for i = 1 to (length a - 1) do\r\n let () = cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x) in\r\n if cost.(i-1) < 0L then cost.(i-1) <- 0L\r\n done in\r\n let sorted_cost = merge_sort cost in\r\n let answer = ref 1L in\r\n let () = \r\n for i = 0 to (length cost - 1) do\r\n if !k >= sorted_cost.(i) then\r\n k := Int64.sub !k sorted_cost.(i)\r\n else\r\n answer := Int64.add !answer 1L\r\n done in\r\n print_number !answer;;"}, {"source_code": "open Int64;;\r\nopen Array;;\r\nlet merge a b =\r\n let n = length a in\r\n let m = length b in\r\n let ret = make (n+m) 0L in\r\n let i = ref 0 in\r\n let j = ref 0 in\r\n let who = ref false in\r\n let ptr = ref 0 in\r\n while !ptr < (n+m) do\r\n let () = \r\n if !i < n then \r\n if !j < m then who := a.(!i) < b.(!j) \r\n else who := true\r\n else who := false in\r\n let () = \r\n if !who = true then ret.(!ptr) <- a.(!i)\r\n else ret.(!ptr) <- b.(!j) in\r\n let () = \r\n if !who = true then i := !i + 1\r\n else j := !j + 1 in\r\n ptr := !ptr + 1\r\n done; \r\n ret;; \r\nlet rec merge_sort a = \r\n if (length a) = 1 then a\r\n else \r\n let l = init ((length a + 1) / 2) (fun i -> a.(i)) in\r\n let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in\r\n merge (merge_sort l) (merge_sort r);;\r\nlet readLong () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet print_number x = print_string (to_string x);;\r\nlet n = readLong();;\r\nlet k = ref (readLong());;\r\nlet x = readLong();;\r\nlet a = Array.init (to_int n) (fun i -> readLong())\r\nlet sorted = merge_sort a;;\r\nlet cost = make (to_int n-1) 0L;; \r\nfor i = 1 to (length a - 1) do\r\n cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x)\r\ndone;;\r\nlet sorted_cost = merge_sort cost;;\r\nlet answer = ref 1L;;\r\nfor i = 0 to (length cost - 1) do\r\n if !k >= sorted_cost.(i) then\r\n k := Int64.sub !k sorted_cost.(i)\r\n else\r\n answer := Int64.add !answer 1L\r\ndone;;\r\nprint_number !answer;;"}], "src_uid": "c6c07ef23cf2def9f99cbfb6076c9810"} {"nl": {"description": "Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either pa\u2009>\u2009pb, or pa\u2009=\u2009pb and ta\u2009<\u2009tb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places y\u2009+\u20091, y\u2009+\u20092, ..., y\u2009+\u2009x. The teams that performed worse than the teams from this group, get their places in the results table starting from the y\u2009+\u2009x\u2009+\u20091-th place.Your task is to count what number of teams from the given list shared the k-th place. ", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u200950). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1\u2009\u2264\u2009pi,\u2009ti\u2009\u2264\u200950) \u2014 the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. ", "output_spec": "In the only line print the sought number of teams that got the k-th place in the final results' table.", "sample_inputs": ["7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n2 1\n1 10", "5 4\n3 1\n3 1\n5 3\n3 1\n3 1"], "sample_outputs": ["3", "4"], "notes": "NoteThe final results' table for the first sample is: 1-3 places \u2014 4 solved problems, the penalty time equals 10 4 place \u2014 3 solved problems, the penalty time equals 20 5-6 places \u2014 2 solved problems, the penalty time equals 1 7 place \u2014 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place \u2014 5 solved problems, the penalty time equals 3 2-5 places \u2014 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams."}, "positive_code": [{"source_code": "let _ =\n let main () =\n let n, k = Scanf.sscanf (read_line ()) \"%d %d\" (fun n k -> n, k) in\n let rec loop i acc =\n if i = 0 then acc else loop (i - 1) (Scanf.sscanf (read_line ()) \"%d %d\" (fun a b -> (a, b) :: acc))\n in\n let l = loop n [] in\n let l = List.sort (fun (p0, t0) (p1, t1) -> compare (-p0, t0) (-p1, t1)) l in\n let r =\n let rec loop pt n hist = function\n | [] -> n :: hist\n | hd :: tl -> if hd = pt then loop pt (n + 1) hist tl\n else loop hd 1 (n :: hist) tl\n in\n match l with\n | [] -> failwith \"\"\n | pt :: tl -> loop pt 1 [] tl\n in\n let rec loop i = function\n | [] -> failwith \"\"\n | hd :: tl -> if i <= k && k < i + hd then Printf.printf \"%d\\n\" hd else loop (i + hd) tl\n in\n loop 1 (List.rev r)\n in\n main ()\n"}], "negative_code": [], "src_uid": "63e03361531999db408dc0d02de93579"} {"nl": {"description": "Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi\u2009-\u2009(ti\u2009-\u2009k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value. ", "input_spec": "The first line contains two space-separated integers \u2014 n (1\u2009\u2264\u2009n\u2009\u2264\u2009104) and k (1\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers \u2014 fi (1\u2009\u2264\u2009fi\u2009\u2264\u2009109) and ti (1\u2009\u2264\u2009ti\u2009\u2264\u2009109) \u2014 the characteristics of the i-th restaurant.", "output_spec": "In a single line print a single integer \u2014 the maximum joy value that the Rabbits will get from the lunch. ", "sample_inputs": ["2 5\n3 3\n4 5", "4 6\n5 8\n3 6\n2 3\n2 2", "1 5\n1 7"], "sample_outputs": ["4", "3", "-1"], "notes": null}, "positive_code": [{"source_code": "open Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet n = gr();;\nlet k = gr();;\nlet optv = ref (- 1001000000);;\n\nlet main() = \n\tbegin\n\t\tfor i = 1 to n do\n\t\t\t\tlet f = gr () in\n\t\t\t\tlet t = gr () in\n\t\t\t\tlet v = if t > k then f - (t-k) else f in\n\t\t\t\tif v > !optv then\n\t\t\t\t\toptv := v\n\t\tdone;\n\t\tprint_int !optv; print_newline ()\n\tend;;\n\nmain();;"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet () = \n let (n,k) = read_pair() in\n let best = ref 0 in\n for i=0 to n-1 do\n let (f,t) = read_pair() in\n let score = if t > k then f - (t-k) else f in\n\tif score > !best || i=0 then best := score\n done;\n Printf.printf \"%d\\n\" !best\n"}], "negative_code": [], "src_uid": "1bb5b64657e16fb518d49d3c799d4823"} {"nl": {"description": "You are given a permutation $$$p$$$ of integers from $$$1$$$ to $$$n$$$, where $$$n$$$ is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type: take two indices $$$i$$$ and $$$j$$$ such that $$$2 \\cdot |i - j| \\geq n$$$ and swap $$$p_i$$$ and $$$p_j$$$. There is no need to minimize the number of operations, however you should use no more than $$$5 \\cdot n$$$ operations. One can show that it is always possible to do that.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 3 \\cdot 10^5$$$, $$$n$$$ is even)\u00a0\u2014 the length of the permutation. The second line contains $$$n$$$ distinct integers $$$p_1, p_2, \\ldots, p_n$$$ ($$$1 \\le p_i \\le n$$$)\u00a0\u2014 the given permutation.", "output_spec": "On the first line print $$$m$$$ ($$$0 \\le m \\le 5 \\cdot n$$$)\u00a0\u2014 the number of swaps to perform. Each of the following $$$m$$$ lines should contain integers $$$a_i, b_i$$$ ($$$1 \\le a_i, b_i \\le n$$$, $$$|a_i - b_i| \\ge \\frac{n}{2}$$$)\u00a0\u2014 the indices that should be swapped in the corresponding swap. Note that there is no need to minimize the number of operations. We can show that an answer always exists.", "sample_inputs": ["2\n2 1", "4\n3 4 1 2", "6\n2 5 3 1 4 6"], "sample_outputs": ["1\n1 2", "4\n1 4\n1 4\n1 3\n2 4", "3\n1 5\n2 5\n1 4"], "notes": "NoteIn the first example, when one swap elements on positions $$$1$$$ and $$$2$$$, the array becomes sorted.In the second example, pay attention that there is no need to minimize number of swaps.In the third example, after swapping elements on positions $$$1$$$ and $$$5$$$ the array becomes: $$$[4, 5, 3, 1, 2, 6]$$$. After swapping elements on positions $$$2$$$ and $$$5$$$ the array becomes $$$[4, 2, 3, 1, 5, 6]$$$ and finally after swapping elements on positions $$$1$$$ and $$$4$$$ the array becomes sorted: $$$[1, 2, 3, 4, 5, 6]$$$."}, "positive_code": [{"source_code": "\nlet swap res p pp i j =\n let t = pp.(p.(i)) in\n pp.(p.(i)) <- pp.(p.(j));\n pp.(p.(j)) <- t;\n let t = p.(i) in\n p.(i) <- p.(j);\n p.(j) <- t;\n (i, j) :: res\n\nlet () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let pp = Array.make (n+1) 0 in\n let p = Array.init (n+1) (fun i -> if i = 0 then 0 else let x = Scanf.scanf \"%d \" (fun x -> x) in pp.(x) <- i; x) in\n let n2 = n/2 in\n let res = ref [] in\n\n for i = 0 to n-2 do\n let ii = n-i in\n let j = pp.(ii) in\n if (ii <> j) then\n if (ii - j) >=n2 then res := swap !res p pp ii j\n else if (j <= n2 && ii <= n2) then begin\n res := swap !res p pp j n;\n res := swap !res p pp n ii;\n res := swap !res p pp j n\n end else if (j <= n2 && ii > n2) then begin\n res := swap !res p pp j n;\n res := swap !res p pp n 1;\n res := swap !res p pp 1 ii;\n res := swap !res p pp j n\n end else if (ii > n2) then begin\n res := swap !res p pp j 1;\n res := swap !res p pp 1 ii\n end else begin\n res := swap !res p pp j 1;\n res := swap !res p pp 1 ii;\n end\n done;\n let ln = List.length !res in\n Printf.printf \"%d\\n\" ln;\n List.iter (fun (x, y) -> Printf.printf \"%d %d\\n\" x y) (!res |> List.rev)\n;;\n"}], "negative_code": [{"source_code": "let swap res p pp i j =\n let t = pp.(p.(i)) in\n pp.(p.(i)) <- pp.(p.(j));\n pp.(p.(j)) <- t;\n let t = p.(i) in\n p.(i) <- p.(j);\n p.(j) <- t;\n (i, j) :: res\n\nlet () =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let pp = Array.make (n+1) 0 in\n let p = Array.init (n+1) (fun i -> if i = 0 then 0 else let x = Scanf.scanf \"%d \" (fun x -> x) in pp.(x) <- i; x) in\n let n2 = n/2 in\n let res = ref [] in\n\n for i = 0 to n-2 do\n let ii = n-i in\n let j = pp.(ii) in\n if (ii <> j) then\n if (ii - j) >=n2 then res := swap !res p pp ii j\n else if (j <= n2 && ii <= n2) then begin\n res := swap !res p pp j n;\n res := swap !res p pp n ii;\n res := swap !res p pp j n\n end else if (j <= n2 && ii > n2) then begin\n res := swap !res p pp j n;\n res := swap !res p pp n 1;\n res := swap !res p pp 1 ii;\n res := swap !res p pp j n\n end else if (ii > n2) then begin\n res := swap !res p pp j 0;\n res := swap !res p pp 0 ii\n end else begin\n res := swap !res p pp j 0;\n res := swap !res p pp 0 ii;\n end\n done;\n let ln = List.length !res in\n Printf.printf \"%d\\n\" ln;\n List.iter (fun (x, y) -> Printf.printf \"%d %d\\n\" x y) (!res |> List.rev)\n;;\n"}], "src_uid": "b1706815238eb940060231848e43ffa8"} {"nl": {"description": "Ashish has $$$n$$$ elements arranged in a line. These elements are represented by two integers $$$a_i$$$\u00a0\u2014 the value of the element and $$$b_i$$$\u00a0\u2014 the type of the element (there are only two possible types: $$$0$$$ and $$$1$$$). He wants to sort the elements in non-decreasing values of $$$a_i$$$.He can perform the following operation any number of times: Select any two elements $$$i$$$ and $$$j$$$ such that $$$b_i \\ne b_j$$$ and swap them. That is, he can only swap two elements of different types in one move. Tell him if he can sort the elements in non-decreasing values of $$$a_i$$$ after performing any number of operations.", "input_spec": "The first line contains one integer $$$t$$$ $$$(1 \\le t \\le 100)$$$\u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ $$$(1 \\le n \\le 500)$$$\u00a0\u2014 the size of the arrays. The second line contains $$$n$$$ integers $$$a_i$$$ $$$(1 \\le a_i \\le 10^5)$$$ \u00a0\u2014 the value of the $$$i$$$-th element. The third line containts $$$n$$$ integers $$$b_i$$$ $$$(b_i \\in \\{0, 1\\})$$$ \u00a0\u2014 the type of the $$$i$$$-th element.", "output_spec": "For each test case, print \"Yes\" or \"No\" (without quotes) depending on whether it is possible to sort elements in non-decreasing order of their value. You may print each letter in any case (upper or lower).", "sample_inputs": ["5\n4\n10 20 20 30\n0 1 0 1\n3\n3 1 2\n0 1 1\n4\n2 2 4 8\n1 1 1 1\n3\n5 15 4\n0 0 0\n4\n20 10 100 50\n1 0 0 1"], "sample_outputs": ["Yes\nYes\nYes\nNo\nYes"], "notes": "NoteFor the first case: The elements are already in sorted order.For the second case: Ashish may first swap elements at positions $$$1$$$ and $$$2$$$, then swap elements at positions $$$2$$$ and $$$3$$$.For the third case: The elements are already in sorted order.For the fourth case: No swap operations may be performed as there is no pair of elements $$$i$$$ and $$$j$$$ such that $$$b_i \\ne b_j$$$. The elements cannot be sorted.For the fifth case: Ashish may swap elements at positions $$$3$$$ and $$$4$$$, then elements at positions $$$1$$$ and $$$2$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n let b = Array.init n read_int in \n\n let is_sorted = forall 0 (n-2) (fun i -> a.(i) <= a.(i+1)) in\n let has_0 = exists 0 (n-1) (fun i -> b.(i) = 0) in\n let has_1 = exists 0 (n-1) (fun i -> b.(i) = 1) in\n\n if is_sorted || (has_0 && has_1) then printf \"Yes\\n\" else printf \"No\\n\"\n done\n"}], "negative_code": [], "src_uid": "4bf3a94119d08a9cd6075a67d0014061"} {"nl": {"description": "There is a straight line colored in white. n black segments are added on it one by one.After each segment is added, determine the number of connected components of black segments (i.\u00a0e. the number of black segments in the union of the black segments). In particular, if one segment ends in a point x, and another segment starts in the point x, these two segments belong to the same connected component.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000) \u2014 the number of segments. The i-th of the next n lines contains two integers li and ri (1\u2009\u2264\u2009li\u2009<\u2009ri\u2009\u2264\u2009109) \u2014 the coordinates of the left and the right ends of the i-th segment. The segments are listed in the order they are added on the white line.", "output_spec": "Print n integers \u2014 the number of connected components of black segments after each segment is added. ", "sample_inputs": ["3\n1 3\n4 5\n2 4", "9\n10 20\n50 60\n30 40\n70 80\n90 100\n60 70\n10 40\n40 50\n80 90"], "sample_outputs": ["1 2 1", "1 2 3 4 5 4 3 2 1"], "notes": "NoteIn the first example there are two components after the addition of the first two segments, because these segments do not intersect. The third added segment intersects the left segment and touches the right segment at the point 4 (these segments belong to the same component, according to the statements). Thus the number of connected components of black segments is equal to 1 after that."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet n = read_int();;\nlet l = Array.make (2*n) (0,0,0);;\nlet qs = Array.init n (fun i -> let x = read_int() in let y = read_int() in\n Array.set l (2*i) (x,i,0);\n Array.set l (2*i+1) (y,i,1);\n x,y);;\nArray.sort Pervasives.compare l;;\nlet i = ref 0;;\nlet (last0,_,_) = l.(0);;\nlet last = ref last0;;\nArray.iter (fun (v,ii,j) ->\n if(v <> !last) then (incr i; last := v);\n let (x,y) = qs.(ii) in\n if(j = 0) then Array.set qs ii (!i,y) else Array.set qs ii (x,!i);\n ()\n ) l;;\nincr i;;\n\n(* let fromX = Hashtbl.create 200000;;\n * S.iter (fun x -> Hashtbl.add fromX x !i; incr i) !allX;;\n *\n * let qs : (int*int) array = Array.map (fun (x,y) -> (Hashtbl.find fromX x, Hashtbl.find fromX y)) qs;; *)\n\nlet uf = Array.init !i (fun j -> j);;\nlet ur = Array.init !i (fun j -> 1);;\nlet ufr = Array.init !i (fun j -> j);;\nlet um = Array.init !i (fun j -> false);;\nlet ans = ref 0;;\n\nlet rec find i = if uf.(i) == i then i else (Array.set uf i (find uf.(i)); uf.(i));;\n\nlet mark i = let i = find i in\n if not um.(i) then (Array.set um i true; incr ans)\n;;\n\nlet aux i j =\n Array.set uf i j;\n Array.set ufr j (max ufr.(i) ufr.(j));\n if(um.(i) && um.(j)) then decr ans;\n Array.set um j (um.(i) || um.(j));\n if ur.(j) = ur.(i) then Array.set ur j (ur.(j)+1)\n;;\n\nlet unite i j =\n let i = find i in\n let j = find j in\n if i <> j then begin\n if(ur.(i) < ur.(j)) then aux i j\n else aux j i\n end;;\n\nArray.iter (fun (x,y) -> begin\n let i = ref (find x) in\n mark !i;\n while y > ufr.(!i) do\n unite !i (ufr.(!i)+1);\n i := find !i\n done;\n Printf.printf \"%d \" !ans\n end) qs;;\n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "3979abbe7bad0f3b5cab15c1cba19f6b"} {"nl": {"description": "You are given a permutation $$$p_1, p_2, \\dots, p_n$$$. A permutation of length $$$n$$$ is a sequence such that each integer between $$$1$$$ and $$$n$$$ occurs exactly once in the sequence.Find the number of pairs of indices $$$(l, r)$$$ ($$$1 \\le l \\le r \\le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \\dots, p_r$$$ is exactly the given number $$$m$$$.The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.For example, if $$$a=[4, 2, 7, 5]$$$ then its median is $$$4$$$ since after sorting the sequence, it will look like $$$[2, 4, 5, 7]$$$ and the left of two middle elements is equal to $$$4$$$. The median of $$$[7, 1, 2, 9, 6]$$$ equals $$$6$$$ since after sorting, the value $$$6$$$ will be in the middle of the sequence.Write a program to find the number of pairs of indices $$$(l, r)$$$ ($$$1 \\le l \\le r \\le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \\dots, p_r$$$ is exactly the given number $$$m$$$.", "input_spec": "The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2\\cdot10^5$$$, $$$1 \\le m \\le n$$$) \u2014 the length of the given sequence and the required value of the median. The second line contains a permutation $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$). Each integer between $$$1$$$ and $$$n$$$ occurs in $$$p$$$ exactly once.", "output_spec": "Print the required number.", "sample_inputs": ["5 4\n2 4 5 3 1", "5 5\n1 2 3 4 5", "15 8\n1 15 2 14 3 13 4 8 12 5 11 6 10 7 9"], "sample_outputs": ["4", "1", "48"], "notes": "NoteIn the first example, the suitable pairs of indices are: $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$ and $$$(2, 4)$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Int64 = struct \n\tinclude Int64\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\tlet (~~|) p = Int64.of_int p\n\tlet (~|) p = Int64.to_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\nend open Int64\n\nlet () =\n\tlet n,m = get_2_i64 ()\n\tin let ar = input_i64_array n\n\tin\n\tlet idx = \n\t\tlet idx = ref 0 in\n\t\tArray.iteri (fun i v -> if v=m then idx:=i) ar;\n\t\t!idx;\n\tin\n\tlet c = Array.make 500010 0L\n\tin let ofs = 250000\n\tin let sum,ans = ref ~~| ofs,ref 0L\n\tin c.(ofs) <- 1L;\n\tfor i=0 to idx-$1 do\n\t\tif ar.(i) < m then sum+= -1L else if ar.(i) > m then sum+= 1L;\n\t\tc.(~| !sum) <- c.(~| !sum) + 1L;\n\tdone;\n\tfor i=idx to ~|n-$1 do\n\t\tif ar.(i) < m then sum+= -1L else if ar.(i) > m then sum+= 1L;\n\t\tans += (c.(~| !sum) + c.((~| !sum) -$ 1));\n\tdone;\n\t!ans |> print_i64_endline"}], "negative_code": [], "src_uid": "52e1fd9d3c82cd70c686e575c92c1442"} {"nl": {"description": "The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of $$$n$$$ characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly $$$0$$$) on this string, partitioning it into several contiguous pieces, each with length at least $$$1$$$. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!For a string we define a ratio as $$$a:b$$$ where 'D' appears in it $$$a$$$ times, and 'K' appears $$$b$$$ times. Note that $$$a$$$ or $$$b$$$ can equal $$$0$$$, but not both. Ratios $$$a:b$$$ and $$$c:d$$$ are considered equal if and only if $$$a\\cdot d = b\\cdot c$$$. For example, for the string 'DDD' the ratio will be $$$3:0$$$, for 'DKD' \u2014 $$$2:1$$$, for 'DKK' \u2014 $$$1:2$$$, and for 'KKKKDD' \u2014 $$$2:4$$$. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 5 \\cdot 10^5$$$)\u00a0\u2014 the length of the wood. The second line of each test case contains a string $$$s$$$ of length $$$n$$$. Every character of $$$s$$$ will be either 'D' or 'K'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \\cdot 10^5$$$.", "output_spec": "For each test case, output $$$n$$$ space separated integers. The $$$i$$$-th of these numbers should equal the answer for the prefix $$$s_{1},s_{2},\\dots,s_{i}$$$.", "sample_inputs": ["5\n3\nDDK\n6\nDDDDDD\n4\nDKDK\n1\nD\n9\nDKDKDDDDK"], "sample_outputs": ["1 2 1 \n1 2 3 4 5 6 \n1 1 1 2 \n1 \n1 1 1 2 1 2 1 1 3"], "notes": "NoteFor the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.For the second test case, you can split each prefix of length $$$i$$$ into $$$i$$$ blocks 'D'."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let s = read_string () in\n let h = Hashtbl.create 10 in\n let rec loop i d k = if i=n then () else (\n (* processing index i, (d,k) = number seen already *)\n let (d,k) = if s.[i] = 'D' then (d+1,k) else (d,k+1) in\n let g = gcd d k in\n let c = try Hashtbl.find h (d/g, k/g) with Not_found -> 0 in\n Hashtbl.replace h (d/g,k/g) (c+1);\n printf \"%d \" (c+1);\n loop (i+1) d k\n ) in\n\n loop 0 0 0;\n print_newline()\n done\n"}], "negative_code": [], "src_uid": "de2e2e12be4464306beb0217875f66c7"} {"nl": {"description": "Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j\u2009<\u2009i and j\u2009\u2265\u2009i\u2009-\u2009Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.", "input_spec": "The first line contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the number of guilty people. Second line contains n space-separated integers L1,\u2009L2,\u2009...,\u2009Ln (0\u2009\u2264\u2009Li\u2009\u2264\u2009109), where Li is the length of the i-th person's claw.", "output_spec": "Print one integer \u2014 the total number of alive people after the bell rings.", "sample_inputs": ["4\n0 1 0 10", "2\n0 0", "10\n1 1 3 0 0 0 2 1 0 3"], "sample_outputs": ["1", "2", "3"], "notes": "NoteIn first sample the last person kills everyone in front of him."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let claw = Array.init n read_int in\n\n let rec scan i reach ac = if i<0 then ac else (\n let ac = if reach > i then ac+1 else ac in\n let reach = min reach (i - claw.(i)) in\n scan (i-1) reach ac\n ) in\n\n printf \"%d\\n\" (scan (n-1) n 0)\n"}], "negative_code": [], "src_uid": "beaeeb8757232b141d510547d73ade04"} {"nl": {"description": "Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.", "input_spec": "The only input line contains three space-separated integers b, n and c (2\u2009\u2264\u2009b\u2009<\u200910106, 1\u2009\u2264\u2009n\u2009<\u200910106, 1\u2009\u2264\u2009c\u2009\u2264\u2009109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.", "output_spec": "In the only line output the amount of numbers written on the same page as the last number.", "sample_inputs": ["2 3 3", "2 3 4"], "sample_outputs": ["1", "4"], "notes": "NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page."}, "positive_code": [{"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\nlet flip f x y = f y x\n\nopen Int64\n\nlet ( ++ ) = add\nlet ( -- ) = sub\nlet ( ** ) = mul\nlet ( // ) = div\nlet ( %% ) = rem\n\nlet phi x =\n let rec go acc x i =\n if i**i > x then\n acc, x\n else if x%%i = 0L then\n let rec go2 x =\n if x%%i <> 0L then\n x\n else\n go2 (x//i)\n in\n go (acc--acc//i) (go2 x) (i++1L)\n else\n go acc x (i++1L)\n in\n let r,x = go x x 2L in\n if x > 1L then\n r--r//x\n else\n r\n\nlet f a p =\n let rec go acc i =\n if i >= String.length a then\n acc\n else\n let acc' = (acc**10L ++ (int_of_char a.[i] - 48 |> of_int)) %%p in\n go acc' (i+1)\n in\n go 0L 0\n\nlet powmod a n p =\n let rec go r a n =\n if n = 0L then\n r\n else if logand n 1L <> 0L then\n go (r**a%%p) (a**a%%p) (n//2L)\n else\n go r (a**a%%p) (n//2L)\n in\n go 1L a n\n\nlet () =\n let bb = read_str 0 in\n let nn = read_str 0 in\n let c = read_int64 0 in\n let phi_c = phi c in\n\n let b = f bb c in\n let n = if String.length nn >= 10 then\n f nn phi_c ++ phi_c\n else\n let n = of_string nn in\n if n--1L >= phi_c then\n n%%phi_c++phi_c\n else\n n\n in\n powmod b (n--1L) c ** (b++c--1L) %% c\n |> (fun x -> if x = 0L then c else x)\n |> Printf.printf \"%Ld\\n\""}, {"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\nlet flip f x y = f y x\n\nopen Int64\n\nlet ( ++ ) = add\nlet ( -- ) = sub\nlet ( ** ) = mul\nlet ( // ) = div\nlet ( %% ) = rem\n\nlet phi x =\n let rec go acc x i =\n if i**i > x then\n acc, x\n else if x%%i = 0L then\n let rec go2 x =\n if x%%i <> 0L then\n x\n else\n go2 (x//i)\n in\n go (acc--acc//i) (go2 x) (i++1L)\n else\n go acc x (i++1L)\n in\n let r,x = go x x 2L in\n if x > 1L then\n r--r//x\n else\n r\n\nlet f a p =\n let rec go acc i =\n if i >= String.length a then\n acc\n else\n let acc' = (acc**10L ++ (int_of_char a.[i] - 48 |> of_int)) %%p in\n go acc' (i+1)\n in\n go 0L 0\n\nlet powmod a n p =\n let rec go r a n =\n if n = 0L then\n r\n else if logand n 1L <> 0L then\n go (r**a%%p) (a**a%%p) (n//2L)\n else\n go r (a**a%%p) (n//2L)\n in\n go 1L a n\n\nlet () =\n let bb = read_str 0 in\n let nn = read_str 0 in\n let c = read_int64 0 in\n let phi_c = phi c in\n\n let b = f bb c in\n let n = if String.length nn >= 10 then\n f nn phi_c ++ phi_c\n else\n let n = of_string nn in\n if n--1L >= phi_c then\n n%%phi_c++phi_c\n else\n n\n in\n powmod b (n--1L) c ** (b++c--1L) %% c\n |> (fun x -> if x = 0L then c else x)\n |> Printf.printf \"%Ld\\n\"\n"}], "negative_code": [{"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\nlet flip f x y = f y x\n\nopen Int64\n\nlet ( ++ ) = add\nlet ( -- ) = sub\nlet ( ** ) = mul\nlet ( // ) = div\nlet ( %% ) = rem\n\nlet phi x =\n let rec go acc x i =\n if i**i > x then\n acc, x\n else if x%%i = 0L then\n let rec go2 x =\n if x%%i <> 0L then\n x\n else\n go2 (x//i)\n in\n go (acc--acc//i) (go2 x) (i++1L)\n else\n go acc x (i++1L)\n in\n let r,x = go x x 2L in\n if x > 1L then\n r--r//x\n else\n r\n\nlet f a p =\n let rec go acc i =\n if i >= String.length a then\n acc\n else\n let acc' = (acc**10L ++ (int_of_char a.[i] - 48 |> of_int)) %%p in\n go acc' (i+1)\n in\n go 0L 0\n\nlet powmod a n p =\n let rec go r a n =\n if n = 0L then\n r\n else if logand n 1L <> 0L then\n go (r**a%%p) (a**a%%p) (n//2L)\n else\n go r (a**a%%p) (n//2L)\n in\n go 1L a n\n\nlet () =\n let bb = read_str 0 in\n let nn = read_str 0 in\n let c = read_int64 0 in\n let phi_c = phi c in\n\n let b = f bb c in\n let b1 = b++c--1L in\n let n = f nn phi_c in\n let n1 = n++phi_c--1L in\n powmod b n1 c ** b1 %% c\n |> (fun x -> if x = 0L then c else x)\n |> Printf.printf \"%Ld\\n\"\n"}], "src_uid": "566adc43d2d6df257c26c5f5495a5745"} {"nl": {"description": "Wilbur the pig really wants to be a beaver, so he decided today to pretend he is a beaver and bite at trees to cut them down.There are n trees located at various positions on a line. Tree i is located at position xi. All the given positions of the trees are distinct.The trees are equal, i.e. each tree has height h. Due to the wind, when a tree is cut down, it either falls left with probability p, or falls right with probability 1\u2009-\u2009p. If a tree hits another tree while falling, that tree will fall in the same direction as the tree that hit it. A tree can hit another tree only if the distance between them is strictly less than h. For example, imagine there are 4 trees located at positions 1, 3, 5 and 8, while h\u2009=\u20093 and the tree at position 1 falls right. It hits the tree at position 3 and it starts to fall too. In it's turn it hits the tree at position 5 and it also starts to fall. The distance between 8 and 5 is exactly 3, so the tree at position 8 will not fall.As long as there are still trees standing, Wilbur will select either the leftmost standing tree with probability 0.5 or the rightmost standing tree with probability 0.5. Selected tree is then cut down. If there is only one tree remaining, Wilbur always selects it. As the ground is covered with grass, Wilbur wants to know the expected total length of the ground covered with fallen trees after he cuts them all down because he is concerned about his grass-eating cow friends. Please help Wilbur.", "input_spec": "The first line of the input contains two integers, n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) and h (1\u2009\u2264\u2009h\u2009\u2264\u2009108) and a real number p (0\u2009\u2264\u2009p\u2009\u2264\u20091), given with no more than six decimal places. The second line of the input contains n integers, x1,\u2009x2,\u2009...,\u2009xn (\u2009-\u2009108\u2009\u2264\u2009xi\u2009\u2264\u2009108) in no particular order.", "output_spec": "Print a single real number\u00a0\u2014 the expected total length of the ground covered by trees when they have all fallen down. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["2 2 0.500000\n1 2", "4 3 0.4\n4 3 1 2"], "sample_outputs": ["3.250000000", "6.631200000"], "notes": "NoteConsider the first example, we have 2 trees with height 2. There are 3 scenarios: 1. Both trees falls left. This can either happen with the right tree falling left first, which has probability (also knocking down the left tree), or the left tree can fall left and then the right tree can fall left, which has probability. Total probability is . 2. Both trees fall right. This is analogous to (1), so the probability of this happening is . 3. The left tree fall left and the right tree falls right. This is the only remaining scenario so it must have probability. Cases 1 and 2 lead to a total of 3 units of ground covered, while case 3 leads to a total of 4 units of ground covered. Thus, the expected value is ."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac +. (f i))\nlet comp x = 1.0 -. x\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_float () = bscanf Scanning.stdib \" %f \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let h = read_int () in\n let pl = read_float () in\n let x = Array.init n (fun _ -> read_int()) in\n Array.sort compare x;\n\n let pr = comp pl in\n\n let topple_left = Array.make n 0 in\n let topple_right = Array.make n (n-1) in\n\n for i=1 to n-1 do\n topple_left.(i) <- if x.(i) - x.(i-1) < h then topple_left.(i-1) else i;\n let j = n-1-i in\n topple_right.(j) <- if x.(j+1) - x.(j) < h then topple_right.(j+1) else j; \n done;\n\n let p = Array.make_matrix n (4*n) 0.0 in\n let int = Array.make ((n+1)*4) 0.0 in\n let inc i j ldir rdir x =\n if i <= j then\n let ind = 4*j + 2*ldir + rdir in\n p.(i).(ind) <- x +. p.(i).(ind)\n in\n\n let incx i ldir rdir x =\n let ind = 4*i + 2*ldir + rdir in\n int.(ind) <- x +. int.(ind)\n in\n\n let geti i ldir rdir = int.(4*i + 2*ldir + rdir) in\n let getp i j ldir rdir = p.(i).(4*j + 2*ldir + rdir) in \n\n inc 0 (n-1) 0 1 1.0;\n\n for i=0 to n-1 do\n for j=n-1 downto i do\n for ldir = 0 to 1 do\n for rdir = 0 to 1 do\n let pstate = getp i j ldir rdir in\n let xl = pstate *. 0.5 *. pl in\n let xr = pstate *. 0.5 *. pr in\n inc (i+1) j 0 rdir xl;\n incx i ldir 0 xl;\n if i=j then incx (j+1) 0 rdir xl;\n inc i (j-1) ldir 1 xr;\n incx (j+1) 1 rdir xr;\n if i=j then incx i ldir 1 xr;\n inc (topple_right.(i)+1) j 1 rdir xr;\n incx i ldir 1 xr;\n if topple_right.(i) >= j then incx (j+1) 1 rdir xr;\n inc i (topple_left.(j)-1) ldir 0 xl;\n incx (j+1) 0 rdir xl;\n if topple_left.(j) <= i then incx i ldir 0 xl; \n done\n done\n done\n done;\n\n let evaluate_gap i =\n let d = if i=0 || i=n then h else x.(i) - x.(i-1) in\n if d < h then\n (comp (geti i 0 1)) *. (float d)\n else\n (geti i 1 0) *. (float (min d (2*h))) +. ((geti i 0 0) +. (geti i 1 1)) *. (float h)\n in\n\n printf \"%1.9f\\n\" (sum 0 n evaluate_gap 0.0)"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac +. (f i))\nlet comp x = 1.0 -. x\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_float () = bscanf Scanning.stdib \" %f \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let h = read_int () in\n let pl = read_float () in\n let x = Array.init n (fun _ -> read_int()) in\n Array.sort compare x;\n\n let pr = comp pl in\n\n let topple_left = Array.make n 0 in\n let topple_right = Array.make n (n-1) in\n\n for i=1 to n-1 do\n topple_left.(i) <- if x.(i) - x.(i-1) < h then topple_left.(i-1) else i;\n let j = n-1-i in\n topple_right.(j) <- if x.(j+1) - x.(j) < h then topple_right.(j+1) else j; \n done;\n\n let p = Array.make_matrix n (4*n) 0.0 in\n let int = Array.make ((n+1)*4) 0.0 in\n let inc i j ldir rdir x =\n if i <= j then\n let ind = 4*j + 2*ldir + rdir in\n p.(i).(ind) <- x +. p.(i).(ind)\n in\n\n let incx i ldir rdir x =\n let ind = 4*i + 2*ldir + rdir in\n int.(ind) <- x +. int.(ind)\n in\n\n let geti i ldir rdir = int.(4*i + 2*ldir + rdir) in\n let getp i j ldir rdir = p.(i).(4*j + 2*ldir + rdir) in \n\n inc 0 (n-1) 0 1 1.0;\n\n for i=0 to n-1 do\n for j=n-1 downto i do\n for ldir = 0 to 1 do\n\tfor rdir = 0 to 1 do\n\t let pstate = getp i j ldir rdir in\n\t let xl = pstate *. 0.5 *. pl in\n\t let xr = pstate *. 0.5 *. pr in\n\t inc (i+1) j 0 rdir xl;\n\t incx i ldir 0 xl;\n\t if i=j then incx (j+1) 0 rdir xl;\n\t inc i (j-1) ldir 1 xr;\n\t incx (j+1) 1 rdir xr;\n\t if i=j then incx i ldir 1 xr;\n\t inc (topple_right.(i)+1) j 1 rdir xr;\n\t incx i ldir 1 xr;\n\t if topple_right.(i) >= j then incx (j+1) 1 rdir xr;\n\t inc i (topple_left.(j)-1) ldir 0 xl;\n\t incx (j+1) 0 rdir xl;\n\t if topple_left.(j) <= i then incx i ldir 0 xl;\t \n\tdone\n done\n done\n done;\n\n let evaluate_gap i =\n let d = if i=0 || i=n then h else x.(i) - x.(i-1) in\n if d < h then\n (comp (geti i 0 1)) *. (float d)\n else\n (geti i 1 0) *. (float (min d (2*h))) +. ((geti i 0 0) +. (geti i 1 1)) *. (float h)\n in\n\n printf \"%1.9f\\n\" (sum 0 n evaluate_gap 0.0)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\n\nlet comp x = 1.0 -. x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_float () = bscanf Scanning.stdib \" %f \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let h = read_int () in\n let pl = read_float () in\n let x = Array.init n (fun _ -> read_int()) in\n Array.sort compare x;\n\n let pr = comp pl in\n\n let topple_left = Array.make n 0 in\n (* topple_left.(i) is the furthest one to the left that topples\n as a result of toppling i to the left *)\n let topple_right = Array.make n (n-1) in\n\n for i=1 to n-1 do\n topple_left.(i) <- if x.(i) - x.(i-1) < h then topple_left.(i-1) else i;\n let j = n-1-i in\n topple_right.(j) <- if x.(j+1) - x.(j) < h then topple_right.(j+1) else j; \n done;\n\n let p = Array.make_matrix n (4*n) 0.0 in\n (* p.(i).(j).(lfalldir).(rfalldir) is the probability of the situation\n where the upright trees are [i,j] and the one to the left of this\n fell in direction lfalldir (0=left, 1=right) and the one to the\n right fell in rfalldir. *)\n\n let int = Array.make ((n+1)*4) 0.0 in\n (* represents the interval (numbered starting from 0 on the left)\n Stores the probability for each of the four ways the interval\n can be resolved. Actually, for short intervals only the \n resolution (0,1) i.e. (left, right) is used *)\n \n let inc i j ldir rdir x =\n if i <= j then\n let ind = 4*j + 2*ldir + rdir in\n p.(i).(ind) <- x +. p.(i).(ind)\n in\n\n let incx i ldir rdir x =\n let ind = 4*i + 2*ldir + rdir in\n int.(ind) <- x +. int.(ind)\n in\n\n let geti i ldir rdir = int.(4*i + 2*ldir + rdir) in\n let getp i j ldir rdir = p.(i).(4*j + 2*ldir + rdir) in \n\n inc 0 (n-1) 0 1 1.0;\n\n for d=n-1 downto 0 do\n for i=0 to n-1-d do\n let j = i+d in\n for ldir = 0 to 1 do\n\tfor rdir = 0 to 1 do\n\t let pstate = getp i j ldir rdir in\n\t let xl = pstate *. 0.5 *. pl in\n\t let xr = pstate *. 0.5 *. pr in\n\t (* i falls to the left *)\n\t inc (i+1) j 0 rdir xl;\n\t incx i ldir 0 xl;\n\t if i=j then incx (j+1) 0 rdir xl;\n\t (* j falls to the right *)\n\t inc i (j-1) ldir 1 xr;\n\t incx (j+1) 1 rdir xr;\n\t if i=j then incx i ldir 1 xr;\n\t (* i falls to the right *)\n\t inc (topple_right.(i)+1) j 1 rdir xr;\n\t incx i ldir 1 xr;\n\t if topple_right.(i) >= j then incx (j+1) 1 rdir xr;\n\t (* j falls to the left *)\n\t inc i (topple_left.(j)-1) ldir 0 xl;\n\t incx (j+1) 0 rdir xl;\n\t if topple_left.(j) <= i then incx i ldir 0 xl;\t \n\tdone\n done\n done\n done;\n\n let evaluate_gap i =\n let d = if i=0 || i=n then h else x.(i) - x.(i-1) in\n if d < h then\n (comp (geti i 0 1)) *. (float d)\n else\n (geti i 1 0) *. (float (min d (2*h))) +. ((geti i 0 0) +. (geti i 1 1)) *. (float h)\n in\n\n printf \"%1.9f\\n\" (sum 0 n evaluate_gap)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\n\nlet comp x = 1.0 -. x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_float () = bscanf Scanning.stdib \" %f \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let h = read_int () in\n let pr = read_float () in\n let x = Array.init n (fun _ -> read_int()) in\n Array.sort compare x;\n\n let g = Array.make_matrix (n+1) (n+1) (-1.0) in\n (* g.(a).(b) is the probability that an interval with\n a trees on the left and b trees on the right survives. *)\n\n let pl = comp pr in\n \n g.(0).(1) <- pr;\n g.(1).(0) <- pl;\n g.(0).(0) <- 1.0;\n \n let rec compg a b =\n if g.(a).(b) >= 0.0 then g.(a).(b) else\n let answer = match (a,b) with\n\t| (0,_) -> 0.5 *. (pr *. (compg 0 (b-1)) +. pr)\n\t| (_,0) -> 0.5 *. (pl *. (compg (a-1) 0) +. pl)\n\t| (_,_) -> 0.5 *. (pl *. (compg (a-1) b) +. pr *. (compg a (b-1)))\n in\n g.(a).(b) <- answer;\n answer\n in\n\n let rec find_blocks i j ac = if j=n-1 then (i,j)::ac else\n (* i....j is an initial part of a block *)\n if x.(j+1) < h + x.(j)\n then find_blocks i (j+1) ac\n else find_blocks (j+1) (j+1) ((i,j)::ac)\n in\n\n let block = Array.of_list (List.rev (find_blocks 0 0 [])) in\n let nb = Array.length block in\n\n (*\n for i=0 to nb-1 do\n printf \"block: (%d,%d) \" (fst block.(i)) (snd block.(i))\n done;\n print_newline();\n\n for a=0 to n do\n for b=0 to n-a do\n printf \"g.(%d).(%d) = %f\\n\" a b (compg a b)\n done\n done;\n *)\n let e_internal_coverage (i,j) =\n sum (i+1) j (fun k ->\n let len = float (x.(k) - x.(k-1)) in\n len *. (comp (compg (k-i) (j+1-k)))\n )\n in\n\n let e_total_coverage =\n sum 0 (nb-1) (fun k -> e_internal_coverage block.(k))\n in\n\n let e_boundary_coverage =\n sum 1 (nb-1) (fun k ->\n let (i,j) = block.(k) in\n let (i',j') = block.(k-1) in\n let lp = comp (compg 0 (j-i+1)) in\n let rp = comp (compg (j'-i'+1) 0) in\n lp *. rp *. (float (min (x.(i) - x.(j')) (2*h))) +.\n\t(comp lp) *. rp *. (float h) +.\n\tlp *. (comp rp) *. (float h)\n )\n in\n\n let e_ends =\n let (i,j) = block.(0) in\n let e_left_end = (comp (compg 0 (j-i+1))) *. (float h) in\n let (i,j) = block.(nb-1) in \n let e_right_end = (comp (compg (j-i+1) 0)) *. (float h) in\n e_left_end +. e_right_end\n in\n\n let answer = e_total_coverage +. e_boundary_coverage +. e_ends in\n\n printf \"%1.9f\\n\" answer\n"}], "src_uid": "c08d8313fccb1f5fa291bb4945747843"} {"nl": {"description": "There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i\u2009+\u20091)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i\u2009-\u20091)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s,\u2009t by looking at the footprints.", "input_spec": "The first line of the input contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u20091000). The second line contains the description of the road \u2014 the string that consists of n characters. Each character will be either \".\" (a block without footprint), or \"L\" (a block with a left footprint), \"R\" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to \".\". Also, the first and the last character will always be \".\". It's guaranteed that a solution exists.", "output_spec": "Print two space-separated integers \u2014 the values of s and t. If there are several possible solutions you can print any of them.", "sample_inputs": ["9\n..RRLL...", "11\n.RRRLLLLL.."], "sample_outputs": ["3 4", "7 5"], "notes": "NoteThe first test sample is the one in the picture."}, "positive_code": [{"source_code": "open String\nopen Printf\nopen Scanf\nlet solve : (string -> int * int) = function\n | str when (not (contains str 'L')) -> (index str 'R' + 1, rindex str 'R' + 2)\n | str when (not (contains str 'R')) -> (rindex str 'L' + 1, index str 'L')\n | str -> (index str 'R' + 1, rindex str 'R' + 1);;\nlet (s,t) = scanf \"%d %s\" (fun _ -> solve);;\nPrintf.printf \"%d %d\\n\" s t\n"}, {"source_code": "open String\nopen Printf\nopen Scanf\nlet solve : (string -> int * int) = function\n | str when not (contains str 'L') -> index str 'R' + 1, rindex str 'R' + 2\n | str when not (contains str 'R') -> rindex str 'L' + 1, index str 'L'\n | str -> index str 'R' + 1, rindex str 'R' + 1;;\nlet s,t = scanf \"%d %s\" (fun _ -> solve);;\nprintf \"%d %d\\n\" s t\n"}], "negative_code": [], "src_uid": "3053cba2426ebd113fcd70a9b026dad0"} {"nl": {"description": "The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.Let's consider a rectangular image that is represented with a table of size n\u2009\u00d7\u2009m. The table elements are integers that specify the brightness of each pixel in the image.A feature also is a rectangular table of size n\u2009\u00d7\u2009m. Each cell of a feature is painted black or white.To calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of W\u2009-\u2009B, where W is the total brightness of the pixels in the image, covered with white feature cells, and B is the total brightness of the pixels covered with black feature cells.Some examples of the most popular Haar features are given below. Your task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.A prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.You have a variable value, whose value is initially zero. In one operation you can count the sum of pixel values \u200b\u200bat any prefix rectangle, multiply it by any integer and add to variable value.You are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of rows and columns in the feature. Next n lines contain the description of the feature. Each line consists of m characters, the j-th character of the i-th line equals to \"W\", if this element of the feature is white and \"B\" if it is black.", "output_spec": "Print a single number \u2014 the minimum number of operations that you need to make to calculate the value of the feature.", "sample_inputs": ["6 8\nBBBBBBBB\nBBBBBBBB\nBBBBBBBB\nWWWWWWWW\nWWWWWWWW\nWWWWWWWW", "3 3\nWBW\nBWW\nWWW", "3 6\nWWBBWW\nWWBBWW\nWWBBWW", "4 4\nBBBB\nBBBB\nBBBB\nBBBW"], "sample_outputs": ["2", "4", "3", "4"], "notes": "NoteThe first sample corresponds to feature B, the one shown in the picture. The value of this feature in an image of size 6\u2009\u00d7\u20098 equals to the difference of the total brightness of the pixels in the lower and upper half of the image. To calculate its value, perform the following two operations: add the sum of pixels in the prefix rectangle with the lower right corner in the 6-th row and 8-th column with coefficient 1 to the variable value (the rectangle is indicated by a red frame); add the number of pixels in the prefix rectangle with the lower right corner in the 3-rd row and 8-th column with coefficient \u2009-\u20092 and variable value. Thus, all the pixels in the lower three rows of the image will be included with factor 1, and all pixels in the upper three rows of the image will be included with factor 1\u2009-\u20092\u2009=\u2009\u2009-\u20091, as required."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let (n,m) = read_pair () in\n let board = Array.init n (fun _ -> read_string()) in\n\n let count = ref 0 in\n\n let count_boundary (a,b) =\n if a = b then 0 else 1\n in\n\n let count_middle (a,b,c,d) =\n if a=b && c=d then 0\n else if a=c && b=d then 0\n else 1\n in\n\n for i=0 to n-1 do\n for j=0 to m-1 do\n count := !count + (\n\tif i=n-1 && j=m-1 then 1\n\telse if i=n-1 then count_boundary (board.(i).[j], board.(i).[j+1])\n\telse if j=m-1 then count_boundary (board.(i).[j], board.(i+1).[j])\n\telse count_middle (board.(i).[j], board.(i).[j+1], board.(i+1).[j], board.(i+1).[j+1])\n )\n done\n done;\n\n printf \"%d\\n\" !count\n"}], "negative_code": [], "src_uid": "ce6b65ca755d2d860fb76688b3d775db"} {"nl": {"description": "You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character \"0\" and \"1\") a and b. Then you try to turn a into b using two types of operations: Write parity(a) to the end of a. For example, . Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of \"1\"s in the string, and 0 otherwise.", "input_spec": "The first line contains the string a and the second line contains the string b (1\u2009\u2264\u2009|a|,\u2009|b|\u2009\u2264\u20091000). Both strings contain only the characters \"0\" and \"1\". Here |x| denotes the length of the string x.", "output_spec": "Print \"YES\" (without quotes) if it is possible to turn a into b, and \"NO\" (without quotes) otherwise.", "sample_inputs": ["01011\n0110", "0011\n1110"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample, the steps are as follows: 01011\u2009\u2192\u20091011\u2009\u2192\u2009011\u2009\u2192\u20090110"}, "positive_code": [{"source_code": "open String\nlet a = read_line ();;\nlet b = read_line ();;\nlet count str c =\n let rec f p a =\n if p = length str\n then a\n else f (p+1) (a + if get str p = c then 1 else 0)\n in f 0 0;;\nlet n1a = count a '1';;\nlet n1a = n1a + n1a mod 2;;\nlet n1b = count b '1';;\nif n1a >= n1b\nthen print_string \"YES\\n\"\nelse print_string \"NO\\n\"\n"}], "negative_code": [], "src_uid": "cf86add6c92fa8a72b8e23efbdb38613"} {"nl": {"description": "There are $$$n$$$ pillars aligned in a row and numbered from $$$1$$$ to $$$n$$$.Initially each pillar contains exactly one disk. The $$$i$$$-th pillar contains a disk having radius $$$a_i$$$.You can move these disks from one pillar to another. You can take a disk from pillar $$$i$$$ and place it on top of pillar $$$j$$$ if all these conditions are met: there is no other pillar between pillars $$$i$$$ and $$$j$$$. Formally, it means that $$$|i - j| = 1$$$; pillar $$$i$$$ contains exactly one disk; either pillar $$$j$$$ contains no disks, or the topmost disk on pillar $$$j$$$ has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $$$n$$$ disks on the same pillar simultaneously?", "input_spec": "The first line contains one integer $$$n$$$ ($$$3 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of pillars. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_i$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_i$$$ is the radius of the disk initially placed on the $$$i$$$-th pillar. All numbers $$$a_i$$$ are distinct.", "output_spec": "Print YES if it is possible to place all the disks on the same pillar simultaneously, and NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).", "sample_inputs": ["4\n1 3 4 2", "3\n3 1 2"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first case it is possible to place all disks on pillar $$$3$$$ using the following sequence of actions: take the disk with radius $$$3$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$; take the disk with radius $$$1$$$ from pillar $$$1$$$ and place it on top of pillar $$$2$$$; take the disk with radius $$$2$$$ from pillar $$$4$$$ and place it on top of pillar $$$3$$$; take the disk with radius $$$1$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$. "}, "positive_code": [{"source_code": "let readInt () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve n a =\n let rec go i = if i >= n then n else if a.(i) = n then i else go (i+1)\n in\n let ix = go 0 in\n let rec dec i d =\n if i < 0 || i >= n then true\n else if a.(i) > a.(i-d) then false\n else dec (i + d) d\n in dec (ix-1) (-1) && dec (ix+1) 1\n\nlet main () =\n let n = readInt () in\n let a = Array.init n (fun _ -> readInt ()) in\n print_endline (if solve n a then \"YES\" else \"NO\")\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "12abfbe7118868a0b1237489b5c92760"} {"nl": {"description": "Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.", "input_spec": "The first line of the input contains one integer, n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive. ", "output_spec": "Print the maximum possible even sum that can be obtained if we use some of the given integers. ", "sample_inputs": ["3\n1 2 3", "5\n999999999 999999999 999999999 999999999 999999999"], "sample_outputs": ["6", "3999999996"], "notes": "NoteIn the first sample, we can simply take all three integers for a total sum of 6.In the second sample Wet Shark should take any four out of five integers 999\u2009999\u2009999."}, "positive_code": [{"source_code": "let ( ++ ) = Int64.add\nlet ( %% ) = Int64.rem\nlet zero = Int64.zero\nlet two = Int64.of_int 2\n\nlet read () = Scanf.scanf \"%d \" (fun n -> n)\nlet read_l () = Scanf.scanf \"%Ld \" (fun n -> n)\nlet print int = Printf.printf \"%Ld\\n\" int\n\nlet input () = \n let n = read () in\n let rec loop i even odd =\n if i < n\n then\n let int = read_l () in\n if int %% two = zero\n then\n loop (i + 1) (int :: even) odd\n else\n loop (i + 1) even (int :: odd)\n else\n (even, odd)\n in loop 0 [] []\n\nlet get_sum list =\n let l = List.length list in\n if l <= 1\n then\n zero\n else\n if l mod 2 = 0\n then\n List.fold_left (fun acc n -> acc ++ n) zero list\n else\n List.fold_left (fun acc n -> acc ++ n) zero (List.tl list) \n\nlet solve (even, odd)=\n let odd_sorted = List.sort (Pervasives.compare) odd in\n let sum_even = List.fold_left (fun acc n -> acc ++ n) zero even in\n let sum_odd = get_sum odd_sorted in\n sum_even ++ sum_odd\n\nlet () = print (solve (input ()))"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> long(read_int())) in\n\n let total = sum 0 (n-1) (fun i -> a.(i)) 0L in\n\n let inf = Int64.max_int in\n\n let is_odd x = x%% 2L = 1L in\n \n let min_odd = minf 0 (n-1) (fun i -> if is_odd a.(i) then a.(i) else inf) in\n\n let answer = if not (is_odd total) then total else total -- min_odd in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "adb66b7b22d70bb37cb625d531d8865f"} {"nl": {"description": "Given the integer $$$n$$$\u00a0\u2014 the number of available blocks. You must use all blocks to build a pedestal. The pedestal consists of $$$3$$$ platforms for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places respectively. The platform for the $$$1$$$-st place must be strictly higher than for the $$$2$$$-nd place, and the platform for the $$$2$$$-nd place must be strictly higher than for the $$$3$$$-rd place. Also, the height of each platform must be greater than zero (that is, each platform must contain at least one block). Example pedestal of $$$n=11$$$ blocks: second place height equals $$$4$$$ blocks, first place height equals $$$5$$$ blocks, third place height equals $$$2$$$ blocks.Among all possible pedestals of $$$n$$$ blocks, deduce one such that the platform height for the $$$1$$$-st place minimum as possible. If there are several of them, output any of them.", "input_spec": "The first line of input data contains an integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Each test case contains a single integer $$$n$$$ ($$$6 \\le n \\le 10^5$$$)\u00a0\u2014 the total number of blocks for the pedestal. All $$$n$$$ blocks must be used. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^6$$$.", "output_spec": "For each test case, output $$$3$$$ numbers $$$h_2, h_1, h_3$$$\u00a0\u2014 the platform heights for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places on a pedestal consisting of $$$n$$$ blocks ($$$h_1+h_2+h_3=n$$$, $$$0 < h_3 < h_2 < h_1$$$). Among all possible pedestals, output the one for which the value of $$$h_1$$$ minimal. If there are several of them, output any of them.", "sample_inputs": ["6\n\n11\n\n6\n\n10\n\n100000\n\n7\n\n8"], "sample_outputs": ["4 5 2\n2 3 1\n4 5 1\n33334 33335 33331\n2 4 1\n3 4 1"], "notes": "NoteIn the first test case we can not get the height of the platform for the first place less than $$$5$$$, because if the height of the platform for the first place is not more than $$$4$$$, then we can use at most $$$4 + 3 + 2 = 9$$$ blocks. And we should use $$$11 = 4 + 5 + 2$$$ blocks. Therefore, the answer 4 5 2 fits. In the second set, the only suitable answer is: 2 3 1."}, "positive_code": [{"source_code": "open String \nopen Printf \n \nlet read_ints() = Array.map (int_of_string) (Array.of_list (Str.split (Str.regexp \" +\") (read_line())));;\nlet n = read_int();;\n\nfor i = 0 to (n - 1) do \n let num = read_int() and \n fi = ref 3 and \n se = ref 2 and \n th = ref 1 in \n let many = ((num - 6) / 3) and \n rest = ref((num - 6) mod 3)\n in \n fi := !fi + many;\n se := !se + many;\n th := !th + many;\n while !rest > 0 do\n if !rest > 0 then (\n fi := !fi + 1;\n rest := !rest - 1\n );\n if !rest > 0 then (\n se := !se + 1;\n rest := !rest - 1\n );\n if !rest > 0 then (\n th := !th + 1;\n rest := !rest - 1\n )\n done;\n print_int !se;\n print_string \" \";\n print_int !fi;\n print_string \" \";\n print_int !th;\n print_newline()\ndone\n\n\n"}], "negative_code": [{"source_code": "open String \nopen Printf \n \nlet read_ints() = Array.map (int_of_string) (Array.of_list (Str.split (Str.regexp \" +\") (read_line())));;\nlet n = read_int();;\n\nfor i = 0 to (n - 1) do \n let num = read_int() and \n fi = ref 3 and \n se = ref 2 and \n th = ref 1 in \n let many = ((num - 6) / 3) and \n rest = ref((num - 6) mod 3)\n in \n fi := !fi + many;\n se := !se + many;\n th := !th + many;\n while !rest > 0 do\n if !rest > 0 then (\n fi := !fi + 1;\n rest := !rest - 1\n );\n if !rest > 0 then (\n se := !se + 1;\n rest := !rest - 1\n );\n if !rest > 0 then (\n th := !th + 1;\n rest := !rest - 1\n )\n done;\n printf \"%d %d %d\" !se !fi !th\ndone\n\n\n"}], "src_uid": "45cf60f551bd5cbb1f3df6ac3004b53c"} {"nl": {"description": "You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string \"[[(){}]<>]\" is RBS, but the strings \"[)()\" and \"][()()\" are not.Determine the least number of replaces to make the string s RBS.", "input_spec": "The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.", "output_spec": "If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s.", "sample_inputs": ["[<}){}", "{()}[]", "]]"], "sample_outputs": ["2", "0", "Impossible"], "notes": null}, "positive_code": [{"source_code": "open Printf\n\nlet rec over a b f k =\n if a >= b then k\n else over (a + 1) b f (f a k)\n\nlet group = function\n | '[' | ']' -> 0\n | '(' | ')' -> 1\n | '<' | '>' -> 2\n | '{' | '}' -> 3\n | _ -> assert false\n\nlet () =\n let s = input_line stdin in\n let x =\n over 0 (String.length s) (fun i x ->\n match s.[i], x with\n | _, None ->\n None\n | ('[' | '<' | '(' | '{'), Some (n, q) ->\n Some (n, group s.[i] :: q)\n | r, Some (n, []) -> \n None\n | r, Some (n, t :: ts) when group r = t ->\n Some (n, ts)\n | r, Some (n, t :: ts) when group r <> t ->\n Some ((n + 1), ts)\n | _ -> assert false\n ) (Some (0, []))\n in\n match x with\n | None -> printf \"Impossible\\n\"\n | Some (_, _ :: _) -> printf \"Impossible\\n\"\n | Some (n, []) -> printf \"%d\\n\" n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let a = Array.make n 0 in\n let pos = ref 0 in\n let push x =\n a.(!pos) <- x;\n incr pos\n in\n let res = ref 0 in\n let pop x =\n if !pos <= 0 then (\n Printf.printf \"Impossible\\n\";\n exit 0;\n );\n if a.(!pos - 1) <> x\n then incr res;\n decr pos;\n in\n for i = 0 to n - 1 do\n let c = s.[i] in\n\tmatch c with\n\t | '(' -> push 0\n\t | '{' -> push 1\n\t | '<' -> push 2\n\t | '[' -> push 3\n\t | ')' -> pop 0\n\t | '}' -> pop 1\n\t | '>' -> pop 2\n\t | ']' -> pop 3\n\t | _ -> assert false\n done;\n if !pos <> 0\n then Printf.printf \"Impossible\\n\"\n else Printf.printf \"%d\\n\" !res\n"}], "negative_code": [], "src_uid": "4147fef7a151c52e92c010915b12c06b"} {"nl": {"description": "A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x\u2009<\u2009y) from the set, such that y\u2009=\u2009x\u00b7k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009109). The next line contains a list of n distinct positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). All the numbers in the lines are separated by single spaces.", "output_spec": "On the only line of the output print the size of the largest k-multiple free subset of {a1,\u2009a2,\u2009...,\u2009an}.", "sample_inputs": ["6 2\n2 3 6 5 4 10"], "sample_outputs": ["3"], "notes": "NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = Scanf.bscanf Scanf.Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\nlet () =\n let n = read_int() in\n let k = read_long() in\n let a = Array.init n (fun _ -> read_long()) in\n\n let () = Array.sort compare a in\n\n let h = Hashtbl.create 100 in\n\n let () = \n for i=0 to n-1 do\n Hashtbl.add h a.(i) false\n done in\n\n let rec mark_chain x i = \n if Hashtbl.mem h x then (\n if Hashtbl.find h x then 0 else (\n\tHashtbl.replace h x true;\n\tmark_chain (x ** k) (i+1)\n )\n ) else i\n in\n \n let count = ref 0 in\n \n for i=0 to n-1 do\n let c = mark_chain a.(i) 0 in\n\tcount := !count + ((c+1)/2)\n done;\n\n if k=1L then Printf.printf \"%d\\n\" n\n else Printf.printf \"%d\\n\" !count\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int () and k = scan_int();;\nlet a = Array.make n 0;;\n\nfor i = 0 to n - 1 do a.(i) <- scan_int() done;\nArray.sort compare a;\n\nlet cnt = ref 0 and q = Queue.create() in\nfor i = n - 1 downto 0 do\n while(not (Queue.is_empty q) && Queue.top q > a.(i)) do Queue.pop q; done;\n if(not (Queue.is_empty q) && Queue.top q = a.(i)) then incr cnt\n else if(a.(i) mod k = 0) then Queue.push (a.(i) / k) q;\ndone;\n\nprint_int(n - !cnt);\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = Scanf.bscanf Scanf.Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\nlet () =\n let n = read_int() in\n let k = read_long() in\n let a = Array.init n (fun _ -> read_long()) in\n\n let () = Array.sort compare a in\n\n let h = Hashtbl.create 100 in\n\n let () = \n for i=0 to n-1 do\n Hashtbl.add h a.(i) false\n done in\n\n let rec mark_chain x i = \n if Hashtbl.mem h x then (\n if Hashtbl.find h x then 0 else (\n\tHashtbl.replace h x true;\n\tmark_chain (x ** k) (i+1)\n )\n ) else i\n in\n \n let count = ref 0 in\n \n for i=0 to n-1 do\n let c = mark_chain a.(i) 0 in\n\tcount := !count + ((c+1)/2)\n done;\n\n Printf.printf \"%d\\n\" !count\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nlet n = scan_int () and k = scan_int();;\nlet a = Array.make n 0;;\n\nfor i = 0 to n - 1 do a.(i) <- scan_int() done;\nArray.sort compare a;\n\nlet cnt = ref 0 and q = Queue.create() in\nfor i = n - 1 downto 0 do\n while(not (Queue.is_empty q) && Queue.top q > a.(i)) do Queue.pop q; done;\n if(not (Queue.is_empty q) && Queue.top q = a.(i)) then incr cnt; \n if(a.(i) mod k = 0) then Queue.push (a.(i) / k) q;\ndone;\n\nprint_int(n - !cnt);\n"}], "src_uid": "4ea1de740aa131cae632c612e1d582ed"} {"nl": {"description": "You have a string $$$s$$$ consisting of digits from $$$0$$$ to $$$9$$$ inclusive. You can perform the following operation any (possibly zero) number of times: You can choose a position $$$i$$$ and delete a digit $$$d$$$ on the $$$i$$$-th position. Then insert the digit $$$\\min{(d + 1, 9)}$$$ on any position (at the beginning, at the end or in between any two adjacent digits). What is the lexicographically smallest string you can get by performing these operations?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ of the same length if and only if the following holds: in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a smaller digit than the corresponding digit in $$$b$$$. ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then the test cases follow. Each test case consists of a single line that contains one string $$$s$$$ ($$$1 \\le |s| \\le 2 \\cdot 10^5$$$) \u2014 the string consisting of digits. Please note that $$$s$$$ is just a string consisting of digits, so leading zeros are allowed. It is guaranteed that the sum of lengths of $$$s$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "Print a single string \u2014 the minimum string that is possible to obtain.", "sample_inputs": ["4\n\n04829\n\n9\n\n01\n\n314752277691991"], "sample_outputs": ["02599\n9\n01\n111334567888999"], "notes": "NoteIn the first test case: Delete $$$8$$$ and insert $$$9$$$ at the end of the notation. The resulting notation is $$$04299$$$. Delete $$$4$$$ and insert $$$5$$$ in the $$$3$$$-rd position of the notation. The resulting notation is $$$02599$$$. Nothing needs to be done in the second and third test cases."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet l2d c = (int_of_char c) - (int_of_char '0') \n \nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let s = read_string () in\n let n = String.length s in\n let t = Array.init n (fun i -> l2d s.[i]) in\n let rightmost = Array.make 10 (-1) in\n\n for i=0 to n-1 do\n rightmost.(t.(i)) <- i\n done;\n \n let rec scan d st =\n (* count the number of d's at or after the point st *)\n if d = 10 || st >= n then ()\n else if rightmost.(d) < 0 then scan (d+1) st else (\n\tfor i = st to rightmost.(d)-1 do\n\t if t.(i) > d then t.(i) <- t.(i) + 1\n\tdone;\n\tscan (d+1) (max st (rightmost.(d)+1))\n )\n in\n\n scan 0 0;\n\n Array.sort compare t;\n\n for i=0 to n-1 do\n printf \"%d\" (min t.(i) 9)\n done;\n print_newline()\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\nlet l2d c = (int_of_char c) - (int_of_char '0') \n \nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let s = read_string () in\n let n = String.length s in\n let get i = l2d s.[i] in\n let t = Array.init n get in\n(*\n let side = Array.make 10 0 in\n*)\n let rightmost = Array.make 10 (-1) in\n\n for i=0 to n-1 do\n let d = get i in\n rightmost.(d) <- i\n done;\n \n let rec scan d st =\n (* count the number of d's at or after the point st *)\n if d = 10 || st >= n then ()\n else if rightmost.(d) < 0 then scan (d+1) st else (\n\t\n\tfor i = st to rightmost.(d)-1 do\n\t if t.(i) > d then t.(i) <- t.(i) + 1\n\tdone;\n\n\tscan (d+1) (rightmost.(d)+1)\n\n )\n in\n\n scan 0 0;\n\n Array.sort compare t;\n\n for i=0 to n-1 do\n printf \"%d\" (min t.(i) 9)\n done;\n print_newline()\n done\n"}], "src_uid": "906b319e41f716e734cf04b34678aa58"} {"nl": {"description": "Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.Subarray a[i... j]\u00a0(1\u2009\u2264\u2009i\u2009\u2264\u2009j\u2009\u2264\u2009n) of array a\u2009=\u2009(a1,\u2009a2,\u2009...,\u2009an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j]\u2009=\u2009(ai,\u2009ai\u2009+\u20091,\u2009...,\u2009aj).", "input_spec": "The first line contains two space-separated integers n, k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u20094\u00b7105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly. The second line contains n space-separated integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 elements of the array.", "output_spec": "Print the single number \u2014 the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in \u0421++. In is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["4 2\n1 2 1 2", "5 3\n1 2 1 1 3", "3 1\n1 1 1"], "sample_outputs": ["3", "2", "6"], "notes": "NoteIn the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1)."}, "positive_code": [{"source_code": "module M=Map.Make (struct type t = int let compare (a:int) b = compare a b end)\n\nlet _ =\n let id x = x in\n\n let get x map = try M.find x map with _ -> 0 in\n let inc x map = M.add x (1 + try M.find x map with _ -> 0) map in\n let del x map = M.add x (M.find x map - 1) map in\n\n let main () =\n let n, lim = Scanf.scanf \"%d %d\" (fun a b -> a, b) in\n let arr = Array.init n (fun _ -> Scanf.scanf \" %d\" id) in\n let rec initloop p map =\n if p >= n then 0. else\n let map = inc arr.(p) map in\n if get arr.(p) map >= lim then loop2 p 0 map 1 (float (n - p)) else\n initloop (p + 1) map\n and loop2 head tail map l acc =\n let x = arr.(tail) in\n if get x map = lim then (\n let l = l - 1 in\n if l > 0 then loop2 head (tail + 1) (del x map) l (acc +. float (n - head))\n else loop3 (head + 1) (tail + 1) (del x map) acc\n ) else (\n loop2 head (tail + 1) (del x map) l (acc +. float (n - head))\n )\n and loop3 head tail map acc =\n if head >= n then acc else\n let map = inc arr.(head) map in\n if get arr.(head) map >= lim then loop2 head tail map 1 (acc +. float (n - head)) else\n loop3 (head + 1) tail map acc\n\n in \n \n let result = initloop 0 M.empty in\n Printf.printf \"%.f\\n%!\" result\n in\n main ()\n"}], "negative_code": [], "src_uid": "5346698abe40ce0477f743779da7c725"} {"nl": {"description": "The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dn\u2009-\u20091 is the distance between the n\u2009-\u20091-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of stations on the circle line. The second line contains n integers d1,\u2009d2,\u2009...,\u2009dn (1\u2009\u2264\u2009di\u2009\u2264\u2009100) \u2014 the distances between pairs of neighboring stations. The third line contains two integers s and t (1\u2009\u2264\u2009s,\u2009t\u2009\u2264\u2009n) \u2014 the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces.", "output_spec": "Print a single number \u2014 the length of the shortest path between stations number s and t.", "sample_inputs": ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"], "sample_outputs": ["5", "15", "1", "0"], "notes": "NoteIn the first sample the length of path 1\u2009\u2192\u20092\u2009\u2192\u20093 equals 5, the length of path 1\u2009\u2192\u20094\u2009\u2192\u20093 equals 13.In the second sample the length of path 4\u2009\u2192\u20091 is 100, the length of path 4\u2009\u2192\u20093\u2009\u2192\u20092\u2009\u2192\u20091 is 15.In the third sample the length of path 3\u2009\u2192\u20091 is 1, the length of path 3\u2009\u2192\u20092\u2009\u2192\u20091 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = -1+read_int() in (u,-1+read_int())\n\nlet () = \n let n = read_int() in\n let d = Array.init n (fun i -> read_int()) in\n let (s,t) = read_pair() in\n\n let rec loop_up i ac = if i=t then ac else loop_up ((i+1) mod n) (ac + d.(i)) in\n\n let rec loop_down i ac = if i=t then ac else let ii = (i+n-1) mod n in loop_down ii (ac + d.(ii)) in\n\n Printf.printf \"%d\\n\" (min (loop_up s 0) (loop_down s 0))\n"}], "negative_code": [], "src_uid": "22ef37041ebbd8266f62ab932f188b31"} {"nl": {"description": "A TV show called \"Guess a number!\" is gathering popularity. The whole Berland, the old and the young, are watching the show.The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions: Is it true that y is strictly larger than number x? Is it true that y is strictly smaller than number x? Is it true that y is larger than or equal to number x? Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, \"yes\" or \"no\".Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print \"Impossible\".", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200910000) \u2014 the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: \"sign x answer\", where the sign is: \">\" (for the first type queries), \"<\" (for the second type queries), \">=\" (for the third type queries), \"<=\" (for the fourth type queries). All values of x are integer and meet the inequation \u2009-\u2009109\u2009\u2264\u2009x\u2009\u2264\u2009109. The answer is an English letter \"Y\" (for \"yes\") or \"N\" (for \"no\"). Consequtive elements in lines are separated by a single space.", "output_spec": "Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation \u2009-\u20092\u00b7109\u2009\u2264\u2009y\u2009\u2264\u20092\u00b7109. If there are many answers, print any of them. If such value doesn't exist, print word \"Impossible\" (without the quotes).", "sample_inputs": ["4\n>= 1 Y\n< 3 N\n<= -3 N\n> 55 N", "2\n> 100 Y\n< -100 Y"], "sample_outputs": ["17", "Impossible"], "notes": null}, "positive_code": [{"source_code": "let n=read_int();;\nlet g=ref (Int64.of_string \"-2000000000\");;\nlet d=ref (Int64.of_string \"2000000000\");;\nlet l=ref (Int64.zero);;\n\nfor i=1 to n do\n let s=read_line() in\n begin\n if s.[1]='=' then l:=Int64.of_string(String.sub s 3 (String.length(s)-5))\n else l:=Int64.of_string(String.sub s 2 (String.length(s)-4));\n if ((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then\n begin\n if !l< !d then d:= !l\n end\n else if ((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then\n begin\n if !l > !g then g:= !l\n end\n else if ((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then\n begin\n if (Int64.succ !l) > !g then g:= (Int64.succ !l)\n end\n else if ((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then\n begin\n if (Int64.pred !l) < !d then d:= (Int64.pred !l)\n end\n end\ndone;;\n\nif !g > !d then print_string \"Impossible\" else print_string(Int64.to_string !g);;"}], "negative_code": [{"source_code": "let n=read_int();;\nlet g=ref (Int64.of_string \"-521\");;\nlet d=ref (Int64.of_string \"512\");;\nlet l=ref (Int64.zero);;\n\nfor i=1 to n do\n let s=read_line() in\n begin\n if s.[1]='=' then l:=Int64.of_string(String.sub s 3 (String.length(s)-5))\n else l:=Int64.of_string(String.sub s 2 (String.length(s)-4));\n if ((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then\n begin\n if !l< !d then d:= !l\n end\n else if ((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then\n begin\n if !l > !g then g:= !l\n end\n else if ((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then\n begin\n if (Int64.succ !l) > !g then g:= (Int64.succ !l)\n end\n else if ((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then\n begin\n if (Int64.pred !l) < !d then d:= (Int64.pred !l)\n end\n end\ndone;;\n\nif !g > !d then print_string \"Impossible\" else print_string(Int64.to_string !g);;"}, {"source_code": "let n=read_int();;\nlet g=ref (Int64.of_string \"-10000000000\");;\nlet d=ref (Int64.of_string \"10000000000\");;\nlet l=ref (Int64.zero);;\n\nfor i=1 to n do\n let s=read_line() in\n begin\n if s.[1]='=' then l:=Int64.of_string(String.sub s 3 (String.length(s)-5))\n else l:=Int64.of_string(String.sub s 2 (String.length(s)-4));\n if ((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then\n begin\n if !l< !d then d:= !l\n end\n else if ((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then\n begin\n if !l > !g then g:= !l\n end\n else if ((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then\n begin\n if (Int64.succ !l) > !g then g:= (Int64.succ !l)\n end\n else if ((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then\n begin\n if (Int64.pred !l) < !d then d:= (Int64.pred !l)\n end\n end\ndone;;\n\nif !g > !d then print_string \"Impossible\" else print_string(Int64.to_string !g);;\n "}], "src_uid": "6c6f29e1f4c951cd0ff15056774f897d"} {"nl": {"description": "Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.", "input_spec": "The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.", "output_spec": "Print a single number \u2014 the number of distinct letters in Anton's set.", "sample_inputs": ["{a, b, c}", "{b, a, b, a}", "{}"], "sample_outputs": ["3", "2", "0"], "notes": null}, "positive_code": [{"source_code": "(* module IntSet = Set.Make(\n struct\n let compare = Pervasives.compare\n type t = int\n end) *)\n\nmodule CharSet = Set.Make(Char)\n\nlet add s b = \n if String.length b == 0 then s\n else CharSet.add (String.get b 0) s\n\nlet x = \n let line = Str.split (Str.regexp \"[{},] *\") (read_line ()) in\n let s = List.fold_left add CharSet.empty line in\n print_int (CharSet.cardinal s);\n print_newline;"}, {"source_code": "let get_list () =\n let letters = Pervasives.read_line () in \n let l = String.length letters in\n let rec loop i list =\n if i < 1 \n then \n list \n else \n loop (i - 3) (letters.[i] :: list)\n in loop (l - 2) []\n\nlet rec get_uniques = function\n | head :: (middle :: _ as tail) -> \n if head = middle \n then \n get_uniques tail \n else \n (head :: get_uniques tail)\n | smaller -> smaller\n\nlet solve () = List.length (get_uniques (List.sort (Pervasives.compare) (get_list ())))\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve ())"}], "negative_code": [{"source_code": "let get_list () =\n let letters = Pervasives.read_line () in \n let l = String.length letters in\n let rec loop i list =\n if i < 1 \n then \n list \n else \n loop (i - 3) (letters.[i] :: list)\n in loop (l - 2) []\n\nlet rec get_uniques = function\n | head :: (middle :: _ as tail) -> \n if head = middle \n then \n get_uniques tail \n else \n (head :: get_uniques tail)\n | smaller -> smaller\n\nlet solve () = List.length (get_uniques (get_list ()))\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve ())"}], "src_uid": "1cbbffd1941ed83b5f04e1ee33c77f61"} {"nl": {"description": "Ivan is collecting coins. There are only $$$N$$$ different collectible coins, Ivan has $$$K$$$ of them. He will be celebrating his birthday soon, so all his $$$M$$$ freinds decided to gift him coins. They all agreed to three terms: Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than $$$L$$$ coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.", "input_spec": "The only line of input contains 4 integers $$$N$$$, $$$M$$$, $$$K$$$, $$$L$$$ ($$$1 \\le K \\le N \\le 10^{18}$$$; $$$1 \\le M, \\,\\, L \\le 10^{18}$$$)\u00a0\u2014 quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection.", "output_spec": "Print one number\u00a0\u2014 minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print \"-1\" (without quotes).", "sample_inputs": ["20 15 2 3", "10 11 2 4"], "sample_outputs": ["1", "-1"], "notes": "NoteIn the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new.In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n\tlet i32,i64,ist = Int64.(to_int,of_int,to_string)\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n\tlet labs = Int64.abs\n\tlet (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *= ) r v = r := !r * v\n\tlet (/=) r v = r := !r / v\n\tlet (%=) r v = r := !r % v\n\t(* math *)\n\tlet ceildiv p q = (p+q-1L) / q\n\tlet rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n\tlet lcm m n = m / gcd m n * n \n\tmodule I64_infix = struct\n\t\tlet (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n\t\t\tlet open Int64 in\n\t\t\t(logand),(logor),(logxor),lognot,\n\t\t\t(fun u v -> shift_left u (i32 v)),\n\t\t\t(fun u v -> shift_right u (i32 v)),\n\t\t\t(fun u v -> shift_right_logical u (i32 v))\n\tend\n\t(* input *)\n\tlet input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n\t(* utils *)\n\texternal id : 'a -> 'a = \"%identity\"\n\tlet alen a = i64 @@ Array.length a\n\tlet llen l = i64 @@ List.length l\n\tlet string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n\tlet string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n\tlet char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n\tlet string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet fail _ = failwith \"fail\"\n\tlet dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n\tlet range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n\tlet cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n\tlet shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n\tlet binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n\t\tlet rec f0 ng ok =\n\t\t\tif labs (ok - ng) <= 1L then ok\n\t\t\telse let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n\t\tin f0 (ng-1L*d) (ok+1L*d)\n\t(* imperative *)\n\tlet rep f t fbod =\n\t\tlet rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done\n\t\tin if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f + t - v\n\tlet repb f t fbod =\n\t\tlet rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done; !c\n\t\tin if f<=t then rep0 f t fbod\n\t\telse rep0 t f @@ fun v -> fbod @@ f + t - v\n\tlet repm f t m0 fbod =\n\t\tlet rep0 f t m0 fbod =\n\t\t\tlet i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m\n\t\tin if f<=t then rep0 f t m0 fbod\n\t\telse rep0 t f m0 @@ fun u v -> fbod u @@ f + t - v\n\tlet repi f t fbod =\n\t\tlet rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done\n\t\tin if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repb f t fbod =\n\t\tlet rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do\n\t\tmatch fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done\n\t\tin if f<=t then rep0 f t fbod\n\t\telse rep0 t f @@ fun v -> fbod @@ f +$ t -$ v\n\tlet repm f t m0 fbod =\n\t\tlet rep0 f t m0 fbod =\n\t\t\tlet i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m\n\t\tin if f<=t then rep0 f t m0 fbod\n\t\telse rep0 t f m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n\t(* output *)\n\tlet print_list_mle f ls = string_of_list f ls |> print_endline\n\tlet print_array_mle f a = string_of_array f a |> print_endline\n\tlet print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\tlet print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n\t(* debug *)\n\tlet dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n\tlet dump_i64_list ls = print_list ist ls\n\tlet dump_i64_array a = print_array ist a\nend open Lib\n\nlet () =\n\tlet n,m,k,l = get_4_i64 0 in\n\tlet ans = ceildiv (l+k) m\n\tin (\n\t\tif\n\t\t\tans < 1L || n < m || m*ans > n || n < l || k+l > n\n\t\tthen -1L else ans\n\t)\n\t|> printf \"%Ld\\n\""}], "negative_code": [], "src_uid": "886029b385c099b3050b7bc6978e433b"} {"nl": {"description": "Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of cockroaches. The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.", "output_spec": "Print one integer\u00a0\u2014 the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.", "sample_inputs": ["5\nrbbrr", "5\nbbbbb", "3\nrbr"], "sample_outputs": ["1", "2", "0"], "notes": "NoteIn the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0."}, "positive_code": [{"source_code": "let kikou tab =\n let red_even = ref 0\n and blu_even = ref 0\n and red_odd = ref 0\n and blu_odd = ref 0\n in\n for i = 0 to String.length tab - 1 do\n incr @@ match tab.[i] , i mod 2 with\n | 'b', 0 -> blu_even\n | 'b', 1 -> blu_odd\n | 'r', 0 -> red_even\n | 'r', 1 -> red_odd\n done;\n !red_even, !blu_even, !red_odd, !blu_odd\n\nlet solve tab =\n let n = String.length tab in\n let (re,be,ro,bo) = kikou tab in\n let a = min re bo in\n let (re',be',ro',bo') = (re-a,be+a,ro+a,bo-a) in\n a + (((n+1)/2) - be') + ((n/2) - ro')\n\nlet olol =\n String.map (fun x -> if x = 'b' then 'r' else 'b')\n\nlet _ =\n let w = Scanf.scanf \"%d %s\" (fun _ w -> w) in\n Printf.printf \"%d\" (min (solve w) (solve (olol w)))\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let s = read_string () in\n\n let comp c = match c with 'r' -> 'b' | 'b' -> 'r' | _ -> failwith \"bad input\" in\n\n let solve c =\n (* c is the goal color of position 0 *)\n let rec loop i c rtob btor =\n if i=n then (rtob, btor) else\n\tlet rtob = rtob + (if s.[i] = 'r' && c = 'b' then 1 else 0) in\n\tlet btor = btor + (if s.[i] = 'b' && c = 'r' then 1 else 0) in\n\tloop (i+1) (comp c) rtob btor\n in\n let (rtob, btor) = loop 0 c 0 0 in\n let swaps = min rtob btor in\n (rtob + btor) - swaps\n in\n\n let answer = min (solve 'r') (solve 'b') in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let s = read_string () in\n\n let comp c = match c with 'r' -> 'b' | 'b' -> 'r' | _ -> failwith \"bad input\" in\n \n let rec color i c ac =\n (* position i is already correctly colored c *)\n (* continue coloring from i+1 to the end *)\n if i = n-1 then ac else (\n if s.[i+1] = comp c then color (i+1) (comp c) ac\n else if i+2 < n && s.[i+2] <> s.[i+1] then color (i+2) c (ac+1)\n else color (i+1) (comp c) (ac+1)\n )\n in\n\n let answer = min (color (-1) 'r' 0) (color (-1) 'b' 0) in\n\n printf \"%d\\n\" answer\n"}], "src_uid": "3adc75a180d89077aa90bbe3d8546e4d"} {"nl": {"description": "Carol is currently curling.She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y\u2009=\u200910100.She then will slide the disks towards the line y\u2009=\u20090 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi,\u200910100). She will then push it so the disk\u2019s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y\u2009=\u20090 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.", "input_spec": "The first line will contain two integers n and r (1\u2009\u2264\u2009n,\u2009r\u2009\u2264\u20091\u2009000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009xi\u2009\u2264\u20091\u2009000)\u00a0\u2014 the x-coordinates of the disks.", "output_spec": "Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10\u2009-\u20096. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if for all coordinates.", "sample_inputs": ["6 2\n5 5 6 8 3 12"], "sample_outputs": ["2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613"], "notes": "NoteThe final positions of the disks will look as follows: In particular, note the position of the last disk. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet sq x = x *. x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i) \n \nlet () = \n let (n,r) = read_pair () in\n let x = Array.init n read_int in\n\n let height x0 x1 =\n let (x0,x1) = (min x0 x1, max x0 x1) in\n let d = x1 - x0 in\n if d > 2*r then -1.0\n else if d = 2*r then 0.0\n else \n let d = float d in\n let r = float r in\n sqrt ((sq (2.0 *. r)) -. (sq d))\n in\n\n let h = Array.make n 0.0 in\n\n h.(0) <- float r;\n printf \"%.8f\" h.(0);\n\n for i=1 to n-1 do\n h.(i) <- maxf 0 (i-1) (fun j ->\n let hh = height x.(i) x.(j) in\n if hh < 0.0 then float r else h.(j) +. hh\n );\n\n printf \" %.8f\" h.(i)\n done;\n\n print_newline()\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet sq x = x *. x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i) \n \nlet () = \n let (n,r) = read_pair () in\n let x = Array.init n read_int in\n\n let height x0 x1 =\n let (x0,x1) = (min x0 x1, max x0 x1) in\n let d = x1 - x0 in\n if d > 2*r then -1.0\n else if d = 2*r then 0.0\n else \n let d = float d in\n let r = float r in\n sqrt ((sq (2.0 *. r)) -. (sq d))\n in\n\n let h = Array.make n 0.0 in\n\n h.(0) <- float r;\n\n for i=1 to n-1 do\n h.(i) <- maxf 0 (i-1) (fun j ->\n let hh = height x.(i) x.(j) in\n if hh < 0.0 then float r else h.(j) +. hh\n );\n\n printf \"%.8f \" h.(i)\n done;\n\n print_newline()\n"}], "src_uid": "3cd019d1016cb3b872ea956c312889eb"} {"nl": {"description": "This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting \"+\" and \"1\" into it we get a correct mathematical expression. For example, sequences \"(())()\", \"()\" and \"(()(()))\" are regular, while \")(\", \"(()\" and \"(()))(\" are not. You have a pattern of a bracket sequence that consists of characters \"(\", \")\" and \"?\". You have to replace each character \"?\" with a bracket so, that you get a regular bracket sequence.For each character \"?\" the cost of its replacement with \"(\" and \")\" is given. Among all the possible variants your should choose the cheapest.", "input_spec": "The first line contains a non-empty pattern of even length, consisting of characters \"(\", \")\" and \"?\". Its length doesn't exceed 5\u00b7104. Then there follow m lines, where m is the number of characters \"?\" in the pattern. Each line contains two integer numbers ai and bi (1\u2009\u2264\u2009ai,\u2009\u2009bi\u2009\u2264\u2009106), where ai is the cost of replacing the i-th character \"?\" with an opening bracket, and bi \u2014 with a closing one.", "output_spec": "Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. ", "sample_inputs": ["(??)\n1 2\n2 8"], "sample_outputs": ["4\n()()"], "notes": null}, "positive_code": [{"source_code": "module type ZeroOrderedType = sig\n type t\n val compare: t -> t -> int\n val zero: t\nend\n\nexception No\n\nmodule Heap(Ord: ZeroOrderedType) = struct\n type 'a t = { mutable size: int; data: 'a array }\n let create capacity = { size = 0; data = Array.make capacity Ord.zero }\n\n let up h pos key =\n let rec go pos =\n let pos2 = (pos-1)/2 in\n if pos > 0 && Ord.compare key h.data.(pos2) < 0 then (\n h.data.(pos) <- h.data.(pos2);\n go pos2\n ) else\n pos\n in\n h.data.(go pos) <- key\n\n let down h pos key =\n let rec go pos =\n let pos2 = ref (pos*2+1) in\n if !pos2 < h.size then (\n if !pos2+1 < h.size && Ord.compare h.data.(!pos2+1) h.data.(!pos2) < 0 then\n pos2 := !pos2+1;\n if Ord.compare h.data.(!pos2) key < 0 then (\n h.data.(pos) <- h.data.(!pos2);\n go !pos2\n ) else\n pos\n ) else\n pos\n in\n h.data.(go pos) <- key\n\n let push h key =\n up h h.size key;\n h.size <- h.size+1\n\n let pop h =\n let ret = h.data.(0) in\n h.size <- h.size-1;\n down h 0 h.data.(h.size);\n ret\n\n let empty h =\n h.size = 0\nend\n\nmodule IIHeap = Heap(struct type t = int*int let compare = compare let zero = 0,0 end)\n\nlet () =\n let c = ref 0\n and ans = ref 0L\n and a = read_line () in\n let h = IIHeap.create (String.length a) in\n try\n String.iteri (fun i ch ->\n (match ch with\n | '(' ->\n c := !c+1\n | ')' ->\n c := !c-1;\n | '?' ->\n let x,y = Scanf.sscanf (read_line ()) \"%d %d\" (fun x y -> x,y) in\n a.[i] <- ')';\n c := !c-1;\n ans := Int64.add !ans (Int64.of_int y);\n IIHeap.push h (x-y,i));\n if !c < 0 then (\n if IIHeap.empty h then (\n c := 1;\n raise No\n );\n let v,p = IIHeap.pop h in\n ans := Int64.add !ans (Int64.of_int v);\n a.[p] <- '(';\n c := !c+2;\n )\n ) a;\n if !c <> 0 then\n raise No;\n Printf.printf \"%Ld\\n%s\\n\" !ans a\n with _ ->\n print_endline \"-1\"\n"}], "negative_code": [{"source_code": "module type ZeroOrderedType = sig\n type t\n val compare: t -> t -> int\n val zero: t\nend\n\nexception No\n\nmodule Heap(Ord: ZeroOrderedType) = struct\n type 'a t = { mutable size: int; data: 'a array }\n let create capacity = { size = 0; data = Array.make capacity Ord.zero }\n\n let up h pos key =\n let rec go pos =\n let pos2 = (pos-1)/2 in\n if pos > 0 && Ord.compare key h.data.(pos2) < 0 then (\n h.data.(pos) <- h.data.(pos2);\n go pos2\n ) else\n pos\n in\n h.data.(go pos) <- key\n\n let down h pos key =\n let rec go pos =\n let pos2 = ref (pos*2+1) in\n if !pos2 < h.size then (\n if !pos2+1 < h.size && Ord.compare h.data.(!pos2+1) h.data.(!pos2) < 0 then\n pos2 := !pos2+1;\n if Ord.compare h.data.(!pos2) key < 0 then (\n h.data.(pos) <- h.data.(!pos2);\n go !pos2\n ) else\n pos\n ) else\n pos\n in\n h.data.(go pos) <- key\n\n let push h key =\n up h h.size key;\n h.size <- h.size+1\n\n let pop h =\n let ret = h.data.(0) in\n h.size <- h.size-1;\n down h 0 h.data.(h.size);\n ret\n\n let empty h =\n h.size = 0\nend\n\nmodule IIHeap = Heap(struct type t = int*int let compare = compare let zero = 0,0 end)\n\nlet () =\n let c = ref 0\n and ans = ref 0\n and a = read_line () in\n let h = IIHeap.create (String.length a) in\n try\n String.iteri (fun i ch ->\n (match ch with\n | '(' ->\n c := !c+1\n | ')' ->\n c := !c-1;\n | '?' ->\n let x,y = Scanf.sscanf (read_line ()) \"%d %d\" (fun x y -> x,y) in\n a.[i] <- ')';\n c := !c-1;\n ans := !ans+y;\n IIHeap.push h (x-y,i));\n if !c < 0 then (\n if IIHeap.empty h then (\n c := 1;\n raise No\n );\n let v,p = IIHeap.pop h in\n ans := !ans+v;\n a.[p] <- '(';\n c := !c+2;\n )\n ) a;\n if !c <> 0 then\n raise No;\n Printf.printf \"%d\\n%s\\n\" !ans a\n with _ ->\n print_endline \"-1\"\n"}], "src_uid": "970cd8ce0cf7214b7f2be337990557c9"} {"nl": {"description": "Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $$$1$$$. Each person is looking through the circle's center at the opposite person. A sample of a circle of $$$6$$$ persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $$$c$$$? If, for the specified $$$a$$$, $$$b$$$, and $$$c$$$, no such circle exists, output -1.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \\le a,b,c \\le 10^8$$$).", "output_spec": "For each test case output in a separate line a single integer $$$d$$$ \u2014 the number of the person being looked at by the person with the number $$$c$$$ in a circle such that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$. If there are multiple solutions, print any of them. Output $$$-1$$$ if there's no circle meeting the given conditions.", "sample_inputs": ["7\n6 2 4\n2 3 1\n2 4 10\n5 3 4\n1 3 2\n2 5 4\n4 3 2"], "sample_outputs": ["8\n-1\n-1\n-1\n4\n1\n-1"], "notes": "NoteIn the first test case, there's a desired circle of $$$8$$$ people. The person with the number $$$6$$$ will look at the person with the number $$$2$$$ and the person with the number $$$8$$$ will look at the person with the number $$$4$$$.In the second test case, there's no circle meeting the conditions. If the person with the number $$$2$$$ is looking at the person with the number $$$3$$$, the circle consists of $$$2$$$ people because these persons are neighbors. But, in this case, they must have the numbers $$$1$$$ and $$$2$$$, but it doesn't meet the problem's conditions.In the third test case, the only circle with the persons with the numbers $$$2$$$ and $$$4$$$ looking at each other consists of $$$4$$$ people. Therefore, the person with the number $$$10$$$ doesn't occur in the circle."}, "positive_code": [{"source_code": "open Array;;\r\nlet readInt () = Scanf.scanf \" %d\" (fun i -> i)\r\n \r\nlet print_number x = print_string (string_of_int x); print_newline();;\r\n\r\nlet abs a =\r\n if a < 0 then a*(-1)\r\n else a;;\r\n\r\nlet check a b c n =\r\n if a > n then false\r\n else if b > n then false\r\n else if c > n then false\r\n else true;;\r\n\r\nlet t = readInt() in\r\nlet ans = ref 0 in\r\nfor i = 1 to t do \r\n let a = readInt() in\r\n let b = readInt() in\r\n let c = readInt() in\r\n let n = 2 * abs (a-b) in\r\n let () = \r\n if check a b c n then\r\n if c > (n/2) then\r\n ans := c - (n/2)\r\n else\r\n ans := c + (n/2)\r\n else\r\n ans := -1\r\n in \r\n print_number !ans;\r\ndone;;"}], "negative_code": [], "src_uid": "07597a8d08b59d4f8f82369bb5d74a49"} {"nl": {"description": "Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size n\u2009\u00d7\u2009n (n is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to n\u2009-\u20091, main diagonal should contain only zeroes and matrix should be symmetric. Moreover, all numbers in each row should be different. Magicians are very tired of the thinking process, so they ask you to write a program to find such matrix.", "input_spec": "The first line contains one integer n (2\u2009\u2264\u2009n\u2009\u2264\u20091000), n is even.", "output_spec": "Output n lines with n numbers each \u2014 the required matrix. Separate numbers with spaces. If there are several solutions, output any.", "sample_inputs": ["2", "4"], "sample_outputs": ["0 1\n1 0", "0 1 3 2\n1 0 2 3\n3 2 0 1\n2 3 1 0"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n for i = 0 to n-1 do\n for j = 0 to n-1 do\n Printf.printf \"%d%c\" (if i = j then 0\n else if i = n-1 || j = n-1 then\n min i j * 2 mod (n-1) + 1\n else\n (i+j) mod (n-1) + 1)\n (if j == n-1 then '\\n' else ' ')\n done\n done\n"}], "negative_code": [], "src_uid": "f5f892203b62dae7eba86f59b13f5a38"} {"nl": {"description": "Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?You can assume that initially Vanya had infinitely many cards with each integer number from \u2009-\u2009x to x. ", "input_spec": "The first line contains two integers: n (1\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of found cards and x (1\u2009\u2264\u2009x\u2009\u2264\u20091000) \u2014 the maximum absolute value of the number on a card. The second line contains n space-separated integers \u2014 the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.", "output_spec": "Print a single number \u2014 the answer to the problem.", "sample_inputs": ["3 2\n-1 1 2", "2 3\n-2 -2"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first sample, Vanya needs to find a single card with number -2.In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let x = read_int() in\n let input = Array.init n (fun _ -> read_int()) in\n let s = sum 0 (n-1) (fun i -> input.(i)) in\n\n (* want the minimum number of cards such that their sum when\n combined with s is zero. *)\n\n let s = abs s in\n let k = s/x in\n let k = if k*x = s then k else k+1 in\n printf \"%d\\n\" k\n"}, {"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and x=read_int();;\nlet s=ref 0;;\nfor i=1 to n do\n s:= !s+read_int()\ndone;;\nif !s<0 then s:= 0- !s;;\ns:= !s+x-1;;\nprint_int ( !s/x);;"}, {"source_code": "let k = int_of_string (List.nth (Str.split (Str.regexp_string \" \") (read_line ())) 1);;\nlet s = List.map int_of_string (Str.split (Str.regexp_string \" \") (read_line ()));;\nlet sum = abs (List.fold_left ( + ) 0 s);;\nprint_newline (print_int ((fun x -> if x * k < sum then (x + 1) else x) (sum / k)));;\n"}], "negative_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and x=read_int();;\nlet s=ref 0;;\nfor i=1 to n do\n s:= !s+read_int()\ndone;;\nif !s<0 then s:= 0- !s;;\nprint_int ( !s/x);;"}, {"source_code": "let k = int_of_string (List.nth (Str.split (Str.regexp_string \" \") (read_line ())) 1);;\nlet s = List.map int_of_string (Str.split (Str.regexp_string \" \") (read_line ()));;\nlet sum = abs (List.fold_left ( + ) 0 s);;\nprint_newline (print_int ((fun x -> if x * k < sum then x + 1 else x) (sum mod k)));;\n"}], "src_uid": "066906ee58af5163636dac9334619ea7"} {"nl": {"description": "Do you know a story about the three musketeers? Anyway, you will learn about its origins now.Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.", "input_spec": "The first line contains two space-separated integers, n and m (3\u2009\u2264\u2009n\u2009\u2264\u20094000, 0\u2009\u2264\u2009m\u2009\u2264\u20094000) \u2014 respectively number of warriors and number of pairs of warriors knowing each other. i-th of the following m lines contains two space-separated integers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi). Warriors ai and bi know each other. Each pair of warriors will be listed at most once.", "output_spec": "If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print \"-1\" (without the quotes).", "sample_inputs": ["5 6\n1 2\n1 3\n2 3\n2 4\n3 4\n4 5", "7 4\n2 1\n3 6\n5 1\n1 7"], "sample_outputs": ["2", "-1"], "notes": "NoteIn the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0\u2009+\u20091\u2009+\u20091\u2009=\u20092.The other possible triple is 2,\u20093,\u20094 but it has greater sum of recognitions, equal to 1\u2009+\u20091\u2009+\u20091\u2009=\u20093.In the second sample there is no triple of warriors knowing each other."}, "positive_code": [{"source_code": "(* number of warriors n\n * number of pairs m *)\nlet () = Scanf.scanf \"%d %d\\n\" (fun n m ->\n\t\t\t\t(* adjacency matrix *)\n\t\t\t\tlet k = Array.make_matrix n n false\n\t\t\t\t(* recognition of each warrior *)\n\t\t\t\tand r = Array.make n 0\n\t\t\t\t(* adjacency list *)\n\t\t\t\tand d = Array.make n [] in\n\n\t\t\t\t(* populate adjacency and recognition *)\n\t\t\t\tfor i = 1 to m do\n\t\t\t\t Scanf.scanf \"%d %d\\n\" (fun a b ->\n\t\t\t\t\t\t\t k.(a - 1).(b - 1) <- true;\n\t\t\t\t\t\t\t k.(b - 1).(a - 1) <- true;\n\t\t\t\t\t\t\t r.(a - 1) <- r.(a - 1) + 1;\n\t\t\t\t\t\t\t r.(b - 1) <- r.(b - 1) + 1;\n\t\t\t\t\t\t\t d.(a - 1) <- (b - 1) :: d.(a - 1);\n\t\t\t\t\t\t\t d.(b - 1) <- (a - 1) :: d.(b - 1))\n\t\t\t\tdone;\n\n\t\t\t\tlet m = ref 15000 in\n\n\t\t\t\tfor i = 0 to (n - 2) do\n\t\t\t\t for j = (i + 1) to (n - 1) do\n\t\t\t\t if k.(i).(j) then\n\t\t\t\t List.iter (fun l -> if k.(j).(l) then m := min !m (r.(i) + r.(j) + r.(l) - 6)) d.(i)\n\t\t\t\t done\n\t\t\t\tdone;\n\n\t\t\t\tPrintf.printf \"%d\\n\" (if !m = 15000 then (-1) else !m))\n"}], "negative_code": [], "src_uid": "24a43df3e6d2af348692cdfbeb8a195c"} {"nl": {"description": "It is the easy version of the problem. The only difference is that in this version $$$a_i \\le 200$$$.You are given an array of $$$n$$$ integers $$$a_0, a_1, a_2, \\ldots a_{n - 1}$$$. Bryap wants to find the longest beautiful subsequence in the array.An array $$$b = [b_0, b_1, \\ldots, b_{m-1}]$$$, where $$$0 \\le b_0 < b_1 < \\ldots < b_{m - 1} < n$$$, is a subsequence of length $$$m$$$ of the array $$$a$$$.Subsequence $$$b = [b_0, b_1, \\ldots, b_{m-1}]$$$ of length $$$m$$$ is called beautiful, if the following condition holds: For any $$$p$$$ ($$$0 \\le p < m - 1$$$) holds: $$$a_{b_p} \\oplus b_{p+1} < a_{b_{p+1}} \\oplus b_p$$$. Here $$$a \\oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \\oplus 4 = 6$$$ and $$$3 \\oplus 1=2$$$.Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^5$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 3 \\cdot 10^5$$$) \u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,...,a_{n-1}$$$ ($$$0 \\leq a_i \\leq 200$$$) \u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \\cdot 10^5$$$.", "output_spec": "For each test case print a single integer \u2014 the length of the longest beautiful subsequence.", "sample_inputs": ["3\n\n2\n\n1 2\n\n5\n\n5 2 4 3 1\n\n10\n\n3 8 8 2 9 1 6 2 8 3"], "sample_outputs": ["2\n3\n6"], "notes": "NoteIn the first test case, we can pick the whole array as a beautiful subsequence because $$$1 \\oplus 1 < 2 \\oplus 0$$$.In the second test case, we can pick elements with indexes $$$1$$$, $$$2$$$ and $$$4$$$ (in $$$0$$$-indexation). For this elements holds: $$$2 \\oplus 2 < 4 \\oplus 1$$$ and $$$4 \\oplus 4 < 1 \\oplus 2$$$."}, "positive_code": [{"source_code": "module A = Array\nmodule L = List\nmodule I = Int64\nmodule B = Big_int\n\nmodule Opt = struct\n let get = function\n | None -> assert false\n | Some v -> v\nend\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\nlet read_array read n = A.init n (fun _ -> read ())\n\nmodule BitTrie = struct\n let inf = 1000000000;\n\n type t = {\n bit_v: int;\n children: (t option) array;\n mx_ans: int array;\n }\n\n let init bit_size = {\n bit_v = bit_size - 1;\n children = [| None; None |];\n mx_ans = [| -inf; -inf; -inf; -inf |]\n }\n\n let insert i x (root:t): t * int =\n let xr = i lxor x in\n let go_to bit_v (bit: int) (t:t) =\n let child = t.children.(bit) in\n if (child = None) then init bit_v\n else Opt.get child\n in\n let rec insert' (t:t): t * int =\n let bit = t.bit_v in\n let bit_x = (x lsr bit) land 1 lxor 1 in\n let bit_i = (i lsr bit) land 1 in\n let bit_xr = (xr lsr bit) land 1 in\n let cur_ans = t.mx_ans.(2 * bit_x + bit_i) in\n let child = go_to bit bit_xr t in\n let (new_child, child_ans) =\n if (bit = 0) then (child, -inf)\n else insert' child in\n let ret_ans = max cur_ans child_ans in\n t.children.(bit_xr) <- Some new_child;\n (t, ret_ans)\n in\n\n let (new_root, mx) = insert' root in\n let ans = max mx 0 + 1 in\n\n let rec relax (t:t) =\n let bit = t.bit_v in\n let bit_x = (x lsr bit) land 1 in\n let bit_i = (i lsr bit) land 1 in\n let coord = 2 * bit_i + bit_x in\n t.mx_ans.(coord) <- max t.mx_ans.(coord) ans;\n let bit_xr = (xr lsr bit) land 1 in\n if (bit = 0) then ()\n else relax (go_to bit bit_xr t)\n in\n relax new_root;\n (new_root, ans)\n\nend\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let a = read_array read_int n in\n let t = BitTrie.init 20 in\n let (_, res) = A.fold_left (\n fun (t, mx) (i, v) ->\n let (new_root, ans) = BitTrie.insert i v t in\n (new_root, max ans mx)\n ) (t, 0) (A.mapi (fun i x -> (i, x)) a) in\n pf \"%d\\n\" res;\n done;"}], "negative_code": [], "src_uid": "eee1ad545b2c4833e871989809355baf"} {"nl": {"description": "You are given an integer $$$n$$$ and an array $$$a_1, a_2, \\ldots, a_n$$$. You should reorder the elements of the array $$$a$$$ in such way that the sum of $$$\\textbf{MEX}$$$ on prefixes ($$$i$$$-th prefix is $$$a_1, a_2, \\ldots, a_i$$$) is maximized.Formally, you should find an array $$$b_1, b_2, \\ldots, b_n$$$, such that the sets of elements of arrays $$$a$$$ and $$$b$$$ are equal (it is equivalent to array $$$b$$$ can be found as an array $$$a$$$ with some reordering of its elements) and $$$\\sum\\limits_{i=1}^{n} \\textbf{MEX}(b_1, b_2, \\ldots, b_i)$$$ is maximized.$$$\\textbf{MEX}$$$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.For example, $$$\\textbf{MEX}(\\{1, 2, 3\\}) = 0$$$, $$$\\textbf{MEX}(\\{0, 1, 2, 4, 5\\}) = 3$$$.", "input_spec": "The first line contains a single integer $$$t$$$ $$$(1 \\le t \\le 100)$$$ \u00a0\u2014 the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \\le n \\le 100)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ $$$(0 \\le a_i \\le 100)$$$.", "output_spec": "For each test case print an array $$$b_1, b_2, \\ldots, b_n$$$ \u00a0\u2014 the optimal reordering of $$$a_1, a_2, \\ldots, a_n$$$, so the sum of $$$\\textbf{MEX}$$$ on its prefixes is maximized. If there exist multiple optimal answers you can find any.", "sample_inputs": ["3\n7\n4 2 0 1 3 3 7\n5\n2 2 8 6 9\n1\n0"], "sample_outputs": ["0 1 2 3 4 7 3 \n2 6 8 9 2 \n0"], "notes": "NoteIn the first test case in the answer $$$\\textbf{MEX}$$$ for prefixes will be: $$$\\textbf{MEX}(\\{0\\}) = 1$$$ $$$\\textbf{MEX}(\\{0, 1\\}) = 2$$$ $$$\\textbf{MEX}(\\{0, 1, 2\\}) = 3$$$ $$$\\textbf{MEX}(\\{0, 1, 2, 3\\}) = 4$$$ $$$\\textbf{MEX}(\\{0, 1, 2, 3, 4\\}) = 5$$$ $$$\\textbf{MEX}(\\{0, 1, 2, 3, 4, 7\\}) = 5$$$ $$$\\textbf{MEX}(\\{0, 1, 2, 3, 4, 7, 3\\}) = 5$$$ The sum of $$$\\textbf{MEX} = 1 + 2 + 3 + 4 + 5 + 5 + 5 = 25$$$. It can be proven, that it is a maximum possible sum of $$$\\textbf{MEX}$$$ on prefixes."}, "positive_code": [{"source_code": "(* https://codeforces.com/contest/1497/problem/0 *)\nlet make_hist arr =\n let histo = Array.make 101 0 in\n Array.iter\n (fun e -> histo.(e) <- histo.(e) + 1)\n arr;\n histo\n\nlet rec add_ntimes i n el arr =\n if n > 0\n then\n let _ = arr.(i) <- el in\n add_ntimes (i+1) (n-1) el arr\n\nlet meximization arr =\n let len = Array.length arr in\n let meximized = Array.make len 0 and\n mex_i = ref 0 and\n histo = make_hist arr in\n Array.iteri\n (fun i e ->\n if e <> 0\n then begin\n meximized.(!mex_i) <- i;\n mex_i := !mex_i + 1;\n histo.(i) <- histo.(i) - 1\n end)\n histo;\n Array.iteri\n (fun i e ->\n if e <> 0\n then begin\n add_ntimes !mex_i e i meximized;\n mex_i := !mex_i + e\n end)\n histo;\n meximized\n\nlet read_case () =\n let _ = read_int () in\n let arr =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string\n |> Array.of_list in\n arr\n\nlet solve_n n =\n let rec helper i =\n if i > 0\n then \n let arr = read_case () in\n let solution = meximization arr in\n let _ = Array.iter (Printf.printf \"%d \") solution and\n _ = print_newline () in\n helper (i-1) in\n helper n\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n\n"}], "negative_code": [], "src_uid": "69838d9f9214c65b84a21d4eb546ea4b"} {"nl": {"description": "Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.", "input_spec": "A single line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100000) \u2014 the number of digits in the set. The second line contains n digits, the digits are separated by a single space. ", "output_spec": "On a single line print the answer to the problem. If such number does not exist, then you should print -1.", "sample_inputs": ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"], "sample_outputs": ["0", "5554443330", "-1"], "notes": "NoteIn the first sample there is only one number you can make \u2014 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number."}, "positive_code": [{"source_code": "let gao a =\n let s = ref 0 in\n for i = 0 to Array.length a - 1 do\n s := !s + i * a.(i)\n done;\n if a.(0) > 0 && !s mod 3 = 0 then begin\n if !s = 0 then a.(0) <- 1;\n for i = Array.length a - 1 downto 0 do\n for j = 0 to a.(i) - 1 do\n print_int i\n done\n done;\n exit 0\n end\n;;\n\nlet _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let a = Array.create 10 0 in\n for i = 1 to n do\n let d = Scanf.scanf \" %d\" (fun x -> x) in\n a.(d) <- a.(d) + 1\n done;\n\n gao a;\n for i = 1 to 9 do\n if a.(i) > 0 then begin\n a.(i) <- a.(i) - 1;\n gao a;\n a.(i) <- a.(i) + 1\n end\n done;\n for i = 1 to 9 do\n if a.(i) > 0 then begin\n a.(i) <- a.(i) - 1;\n for j = 1 to i do\n if a.(j) > 0 then begin\n a.(j) <- a.(j) - 1;\n gao a;\n a.(j) <- a.(j) + 1\n end\n done;\n a.(i) <- a.(i) + 1\n end\n done;\n\n print_int (-1)\n;;\n"}], "negative_code": [], "src_uid": "b263917e47e1c84340bcb1c77999fd7e"} {"nl": {"description": "Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya must swap some two integers even if the original array meets all requirements.Array a (the array elements are indexed from 1) consisting of n elements is called sorted if it meets at least one of the following two conditions: a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009an; a1\u2009\u2265\u2009a2\u2009\u2265\u2009...\u2009\u2265\u2009an. Help Petya find the two required positions to swap or else say that they do not exist.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n non-negative space-separated integers a1,\u2009a2,\u2009...,\u2009an \u2014 the elements of the array that Petya's mother presented him. All integers in the input do not exceed 109.", "output_spec": "If there is a pair of positions that make the array unsorted if swapped, then print the numbers of these positions separated by a space. If there are several pairs of positions, print any of them. If such pair does not exist, print -1. The positions in the array are numbered with integers from 1 to n.", "sample_inputs": ["1\n1", "2\n1 2", "4\n1 2 3 4", "3\n1 1 1"], "sample_outputs": ["-1", "-1", "1 2", "-1"], "notes": "NoteIn the first two samples the required pairs obviously don't exist.In the third sample you can swap the first two elements. After that the array will look like this: 2 1 3 4. This array is unsorted."}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun i -> read_int()) in\n\n let rec findud i ac = if i=n-1 then List.rev ac else (\n if a.(i) < a.(i+1) then findud (i+1) ((1,i)::ac)\n else if a.(i) > a.(i+1) then findud (i+1) ((-1,i)::ac)\n else findud (i+1) ac\n )\n in\n let li = findud 0 [] in\n let m = List.length li in\n let (a,b) = \n if m=0 || n <= 2 then (-1,-1)\n else if m=1 then (\n let (_,i1) = List.nth li 0 in\n\t(i1, i1+1)\n ) else if m=2 then (\n let (d1,i1) = List.nth li 0 in\n let (d2,i2) = List.nth li 1 in\n\tif n=3 then (\n\t if d1=d2 then (i1, i1+1)\n\t else if a.(0) <> a.(n-1) then (0,n-1)\n\t else (-1,-1)\n\t) else (\n\t if d1=d2 then (i1, i1+1)\n\t else if i1=0 then (i2, i2+1)\n\t else (i1, i1+1)\n\t)\n ) else (\n (* uuu -> duu swap 1\n uud -> dud swap 1\n udu -> d?u swap 1 (or 3)\n\t udd -> udu swap 3\n duu -> dud swap 3\n dud -> u?d swap 1 (or 3)\n\t ddu -> udu swap 1\n ddd -> udd swap 1\n *)\n let (d1,i1) = List.nth li 0 in\n let (d2,i2) = List.nth li 1 in\n let (d3,i3) = List.nth li 2 in\n\tif d1=d2 then (i1, i1+1)\n\telse (i3, i3+1)\n )\n in\n if (a,b) = (-1,-1) then Printf.printf \"-1\\n\" else Printf.printf \"%d %d\\n\" (a+1) (b+1)\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun i -> read_int()) in\n\n let rec findud i ac = if i=n-1 then List.rev ac else (\n if a.(i) < a.(i+1) then findud (i+1) ((1,i)::ac)\n else if a.(i) > a.(i+1) then findud (i+1) ((-1,i)::ac)\n else findud (i+1) ac\n )\n in\n let li = findud 0 [] in\n let m = List.length li in\n if m<=1 then Printf.printf \"-1\\n\"\n else if m=2 then\n if a.(0) = a.(n-1) then Printf.printf \"-1\\n\" else \n\tlet (d1,i1) = List.nth li 0 in\n\tlet (d2,i2) = List.nth li 1 in\n\t if d1=d2 then Printf.printf \"%d %d\\n\" (i1+1) (i1+2) else Printf.printf \"%d %d\\n\" 1 n\n else (\n (* uuu -> duu swap 1\n\t duu -> dud swap 3\n\t udu -> d?u swap 1\n\t ddu -> udu swap 1\n *)\n let (d1,i1) = List.nth li 0 in\n let (d2,i2) = List.nth li 1 in\n let (d3,i3) = List.nth li 2 in\n\tif d1=d2 then Printf.printf \"%d %d\\n\" (i1+1) (i1+2)\n\telse Printf.printf \"%d %d\\n\" (i3+1) (i3+2)\n )\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun i -> read_int()) in\n\n if a.(0) = a.(n-1) || n=2 then Printf.printf \"-1\\n\" else (\n if n>3 then Printf.printf \"1 %d\\n\" n else (\n\tif a.(0) <> a.(1) then Printf.printf \"1 2\\n\" else Printf.printf \"2 3\\n\"\n )\n )\n\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun i -> read_int()) in\n\n if a.(0) = a.(n-1) || n=2 then Printf.printf \"-1\\n\" else (\n let rec loop i =\n\tif a.(i) <> a.(i+1) then Printf.printf \"%d %d\\n\" (i+1) (i+2) else loop (i+1)\n in\n\tloop 0\n )\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun i -> read_int()) in\n\n let rec findud i ac = if i=n-1 then List.rev ac else (\n if a.(i) < a.(i+1) then findud (i+1) ((1,i)::ac)\n else if a.(i) > a.(i+1) then findud (i+1) ((-1,i)::ac)\n else findud (i+1) ac\n )\n in\n let li = findud 0 [] in\n let m = List.length li in\n if m<=1 then Printf.printf \"-1\\n\"\n else if m=2 then\n if a.(0) = a.(n-1) then Printf.printf \"-1\\n\" else Printf.printf \"%d %d\\n\" 1 n\n else (\n (* uuu -> duu swap 1\n\t duu -> dud swap 3\n\t udu -> d?u swap 1\n\t ddu -> udu swap 1\n *)\n let (d1,i1) = List.nth li 0 in\n let (d2,i2) = List.nth li 1 in\n let (d3,i3) = List.nth li 2 in\n\tif d1=d2 then Printf.printf \"%d %d\\n\" (i1+1) (i1+2)\n\telse Printf.printf \"%d %d\\n\" (i3+1) (i3+2)\n )\n"}], "src_uid": "2ae4d2ca09f28d10fa2c71eb2abdaa1c"} {"nl": {"description": "Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n\u2009\u00d7\u2009n matrix W, consisting of integers, and you should find two n\u2009\u00d7\u2009n matrices A and B, all the following conditions must hold: Aij\u2009=\u2009Aji, for all i,\u2009j (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n); Bij\u2009=\u2009\u2009-\u2009Bji, for all i,\u2009j (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n); Wij\u2009=\u2009Aij\u2009+\u2009Bij, for all i,\u2009j (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n). Can you solve the problem?", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009170). Each of the following n lines contains n integers. The j-th integer in the i-th line is Wij (0\u2009\u2264\u2009|Wij|\u2009<\u20091717).", "output_spec": "The first n lines must contain matrix A. The next n lines must contain matrix B. Print the matrices in the format equal to format of matrix W in input. It is guaranteed that the answer exists. If there are multiple answers, you are allowed to print any of them. The answer will be considered correct if the absolute or relative error doesn't exceed 10\u2009-\u20094.", "sample_inputs": ["2\n1 4\n3 2", "3\n1 2 3\n4 5 6\n7 8 9"], "sample_outputs": ["1.00000000 3.50000000\n3.50000000 2.00000000\n0.00000000 0.50000000\n-0.50000000 0.00000000", "1.00000000 3.00000000 5.00000000\n3.00000000 5.00000000 7.00000000\n5.00000000 7.00000000 9.00000000\n0.00000000 -1.00000000 -2.00000000\n1.00000000 0.00000000 -1.00000000\n2.00000000 1.00000000 0.00000000"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let n = Scanf.scanf \"%d \" (fun x -> x) in\n let w = Array.make_matrix n n 0. in\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n w.(i).(j) <- Scanf.scanf \"%f \" (fun x -> x);\n done;\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n Printf.printf \"%.1f \" ((w.(i).(j) +. w.(j).(i)) /. 2.)\n done;\n print_newline ();\n done;\n for i = 0 to n - 1 do\n for j = 0 to n - 1 do\n Printf.printf \"%.1f \" ((w.(i).(j) -. w.(j).(i)) /. 2.)\n done;\n print_newline ();\n done;\n"}], "negative_code": [], "src_uid": "6a6c259befa63f2aed17f23db21def63"} {"nl": {"description": "'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n\u2009-\u2009m of them are regular questions. Each question has a price. The price of the i-th question is ai points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100;\u00a0m\u2009\u2264\u2009min(n,\u200930)) \u2014 the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009107) \u2014 the prices of the questions. The third line contains m distinct integers bi (1\u2009\u2264\u2009bi\u2009\u2264\u2009n) \u2014 the numbers of auction questions. Assume that the questions are numbered from 1 to n.", "output_spec": "In the single line, print the answer to the problem \u2014 the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type.", "sample_inputs": ["4 1\n1 3 7 5\n3", "3 2\n10 3 8\n2 3", "2 2\n100 200\n1 2"], "sample_outputs": ["18", "40", "400"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and m=read_int();;\nlet tab=Array.make (n+1) 0;;\nfor i=1 to n do\n tab.(i)<-read_int()\ndone;;\nlet boo=Array.make (n+1) 0;;\nfor i=1 to m do\n boo.(read_int())<-1\ndone;;\nlet auction=Array.make m 0;;\nlet non_auction=Array.make (n-m) 0;;\nlet j=ref 0;;\nlet k=ref 0;;\nfor i=1 to n do\n if boo.(i)=1 then (auction.(!j)<-tab.(i);incr j)\n else (non_auction.(!k)<-tab.(i);incr k)\ndone;;\nArray.fast_sort (fun x y -> if x=y then 0 else if x>y then -1 else 1) auction;;\nlet sum=ref Int64.zero;;\nfor i=0 to n-m-1 do\n sum:=Int64.add (!sum) (Int64.of_int(non_auction.(i)))\ndone;;\nlet j=ref 0;;\nfor i=0 to m-1 do\n let x=Int64.of_int(auction.(i)) in\n begin\n if x> !sum then sum:=Int64.add (!sum) x\n else sum:=Int64.add (!sum) (!sum)\n end\ndone;;\nprint_string (Int64.to_string(!sum));;"}], "negative_code": [], "src_uid": "913925f7b43ad737809365eba040e8da"} {"nl": {"description": "The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i,\u2009j).You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri,\u2009ai,\u2009bi (ai\u2009\u2264\u2009bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.Your task is to find the minimum number of moves the king needs to get from square (x0,\u2009y0) to square (x1,\u2009y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.", "input_spec": "The first line contains four space-separated integers x0,\u2009y0,\u2009x1,\u2009y1 (1\u2009\u2264\u2009x0,\u2009y0,\u2009x1,\u2009y1\u2009\u2264\u2009109), denoting the initial and the final positions of the king. The second line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri,\u2009ai,\u2009bi (1\u2009\u2264\u2009ri,\u2009ai,\u2009bi\u2009\u2264\u2009109,\u2009ai\u2009\u2264\u2009bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily. It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.", "output_spec": "If there is no path between the initial and final position along allowed cells, print -1. Otherwise print a single integer \u2014 the minimum number of moves the king needs to get from the initial position to the final one.", "sample_inputs": ["5 7 6 11\n3\n5 3 8\n6 7 11\n5 2 5", "3 4 3 10\n3\n3 1 4\n4 5 9\n3 10 10", "1 1 2 10\n2\n1 1 3\n2 6 10"], "sample_outputs": ["4", "6", "-1"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet bound = 1_000_000_000\n\nlet () = \n let x0 = read_int() in\n let y0 = read_int() in\n let x1 = read_int() in\n let y1 = read_int() in\n let n = read_int() in\n let strip = Array.init n (\n fun _ ->\n let r = read_int() in\n let a = read_int() in\n let b = read_int() in\n\t(r,a,b)\n ) in\n \n let h = Hashtbl.create 1000 in\n for i=0 to n-1 do\n let (r,a,b) = strip.(i) in\n\tfor c=a to b do\n\t Hashtbl.add h (r,c) true\n\tdone\n done;\n\n let neighbors (r,c) = \n let dl = List.map (fun (dr,dc) -> (r+dr, c+dc))\n\t[(1,1);(1,0);(1,-1);(0,1);(0,-1);(-1,1);(-1,0);(-1,-1)] in\n\tList.filter (\n\t fun (r,c) -> \n\t r >= 1 && c >= 1 && r <= bound && c<=bound &\n\t Hashtbl.mem h (r,c)\n\t) dl\n in\n \n let rec pass prev current = \n Pset.fold (\n\tfun p s ->\n\t let xnew = List.filter (\n\t fun ne -> (not (Pset.mem ne current)) && (not (Pset.mem ne prev))\n\t ) (neighbors p)\n\t in\n\t List.fold_left (fun s ne -> Pset.add ne s) s xnew \n ) current Pset.empty\n in\n\n let rec loop prev current d = \n if Pset.is_empty current then None\n else if Pset.mem (x1,y1) current then Some d \n else loop current (pass prev current) (d+1)\n in\n\n let ans = \n match loop Pset.empty (Pset.singleton (x0,y0)) 0 with \n\t| None -> -1\n\t| Some d -> d\n in\n\n Printf.printf \"%d\\n\" ans\n"}], "negative_code": [], "src_uid": "c3cbc9688594d6611fd7bdd98d9afaa0"} {"nl": {"description": "Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array $$$a$$$ with elements $$$a_1, a_2, \\ldots, a_{2k-1}$$$, is the array $$$b$$$ with elements $$$b_1, b_2, \\ldots, b_{k}$$$ such that $$$b_i$$$ is equal to the median of $$$a_1, a_2, \\ldots, a_{2i-1}$$$ for all $$$i$$$. Omkar has found an array $$$b$$$ of size $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$, $$$-10^9 \\leq b_i \\leq 10^9$$$). Given this array $$$b$$$, Ray wants to test Omkar's claim and see if $$$b$$$ actually is an OmkArray of some array $$$a$$$. Can you help Ray?The median of a set of numbers $$$a_1, a_2, \\ldots, a_{2i-1}$$$ is the number $$$c_{i}$$$ where $$$c_{1}, c_{2}, \\ldots, c_{2i-1}$$$ represents $$$a_1, a_2, \\ldots, a_{2i-1}$$$ sorted in nondecreasing order. ", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 2 \\cdot 10^5$$$) \u2014 the length of the array $$$b$$$. The second line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$-10^9 \\leq b_i \\leq 10^9$$$) \u2014 the elements of $$$b$$$. It is guaranteed the sum of $$$n$$$ across all test cases does not exceed $$$2 \\cdot 10^5$$$. ", "output_spec": "For each test case, output one line containing YES if there exists an array $$$a$$$ such that $$$b_i$$$ is the median of $$$a_1, a_2, \\dots, a_{2i-1}$$$ for all $$$i$$$, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted).", "sample_inputs": ["5\n4\n6 2 1 3\n1\n4\n5\n4 -8 5 6 -7\n2\n3 3\n4\n2 1 2 3", "5\n8\n-8 2 -6 -5 -4 3 3 2\n7\n1 1 3 1 0 -2 -1\n7\n6 12 8 6 2 6 10\n6\n5 1 2 3 6 7\n5\n1 3 4 3 0"], "sample_outputs": ["NO\nYES\nNO\nYES\nYES", "NO\nYES\nNO\nNO\nNO"], "notes": "NoteIn the second case of the first sample, the array $$$[4]$$$ will generate an OmkArray of $$$[4]$$$, as the median of the first element is $$$4$$$.In the fourth case of the first sample, the array $$$[3, 2, 5]$$$ will generate an OmkArray of $$$[3, 3]$$$, as the median of $$$3$$$ is $$$3$$$ and the median of $$$2, 3, 5$$$ is $$$3$$$.In the fifth case of the first sample, the array $$$[2, 1, 0, 3, 4, 4, 3]$$$ will generate an OmkArray of $$$[2, 1, 2, 3]$$$ as the median of $$$2$$$ is $$$2$$$ the median of $$$0, 1, 2$$$ is $$$1$$$ the median of $$$0, 1, 2, 3, 4$$$ is $$$2$$$ and the median of $$$0, 1, 2, 3, 3, 4, 4$$$ is $$$3$$$. In the second case of the second sample, the array $$$[1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5]$$$ will generate an OmkArray of $$$[1, 1, 3, 1, 0, -2, -1]$$$, as the median of $$$1$$$ is $$$1$$$ the median of $$$0, 1, 4$$$ is $$$1$$$ the median of $$$0, 1, 3, 4, 5$$$ is $$$3$$$ the median of $$$-2, -2, 0, 1, 3, 4, 5$$$ is $$$1$$$ the median of $$$-4, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$0$$$ the median of $$$-4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$-2$$$ and the median of $$$-4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5$$$ is $$$-1$$$ For all cases where the answer is NO, it can be proven that it is impossible to find an array $$$a$$$ such that $$$b$$$ is the OmkArray of $$$a$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\n(* set code from ~/Sync/contest-work/codeforces-709/d.ml *)\n\nmodule Iset = Set.Make (struct type t = int let compare = compare end)\nopen Iset\n\nlet pred x s = \n let (l,_,_) = split x s in\n max_elt (if is_empty l then s else l)\n\nlet succ x s = \n let (_,_,r) = split x s in\n min_elt (if is_empty r then s else r)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let b = Array.init n read_int in\n\n let rec loop s i = if i=n then true\n (* b.(i-1) is the last median before the current one *)\n else if b.(i) > b.(i-1) then (\n\tlet z = succ b.(i-1) s in\n\tif z > b.(i-1) && b.(i) > z then false\n\telse loop (add b.(i) s) (i+1)\n ) else if b.(i) < b.(i-1) then (\n\tlet z = pred b.(i-1) s in\n\tif z < b.(i-1) && b.(i) < z then false\n\telse loop (add b.(i) s) (i+1)\n ) else loop s (i+1)\n in\n if loop (singleton b.(0)) 1 then printf \"YES\\n\" else printf \"NO\\n\"\n done\n"}], "negative_code": [], "src_uid": "6ed24fef3b7f0f0dc040fc5bed535209"} {"nl": {"description": "Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n\u2009=\u2009p1\u00b7p2\u00b7...\u00b7pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109\u2009+\u20097 is the password to the secret data base. Now he wants to calculate this value.", "input_spec": "The first line of the input contains a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of primes in factorization of n. The second line contains m primes numbers pi (2\u2009\u2264\u2009pi\u2009\u2264\u2009200\u2009000).", "output_spec": "Print one integer\u00a0\u2014 the product of all divisors of n modulo 109\u2009+\u20097.", "sample_inputs": ["2\n2 3", "3\n2 3 2"], "sample_outputs": ["36", "1728"], "notes": "NoteIn the first sample n\u2009=\u20092\u00b73\u2009=\u20096. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1\u00b72\u00b73\u00b76\u2009=\u200936.In the second sample 2\u00b73\u00b72\u2009=\u200912. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1\u00b72\u00b73\u00b74\u00b76\u00b712\u2009=\u20091728."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet p = 1_000_000_007L\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n \nlet ( *** ) a b = (a**b) %% p\nlet ( +++ ) a b = let x = a++b in if x>=p then x--p else x\nlet ( --- ) a b = let x = a--b in if x<0L then x++p else x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \n \nlet rec ( ^ ) b e = \n if e=0L then 1L else\n let a = b ^ (e//2L) in\n if (Int64.logand e 1L)=0L then a***a else b***a***a\n \nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n \nlet () = \n let m = read_int () in\n\n let h = Hashtbl.create 10 in\n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0L in\n Hashtbl.replace h t (c++1L)\n in\n\n for i=0 to m-1 do\n increment (read_long ())\n done;\n\n let primefact = Array.of_list (\n Hashtbl.fold (fun pr pow ac -> (pr,pow)::ac) h []) in\n let np = Array.length primefact in\n\n let alphaprefix = Array.make (np+1) 1L in\n let alphasuffix = Array.make (np+1) 1L in\n\n for i=1 to np do\n let (_,pow) = primefact.(i-1) in\n alphaprefix.(i) <- (alphaprefix.(i-1) ** (pow++1L)) %% (p--1L)\n done;\n\n for i=np-1 downto 0 do\n let (_,pow) = primefact.(i) in\n alphasuffix.(i) <- (alphasuffix.(i+1) ** (pow++1L)) %% (p--1L)\n done;\n\n (* alphaprefix.(i) = pow0 * pow1 * ... * pow(i-1) *)\n (* alphasuffix.(i) = pow(np-1) * pow(np-2) * ... * pow(i) *) \n\n (* the product of the powers (mod p-1) without pow(i) is\n alphaprefix.(i) * alphasuffix.(i+1)\n *)\n \n let answer = fold 0 (np-1) (fun i ac -> \n let (pr,pow) = primefact.(i) in\n let alphaprod = (alphaprefix.(i) ** alphasuffix.(i+1)) %% (p--1L) in\n let x = ((pow ** (pow ++ 1L)) // 2L) %% (p--1L) in\n let y = (x ** alphaprod) %% (p--1L) in\n let z = pr ^ y in\n ac *** z\n ) 1L in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "9a5bd9f937da55c3d26d5ecde6e50280"} {"nl": {"description": "President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The \u00abperiod\u00bb character (\u00ab.\u00bb) stands for an empty cell. ", "input_spec": "The first line contains two separated by a space integer numbers n, m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the length and the width of the office-room, and c character \u2014 the President's desk colour. The following n lines contain m characters each \u2014 the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.", "output_spec": "Print the only number \u2014 the amount of President's deputies.", "sample_inputs": ["3 4 R\nG.B.\n.RR.\nTTT.", "3 3 Z\n...\n.H.\n..Z"], "sample_outputs": ["2", "0"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let r = (read_str 0).[0] in\n let a = Array.init n read_str in\n let h = Hashtbl.create n in\n for i = 0 to n-1 do\n for j = 0 to m-1 do\n if a.(i).[j] = r then\n List.iter2 (fun di dj ->\n let ii = i+di in\n let jj = j+dj in\n if 0 <= ii && ii < n && 0 <= jj && jj < m && a.(ii).[jj] <> '.' &&\n a.(ii).[jj] <> r then\n Hashtbl.replace h a.(ii).[jj] ()\n ) [-1;0;1;0] [0;1;0;-1]\n done\n done;\n Printf.printf \"%d\\n\" (Hashtbl.length h)\n"}], "negative_code": [], "src_uid": "d7601c9bb06a6852f04957fbeae54925"} {"nl": {"description": "One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day.Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume that the string contains the letters of some users of the R1 mail. Recovering letters is a tedious mostly manual work. So before you start this process, it was decided to estimate the difficulty of recovering. Namely, we need to calculate the number of different substrings of the saved string that form correct e-mail addresses.We assume that valid addresses are only the e-mail addresses which meet the following criteria: the address should begin with a non-empty sequence of letters, numbers, characters '_', starting with a letter; then must go character '@'; then must go a non-empty sequence of letters or numbers; then must go character '.'; the address must end with a non-empty sequence of letters. You got lucky again and the job was entrusted to you! Please note that the substring is several consecutive characters in a string. Two substrings, one consisting of the characters of the string with numbers l1,\u2009l1\u2009+\u20091,\u2009l1\u2009+\u20092,\u2009...,\u2009r1 and the other one consisting of the characters of the string with numbers l2,\u2009l2\u2009+\u20091,\u2009l2\u2009+\u20092,\u2009...,\u2009r2, are considered distinct if l1\u2009\u2260\u2009l2 or r1\u2009\u2260\u2009r2.", "input_spec": "The first and the only line contains the sequence of characters s1s2... sn (1\u2009\u2264\u2009n\u2009\u2264\u2009106) \u2014 the saved string. It is guaranteed that the given string contains only small English letters, digits and characters '.', '_', '@'.", "output_spec": "Print in a single line the number of substrings that are valid e-mail addresses.", "sample_inputs": ["gerald.agapov1991@gmail.com", "x@x.x@x.x_e_@r1.com", "a___@1.r", ".asd123__..@"], "sample_outputs": ["18", "8", "1", "0"], "notes": "NoteIn the first test case all the substrings that are correct e-mail addresses begin from one of the letters of the word agapov and end in one of the letters of the word com.In the second test case note that the e-mail x@x.x is considered twice in the answer. Note that in this example the e-mail entries overlap inside the string."}, "positive_code": [{"source_code": "let s=read_line();;\nlet n=String.length(s)-1;;\n\nlet isvalid c=\nif (c<>'.')&&(c<>'@')&&(c<>'_') then true else false;;\n\nlet isletter c=\nif (c>='a')&&(c<='z') then true else false;;\n\nlet sol=ref Int64.zero;;\n\nlet rec faire i deb etape=\nif i>n then ()\nelse if etape=\"debut\" then\n begin\n if s.[i]='@' then \n begin\n if deb<>0 then faire (i+1) deb \"arobase1\"\n else faire (i+1) 0 \"debut\"\n end\n else if s.[i]='.' then faire (i+1) 0 \"debut\"\n else if (isletter s.[i]) then faire (i+1) (deb+1) \"debut\"\n else faire (i+1) deb \"debut\"\n end\nelse if etape=\"arobase1\" then\n begin\n if (isvalid s.[i]) then faire (i+1) deb \"arobase2\" else faire (i+1) 0 \"debut\"\n end\nelse if etape=\"arobase2\" then\n begin\n if (isvalid s.[i]) then faire (i+1) deb \"arobase2\"\n else if s.[i]='.' then faire (i+1) deb \"point\"\n else faire (i-1) 0 \"retour_arobase\"\n end\nelse if etape=\"point\" then\n begin\n if (isletter s.[i]) then (sol:= Int64.add (!sol) (Int64.of_int deb);faire (i+1) deb \"point\")\n else faire (i-1) 0 \"retour_point\"\n end\nelse if etape=\"retour_point\" then\n begin\n if s.[i]='.' then faire (i+1) 0 \"debut\"\n else faire (i-1) 0 \"retour_point\"\n end\nelse if s.[i]='@' then faire (i+1) 0 \"debut\"\nelse faire (i-1) 0 \"retour_arobase\";;\n\nfaire 0 0 \"debut\";;\n \nprint_string( Int64.to_string(!sol));;"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n (*let s = \"gerald.agapov1991@gmail.com\" in\n let s = \"x@x.x@x.x_e_@r1.com\" in*)\n let n = String.length s in\n let c = ref 0 in\n let c2 = ref 0 in\n let a = Array.make n 0 in\n let b = Array.make n 0 in\n let res = ref 0L in\n for i = 0 to n - 1 do\n match s.[i] with\n\t| '@' ->\n\t a.(i) <- !c;\n\t c := 0;\n\t| '.' -> c := 0;\n\t| 'a'..'z' -> incr c;\n\t| '0'..'9' -> ()\n\t| '_' -> ()\n\t| _ -> assert false\n done;\n c := 0;\n for i = n - 1 downto 0 do\n match s.[i] with\n\t| '@' ->\n\t if !c2 <> 0 && s.[i + 1] <> '.'\n\t then b.(i) <- !c2;\n\t c2 := 0;\n\t c := 0;\n\t| '.' ->\n\t c2 := !c;\n\t c := 0;\n\t| 'a'..'z' ->\n\t incr c;\n\t| '0'..'9' ->\n\t c := 0;\n\t| '_' ->\n\t c := 0;\n\t c2 := 0;\n\t| _ -> assert false\n done;\n for i = 0 to n - 1 do\n if s.[i] = '@'\n then res := Int64.add !res (Int64.mul (Int64.of_int a.(i))\n\t\t\t\t (Int64.of_int b.(i)))\n done;\n Printf.printf \"%Ld\\n\" !res;\n a, b\n"}], "negative_code": [{"source_code": "let s=read_line();;\nlet n=String.length(s)-1;;\n\nlet isvalid c=\nif (c<>'.')&&(c<>'@')&&(c<>'_') then true else false;;\n\nlet isletter c=\nif (c>='a')&&(c<='z') then true else false;;\n\nlet sol=ref 0;;\n\nlet rec faire i deb etape=\nif i>n then ()\nelse if etape=\"debut\" then\n begin\n if s.[i]='@' then \n begin\n if deb<>0 then faire (i+1) deb \"arobase1\"\n else faire (i+1) 0 \"debut\"\n end\n else if s.[i]='.' then faire (i+1) 0 \"debut\"\n else if (isletter s.[i]) then faire (i+1) (deb+1) \"debut\"\n else faire (i+1) deb \"debut\"\n end\nelse if etape=\"arobase1\" then\n begin\n if (isvalid s.[i]) then faire (i+1) deb \"arobase2\" else faire (i+1) 0 \"debut\"\n end\nelse if etape=\"arobase2\" then\n begin\n if (isvalid s.[i]) then faire (i+1) deb \"arobase2\"\n else if s.[i]='.' then faire (i+1) deb \"point\"\n else faire (i-1) 0 \"retour_arobase\"\n end\nelse if etape=\"point\" then\n begin\n if (isletter s.[i]) then (sol:= !sol+deb;faire (i+1) deb \"point\")\n else faire (i-1) 0 \"retour_point\"\n end\nelse if etape=\"retour_point\" then\n begin\n if s.[i]='.' then faire (i+1) 0 \"debut\"\n else faire (i-1) 0 \"retour_point\"\n end\nelse if s.[i]='@' then faire (i+1) 0 \"debut\"\nelse faire (i-1) 0 \"retour_arobase\";;\n\nfaire 0 0 \"debut\";;\n \nprint_int( !sol);;\n \n\n"}, {"source_code": "let s=read_line();;\nlet n=String.length(s)-1;;\n\nlet isvalid c=\nif (c<>'.')&&(c<>'@')&&(c<>'_') then true else false;;\n\nlet isletter c=\nif (c>='a')&&(c<='z') then true else false;;\n\nlet sol=ref 0;;\n\nlet rec faire i deb etape=\nif i>n then ()\nelse if etape=\"debut\" then\n begin\n if s.[i]='@' then \n begin\n if deb<>0 then faire (i+2) deb \"arobase1\"\n else faire (i+1) 0 \"debut\"\n end\n else if s.[i]='.' then faire (i+1) 0 \"debut\"\n else if (isletter s.[i]) then faire (i+1) (deb+1) \"debut\"\n else faire (i+1) deb \"debut\"\n end\nelse if etape=\"arobase1\" then\n begin\n if (isvalid s.[i]) then faire (i+1) deb \"arobase2\" else faire (i+1) 0 \"debut\"\n end\nelse if etape=\"arobase2\" then\n begin\n if (isvalid s.[i]) then faire (i+1) deb \"arobase2\"\n else if s.[i]='.' then faire (i+2) deb \"point\"\n else faire (i-1) 0 \"retour_arobase\"\n end\nelse if etape=\"point\" then\n begin\n if (isletter s.[i]) then (sol:= !sol+deb;faire (i+1) deb \"point\")\n else faire (i-1) 0 \"retour_point\"\n end\nelse if etape=\"retour_point\" then\n begin\n if s.[i]='.' then faire (i+1) 0 \"debut\"\n else faire (i-1) 0 \"retour_point\"\n end\nelse if s.[i]='@' then faire (i+1) 0 \"debut\"\nelse faire (i-1) 0 \"retour_arobase\";;\n\nfaire 0 0 \"debut\";;\n \nprint_int( !sol);;"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n (*let s = \"gerald.agapov1991@gmail.com\" in\n let s = \"x@x.x@x.x_e_@r1.com\" in*)\n let n = String.length s in\n let c = ref 0 in\n let c2 = ref 0 in\n let st = ref 0 in\n let a = Array.make n 0 in\n let b = Array.make n 0 in\n let res = ref 0L in\n for i = 0 to n - 1 do\n match s.[i] with\n\t| '@' ->\n\t a.(i) <- !c;\n\t c := 0;\n\t| '.' -> c := 0;\n\t| 'a'..'z' -> incr c;\n\t| '0'..'9' -> ()\n\t| '_' -> ()\n\t| _ -> assert false\n done;\n c := 0;\n for i = n - 1 downto 0 do\n match s.[i] with\n\t| '@' ->\n\t b.(i) <- !c2;\n\t c2 := 0;\n\t c := 0;\n\t| '.' ->\n\t c2 := !c;\n\t c := 0;\n\t| 'a'..'z' ->\n\t incr c;\n\t| '0'..'9' ->\n\t c := 0;\n\t| '_' ->\n\t c := 0;\n\t c2 := 0;\n\t| _ -> assert false\n done;\n for i = 0 to n - 1 do\n if s.[i] = '@'\n then res := Int64.add !res (Int64.mul (Int64.of_int a.(i))\n\t\t\t\t (Int64.of_int b.(i)))\n done;\n Printf.printf \"%Ld\\n\" !res;\n a, b\n"}], "src_uid": "08924ff11b857559a44c1637761b508a"} {"nl": {"description": "You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.", "input_spec": "The first line contains two integers nA,\u2009nB (1\u2009\u2264\u2009nA,\u2009nB\u2009\u2264\u2009105), separated by a space \u2014 the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1\u2009\u2264\u2009k\u2009\u2264\u2009nA,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009nB), separated by a space. The third line contains nA numbers a1,\u2009a2,\u2009... anA (\u2009-\u2009109\u2009\u2264\u2009a1\u2009\u2264\u2009a2\u2009\u2264\u2009...\u2009\u2264\u2009anA\u2009\u2264\u2009109), separated by spaces \u2014 elements of array A. The fourth line contains nB integers b1,\u2009b2,\u2009... bnB (\u2009-\u2009109\u2009\u2264\u2009b1\u2009\u2264\u2009b2\u2009\u2264\u2009...\u2009\u2264\u2009bnB\u2009\u2264\u2009109), separated by spaces \u2014 elements of array B.", "output_spec": "Print \"YES\" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print \"NO\" (without the quotes).", "sample_inputs": ["3 3\n2 1\n1 2 3\n3 4 5", "3 3\n3 3\n1 2 3\n3 4 5", "5 2\n3 1\n1 1 1 1 1\n2 2"], "sample_outputs": ["YES", "NO", "YES"], "notes": "NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: ."}, "positive_code": [{"source_code": "let () = Scanf.scanf \"%d %d\\n%d %d\\n\" (fun na nb k m ->\n let a = Array.init na (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x))\n and b = Array.init nb (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x))\n in\n\n print_endline (if a.(k - 1) < b.(nb - m) then \"YES\" else \"NO\"))\n"}], "negative_code": [], "src_uid": "8e0581cce19d6bf5eba30a0aebee9a08"} {"nl": {"description": "Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.The prison can be represented as a rectangle $$$a\\times b$$$ which is divided into $$$ab$$$ cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible.Your task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1\\leq t\\leq 100$$$)\u00a0\u2014 the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1\\leq a, b\\leq 100$$$), representing a corresponding test case.", "output_spec": "For each test case print the single integer on a separate line\u00a0\u2014 the answer to the problem.", "sample_inputs": ["2\n2 2\n1 3"], "sample_outputs": ["4\n3"], "notes": "NoteSome possible escape plans for the example test cases are shown below. Broken walls are shown in gray, not broken walls are shown in black. "}, "positive_code": [{"source_code": "let n = read_int ()\r\n;;\r\nlet read_pair _ = Scanf.bscanf Scanf.Scanning.stdin \" %d %d \" (fun x y -> (x,y))\r\n;;\r\n\r\nfor i = 1 to n do\r\n let (a,b) = read_pair () in\r\n Printf.printf \"%d\\n\" (a*b)\r\ndone"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let (a,b) = read_pair () in\n printf \"%d\\n\" (a*b)\n done\n"}], "negative_code": [], "src_uid": "806dcdab8364f5169334e172a192598a"} {"nl": {"description": "You have an array $$$a$$$ of length $$$n$$$. For every positive integer $$$x$$$ you are going to perform the following operation during the $$$x$$$-th second: Select some distinct indices $$$i_{1}, i_{2}, \\ldots, i_{k}$$$ which are between $$$1$$$ and $$$n$$$ inclusive, and add $$$2^{x-1}$$$ to each corresponding position of $$$a$$$. Formally, $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ for $$$j = 1, 2, \\ldots, k$$$. Note that you are allowed to not select any indices at all. You have to make $$$a$$$ nondecreasing as fast as possible. Find the smallest number $$$T$$$ such that you can make the array nondecreasing after at most $$$T$$$ seconds.Array $$$a$$$ is nondecreasing if and only if $$$a_{1} \\le a_{2} \\le \\ldots \\le a_{n}$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^{4}$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$1 \\le n \\le 10^{5}$$$)\u00a0\u2014 the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \\ldots, a_{n}$$$ ($$$-10^{9} \\le a_{i} \\le 10^{9}$$$).", "output_spec": "For each test case, print the minimum number of seconds in which you can make $$$a$$$ nondecreasing.", "sample_inputs": ["3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4"], "sample_outputs": ["2\n0\n3"], "notes": "NoteIn the first test case, if you select indices $$$3, 4$$$ at the $$$1$$$-st second and $$$4$$$ at the $$$2$$$-nd second, then $$$a$$$ will become $$$[1, 7, 7, 8]$$$. There are some other possible ways to make $$$a$$$ nondecreasing in $$$2$$$ seconds, but you can't do it faster.In the second test case, $$$a$$$ is already nondecreasing, so answer is $$$0$$$.In the third test case, if you do nothing at first $$$2$$$ seconds and select index $$$2$$$ at the $$$3$$$-rd second, $$$a$$$ will become $$$[0, 0]$$$."}, "positive_code": [{"source_code": "let r_long () = Int64.of_int (Scanf.scanf \" %d\" (fun x -> x)) in\nlet r_int () = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet rec max_diff maxi = function\n| 0 -> 0L\n| nbNombres -> \n let nombre = r_long () in\n let nouvMax = max nombre maxi in\n max (Int64.sub maxi nombre) (max_diff nouvMax (nbNombres - 1))\nin\n\nlet rec log = function\n| 0L -> 0\n| n -> 1 + log (Int64.div n 2L)\nin\n\nlet nbTests = r_int () in\nfor iTest = 1 to nbTests do\n let nbNombres = r_int () in\n let diff = max_diff (r_long ()) (nbNombres - 1) in\n print_int (log diff);\n print_newline ()\ndone;"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec topbit d = if d lsr 1 = 0 then 0 else 1 + topbit (d lsr 1)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n let rec loop i mb = if i=n-1 then mb else (\n if a.(i) <= a.(i+1) then loop (i+1) mb\n else (\n\tlet d = a.(i) - a.(i+1) in\n\ta.(i+1) <- a.(i);\n\tlet mb = max mb (1 + topbit d) in\n\tloop (i+1) mb\n )\n )\n in\n printf \"%d\\n\" (if n = 1 then 0 else loop 0 0)\n done\n"}], "negative_code": [{"source_code": "let r_int () = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet rec max_diff maxi = function\n| 0 -> 0\n| nbNombres -> \n let nombre = r_int () in\n let nouvMax = max nombre maxi in\n max (maxi - nombre) (max_diff nouvMax (nbNombres - 1))\nin\n\nlet rec log = function\n| 0 -> 0\n| n -> 1 + log (n / 2)\nin\n\nlet nbTests = r_int () in\nfor iTest = 1 to nbTests do\n let nbNombres = r_int () in\n let diff = max_diff (r_int ()) (nbNombres - 1) in\n print_int (log diff);\n print_newline ()\ndone;"}], "src_uid": "bfc2e7de37db4a0a74cdd55f2124424a"} {"nl": {"description": "Consider a tunnel on a one-way road. During a particular day, $$$n$$$ cars numbered from $$$1$$$ to $$$n$$$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.Traffic regulations prohibit overtaking inside the tunnel. If car $$$i$$$ overtakes any other car $$$j$$$ inside the tunnel, car $$$i$$$ must be fined. However, each car can be fined at most once.Formally, let's say that car $$$i$$$ definitely overtook car $$$j$$$ if car $$$i$$$ entered the tunnel later than car $$$j$$$ and exited the tunnel earlier than car $$$j$$$. Then, car $$$i$$$ must be fined if and only if it definitely overtook at least one other car.Find the number of cars that must be fined. ", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 10^5$$$), denoting the number of cars. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le n$$$), denoting the ids of cars in order of entering the tunnel. All $$$a_i$$$ are pairwise distinct. The third line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le n$$$), denoting the ids of cars in order of exiting the tunnel. All $$$b_i$$$ are pairwise distinct.", "output_spec": "Output the number of cars to be fined.", "sample_inputs": ["5\n3 5 2 1 4\n4 3 2 5 1", "7\n5 2 3 6 7 1 4\n2 3 6 7 1 4 5", "2\n1 2\n1 2"], "sample_outputs": ["2", "6", "0"], "notes": "NoteThe first example is depicted below:Car $$$2$$$ definitely overtook car $$$5$$$, while car $$$4$$$ definitely overtook cars $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. Cars $$$2$$$ and $$$4$$$ must be fined.In the second example car $$$5$$$ was definitely overtaken by all other cars.In the third example no car must be fined."}, "positive_code": [{"source_code": "let n = read_int() in\nlet mp = Array.make (n+1) 0 in\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x) in\nlet rec read_mp i = \n if (i > n) then () else \n begin\n mp.(scan_int()) <- i;\n read_mp (i+1)\n end\nin\nlet () = read_mp 1 in\nlet rec read_int_list n cur = match n with\n | 0 -> cur\n | n -> let x = scan_int() in read_int_list (n-1) (x::cur)\nin\nlet a = read_int_list n [] in\nlet rec count_bad b mn total = match b with\n | [] -> total\n | x::xs -> begin\n let x = mp.(x) in \n count_bad xs (if x < mn then x else mn) (if x > mn then (total+1) else total)\n end\nin Printf.printf \"%d\\n\" (count_bad a (n+1) 0)\n\n"}], "negative_code": [{"source_code": "let n = read_int() in\nlet mp = Array.make (n+1) 0 in\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x) in\nlet rec read_mp i = \n if (i > n) then () else \n begin\n (mp.(i) <- scan_int());\n read_mp (i+1)\n end\nin\nlet () = read_mp 1 in\nlet rec read_int_list n cur = match n with\n | 0 -> cur\n | n -> let x = scan_int() in read_int_list (n-1) (x::cur)\nin\nlet a = read_int_list n [] in\nlet rec count_bad b mn total = match b with\n | [] -> total\n | x::xs ->\n let x = mp.(x) in \n count_bad xs (if x < mn then x else mn) (if x > mn then (total+1) else total)\nin Printf.printf \"%d\\n\" (count_bad a (n+1) 0)\n\n"}], "src_uid": "f5178609cc7782edd40bc50b8797522e"} {"nl": {"description": "You are given an array a with n elements. Each element of a is either 0 or 1.Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u20093\u00b7105,\u20090\u2009\u2264\u2009k\u2009\u2264\u2009n) \u2014 the number of elements in a and the parameter k. The second line contains n integers ai (0\u2009\u2264\u2009ai\u2009\u2264\u20091) \u2014 the elements of a.", "output_spec": "On the first line print a non-negative integer z \u2014 the maximal value of f(a) after no more than k changes of zeroes to ones. On the second line print n integers aj \u2014 the elements of the array a after the changes. If there are multiple answers, you can print any one of them.", "sample_inputs": ["7 1\n1 0 0 1 1 0 1", "10 2\n1 0 0 1 0 1 0 1 0 1"], "sample_outputs": ["4\n1 0 0 1 1 1 1", "5\n1 0 0 1 1 1 1 1 0 1"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let l = ref 0 in\n let z = ref 0 in\n let b = ref 0 in\n let bl = ref 0 in\n let br = ref 0 in\n for r = 0 to n - 1 do\n if a.(r) = 0 then (\n\tincr z;\n );\n while !l <= r && !z > k do\n\tif a.(!l) = 0\n\tthen decr z;\n\tincr l;\n done;\n if r - !l + 1 >= !b then (\n\tb := r - !l + 1;\n\tbl := !l;\n\tbr := r;\n );\n done;\n Printf.printf \"%d\\n\" !b;\n for i = 0 to n - 1 do\n let x =\n\tif !bl <= i && i <= !br\n\tthen 1\n\telse a.(i)\n in\n\tPrintf.printf \"%d \" x\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "ec9b03577868d8999bcc54dfc1aae056"} {"nl": {"description": "Ujan decided to make a new wooden roof for the house. He has $$$n$$$ rectangular planks numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th plank has size $$$a_i \\times 1$$$ (that is, the width is $$$1$$$ and the height is $$$a_i$$$).Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.For example, if Ujan had planks with lengths $$$4$$$, $$$3$$$, $$$1$$$, $$$4$$$ and $$$5$$$, he could choose planks with lengths $$$4$$$, $$$3$$$ and $$$5$$$. Then he can cut out a $$$3 \\times 3$$$ square, which is the maximum possible. Note that this is not the only way he can obtain a $$$3 \\times 3$$$ square. What is the maximum side length of the square Ujan can get?", "input_spec": "The first line of input contains a single integer $$$k$$$ ($$$1 \\leq k \\leq 10$$$), the number of test cases in the input. For each test case, the first line contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 1\\,000$$$), the number of planks Ujan has in store. The next line contains $$$n$$$ integers $$$a_1, \\ldots, a_n$$$ ($$$1 \\leq a_i \\leq n$$$), the lengths of the planks.", "output_spec": "For each of the test cases, output a single integer, the maximum possible side length of the square.", "sample_inputs": ["4\n5\n4 3 1 4 5\n4\n4 4 4 4\n3\n1 1 1\n5\n5 5 1 1 5"], "sample_outputs": ["3\n4\n1\n3"], "notes": "NoteThe first sample corresponds to the example in the statement.In the second sample, gluing all $$$4$$$ planks will result in a $$$4 \\times 4$$$ square.In the third sample, the maximum possible square is $$$1 \\times 1$$$ and can be taken simply as any of the planks."}, "positive_code": [{"source_code": "open Printf\n\nlet can_square n l =\n (List.fold_left (fun a x -> if x > n then a+1 else a) 0 l) > n\n\nlet split_on_char char str =\n let re = Str.regexp char in\n Str.split re str\n\nlet solve l =\n let rec solve' n l =\n if can_square n l then solve' (n+1) l else n\n in\n solve' 0 l\n \nlet rec parse_problems () =\n let _ = input_line stdin in\n let sticks = input_line stdin in\n let problem = List.map int_of_string (split_on_char \" \" sticks) in\n printf \"%d\\n\" (solve problem);\n parse_problems ()\n\nlet () =\n let _ = input_line stdin in\n try parse_problems ()\n with End_of_file -> ()\n"}], "negative_code": [], "src_uid": "09236a3faa7fce573a4e5e758287040f"} {"nl": {"description": "You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: the Power Gem of purple color, the Time Gem of green color, the Space Gem of blue color, the Soul Gem of orange color, the Reality Gem of red color, the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.", "input_spec": "In the first line of input there is one integer $$$n$$$ ($$$0 \\le n \\le 6$$$)\u00a0\u2014 the number of Gems in Infinity Gauntlet. In next $$$n$$$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.", "output_spec": "In the first line output one integer $$$m$$$ ($$$0 \\le m \\le 6$$$)\u00a0\u2014 the number of absent Gems. Then in $$$m$$$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.", "sample_inputs": ["4\nred\npurple\nyellow\norange", "0"], "sample_outputs": ["2\nSpace\nTime", "6\nTime\nMind\nSoul\nPower\nReality\nSpace"], "notes": "NoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six."}, "positive_code": [{"source_code": "\nmodule StringSet = Set.Make(String)\n\nmodule StringMap = Map.Make(String)\n\nlet all_colors = (StringSet.of_list [\n \"purple\"; \"green\"; \"blue\"; \"orange\"; \"red\"; \"yellow\"\n ])\n\nlet gem_of_color = ref StringMap.empty\n \nlet () =\n List.iter\n (fun (k, v) -> gem_of_color := StringMap.add k v !gem_of_color)\n [\n (\"purple\", \"Power\");\n (\"green\", \"Time\");\n (\"blue\", \"Space\");\n (\"orange\", \"Soul\");\n (\"red\", \"Reality\");\n (\"yellow\", \"Mind\");\n ];\n let m = Scanf.scanf \"%d\" (fun i -> i) in\n let colors = ref all_colors in\n for i = 1 to m do\n let s = Scanf.scanf \" %s\" (fun i -> i) in\n colors := StringSet.remove s !colors\n done;\n Printf.printf \"%d\\n\" (StringSet.cardinal !colors);\n StringSet.iter (fun s ->\n Printf.printf \"%s\\n\" (StringMap.find s !gem_of_color)) !colors\n"}, {"source_code": "let gems =\n [(\"purple\", \"Power\");\n (\"green\", \"Time\");\n (\"blue\", \"Space\");\n (\"orange\", \"Soul\");\n (\"red\", \"Reality\");\n (\"yellow\", \"Mind\")]\n\nlet () =\n let n = int_of_string (input_line stdin) in\n let pr = ref [] in\n for i = 0 to n - 1 do\n pr := (input_line stdin) :: !pr\n done;\n let present = !pr in\n let p (gem_colour, gem_name) = not (List.mem gem_colour present) in\n let f (gem_colour, gem_name) = gem_name in\n let toprint = List.map f (List.filter p gems) in\n print_endline (string_of_int (List.length toprint));\n ignore (List.map print_endline toprint)"}], "negative_code": [], "src_uid": "7eff98fbcf4e4a3284e2d2f98351fe4a"} {"nl": {"description": "Consider a simplified penalty phase at the end of a football match.A penalty phase consists of at most $$$10$$$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (note that it goes against the usual football rules). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the $$$7$$$-th kick the first team has scored $$$1$$$ goal, and the second team has scored $$$3$$$ goals, the penalty phase ends \u2014 the first team cannot reach $$$3$$$ goals.You know which player will be taking each kick, so you have your predictions for each of the $$$10$$$ kicks. These predictions are represented by a string $$$s$$$ consisting of $$$10$$$ characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way: if $$$s_i$$$ is 1, then the $$$i$$$-th kick will definitely score a goal; if $$$s_i$$$ is 0, then the $$$i$$$-th kick definitely won't score a goal; if $$$s_i$$$ is ?, then the $$$i$$$-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that the referee doesn't take into account any predictions when deciding to stop the penalty phase \u2014 you may know that some kick will/won't be scored, but the referee doesn't.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1\\,000$$$) \u2014 the number of test cases. Each test case is represented by one line containing the string $$$s$$$, consisting of exactly $$$10$$$ characters. Each character is either 1, 0, or ?.", "output_spec": "For each test case, print one integer \u2014 the minimum possible number of kicks in the penalty phase.", "sample_inputs": ["4\n1?0???1001\n1111111111\n??????????\n0100000000"], "sample_outputs": ["7\n10\n6\n9"], "notes": "NoteConsider the example test:In the first test case, consider the situation when the $$$1$$$-st, $$$5$$$-th and $$$7$$$-th kicks score goals, and kicks $$$2$$$, $$$3$$$, $$$4$$$ and $$$6$$$ are unsuccessful. Then the current number of goals for the first team is $$$3$$$, for the second team is $$$0$$$, and the referee sees that the second team can score at most $$$2$$$ goals in the remaining kicks. So the penalty phase can be stopped after the $$$7$$$-th kick.In the second test case, the penalty phase won't be stopped until all $$$10$$$ kicks are finished.In the third test case, if the first team doesn't score any of its three first kicks and the second team scores all of its three first kicks, then after the $$$6$$$-th kick, the first team has scored $$$0$$$ goals and the second team has scored $$$3$$$ goals, and the referee sees that the first team can score at most $$$2$$$ goals in the remaining kicks. So, the penalty phase can be stopped after the $$$6$$$-th kick.In the fourth test case, even though you can predict the whole penalty phase, the referee understands that the phase should be ended only after the $$$9$$$-th kick."}, "positive_code": [{"source_code": "(* Codeforces 1553 C Penalty train *)\r\n \r\n(* you can use either gr or rdln but not both *)\r\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\r\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\r\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet rdln() = input_line stdin;;\r\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\r\nlet debug = false;;\r\n \r\n(* reading reversed list *)\r\nlet rec readlist n acc = match n with\r\n\t| 0 -> acc\r\n\t| _ -> readlist (n -1) (gr() :: acc);;\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\r\n\r\n(* end my library. below concrete program *) \r\n\r\ntype tside = First | Second;;\r\n\r\nlet other side = match side with\r\n\t| First -> Second\r\n\t| Second -> First;;\r\n\r\nlet sideName side = match side with\r\n\t| First -> \"First\"\r\n\t| Second -> \"Second\";;\r\n\r\nlet won step nfirst nsecond = \r\n\tlet canF = (10 - step) / 2 in\r\n\tlet canS = (10 - step + 1) /2 in\r\n\tlet wonF = nfirst > (nsecond + canS) in\r\n\tlet wonS = nsecond > (nfirst + canF) in\r\n\twonF || wonS;;\r\n\r\nlet rec game s side forFirst step nfirst nsecond = \r\n\tif step==10 then step\r\n\telse \r\n\t\tlet _ = if debug then Printf.printf \"game %s %s %b %d %d %d\\n\" \r\n\t\t\t\t\t\ts (sideName side) forFirst step nfirst nsecond in \r\n\t\tlet nside = other side in\r\n\t\tlet nstep = step+1 in\r\n\t\tlet ch = s.[step-1] in\r\n\t\tlet nch = if (ch != '?') then ch\r\n\t\t\t\telse if (((side==First) && forFirst) || (side==Second && (not forFirst)))\r\n\t\t\t\t\tthen\t'1'\r\n\t\t\t\t\telse '0' in\r\n\t\tlet ich = if nch == '1' then 1 else 0 in\r\n\t\tlet _ = if debug then \r\n\t\t\t\tPrintf.printf \"ch,nch,ich %c %c %d\\n\" ch nch ich in\r\n\t\tlet nnfirst = if side==First then nfirst+ich else nfirst in\r\n\t\tlet nnsecond = if side==Second then nsecond+ich else nsecond in\r\n\t\tif won step nnfirst nnsecond \r\n\t\t\tthen\r\n\t\t\t\tlet _ = if debug then Printf.printf \"won step,nfirst,nsecond = %d %d %d\\n\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstep nnfirst nnsecond in\r\n\t\t\t\tstep \r\n\t\telse \r\n\t\t\tgame s nside forFirst nstep nnfirst nnsecond;;\r\n\r\nlet do_one () = \r\n let s = rdln() in\r\n let gameF = game s First true 1 0 0 in\r\n\t\tlet gameS = game s First false 1 0 0 in\r\n\t\tlet nwin = if gameF < gameS then gameF else gameS in\r\n Printf.printf \"%d\\n\" nwin;;\r\n \r\nlet do_all t = \r\n for i = 1 to t do\r\n do_one ()\r\n done;;\r\n \r\nlet main() =\r\n\tlet st = rdln () in\r\n\tlet t = int_of_string st in\r\n\tdo_all t;;\r\n \r\nmain();;"}], "negative_code": [{"source_code": "(* Codeforces 1553 C Penalty train *)\r\n \r\n(* you can use either gr or rdln but not both *)\r\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\r\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\r\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet rdln() = input_line stdin;;\r\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\r\nlet debug = false;;\r\n \r\n(* reading reversed list *)\r\nlet rec readlist n acc = match n with\r\n\t| 0 -> acc\r\n\t| _ -> readlist (n -1) (gr() :: acc);;\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\r\n\r\n(* end my library. below concrete program *) \r\n\r\ntype tside = First | Second;;\r\n\r\nlet other side = match side with\r\n\t| First -> Second\r\n\t| Second -> First;;\r\n\r\nlet sideName side = match side with\r\n\t| First -> \"First\"\r\n\t| Second -> \"Second\";;\r\n\r\nlet won step nfirst nsecond = \r\n\tlet canF = (10 - step) / 2 in\r\n\tlet canS = (10 - step + 1) /2 in\r\n\tlet wonF = nfirst > (nsecond + canS) in\r\n\tlet wonS = nsecond > (nfirst + canF) in\r\n\twonF || wonS;;\r\n\r\nlet rec game s side forFirst step nfirst nsecond = \r\n\tif step==10 then step\r\n\telse if won step nfirst nsecond then step \r\n\telse \r\n\t\t(* let _ = Printf.printf \"game %s %s %b %d %d %d\\n\" \r\n\t\t\t\t\t\ts (sideName side) forFirst step nfirst nsecond in *)\r\n\t\tlet nside = other side in\r\n\t\tlet nstep = step+1 in\r\n\t\tlet ch = s.[step-1] in\r\n\t\tlet nch = if (ch != '?') then ch\r\n\t\t\t\telse if (((side==First) && forFirst) || (side==Second && (not forFirst)))\r\n\t\t\t\t\tthen\t'1'\r\n\t\t\t\t\telse '0' in\r\n\t\tlet ich = if nch == '1' then 1 else 0 in\r\n\t\t(*let _ = Printf.printf \"ch,nch,ich %c %c %d\\n\" ch nch ich in*)\r\n\t\tlet nnfirst = if side==First then nfirst+ich else nfirst in\r\n\t\tlet nnsecond = if side==Second then nsecond+ich else nsecond in\r\n\t\tgame s nside forFirst nstep nnfirst nnsecond;;\r\n\r\nlet do_one () = \r\n let s = rdln() in\r\n let gameF = game s First true 1 0 0 in\r\n\t\tlet gameS = game s First false 1 0 0 in\r\n\t\tlet nwin = if gameF < gameS then gameF else gameS in\r\n Printf.printf \"%d\\n\" nwin;;\r\n \r\nlet do_all t = \r\n for i = 1 to t do\r\n do_one ()\r\n done;;\r\n \r\nlet main() =\r\n\tlet st = rdln () in\r\n\tlet t = int_of_string st in\r\n\tdo_all t;;\r\n \r\nmain();;"}], "src_uid": "ba1aa2483f88164c1f281eebaab2cfbd"} {"nl": {"description": "Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar. So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become and height of Abol will become where x1,\u2009y1,\u2009x2 and y2 are some integer numbers and denotes the remainder of a modulo b.Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.Mike has asked you for your help. Calculate the minimum time or say it will never happen.", "input_spec": "The first line of input contains integer m (2\u2009\u2264\u2009m\u2009\u2264\u2009106). The second line of input contains integers h1 and a1 (0\u2009\u2264\u2009h1,\u2009a1\u2009<\u2009m). The third line of input contains integers x1 and y1 (0\u2009\u2264\u2009x1,\u2009y1\u2009<\u2009m). The fourth line of input contains integers h2 and a2 (0\u2009\u2264\u2009h2,\u2009a2\u2009<\u2009m). The fifth line of input contains integers x2 and y2 (0\u2009\u2264\u2009x2,\u2009y2\u2009<\u2009m). It is guaranteed that h1\u2009\u2260\u2009a1 and h2\u2009\u2260\u2009a2.", "output_spec": "Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.", "sample_inputs": ["5\n4 2\n1 1\n0 1\n2 3", "1023\n1 2\n1 0\n1 2\n1 1"], "sample_outputs": ["3", "-1"], "notes": "NoteIn the first sample, heights sequences are following:Xaniar: Abol: "}, "positive_code": [{"source_code": "module I = Int64\n\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet cyclize m h a x y =\n let lim = 1000*1000 in\n let x = I.of_int x in\n let y = I.of_int y in\n let m = I.of_int m in\n let adv h = I.to_int (I.rem (I.add (I.mul x (I.of_int h)) (y)) m) in\n let rec search i h =\n if i = lim then raise Not_found\n else\n if h = a\n then (i, search2 1 (adv h))\n else search (i+1) (adv h)\n and search2 i h =\n if i = lim then 0\n else\n if h = a\n then i\n else (search2 (i+1) (adv h))\n in\n search 0 h\n\n(* Timize is probably wrong, but nobody will ever observe this *)\nlet timize t1 p1 t2 p2 =\n let lim = 1000 * 1000 in\n let t1 = I.of_int t1 in\n let t2 = I.of_int t2 in\n let p1 = I.of_int p1 in\n let p2 = I.of_int p2 in\n (* Advance one and another until meet or limit *)\n let rec search i j t1 t2 =\n if i > lim || j > lim then raise Not_found\n else\n if t1 = t2 then t2\n else if t1 > t2 then (if p2 = I.zero then raise Not_found; search (i+1) j t1 (I.add t2 p2))\n else (if p1 = I.zero then raise Not_found; search i (j+1) (I.add t1 p1) t2)\n in\n search 0 0 t1 t2\n\nlet _ =\n let m = read_int () in\n let h1 = read_int () in\n let a1 = read_int () in\n let x1 = read_int () in\n let y1 = read_int () in\n let h2 = read_int () in\n let a2 = read_int () in\n let x2 = read_int () in\n let y2 = read_int () in\n try\n let (t1,p1) = cyclize m h1 a1 x1 y1 in\n let (t2,p2) = cyclize m h2 a2 x2 y2 in\n(* Printf.printf \"Stopped at (%d,%d) and (%d,%d)\\n\" t1 p1 t2 p2; *)\n Printf.printf \"%Ld\\n\" (timize t1 p1 t2 p2)\n with\n Not_found -> Printf.printf \"-1\\n\"\n"}], "negative_code": [{"source_code": "module I = Int64\n\nlet read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet cyclize m h a x y =\n let lim = 1000*1000 in\n let x = I.of_int x in\n let y = I.of_int y in\n let m = I.of_int m in\n let adv h = I.to_int (I.rem (I.add (I.mul x (I.of_int h)) (y)) m) in\n let rec search i h =\n if i = lim then raise Not_found\n else\n if h = a\n then (i, search2 1 (adv h))\n else search (i+1) (adv h)\n and search2 i h =\n if i = lim then 0\n else\n if h = a\n then i\n else (search2 (i+1) (adv h))\n in\n search 0 h\n\n(* Timize is probably wrong, but nobody will ever observe this *)\nlet timize t1 p1 t2 p2 =\n let lim = 1000 * 1000 in\n let t1 = I.of_int t1 in\n let t2 = I.of_int t2 in\n let p1 = I.of_int p1 in\n let p2 = I.of_int p2 in\n (* Advance one and another until meet or limit *)\n let rec search i j t1 t2 =\n if i > lim || j > lim then raise Not_found\n else\n if t1 = t2 then t2\n else if t1 > t2 then (if p2 = I.zero then raise Not_found; search (i+1) j t1 (I.add t2 p2))\n else (if p1 = I.zero then raise Not_found; search i (j+1) (I.add t1 p1) t2)\n in\n search 0 0 t1 t2\n\nlet _ =\n let m = read_int () in\n let h1 = read_int () in\n let a1 = read_int () in\n let x1 = read_int () in\n let y1 = read_int () in\n let h2 = read_int () in\n let a2 = read_int () in\n let x2 = read_int () in\n let y2 = read_int () in\n try\n let (t1,p1) = cyclize m h1 a1 x1 y1 in\n let (t2,p2) = cyclize m h2 a2 x2 y2 in\n Printf.printf \"Stopped at (%d,%d) and (%d,%d)\\n\" t1 p1 t2 p2;\n Printf.printf \"%Ld\\n\" (timize t1 p1 t2 p2)\n with\n Not_found -> Printf.printf \"-1\\n\"\n"}], "src_uid": "7225266f663699ff7e16b726cadfe9ee"} {"nl": {"description": "Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $$$(x_1,y_1)$$$ to the point $$$(x_2,y_2)$$$.He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $$$1$$$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $$$1$$$ unit. For example, if the box is at the point $$$(1,2)$$$ and Wabbit is standing at the point $$$(2,2)$$$, he can pull the box right by $$$1$$$ unit, with the box ending up at the point $$$(2,2)$$$ and Wabbit ending at the point $$$(3,2)$$$.Also, Wabbit can move $$$1$$$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $$$1$$$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes $$$1$$$ second to travel $$$1$$$ unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$. Note that the point where Wabbit ends up at does not matter.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 1000)$$$: the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains four space-separated integers $$$x_1, y_1, x_2, y_2$$$ $$$(1 \\leq x_1, y_1, x_2, y_2 \\leq 10^9)$$$, describing the next test case.", "output_spec": "For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$.", "sample_inputs": ["2\n1 2 2 2\n1 1 2 2"], "sample_outputs": ["1\n4"], "notes": "NoteIn the first test case, the starting and the ending points of the box are $$$(1,2)$$$ and $$$(2,2)$$$ respectively. This is the same as the picture in the statement. Wabbit needs only $$$1$$$ second to move as shown in the picture in the statement.In the second test case, Wabbit can start at the point $$$(2,1)$$$. He pulls the box to $$$(2,1)$$$ while moving to $$$(3,1)$$$. He then moves to $$$(3,2)$$$ and then to $$$(2,2)$$$ without pulling the box. Then, he pulls the box to $$$(2,2)$$$ while moving to $$$(2,3)$$$. It takes $$$4$$$ seconds."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n \nlet solve_test() =\n let xs = Int32.of_int( read_int() ) and \n ys = Int32.of_int( read_int() ) and \n xf = Int32.of_int( read_int() ) and \n yf = Int32.of_int( read_int() ) in\n let d = Int32.add (Int32.abs (Int32.sub xs xf)) (Int32.abs (Int32.sub ys yf)) in\n let ans = if (xs = xf) || (ys = yf) then d else Int32.add d (Int32.of_int(2)) in\n print_string (Int32.to_string ans);\n print_newline()\n \nlet t = read_int();;\n \nlet () =\n for i = 1 to t do\n solve_test ()\n done"}], "negative_code": [{"source_code": "\nlet read_int () = Scanf.scanf \" %d \" (fun x -> x) ;;\n\nlet myabs x =\n if x >= 0 then x else -x ;;\n\nlet solve_test() =\n let xs = read_int() and ys = read_int() and xf = read_int() and yf = read_int() in\n let d = abs (xs - xf) + abs (ys - yf) in\n let ans = if xs == xf || ys == yf then d else d + 2 in\n Printf.printf \"%d\\n\" ans\n\nlet t = read_int();;\n\nlet () =\n for i = 1 to t do\n solve_test ()\n done"}, {"source_code": "\nlet read_int () = Scanf.scanf \" %d \" (fun x -> x) ;;\n\nlet myabs x =\n if x >= 0 then x else -x ;;\n\nlet solve_test() =\n let xs = read_int() and ys = read_int() and xf = read_int() and yf = read_int() in\n let d = abs (xs - xf) + abs (ys - yf) in\n let ans = if xs == yf || ys == yf then d else d + 2 in\n Printf.printf \"%d\\n\" ans ;;\n\nlet t = read_int();;\n\nlet () =\n for i = 1 to t do\n solve_test ()\n done"}], "src_uid": "6a333044e2ed8f9f4fa44bc16b994418"} {"nl": {"description": "You are fighting with Zmei Gorynich \u2014 a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads! Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2013 the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \\le n \\le 100$$$, $$$1 \\le x \\le 10^9$$$) \u2014 the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \\le d_i, h_i \\le 10^9$$$) \u2014 the description of the $$$i$$$-th blow.", "output_spec": "For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich. If Zmei Gorynuch cannot be defeated print $$$-1$$$.", "sample_inputs": ["3\n3 10\n6 3\n8 2\n1 4\n4 10\n4 1\n3 2\n2 6\n1 100\n2 15\n10 11\n14 100"], "sample_outputs": ["2\n3\n-1"], "notes": "NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?"}, "positive_code": [{"source_code": "let pow a n =\n let rec loop a n acc =\n if n = 0 then acc\n else if n mod 2 = 0 then loop (a * a) (n / 2) acc\n else loop (a * a) (n / 2) (acc * a) in\n loop a n 1\n\nlet ceil_div x y = if x > 0\n then (x + y - 1) / y\n else 0\n\nlet repeat f =\n let rec loop acc = function\n | 0 -> List.rev acc\n | n -> loop (f () :: acc) (n - 1) in\n loop []\n\nlet max_list key default ls =\n List.fold_left (fun x y -> if key x < key y then y else x) default ls\n\nlet solve x dhs =\n let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in\n let last = List.fold_left (fun x (d, h) -> max x d) (-1) dhs in\n if last < x && d - h <= 0\n then -1\n else 1 + ceil_div (x - last) (d - h)\n\n\nlet () =\n let t = Scanf.scanf \"%d\\n\" (fun t -> t) in\n for tc = 1 to t do\n let n, x = Scanf.scanf \"%d %d\\n\" (fun n x -> (n, x)) in\n let dhs = repeat (fun () -> Scanf.scanf \"%d %d\\n\" (fun d h -> (d, h))) n in\n Printf.printf \"%d\\n\" (solve x dhs);\n flush stdout\n done\n"}], "negative_code": [{"source_code": "let pow a n =\n let rec loop a n acc =\n if n = 0 then acc\n else if n mod 2 = 0 then loop (a * a) (n / 2) acc\n else loop (a * a) (n / 2) (acc * a) in\n loop a n 1\n\nlet ceil_div x y = (x + y - 1) / y\n\nlet repeat f =\n let rec loop acc = function\n | 0 -> List.rev acc\n | n -> loop (f () :: acc) (n - 1) in\n loop []\n\nlet max_list key default ls =\n List.fold_left (fun x y -> if key x < key y then y else x) default ls\n\nlet solve x dhs =\n let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in\n let last = List.fold_left (fun x (d, h) -> max x d) (-1) dhs in\n if d < x && d - h <= 0 then\n -1\n else\n 1 + ceil_div (x - last) (d - h)\n\n\nlet () =\n let t = Scanf.scanf \"%d\\n\" (fun t -> t) in\n for tc = 1 to t do\n let n, x = Scanf.scanf \"%d %d\\n\" (fun n x -> (n, x)) in\n let dhs = repeat (fun () -> Scanf.scanf \"%d %d\\n\" (fun d h -> (d, h))) n in\n Printf.printf \"%d\\n\" (solve x dhs);\n flush stdout\n done\n"}, {"source_code": "let pow a n =\n let rec loop a n acc =\n if n = 0 then acc\n else if n mod 2 = 0 then loop (a * a) (n / 2) acc\n else loop (a * a) (n / 2) (acc * a) in\n loop a n 1\n\nlet ceil_div x y = (x + y - 1) / y\n\nlet repeat f =\n let rec loop acc = function\n | 0 -> List.rev acc\n | n -> loop (f () :: acc) (n - 1) in\n loop []\n\nlet max_list key default ls =\n List.fold_left (fun x y -> if key x < key y then y else x) default ls\n\nlet solve x dhs =\n let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in\n if d - h <= 0 then\n -1\n else\n 1 + ceil_div (x - d) (d - h)\n\n\nlet () =\n let t = Scanf.scanf \"%d\\n\" (fun t -> t) in\n for tc = 1 to t do\n let n, x = Scanf.scanf \"%d %d\\n\" (fun n x -> (n, x)) in\n let dhs = repeat (fun () -> Scanf.scanf \"%d %d\\n\" (fun d h -> (d, h))) n in\n Printf.printf \"%d\\n\" (solve x dhs);\n flush stdout\n done\n"}, {"source_code": "let pow a n =\n let rec loop a n acc =\n if n = 0 then acc\n else if n mod 2 = 0 then loop (a * a) (n / 2) acc\n else loop (a * a) (n / 2) (acc * a) in\n loop a n 1\n\nlet ceil_div x y = (x + y - 1) / y\n\nlet repeat f =\n let rec loop acc = function\n | 0 -> List.rev acc\n | n -> loop (f () :: acc) (n - 1) in\n loop []\n\nlet max_list key default ls =\n List.fold_left (fun x y -> if key x < key y then y else x) default ls\n\nlet solve x dhs =\n let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in\n let last = List.fold_left (fun x (d, h) -> max x d) (-1) dhs in\n if d - h <= 0 then\n -1\n else\n 1 + ceil_div (x - last) (d - h)\n\n\nlet () =\n let t = Scanf.scanf \"%d\\n\" (fun t -> t) in\n for tc = 1 to t do\n let n, x = Scanf.scanf \"%d %d\\n\" (fun n x -> (n, x)) in\n let dhs = repeat (fun () -> Scanf.scanf \"%d %d\\n\" (fun d h -> (d, h))) n in\n Printf.printf \"%d\\n\" (solve x dhs);\n flush stdout\n done\n"}, {"source_code": "let pow a n =\n let rec loop a n acc =\n if n = 0 then acc\n else if n mod 2 = 0 then loop (a * a) (n / 2) acc\n else loop (a * a) (n / 2) (acc * a) in\n loop a n 1\n\nlet ceil_div x y = (x + y - 1) / y\n\nlet repeat f =\n let rec loop acc = function\n | 0 -> List.rev acc\n | n -> loop (f () :: acc) (n - 1) in\n loop []\n\nlet max_list key default ls =\n List.fold_left (fun x y -> if key x < key y then y else x) default ls\n\nlet solve x dhs =\n let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in\n let last = List.fold_left (fun x (d, h) -> max x d) (-1) dhs in\n if last < x && d - h <= 0 then\n -1\n else\n 1 + ceil_div (x - last) (d - h)\n\n\nlet () =\n let t = Scanf.scanf \"%d\\n\" (fun t -> t) in\n for tc = 1 to t do\n let n, x = Scanf.scanf \"%d %d\\n\" (fun n x -> (n, x)) in\n let dhs = repeat (fun () -> Scanf.scanf \"%d %d\\n\" (fun d h -> (d, h))) n in\n Printf.printf \"%d\\n\" (solve x dhs);\n flush stdout\n done\n"}], "src_uid": "36099a612ec5bbec1b95f2941e759c00"} {"nl": {"description": "The determinant of a matrix 2\u2009\u00d7\u20092 is defined as follows:A matrix is called degenerate if its determinant is equal to zero. The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements.You are given a matrix . Consider any degenerate matrix B such that norm ||A\u2009-\u2009B|| is minimum possible. Determine ||A\u2009-\u2009B||.", "input_spec": "The first line contains two integers a and b (|a|,\u2009|b|\u2009\u2264\u2009109), the elements of the first row of matrix A. The second line contains two integers c and d (|c|,\u2009|d|\u2009\u2264\u2009109) the elements of the second row of matrix A.", "output_spec": "Output a single real number, the minimum possible value of ||A\u2009-\u2009B||. Your answer is considered to be correct if its absolute or relative error does not exceed 10\u2009-\u20099.", "sample_inputs": ["1 2\n3 4", "1 0\n0 1"], "sample_outputs": ["0.2000000000", "0.5000000000"], "notes": "NoteIn the first sample matrix B is In the second sample matrix B is "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let a = read_int() in\n let b = read_int() in\n let c = read_int() in\n let d = read_int() in\n\n let det = (long a) ** (long d) -- (long b) ** (long c) in\n if det = 0L then printf \"0.0\\n\" else\n\n let (a,b,c,d) = (float a, float b, float c, float d) in\n let big = (max (max (abs_float a) (abs_float b)) (max (abs_float c) (abs_float d))) in\n let (a,b,c,d) = if (big = 0.0) then (a,b,c,d) else (a/.big, b/.big, c/.big, d/.big) in\n \n let lohi a b e =\n let x1 = (a -. e) *. (b -. e) in\n let x2 = (a +. e) *. (b -. e) in\n let x3 = (a -. e) *. (b +. e) in\n let x4 = (a +. e) *. (b +. e) in\n let hi = max (max x1 x2) (max x3 x4) in\n let lo = min (min x1 x2) (min x3 x4) in\n (lo,hi)\n in\n \n let intervals_intersect (lo1, hi1) (lo2, hi2) =\n if hi1 < lo2 then false\n else if hi2 < lo1 then false\n else true\n in\n \n let test e =\n intervals_intersect (lohi a d e) (lohi b c e)\n in\n \n let rec bsearch x y =\n let m = (x +. y) /. 2.0 in\n if abs_float (x -. y) < (1e-13) *. m then m\n else if test m then bsearch x m else bsearch m y\n in\n \n let answer = bsearch 0.0 1.0 in\n \n printf \"%.10f\\n\" (answer *. big)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let a = float (read_int()) in\n let b = float (read_int()) in\n let c = float (read_int()) in\n let d = float (read_int()) in\n\n let lohi a b e =\n let x1 = (a -. e) *. (b -. e) in\n let x2 = (a +. e) *. (b -. e) in\n let x3 = (a -. e) *. (b +. e) in\n let x4 = (a +. e) *. (b +. e) in\n let hi = max (max x1 x2) (max x3 x4) in\n let lo = min (min x1 x2) (min x3 x4) in\n (lo,hi)\n in\n \n let intervals_intersect (lo1, hi1) (lo2, hi2) =\n if hi1 < lo2 then false\n else if hi2 < lo1 then false\n else true\n in\n \n let test e =\n intervals_intersect (lohi a d e) (lohi b c e)\n in\n \n let rec bsearch x y n =\n let m = (x +. y) /. 2.0 in\n if n=0 then m\n else if test m then bsearch x m (n-1) else bsearch m y (n-1)\n in\n \n printf \"%.10f\\n\" (bsearch 0.0 1e10 200)\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let a = float (read_int()) in\n let b = float (read_int()) in\n let c = float (read_int()) in\n let d = float (read_int()) in\n\n let big = (max (max (abs_float a) (abs_float b)) (max (abs_float c) (abs_float d))) in\n\n let (a,b,c,d) = if (big = 0.0) then (a,b,c,d) else (a/.big, b/.big, c/.big, d/.big) in\n\n let lohi a b e =\n let x1 = (a -. e) *. (b -. e) in\n let x2 = (a +. e) *. (b -. e) in\n let x3 = (a -. e) *. (b +. e) in\n let x4 = (a +. e) *. (b +. e) in\n let hi = max (max x1 x2) (max x3 x4) in\n let lo = min (min x1 x2) (min x3 x4) in\n (lo,hi)\n in\n\n let intervals_intersect (lo1, hi1) (lo2, hi2) =\n if hi1 < lo2 then false\n else if hi2 < lo1 then false\n else true\n in\n \n let test e =\n intervals_intersect (lohi a d e) (lohi b c e)\n in\n\n let rec bsearch x y =\n let m = (x +. y) /. 2.0 in\n if abs_float (x -. y) < 1e-15 then m\n else if test m then bsearch x m else bsearch m y\n in\n\n let answer = bsearch 0.0 1.0 in\n\n printf \"%.9f\\n\" (answer *. big)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () =\n let a = read_int() in\n let b = read_int() in\n let c = read_int() in\n let d = read_int() in\n\n let det = (long a) ** (long d) -- (long b) ** (long c) in\n if det = 0L then printf \"0.0\\n\" else\n\n let (a,b,c,d) = (float a, float b, float c, float d) in\n let big = (max (max (abs_float a) (abs_float b)) (max (abs_float c) (abs_float d))) in\n let (a,b,c,d) = if (big = 0.0) then (a,b,c,d) else (a/.big, b/.big, c/.big, d/.big) in\n \n let lohi a b e =\n let x1 = (a -. e) *. (b -. e) in\n let x2 = (a +. e) *. (b -. e) in\n let x3 = (a -. e) *. (b +. e) in\n let x4 = (a +. e) *. (b +. e) in\n let hi = max (max x1 x2) (max x3 x4) in\n let lo = min (min x1 x2) (min x3 x4) in\n (lo,hi)\n in\n \n let intervals_intersect (lo1, hi1) (lo2, hi2) =\n if hi1 < lo2 then false\n else if hi2 < lo1 then false\n else true\n in\n \n let test e =\n intervals_intersect (lohi a d e) (lohi b c e)\n in\n \n let rec bsearch x y =\n let m = (x +. y) /. 2.0 in\n if abs_float (x -. y) < 1e-13 then m\n else if test m then bsearch x m else bsearch m y\n in\n \n let answer = bsearch 0.0 1.0 in\n \n printf \"%.9f\\n\" (answer *. big)\n"}], "src_uid": "b779946fe86b1a2a4449bc85ff887367"} {"nl": {"description": "Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.", "input_spec": "The first line of the input contains integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100)\u00a0\u2014 the number of buttons and the number of bulbs respectively. Each of the next n lines contains xi (0\u2009\u2264\u2009xi\u2009\u2264\u2009m)\u00a0\u2014 the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1\u2009\u2264\u2009yij\u2009\u2264\u2009m)\u00a0\u2014 the numbers of these bulbs.", "output_spec": "If it's possible to turn on all m bulbs print \"YES\", otherwise print \"NO\".", "sample_inputs": ["3 4\n2 1 4\n3 1 3 1\n1 2", "3 3\n1 1\n1 2\n1 1"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp."}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet rec loop n tab =\n if n >= 0 then\n let x = read n in\n tab.(x) <- true;\n loop (n-1) tab\n else ();;\n\nlet _ = \n let (n, m) = read2 () in\n let tab = Array.make (m+1) false in\n tab.(0) <- true;\n for i=1 to n do\n let k = Scanf.scanf \"%d \" ( fun x -> x ) in\n loop (k-1) tab\n done;\n Printf.printf \"%s\\n\" (Array.fold_left ( fun a x -> if not x then \"NO\" else a ) \"YES\" tab);;\n\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let (n,m) = read_pair () in\n let mark = Array.make m false in\n for i=0 to n-1 do\n let x = read_int () in\n for j=0 to x-1 do\n let y = -1 + read_int() in\n mark.(y) <- true;\n done\n done;\n\n if forall 0 (m-1) (fun i -> mark.(i)) then printf \"YES\\n\" else printf \"NO\\n\"\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet () = \n let (n,m) = read_pair () in\n let mark = Array.make m false in\n for i=0 to n-1 do\n let x = read_int () in\n for j=0 to x-1 do\n let y = -1 + read_int() in\n mark.(y) <- true;\n done\n done;\n\n if forall 0 (n-1) (fun i -> mark.(i)) then printf \"YES\\n\" else printf \"NO\\n\"\n"}], "src_uid": "9438ce92e10e846dd3ab7c61a1a2e3af"} {"nl": {"description": "You are given an integer $$$n$$$. Check if $$$n$$$ has an odd divisor, greater than one (does there exist such a number $$$x$$$ ($$$x > 1$$$) that $$$n$$$ is divisible by $$$x$$$ and $$$x$$$ is odd).For example, if $$$n=6$$$, then there is $$$x=3$$$. If $$$n=4$$$, then such a number does not exist.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$2 \\le n \\le 10^{14}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.", "output_spec": "For each test case, output on a separate line: \"YES\" if $$$n$$$ has an odd divisor, greater than one; \"NO\" otherwise. You can output \"YES\" and \"NO\" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).", "sample_inputs": ["6\n2\n3\n4\n5\n998244353\n1099511627776"], "sample_outputs": ["NO\nYES\nNO\nYES\nYES\nNO"], "notes": null}, "positive_code": [{"source_code": "(** https://codeforces.com/problemset/problem/1475/A *)\n\nlet (+>>) = Int64.shift_right and\n(+&) = Int64.logand\n\nlet odd64 n =\n n +& 1L = 1L\n\nlet has_odd_divisor n =\n let rec helper i =\n\t\tif odd64 i\n\t\tthen (if i > 1L then true else false)\n\t\telse helper (i +>> 1) in\n\thelper n\n \nlet solve_n nb_cases =\n let rec helper i =\n if i > 0\n then (\n let n = read_line () |> Int64.of_string in\n (if has_odd_divisor n then \"YES\" else \"NO\")\n |> print_endline;\n helper (i-1)\n ) in\n helper nb_cases\n \nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}], "negative_code": [], "src_uid": "f4958b4833cafa46fa71357ab1ae41af"} {"nl": {"description": "Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$=\"wowwo\", the following strings are subsequences: \"wowwo\", \"wowo\", \"oo\", \"wow\", \"\", and others, but the following are not subsequences: \"owoo\", \"owwwo\", \"ooo\".The wow factor of a string is the number of its subsequences equal to the word \"wow\". Bob wants to write a string that has a large wow factor. However, the \"w\" key on his keyboard is broken, so he types two \"v\"s instead. Little did he realise that he may have introduced more \"w\"s than he thought. Consider for instance the string \"ww\". Bob would type it as \"vvvv\", but this string actually contains three occurrences of \"w\": \"vvvv\" \"vvvv\" \"vvvv\" For example, the wow factor of the word \"vvvovvv\" equals to four because there are four wows: \"vvvovvv\" \"vvvovvv\" \"vvvovvv\" \"vvvovvv\" Note that the subsequence \"vvvovvv\" does not count towards the wow factor, as the \"v\"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing \"w\" with \"vv\". For example, $$$s$$$ can be equal to \"vov\".", "input_spec": "The input contains a single non-empty string $$$s$$$, consisting only of characters \"v\" and \"o\". The length of $$$s$$$ is at most $$$10^6$$$.", "output_spec": "Output a single integer, the wow factor of $$$s$$$.", "sample_inputs": ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"], "sample_outputs": ["4", "100"], "notes": "NoteThe first example is explained in the legend."}, "positive_code": [{"source_code": "let readString () = Scanf.scanf \" %s\" (fun s -> s)\n\nlet (++) = Int64.add\nlet (--) = Int64.sub\nlet ( ** ) = Int64.mul\nlet (//) = Int64.div\nlet (%%) = Int64.rem\n\nlet solve s =\n let n = String.length s in\n let l = Array.make (n+1) 0L in\n let r = Array.make (n+1) 0L in\n for i=0 to n-1 do\n l.(i+1) <- l.(i) ++ (if i > 0 && String.sub s (i-1) 2 = \"vv\" then 1L else 0L)\n done;\n let i = ref (n-1) in\n while !i >= 0 do\n r.(!i) <- r.(!i+1) ++ (if !i < n-1 && String.sub s !i 2 = \"vv\" then 1L else 0L);\n decr i\n done;\n let sum = ref 0L in\n for i=0 to n-1 do\n if s.[i] = 'o' then sum := !sum ++ l.(i)**r.(i)\n done;\n !sum\n\nlet main () =\n let s = readString () in\n Printf.printf \"%Ld\\n\" (solve s)\n\nlet () = main ()\n"}], "negative_code": [], "src_uid": "6cc6db6f426bb1bce59f23bfcb762b08"} {"nl": {"description": "You are given a grid, consisting of $$$2$$$ rows and $$$n$$$ columns. Each cell of this grid should be colored either black or white.Two cells are considered neighbours if they have a common border and share the same color. Two cells $$$A$$$ and $$$B$$$ belong to the same component if they are neighbours, or if there is a neighbour of $$$A$$$ that belongs to the same component with $$$B$$$.Let's call some bicoloring beautiful if it has exactly $$$k$$$ components.Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $$$998244353$$$.", "input_spec": "The only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 1000$$$, $$$1 \\le k \\le 2n$$$) \u2014 the number of columns in a grid and the number of components required.", "output_spec": "Print a single integer \u2014 the number of beautiful bicolorings modulo $$$998244353$$$.", "sample_inputs": ["3 4", "4 1", "1 2"], "sample_outputs": ["12", "2", "2"], "notes": "NoteOne of possible bicolorings in sample $$$1$$$: "}, "positive_code": [{"source_code": "open Printf open Scanf\n\nlet dp = Array.init 1024 (fun _ ->\n\tArray.init 2048 (fun _ -> \n\t\tArray.init 2 (fun _ ->\n\t\t\tArray.make 2 0L)))\nlet md = 998244353L\nlet hoge p q r s =\n\tlet m q = Int64.rem q md in\n\tp |> m |> Int64.add q |> m |> Int64.add r |> m |> Int64.add s |> m\nlet (@~) a (i,j,k,l) =\n\ta.(i).(j).(k).(l)\nlet (<@~) a (i,j,k,l,v) = a.(i).(j).(k).(l) <- v\nlet (+%) p q =\n\tlet m q = Int64.rem q md in\n\tp |> m |> Int64.add q |> m\nlet rep f t fbod = for i=f to t do fbod i done\nlet () =\n\tlet n,k = scanf \" %d %d\" (fun u v -> u,v) in\n\tdp.(1).(2).(0).(0) <- 1L;\n\tdp.(1).(3).(0).(1) <- 1L;\n\tdp.(1).(3).(1).(0) <- 1L;\n\tdp.(1).(2).(1).(1) <- 1L;\n\t(* for i=2 to n do\n\t\tfor j=2 to i*2+1 do *)\n\trep 2 n (fun i ->\n\t\trep 2 (i*2+1) (fun j ->\n\t\t\tdp<@~(i,j,0,0,(\n\t\t\t\t(dp@~(i-1,j,0,0))\n\t\t\t\t+% (dp@~(i-1,j,0,1))\n\t\t\t\t+% (dp@~(i-1,j,1,0))\n\t\t\t\t+% (dp@~(i-1,j-1,1,1))\n\t\t\t));\n\t\t\tdp<@~(i,j,1,1,(\n\t\t\t\t(dp@~(i-1,j,1,1))\n\t\t\t\t+% (dp@~(i-1,j,0,1))\n\t\t\t\t+% (dp@~(i-1,j,1,0))\n\t\t\t\t+% (dp@~(i-1,j-1,0,0))\n\t\t\t));\n\t\t\tdp<@~(i,j,1,0,(\n\t\t\t\t(dp@~(i-1,j,1,0))\n\t\t\t\t+% (dp@~(i-1,j-1,1,1))\n\t\t\t\t+% (dp@~(i-1,j-1,0,0))\n\t\t\t\t+% (dp@~(i-1,j-2,0,1))\n\t\t\t));\n\t\t\tdp<@~(i,j,0,1,(\n\t\t\t\t(dp@~(i-1,j,0,1))\n\t\t\t\t+% (dp@~(i-1,j-1,1,1))\n\t\t\t\t+% (dp@~(i-1,j-1,0,0))\n\t\t\t\t+% (dp@~(i-1,j-2,1,0))\n\t\t\t));\n\t\t\t(* dp.(i).(j).(0).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(0)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1);\n\t\t\tdp.(i).(j).(1).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(1)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0);\n\t\t\tdp.(i).(j).(1).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(0).(1);\n\t\t\tdp.(i).(j).(0).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(1).(0); *)\n\t\t(* done;\n\tdone; *)\n\t));\n\tprintf \"%Ld\" (\n\t\thoge\n\t\t\tdp.(n).(k+1).(0).(0)\n\t\t\tdp.(n).(k+1).(0).(1)\n\t\t\tdp.(n).(k+1).(1).(0)\n\t\t\tdp.(n).(k+1).(1).(1)\n\t)\n\n"}, {"source_code": "open Printf open Scanf\n\nlet dp = Array.init 1024 (fun _ ->\n\tArray.init 2048 (fun _ -> \n\t\tArray.init 2 (fun _ ->\n\t\t\tArray.make 2 0L)))\nlet md = 998244353L\nlet hoge p q r s =\n\tlet m p q = Int64.rem q p in\n\tp |> m md |> Int64.add q |> m md |> Int64.add r |> m md |> Int64.add s |> m md\nlet () =\n\tlet n,k = scanf \" %d %d\" (fun u v -> u,v) in\n\tdp.(1).(2).(0).(0) <- 1L;\n\tdp.(1).(3).(0).(1) <- 1L;\n\tdp.(1).(3).(1).(0) <- 1L;\n\tdp.(1).(2).(1).(1) <- 1L;\n\tfor i=2 to n do\n\t\tfor j=2 to i*2+1 do\n\t\t\tdp.(i).(j).(0).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(0)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1);\n\t\t\tdp.(i).(j).(1).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(1)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0);\n\t\t\tdp.(i).(j).(1).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(0).(1);\n\t\t\tdp.(i).(j).(0).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(1).(0);\n\t\tdone;\n\tdone;\n\tprintf \"%Ld\" (\n\t\thoge\n\t\t\tdp.(n).(k+1).(0).(0)\n\t\t\tdp.(n).(k+1).(0).(1)\n\t\t\tdp.(n).(k+1).(1).(0)\n\t\t\tdp.(n).(k+1).(1).(1)\n\t)\n\n"}, {"source_code": "open Printf open Scanf\n\nlet dp = Array.init 1024 (fun _ ->\n\tArray.init 2048 (fun _ -> \n\t\tArray.init 2 (fun _ ->\n\t\t\tArray.make 2 0L)))\nlet md = 998244353L\nlet hoge p q r s =\n\tlet m q = Int64.rem q md in\n\tp |> m |> Int64.add q |> m |> Int64.add r |> m |> Int64.add s |> m\nlet (@~) a (i,j,k,l) =\n\ta.(i).(j).(k).(l)\nlet (<@~) a (i,j,k,l,v) = a.(i).(j).(k).(l) <- v\nlet (+%) p q =\n\tlet m q = Int64.rem q md in\n\tp |> m |> Int64.add q |> m\nlet rep f t fbod = for i=f to t do fbod i done\nlet () =\n\tlet n,k = scanf \" %d %d\" (fun u v -> u,v) in\n\tdp.(1).(2).(0).(0) <- 1L;\n\tdp.(1).(3).(0).(1) <- 1L;\n\tdp.(1).(3).(1).(0) <- 1L;\n\tdp.(1).(2).(1).(1) <- 1L;\n\t(* for i=2 to n do\n\t\tfor j=2 to i*2+1 do *)\n\trep 2 n (fun i ->\n\t\trep 2 (i*2+1) (fun j ->\n\t\t\tdp<@~(i,j,0,0,(\n\t\t\t\thoge\n\t\t\t\t\t(dp@~(i-1,j,0,0))\n\t\t\t\t\t(dp@~(i-1,j,0,1))\n\t\t\t\t\t(dp@~(i-1,j,1,0))\n\t\t\t\t\t(dp@~(i-1,j-1,1,1))\n\t\t\t));\n\t\t\tdp<@~(i,j,1,1,(\n\t\t\t\thoge\n\t\t\t\t\t(dp@~(i-1,j,1,1))\n\t\t\t\t\t(dp@~(i-1,j,0,1))\n\t\t\t\t\t(dp@~(i-1,j,1,0))\n\t\t\t\t\t(dp@~(i-1,j-1,0,0))\n\t\t\t));\n\t\t\tdp<@~(i,j,1,0,(\n\t\t\t\thoge\n\t\t\t\t\t(dp@~(i-1,j,1,0))\n\t\t\t\t\t(dp@~(i-1,j-1,1,1))\n\t\t\t\t\t(dp@~(i-1,j-1,0,0))\n\t\t\t\t\t(dp@~(i-1,j-2,0,1))\n\t\t\t));\n\t\t\tdp<@~(i,j,0,1,(\n\t\t\t\thoge\n\t\t\t\t\t(dp@~(i-1,j,0,1))\n\t\t\t\t\t(dp@~(i-1,j-1,1,1))\n\t\t\t\t\t(dp@~(i-1,j-1,0,0))\n\t\t\t\t\t(dp@~(i-1,j-2,1,0))\n\t\t\t));\n\t\t\t(* dp<@~(i,j,0,0,(\n\t\t\t\t(dp@~(i-1,j,0,0))\n\t\t\t\t+% (dp@~(i-1,j,0,1))\n\t\t\t\t+% (dp@~(i-1,j,1,0))\n\t\t\t\t+% (dp@~(i-1,j-1,1,1))\n\t\t\t));\n\t\t\tdp<@~(i,j,1,1,(\n\t\t\t\t(dp@~(i-1,j,1,1))\n\t\t\t\t+% (dp@~(i-1,j,0,1))\n\t\t\t\t+% (dp@~(i-1,j,1,0))\n\t\t\t\t+% (dp@~(i-1,j-1,0,0))\n\t\t\t));\n\t\t\tdp<@~(i,j,1,0,(\n\t\t\t\t(dp@~(i-1,j,1,0))\n\t\t\t\t+% (dp@~(i-1,j-1,1,1))\n\t\t\t\t+% (dp@~(i-1,j-1,0,0))\n\t\t\t\t+% (dp@~(i-1,j-2,0,1))\n\t\t\t));\n\t\t\tdp<@~(i,j,0,1,(\n\t\t\t\t(dp@~(i-1,j,0,1))\n\t\t\t\t+% (dp@~(i-1,j-1,1,1))\n\t\t\t\t+% (dp@~(i-1,j-1,0,0))\n\t\t\t\t+% (dp@~(i-1,j-2,1,0))\n\t\t\t)); *)\n\t\t\t(* dp.(i).(j).(0).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(0)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1);\n\t\t\tdp.(i).(j).(1).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(1)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0);\n\t\t\tdp.(i).(j).(1).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(0).(1);\n\t\t\tdp.(i).(j).(0).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(1).(0); *)\n\t\t(* done;\n\tdone; *)\n\t));\n\tprintf \"%Ld\" (\n\t\thoge\n\t\t\tdp.(n).(k+1).(0).(0)\n\t\t\tdp.(n).(k+1).(0).(1)\n\t\t\tdp.(n).(k+1).(1).(0)\n\t\t\tdp.(n).(k+1).(1).(1)\n\t)\n\n"}, {"source_code": "(* infix abuse harms? *)\n\nopen Printf open Scanf\n\nlet dp = Array.init 1024 (fun _ ->\n\tArray.init 2048 (fun _ -> \n\t\tArray.init 2 (fun _ ->\n\t\t\tArray.make 2 0L)))\nlet md = 998244353L\nlet hoge p q r s =\n\tlet m q = Int64.rem q md in\n\tp |> m |> Int64.add q |> m |> Int64.add r |> m |> Int64.add s |> m\nlet (@~) a (i,j,k,l) = a.(i).(j).(k).(l)\nlet (<@~) a (i,j,k,l,v) = a.(i).(j).(k).(l) <- v\nlet (+%) p q =\n\tlet m q = Int64.rem q md in\n\tp |> m |> Int64.add q |> m\nlet () =\n\tlet n,k = scanf \" %d %d\" (fun u v -> u,v) in\n\tdp.(1).(2).(0).(0) <- 1L;\n\tdp.(1).(3).(0).(1) <- 1L;\n\tdp.(1).(3).(1).(0) <- 1L;\n\tdp.(1).(2).(1).(1) <- 1L;\n\tfor i=2 to n do\n\t\tfor j=2 to i*2+1 do\n\t\t\tdp<@~(i,j,0,0,(\n\t\t\t\t(dp@~(i-1,j,0,0))\n\t\t\t\t+% (dp@~(i-1,j,0,1))\n\t\t\t\t+% (dp@~(i-1,j,1,0))\n\t\t\t\t+% (dp@~(i-1,j-1,1,1))\n\t\t\t));\n\t\t\tdp<@~(i,j,1,1,(\n\t\t\t\t(dp@~(i-1,j,1,1))\n\t\t\t\t+% (dp@~(i-1,j,0,1))\n\t\t\t\t+% (dp@~(i-1,j,1,0))\n\t\t\t\t+% (dp@~(i-1,j-1,0,0))\n\t\t\t));\n\t\t\tdp<@~(i,j,1,0,(\n\t\t\t\t(dp@~(i-1,j,1,0))\n\t\t\t\t+% (dp@~(i-1,j-1,1,1))\n\t\t\t\t+% (dp@~(i-1,j-1,0,0))\n\t\t\t\t+% (dp@~(i-1,j-2,0,1))\n\t\t\t));\n\t\t\tdp<@~(i,j,0,1,(\n\t\t\t\t(dp@~(i-1,j,0,1))\n\t\t\t\t+% (dp@~(i-1,j-1,1,1))\n\t\t\t\t+% (dp@~(i-1,j-1,0,0))\n\t\t\t\t+% (dp@~(i-1,j-2,1,0))\n\t\t\t));\n\t\t\t(*\n\t\t\tdp.(i).(j).(0).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(0)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1);\n\t\t\tdp.(i).(j).(1).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(1)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0);\n\t\t\tdp.(i).(j).(1).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(0).(1);\n\t\t\tdp.(i).(j).(0).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(1).(0); *)\n\t\tdone;\n\tdone;\n\tprintf \"%Ld\" (\n\t\thoge\n\t\t\tdp.(n).(k+1).(0).(0)\n\t\t\tdp.(n).(k+1).(0).(1)\n\t\t\tdp.(n).(k+1).(1).(0)\n\t\t\tdp.(n).(k+1).(1).(1)\n\t)\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\n\nlet dp = Array.init 1024 (fun _ ->\n\tArray.init 2048 (fun _ -> \n\t\tArray.init 2 (fun _ ->\n\t\t\tArray.make 2 0)))\nlet md = 998244353\nlet hoge p q r s =\n\tlet m p q = q mod p in\n\tp |> (+) q |> m md |> (+) r |> m md |> (+) s |> m md\nlet () =\n\tlet n,k = scanf \" %d %d\" (fun u v -> u,v) in\n\tdp.(1).(2).(0).(0) <- 1;\n\tdp.(1).(3).(0).(1) <- 1;\n\tdp.(1).(3).(1).(0) <- 1;\n\tdp.(1).(2).(1).(1) <- 1;\n\tfor i=2 to n do\n\t\tfor j=2 to i*2+1 do\n\t\t\tdp.(i).(j).(0).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(0)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1);\n\t\t\tdp.(i).(j).(1).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(1)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0);\n\t\t\tdp.(i).(j).(1).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(0).(1);\n\t\t\tdp.(i).(j).(0).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(1).(0);\n\t\tdone;\n\tdone;\n\tprintf \"%d\" (\n\t\thoge\n\t\t\tdp.(n).(k+1).(0).(0)\n\t\t\tdp.(n).(k+1).(0).(1)\n\t\t\tdp.(n).(k+1).(1).(0)\n\t\t\tdp.(n).(k+1).(1).(1)\n\t)\n\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\n\nmodule ModCalc = struct\n\t(* let md = 1000000007L *)\n\tlet md = 998244353L\n\tlet validate v =\n\t\t(v + (labs(v) / md + 1L) * md) mod md\n\tlet _add_mod md u v = u mod md + v mod md |> validate\n\tlet _sub_mod md u v = u mod md - v mod md |> validate\n\tlet _mul_mod md u v = u mod md * v mod md |> validate\n\tlet rec pw u v =\n\t\tif v=0L then 1L\n\t\telse if v=1L then u mod md\n\t\telse let p = pw u (v/2L) in\n\t\t\tif v mod 2L = 0L then _mul_mod md p p\n\t\t\telse _mul_mod md (_mul_mod md p p) u\n\tlet _inv md v = pw v (md-2L)\n\tlet _div_mod md u v = \n\t\t_mul_mod md u (_inv md v)\n\n\tlet (+%) u v = _add_mod md u v\n\tlet (-%) u v = _sub_mod md u v\n\tlet ( *%) u v = _mul_mod md u v\n\tlet (/%) u v = _div_mod md u v\n\tlet rec pow x n = if n = 0L then 1L\n\t\telse if n mod 2L = 1L then x *% pow x (n-1L)\n\t\telse let w = pow x (n/2L) in w *% w\n\tlet fact n = let rec f0 n v = if n = 0L then v else f0 (n-1L) (n*%v) in f0 n 1L\nend open ModCalc\n\n\nlet make_3darray p q r d = Array.init (~|p) (fun _ -> Array.make_matrix (~|q) (~|r) d)\nlet make_4darray p q r s d = Array.init (~|p) (fun _ -> make_3darray q r s d)\nlet (@~) a (i,j,k,l) = try a.(~|i).(~|j).(~|k).(~|l) with | Invalid_argument _ -> 0L\nlet (<@~) a (i,j,k,l,v) = a.(~|i).(~|j).(~|k).(~|l) <- v\nlet dp = make_4darray 1024L 2048L 2L 2L 0L\n\nlet () =\n\tlet n,k = get_2_i64 0 in\n\tdp.(1).(1).(0).(0) <- 1L;\n\tdp.(1).(2).(0).(1) <- 1L;\n\tdp.(1).(2).(1).(0) <- 1L;\n\tdp.(1).(1).(1).(1) <- 1L;\n\trep 2L n (fun i ->\n\t\trep 1L (i*2L+2L) (fun j ->\n\t\t\tdp<@~(i,j,0L,0L,(\n\t\t\t\t(dp@~(i-1L,j,0L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,0L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,1L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-2L,1L,1L))\n\t\t\t));\n\t\t\tdp<@~(i,j,1L,1L,(\n\t\t\t\t(dp@~(i-1L,j,1L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,0L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,1L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-2L,0L,0L))\n\t\t\t));\n\t\t\tdp<@~(i,j,1L,0L,(\n\t\t\t\t(dp@~(i-1L,j,1L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,1L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,0L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-2L,0L,1L))\n\t\t\t));\n\t\t\tdp<@~(i,j,0L,1L,(\n\t\t\t\t(dp@~(i-1L,j,0L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,1L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,0L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-2L,1L,0L))\n\t\t\t));\n\t\t\t`Ok\n\t\t);\n\t\t`Ok\n\t);\n\tprintf \"%Ld\\n\" (\n\t\t(dp@~(n,k,0L,0L))\n\t\t+% (dp@~(n,k,0L,1L))\n\t\t+% (dp@~(n,k,1L,0L))\n\t\t+% (dp@~(n,k,1L,1L))\n\t)"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\n\nmodule ModCalc = struct\n\t(* let md = 1000000007L *)\n\tlet md = 998244353L\n\tlet validate v =\n\t\t(v + (labs(v) / md + 1L) * md) mod md\n\tlet _add_mod md u v = u mod md + v mod md |> validate\n\tlet _sub_mod md u v = u mod md - v mod md |> validate\n\tlet _mul_mod md u v = u mod md * v mod md |> validate\n\tlet rec pw u v =\n\t\tif v=0L then 1L\n\t\telse if v=1L then u mod md\n\t\telse let p = pw u (v/2L) in\n\t\t\tif v mod 2L = 0L then _mul_mod md p p\n\t\t\telse _mul_mod md (_mul_mod md p p) u\n\tlet _inv md v = pw v (md-2L)\n\tlet _div_mod md u v = \n\t\t_mul_mod md u (_inv md v)\n\n\tlet (+%) u v = _add_mod md u v\n\tlet (-%) u v = _sub_mod md u v\n\tlet ( *%) u v = _mul_mod md u v\n\tlet (/%) u v = _div_mod md u v\n\tlet rec pow x n = if n = 0L then 1L\n\t\telse if n mod 2L = 1L then x *% pow x (n-1L)\n\t\telse let w = pow x (n/2L) in w *% w\n\tlet fact n = let rec f0 n v = if n = 0L then v else f0 (n-1L) (n*%v) in f0 n 1L\nend open ModCalc\n\n\nlet make_3darray p q r d = Array.init (~|p) (fun _ -> Array.make_matrix (~|q) (~|r) d)\nlet make_4darray p q r s d = Array.init (~|p) (fun _ -> make_3darray q r s d)\nlet (@~) a (i,j,k,l) = try a.(~|i).(~|j).(~|k).(~|l) with | Invalid_argument _ -> 0L\nlet (<@~) a (i,j,k,l,v) = a.(~|i).(~|j).(~|k).(~|l) <- v\nlet dp = make_4darray 1024L 2048L 2L 2L 0L\n\nlet () =\n\tlet n,k = get_2_i64 0 in\n\tdp.(1).(1).(0).(0) <- 1L;\n\tdp.(1).(2).(0).(1) <- 1L;\n\tdp.(1).(2).(1).(0) <- 1L;\n\tdp.(1).(1).(1).(1) <- 1L;\n\trep 2L n (fun i ->\n\t\trep 1L (i*2L+2L) (fun j ->\n\t\t\tdp<@~(i,j,0L,0L,(\n\t\t\t\t(dp@~(i-1L,j,0L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,0L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,1L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,1L,1L))\n\t\t\t));\n\t\t\tdp<@~(i,j,1L,1L,(\n\t\t\t\t(dp@~(i-1L,j,1L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,0L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,1L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,0L,0L))\n\t\t\t));\n\t\t\tdp<@~(i,j,1L,0L,(\n\t\t\t\t(dp@~(i-1L,j,1L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,1L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,0L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-2L,0L,1L))\n\t\t\t));\n\t\t\tdp<@~(i,j,0L,1L,(\n\t\t\t\t(dp@~(i-1L,j,0L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,1L,1L))\n\t\t\t\t+% (dp@~(i-1L,j-1L,0L,0L))\n\t\t\t\t+% (dp@~(i-1L,j-2L,1L,0L))\n\t\t\t));\n\t\t\t`Ok\n\t\t);\n\t\t`Ok\n\t);\n\tprintf \"%Ld\\n\" (\n\t\t(dp@~(n,k,0L,0L))\n\t\t+% (dp@~(n,k,0L,1L))\n\t\t+% (dp@~(n,k,1L,0L))\n\t\t+% (dp@~(n,k,1L,1L))\n\t)"}, {"source_code": "open Printf open Scanf\n\nlet dp = Array.init 1024 (fun _ ->\n\tArray.init 2048 (fun _ -> \n\t\tArray.init 2 (fun _ ->\n\t\t\tArray.make 2 0)))\nlet md = 998244353\nlet hoge p q r s =\n\tlet m p q = q mod p in\n\tp |> m md |> (+) q |> m md |> (+) r |> m md |> (+) s |> m md\nlet () =\n\tlet n,k = scanf \" %d %d\" (fun u v -> u,v) in\n\tdp.(1).(2).(0).(0) <- 1;\n\tdp.(1).(3).(0).(1) <- 1;\n\tdp.(1).(3).(1).(0) <- 1;\n\tdp.(1).(2).(1).(1) <- 1;\n\tfor i=2 to n do\n\t\tfor j=2 to i*2+1 do\n\t\t\tdp.(i).(j).(0).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(0)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1);\n\t\t\tdp.(i).(j).(1).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(1)\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0);\n\t\t\tdp.(i).(j).(1).(0) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(1).(0)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(0).(1);\n\t\t\tdp.(i).(j).(0).(1) <-\n\t\t\t\thoge\n\t\t\t\t\tdp.(i-1).(j).(0).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(1).(1)\n\t\t\t\t\tdp.(i-1).(j-1).(0).(0)\n\t\t\t\t\tdp.(i-1).(j-2).(1).(0);\n\t\tdone;\n\tdone;\n\tprintf \"%d\" (\n\t\thoge\n\t\t\tdp.(n).(k+1).(0).(0)\n\t\t\tdp.(n).(k+1).(0).(1)\n\t\t\tdp.(n).(k+1).(1).(0)\n\t\t\tdp.(n).(k+1).(1).(1)\n\t)\n\n"}], "src_uid": "7e6a2329633ee283e3327413114901d1"} {"nl": {"description": "On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1,\u2009x2,\u2009...,\u2009xk, then the cost of item xj is axj\u2009+\u2009xj\u00b7k for 1\u2009\u2264\u2009j\u2009\u2264\u2009k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?", "input_spec": "The first line contains two integers n and S (1\u2009\u2264\u2009n\u2009\u2264\u2009105 and 1\u2009\u2264\u2009S\u2009\u2264\u2009109)\u00a0\u2014 the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105)\u00a0\u2014 the base costs of the souvenirs.", "output_spec": "On a single line, print two integers k, T\u00a0\u2014 the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs.", "sample_inputs": ["3 11\n2 3 5", "4 100\n1 2 5 6", "1 7\n7"], "sample_outputs": ["2 11", "4 54", "0 0"], "notes": "NoteIn the first example, he cannot take the three items because they will cost him [5,\u20099,\u200914] with total cost 28. If he decides to take only two items, then the costs will be [4,\u20097,\u200911]. So he can afford the first and second items.In the second example, he can buy all items as they will cost him [5,\u200910,\u200917,\u200922].In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it."}, "positive_code": [{"source_code": "(* start:1:36 done: 1:55*)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let s = long (read_int ()) in\n let a = Array.init n (fun _ -> long (read_int())) in\n let c = Array.make n 0L in\n\n let min_cost k =\n (* the minimum cost to buy k things *)\n for i=0 to n-1 do\n c.(i) <- a.(i) ++ (long k)**(long (i+1))\n done;\n\n Array.sort compare c;\n\n sum 0 (k-1) (fun i -> c.(i))\n in\n\n let rec bsearch lo c_lo hi c_hi =\n (* min_cost lo <= s, and min_cost hi > s *)\n if lo + 1 = hi then (lo,c_lo)\n else\n let m = (lo+hi)/2 in\n let c_m = min_cost m in\n if c_m <= s then bsearch m c_m hi c_hi else bsearch lo c_lo m c_m\n in\n\n let rec run_search hi0 c_hi0 =\n (* c_hi0 <= s *)\n let hi1 = min n (2*(max 1 hi0)) in\n let c_hi1 = min_cost hi1 in\n if c_hi1 > s then bsearch hi0 c_hi0 hi1 c_hi1 else run_search hi1 c_hi1\n in\n\n let cost_of_all = min_cost n in\n\n let (k, c_k) = if cost_of_all <= s then (n, cost_of_all) else run_search 0 0L in\n\n printf \"%d %Ld\\n\" k c_k\n"}], "negative_code": [], "src_uid": "b1fd037d5ac6023ef3250fc487656db5"} {"nl": {"description": "There is a special offer in Vasya's favourite supermarket: if the customer buys $$$a$$$ chocolate bars, he or she may take $$$b$$$ additional bars for free. This special offer can be used any number of times.Vasya currently has $$$s$$$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $$$c$$$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of testcases. Each of the next $$$t$$$ lines contains four integers $$$s, a, b, c~(1 \\le s, a, b, c \\le 10^9)$$$ \u2014 the number of roubles Vasya has, the number of chocolate bars you have to buy to use the special offer, the number of bars you get for free, and the cost of one bar, respectively.", "output_spec": "Print $$$t$$$ lines. $$$i$$$-th line should contain the maximum possible number of chocolate bars Vasya can get in $$$i$$$-th test.", "sample_inputs": ["2\n10 3 1 1\n1000000000 1 1000000000 1"], "sample_outputs": ["13\n1000000001000000000"], "notes": "NoteIn the first test of the example Vasya can buy $$$9$$$ bars, get $$$3$$$ for free, buy another bar, and so he will get $$$13$$$ bars.In the second test Vasya buys $$$1000000000$$$ bars and gets $$$1000000000000000000$$$ for free. So he has $$$1000000001000000000$$$ bars."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet () =\n\tlet t = get_i64 0 in\n\trep 1L t (fun _ ->\n\t\tlet s,a,b,c = get_4_i64 0 in\n\t\tlet buy = s / c in\n\t\tlet d = buy / a in\n\t\t(d*(a+b) + (buy - d*a)) |> printf \"%Ld\\n\";\n\t\t(* printf \"%Ld %Ld\\n\" buy d; *)\n\t\t`Ok\n\t)\t\n\n"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_string () = Scanf.scanf \" %s\" (fun x -> x);;\nlet psp () = print_string \" \";;\nlet b2i x = if x == true then 1 else 0;;\n\nopen Int64;;\nlet t = scan_int();;\n\nlet f s a b c =\n let c1 = mul a c in\n let ile = div s c1 in\n add (mul ile (add a b)) (div (sub s (mul ile c1)) c);;\n\nfor i = 0 to t - 1 do\n let a = Int64.of_int(scan_int()) and \n b = Int64.of_int(scan_int()) and\n c = Int64.of_int(scan_int()) and\n d = Int64.of_int(scan_int()) in\n print_string(Int64.to_string(f a b c d)); print_newline();\ndone;;"}], "negative_code": [], "src_uid": "ec8060260a6c7f4ff3e6afc9fd248afc"} {"nl": {"description": "Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters \"x\" and \"y\", and uses two following operations at runtime: Find two consecutive characters in the string, such that the first of them equals \"y\", and the second one equals \"x\" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. Find in the string two consecutive characters, such that the first of them equals \"x\" and the second one equals \"y\". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string s, and the algorithm works as follows: If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string. If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.", "input_spec": "The first line contains a non-empty string s. It is guaranteed that the string only consists of characters \"x\" and \"y\". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.", "output_spec": "In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.", "sample_inputs": ["x", "yxyxy", "xxxxxy"], "sample_outputs": ["x", "y", "xxxx"], "notes": "NoteIn the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.In the second test the transformation will be like this: string \"yxyxy\" transforms into string \"xyyxy\"; string \"xyyxy\" transforms into string \"xyxyy\"; string \"xyxyy\" transforms into string \"xxyyy\"; string \"xxyyy\" transforms into string \"xyy\"; string \"xyy\" transforms into string \"y\". As a result, we've got string \"y\". In the third test case only one transformation will take place: string \"xxxxxy\" transforms into string \"xxxx\". Thus, the answer will be string \"xxxx\"."}, "positive_code": [{"source_code": "(* Codeforces 252B RazborCode 255B *)\n\nopen Filename;;\nopen String;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec cntxy s idx cntx cnty =\n\tif idx >= (length s) then (cntx, cnty)\n\telse begin\n\t\tlet c = s.[idx] in\n\t\tlet id1 = idx +1 in\n\t\tif c = 'x' then\n\t\t\tcntxy s id1 (cntx + 1) cnty\n\t\telse cntxy s id1 cntx (cnty + 1)\n\tend;;\n\nlet rec reppri s n = match n with\n\t| 0 -> ()\n\t| _ -> begin\n\t\t\t\tprint_string s;\n\t\t\t\treppri s (n -1)\n\t\t\tend;;\n\nlet main () =\n\tlet s = rdln() in\n\tlet (cx, cy) = cntxy s 0 0 0 in\n\tbegin\n\t\t(* print_string \" cx,cy = \"; print_int cx; print_string \" \"; print_int *)\n\t\t(* cy; *)\n\t\tif cx < cy then reppri \"y\" (cy - cx) \n\t\t\telse reppri \"x\" (cx - cy);\n\t\tprint_newline()\n\tend;;\n\nmain();;\n"}, {"source_code": "let read_string () = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x) \n\nlet explode s = \n let rec exp i l = \n if i < 0 then l else exp (i - 1) (s.[i] :: l) \n in exp (String.length s - 1) [] ;;\n \nlet s = explode (read_string ()) ;;\n\nlet count s =\n let rec loop (x, y) = function\n | [] -> (x, y)\n | h :: t -> \n if h = 'x' then loop (x + 1, y) t \n else loop (x, y + 1) t\n in loop (0, 0) s ;;\n\nlet result = \n let (x, y) = count s in \n if x > y then String.make (x - y) 'x'\n else String.make (y - x) 'y' ;;\n\nPrintf.printf \"%s\\n\" result ;;"}, {"source_code": "let () = \n let s = read_line() in\n let c = Array.make 2 0 in\n for i = 0 to (String.length s)-1 do\n let w = if s.[i] = 'x' then 0 else 1 in\n\tc.(w) <- c.(w) + 1\n done;\n\n let b = if c.(0) > c.(1) then 'x' else 'y' in\n let n = abs (c.(0) - c.(1)) in\n for i=0 to n-1 do\n\tprint_char b\n done;\n print_newline()\n"}], "negative_code": [], "src_uid": "528459e7624f90372cb2c3a915529a23"} {"nl": {"description": "For the New Year, Polycarp decided to send postcards to all his $$$n$$$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $$$w \\times h$$$, which can be cut into pieces.Polycarp can cut any sheet of paper $$$w \\times h$$$ that he has in only two cases: If $$$w$$$ is even, then he can cut the sheet in half and get two sheets of size $$$\\frac{w}{2} \\times h$$$; If $$$h$$$ is even, then he can cut the sheet in half and get two sheets of size $$$w \\times \\frac{h}{2}$$$; If $$$w$$$ and $$$h$$$ are even at the same time, then Polycarp can cut the sheet according to any of the rules above.After cutting a sheet of paper, the total number of sheets of paper is increased by $$$1$$$.Help Polycarp to find out if he can cut his sheet of size $$$w \\times h$$$ at into $$$n$$$ or more pieces, using only the rules described above.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three integers $$$w$$$, $$$h$$$, $$$n$$$ ($$$1 \\le w, h \\le 10^4, 1 \\le n \\le 10^9$$$)\u00a0\u2014 the width and height of the sheet Polycarp has and the number of friends he needs to send a postcard to.", "output_spec": "For each test case, output on a separate line: \"YES\", if it is possible to cut a sheet of size $$$w \\times h$$$ into at least $$$n$$$ pieces; \"NO\" otherwise. You can output \"YES\" and \"NO\" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).", "sample_inputs": ["5\n2 2 3\n3 3 2\n5 10 2\n11 13 1\n1 4 4"], "sample_outputs": ["YES\nNO\nYES\nYES\nYES"], "notes": "NoteIn the first test case, you can first cut the $$$2 \\times 2$$$ sheet into two $$$2 \\times 1$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \\times 1$$$. We can choose any three of them and send them to our friends.In the second test case, a $$$3 \\times 3$$$ sheet cannot be cut, so it is impossible to get two sheets.In the third test case, you can cut a $$$5 \\times 10$$$ sheet into two $$$5 \\times 5$$$ sheets.In the fourth test case, there is no need to cut the sheet, since we only need one sheet.In the fifth test case, you can first cut the $$$1 \\times 4$$$ sheet into two $$$1 \\times 2$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \\times 1$$$."}, "positive_code": [{"source_code": "(** https://codeforces.com/problemset/problem/1472/A *)\n\nlet max_friends width height =\n let rec helper num i =\n if num land 1 = 1\n then i\n else helper (num lsr 1) (i+1) in\n let cut_width = helper width 0 and\n cut_height = helper height 0 in\n let rec pow2 i res =\n if i = 0\n then res\n else pow2 (i-1) (res lsl 1) in\n pow2 (cut_width+cut_height) 1\n \nlet solve_n nb_cases =\n let rec helper i =\n if i > 0\n then (\n let [width; height; friends] =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n (if max_friends width height >= friends then \"YES\" else \"NO\")\n |> print_endline;\n helper (i-1)\n ) in\n helper nb_cases\n\nlet () =\n let nb_cases = read_int () in\n solve_n nb_cases\n"}, {"source_code": "(* #load \"str.cma\" *)\r\nmodule Stdlib = Pervasives;;\r\n(* let std_inp = Stdlib.open_in \"input.txt\";; *)\r\nlet std_inp = Stdlib.stdin;;\r\nlet std_outp = Stdlib.stdout;;\r\n\r\nlet identity x = x;;\r\nlet tup3 x1 x2 x3 = (x1, x2, x3);;\r\n\r\nlet rec slices n =\r\n if n mod 2 == 0 then 1 + slices (n / 2)\r\n else 0;;\r\n\r\nlet rec pow base = function\r\n| 0 -> 1\r\n| n -> base * (pow base (n - 1));;\r\n\r\nlet solution inp outp =\r\n let (w, h, n) = let line = input_line inp in Scanf.sscanf line \"%d %d %d\" tup3 in\r\n let w_count = slices w and h_count = slices h in\r\n (* let _ = Printf.printf \"W: %d; H: %d; N: %d\\n\" w h n in *)\r\n (* let _ = Printf.printf \"WC: %d; HC: %d\\n\" w_count h_count in *)\r\n let _ =\r\n if (pow 2 w_count) * (pow 2 h_count) >= n then Printf.printf \"YES\\n\"\r\n else Printf.printf \"NO\\n\"\r\n in\r\n ();;\r\nlet rec run_test = function\r\n| (0, _, _) -> ()\r\n| (t, inp, outp) ->\r\n let _ = solution inp outp in\r\n run_test (t - 1, inp, outp);;\r\n\r\nlet (_:unit) =\r\n let inp = std_inp and outp = std_outp in\r\n let tests_count = let line = input_line inp in Scanf.sscanf line \"%d\" identity in\r\n let _ = run_test (tests_count, inp, outp) in\r\n ();;"}], "negative_code": [], "src_uid": "a8201326dda46542b23dc4e528d413eb"} {"nl": {"description": "Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m\u2009-\u20091 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,\u2009y) either y\u2009=\u20090, or there is a cube with coordinates (x\u2009-\u20091,\u2009y\u2009-\u20091), (x,\u2009y\u2009-\u20091) or (x\u2009+\u20091,\u2009y\u2009-\u20091).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109\u2009+\u20099.", "input_spec": "The first line contains number m (2\u2009\u2264\u2009m\u2009\u2264\u2009105). The following m lines contain the coordinates of the cubes xi,\u2009yi (\u2009-\u2009109\u2009\u2264\u2009xi\u2009\u2264\u2009109, 0\u2009\u2264\u2009yi\u2009\u2264\u2009109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place.", "output_spec": "In the only line print the answer to the problem.", "sample_inputs": ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"], "sample_outputs": ["19", "2930"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Iset = Set.Make (struct type t = int let compare = compare end)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\n\nlet mm = 1_000_000_009L\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let m = read_int () in\n let cube = Array.init m (fun _ -> read_pair()) in\n\n let h = Hashtbl.create 10 in\n\n for i=0 to m-1 do\n Hashtbl.replace h cube.(i) i\n done;\n\n let btoi p = if p then 1 else 0 in\n\n let count_support (x,y) =\n if y=0 || not (Hashtbl.mem h (x,y)) then 3 else\n btoi (Hashtbl.mem h (x-1,y-1)) \n + btoi (Hashtbl.mem h (x,y-1)) \n + btoi (Hashtbl.mem h (x+1,y-1))\n in\n\n let removable p =\n (* returns true if p is removable in the current configuration *)\n let (x,y) = cube.(p) in\n (count_support (x-1,y+1)>1) \n && (count_support (x,y+1)>1) \n && (count_support (x+1,y+1)>1)\n in\n\n let remove_it p set =\n let (x,y) = cube.(p) in\n Hashtbl.remove h (x,y);\n let update_set (xx,yy) set = \n if not (Hashtbl.mem h (xx,yy)) then set else\n\tlet i = Hashtbl.find h (xx,yy) in\n\tif removable i then Iset.add i set else Iset.remove i set\n in\n let set = update_set (x-1,y-1) set in\n let set = update_set (x,y-1) set in\n let set = update_set (x+1,y-1) set in\n let set = update_set (x-2,y) set in\n let set = update_set (x-1,y) set in\n let set = update_set (x+1,y) set in\n let set = update_set (x+2,y) set in\n set\n in\n\n let rec build_removable i ac = if i=m then ac else\n let ac = if removable i then Iset.add i ac else ac in\n build_removable (i+1) ac\n in\n\n let initial_set = build_removable 0 Iset.empty in\n\n let rec simulate move_num set ac = if move_num = m then ac else\n let remove_me =\n\tif move_num land 1 = 0 then Iset.max_elt set else Iset.min_elt set\n in\n let set = Iset.remove remove_me set in\n let set = remove_it remove_me set in\n simulate (move_num+1) set (remove_me::ac)\n in\n\n let li = simulate 0 initial_set [] in\n\n let rec eval li ac = match li with [] -> ac\n | d::tail -> \n let ac = (ac ** (long m) ++ (long d)) %% mm in\n eval tail ac\n in\n\n let answer = eval (List.rev li) 0L in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Iset = Set.Make (struct type t = int let compare = compare end)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\n\nlet mm = 1_000_000_009L\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let m = read_int () in\n let cube = Array.init m (fun _ -> read_pair()) in\n\n let h = Hashtbl.create 10 in\n\n for i=0 to m-1 do\n Hashtbl.replace h cube.(i) i\n done;\n\n let btoi p = if p then 1 else 0 in\n\n let count_support (x,y) =\n if y=0 || not (Hashtbl.mem h (x,y)) then 3 else\n btoi (Hashtbl.mem h (x-1,y-1)) \n + btoi (Hashtbl.mem h (x,y-1)) \n + btoi (Hashtbl.mem h (x+1,y-1))\n in\n\n let removable p =\n (* returns true if p is removable in the current configuration *)\n let (x,y) = cube.(p) in\n (count_support (x-1,y+1)>1) \n && (count_support (x,y+1)>1) \n && (count_support (x+1,y+1)>1)\n in\n\n let remove_it p set =\n let (x,y) = cube.(p) in\n Hashtbl.remove h (x,y);\n let update_set (xx,yy) set = \n if not (Hashtbl.mem h (xx,yy)) then set else\n\tlet i = Hashtbl.find h (xx,yy) in\n\tif removable i then Iset.add i set else Iset.remove i set\n in\n let set = update_set (x-1,y-1) set in\n let set = update_set (x,y-1) set in\n let set = update_set (x+1,y-1) set in\n set\n in\n\n let rec build_removable i ac = if i=m then ac else\n let ac = if removable i then Iset.add i ac else ac in\n build_removable (i+1) ac\n in\n\n let initial_set = build_removable 0 Iset.empty in\n\n let rec simulate move_num set ac = if move_num = m then ac else\n let remove_me =\n\tif move_num land 1 = 0 then Iset.max_elt set else Iset.min_elt set\n in\n let set = Iset.remove remove_me set in\n let set = remove_it remove_me set in\n simulate (move_num+1) set (remove_me::ac)\n in\n\n let li = simulate 0 initial_set [] in\n\n let rec eval li ac = match li with [] -> ac\n | d::tail -> \n let ac = (ac ** (long m) ++ (long d)) %% mm in\n eval tail ac\n in\n\n let answer = eval (List.rev li) 0L in\n\n printf \"%Ld\\n\" answer\n"}, {"source_code": "open Printf\nopen Scanf\n\nmodule Iset = Set.Make (struct type t = int let compare = compare end)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\n\nlet mm = 1_000_000_009L\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let m = read_int () in\n let cube = Array.init m (fun _ -> read_pair()) in\n\n let h = Hashtbl.create 10 in\n\n for i=0 to m-1 do\n Hashtbl.replace h cube.(i) i\n done;\n\n let btoi p = if p then 1 else 0 in\n\n let count_support (x,y) =\n if y=0 || not (Hashtbl.mem h (x,y)) then 3 else\n btoi (Hashtbl.mem h (x-1,y-1)) \n + btoi (Hashtbl.mem h (x,y-1)) \n + btoi (Hashtbl.mem h (x+1,y-1))\n in\n\n let removable p =\n (* returns true if p is removable in the current configuration *)\n let (x,y) = cube.(p) in\n (count_support (x-1,y+1)>1) \n && (count_support (x,y+1)>1) \n && (count_support (x+1,y+1)>1)\n in\n\n let remove_it p set =\n let (x,y) = cube.(p) in\n Hashtbl.remove h (x,y);\n if y=0 then set else\n let update_set (xx,yy) set = \n\tif not (Hashtbl.mem h (xx,yy)) then set else\n\t let i = Hashtbl.find h (xx,yy) in\n\t if removable i then Iset.add i set else Iset.remove i set\n in\n let set = update_set (x-1,y-1) set in\n let set = update_set (x,y-1) set in\n let set = update_set (x+1,y-1) set in\n set\n in\n\n let rec build_removable i ac = if i=m then ac else\n let ac = if removable i then Iset.add i ac else ac in\n build_removable (i+1) ac\n in\n\n let initial_set = build_removable 0 Iset.empty in\n\n let rec simulate move_num set ac = if move_num = m then ac else\n let remove_me =\n\tif move_num land 1 = 0 then Iset.max_elt set else Iset.min_elt set\n in\n let set = Iset.remove remove_me set in\n let set = remove_it remove_me set in\n simulate (move_num+1) set (remove_me::ac)\n in\n\n let li = simulate 0 initial_set [] in\n\n let rec eval li ac = match li with [] -> ac\n | d::tail -> \n let ac = (ac ** (long m) ++ (long d)) %% mm in\n eval tail ac\n in\n\n let answer = eval (List.rev li) 0L in\n\n printf \"%Ld\\n\" answer\n"}], "src_uid": "9f36d49541e6dd7082e37416cdb1949c"} {"nl": {"description": "The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?", "input_spec": "The first line contains two integers, n and k (1\u2009\u2264\u2009n\u2009\u2264\u20092000;\u00a01\u2009\u2264\u2009k\u2009\u2264\u20095). The next line contains n integers: y1,\u2009y2,\u2009...,\u2009yn (0\u2009\u2264\u2009yi\u2009\u2264\u20095), where yi shows the number of times the i-th person participated in the ACM ICPC world championship.", "output_spec": "Print a single number \u2014 the answer to the problem.", "sample_inputs": ["5 2\n0 4 5 1 0", "6 4\n0 1 2 3 4 5", "6 5\n0 0 0 0 0 0"], "sample_outputs": ["1", "0", "2"], "notes": "NoteIn the first sample only one team could be made: the first, the fourth and the fifth participants.In the second sample no teams could be created.In the third sample two teams could be created. Any partition into two teams fits."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let n = read () in\n let k = read () in\n let rec loop i list =\n if i < n\n then\n let temp = read () in\n loop (i + 1) (temp :: list)\n else\n (k, list)\n in loop 0 []\n\nlet solve (k, list) = \n let qualified = List.filter (fun m -> m + k <= 5) list in\n List.length qualified / 3\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet k=read_int();;\nlet nb=ref 0;;\nfor i=1 to n-1 do\n let x=read_int() in\n if x<=5-k then incr nb\ndone;;\nlet a=Scanf.scanf \"%d\" (fun x->x) in if a<=5-k then incr nb;;\nprint_int( (!nb)/3);;"}, {"source_code": "let k = List.nth (read_line () |> Str.split (Str.regexp \" +\") ) 1 |> int_of_string and\n ys = read_line() |> Str.split (Str.regexp \" +\") |> List.map int_of_string in\n \n ys |> List.map (fun x -> x + k) |> List.filter (fun x -> x <=5) |> List.length |> fun x -> x / 3 |> print_int \n"}, {"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet k=read_int();;\nlet nb=ref 0;;\nfor i=1 to n-1 do\n let x=read_int() in\n if x<=5-k then incr nb\ndone;;\nlet a=Scanf.scanf \"%d\" (fun x->x) in if a<=5-k then incr nb;;\nprint_int( (!nb)/3);;"}, {"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\n(* int *)\nlet intsqrt n = \n if n < 0 then raise (Invalid_argument \"sqrt of negative int\") else \n let rec bs a b = begin \n if b - a = 1 then a else \n let mid = (a+b)/2 in \n if mid*mid <= n then bs mid b else bs a mid\n end in \n bs 0 (1 lsl 31)\n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet default x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* tuple *)\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet _ = \n let len = read_int() in \n let k = read_int() in \n let arr = init len (fun i -> read_int() ) in \n sort compare arr;\n let rec upper_bound a b =\n if b - a = 1 then b else \n let mid = (a+b)/2 in \n if arr.(mid) <= 5-k then upper_bound mid b else upper_bound a mid \n in \n printf \"%d\\n\" ((upper_bound (-1) len)/3)"}], "negative_code": [], "src_uid": "fbde1e2ee02055592ff72fb04366812b"} {"nl": {"description": "Monocarp has just learned a new card trick, and can't wait to present it to you. He shows you the entire deck of $$$n$$$ cards. You see that the values of cards from the topmost to the bottommost are integers $$$a_1, a_2, \\dots, a_n$$$, and all values are different.Then he asks you to shuffle the deck $$$m$$$ times. With the $$$j$$$-th shuffle, you should take $$$b_j$$$ topmost cards and move them under the remaining $$$(n - b_j)$$$ cards without changing the order.And then, using some magic, Monocarp tells you the topmost card of the deck. However, you are not really buying that magic. You tell him that you know the topmost card yourself. Can you surprise Monocarp and tell him the topmost card before he shows it?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$)\u00a0\u2014 the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of cards in the deck. The second line contains $$$n$$$ pairwise distinct integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$)\u00a0\u2014 the values of the cards. The third line contains a single integer $$$m$$$ ($$$1 \\le m \\le 2 \\cdot 10^5$$$)\u00a0\u2014 the number of shuffles. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \\dots, b_m$$$ ($$$1 \\le b_j \\le n - 1$$$)\u00a0\u2014 the amount of cards that are moved on the $$$j$$$-th shuffle. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each testcase, print a single integer\u00a0\u2014 the value of the card on the top of the deck after the deck is shuffled $$$m$$$ times.", "sample_inputs": ["3\n\n2\n\n1 2\n\n3\n\n1 1 1\n\n4\n\n3 1 4 2\n\n2\n\n3 1\n\n5\n\n2 1 5 4 3\n\n5\n\n3 2 1 2 1"], "sample_outputs": ["2\n3\n3"], "notes": "NoteIn the first testcase, each shuffle effectively swaps two cards. After three swaps, the deck will be $$$[2, 1]$$$.In the second testcase, the second shuffle cancels what the first shuffle did. First, three topmost cards went underneath the last card, then that card went back below the remaining three cards. So the deck remained unchanged from the initial one\u00a0\u2014 the topmost card has value $$$3$$$."}, "positive_code": [{"source_code": " open Printf\n open Scanf\n \n let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\n let read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\n let read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n let () =\n \n let cases = read_int()in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n let m = read_int() in\n let b = Array.init m read_int in\n\tlet sum i j f = fold i j (fun i a -> ((f i) + a) mod n) 0 in\n let bsum = sum 0 (m-1) (fun i -> b.(i)) in\n printf \"%d\\n\" a.(bsum)\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () =\n\n let cases = read_int()in\n for case = 1 to cases do\n let n = read_int() in\n let a = Array.init n read_int in\n let m = read_int() in\n let b = Array.init m read_int in\n let bsum = sum 0 (m-1) (fun i -> b.(i)) in\n printf \"%d\\n\" a.(bsum mod n)\n done\n"}], "src_uid": "c9da10199ad1a5358195b693325e628b"} {"nl": {"description": "You have an n\u2009\u00d7\u2009m rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally: each cell must be painted some color (the colors are marked by uppercase Latin letters); we will assume that two cells of the table are connected if they are of the same color and share a side; each connected region of the table must form a square. Given n and m, find lexicographically minimum coloring of the table that meets the described properties.", "input_spec": "The first line contains two integers, n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100).", "output_spec": "Print lexicographically minimum coloring of the table that meets the described conditions. One coloring (let's call it X) is considered lexicographically less than the other one (let's call it Y), if: consider all the table cells from left to right and from top to bottom (first, the first cell in the first row, then the second cell in the first row and so on); let's find in this order the first cell that has distinct colors in two colorings; the letter that marks the color of the cell in X, goes alphabetically before the letter that marks the color of the cell in Y. ", "sample_inputs": ["1 3", "2 2", "3 4"], "sample_outputs": ["ABA", "AA\nAA", "AAAB\nAAAC\nAAAB"], "notes": null}, "positive_code": [{"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\n(* int *)\nlet intsqrt n = \n if n < 0 then raise (Invalid_argument \"sqrt of negative int\") else \n let rec bs a b = begin \n if b - a = 1 then a else \n let mid = (a+b)/2 in \n if mid*mid <= n then bs mid b else bs a mid\n end in \n bs 0 (1 lsl 31)\n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet option x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* tuple *)\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet nei = [| (1,0) ; (-1,0) ; (0,1) ; (0,-1) |]\nlet _ = \n let height = read_int() in \n let width = read_int() in \n\n let mat = make_matrix height width '\\000' in \n\n let find_c i j =\n let set = for_ 0 (length nei) [] (fun k lis -> \n let dy,dx = nei.(k) in \n let i' = i + dy in \n let j' = j + dx in \n if 0 <= i' && i' < height\n && 0 <= j' && j' < width \n && mat.(i').(j') <> '\\000' then \n mat.(i').(j') :: lis\n else \n lis \n ) in \n let colors = \"ABCD\" in \n let rec select_color i = \n let c = colors.[i] in \n if List.mem c set then select_color (i+1) else \n c \n in \n select_color 0 \n in \n\n let find_h c i j = \n let rec run i' = \n if i' = height then 0 else begin \n let c' = mat.(i').(j) in \n if c' <> '\\000' then 0 else \n 1 + run (i'+1)\n end\n in \n run i \n in \n\n let find_w c i j = \n let rec run j' = \n if j' = width then 0 else begin \n let c' = mat.(i).(j') in \n let c'' = find_c i j' in \n if c' <> '\\000' || c <> c'' then 0 else \n 1 + run (j'+1)\n end \n in \n run j \n in \n\n\n let fill i j l c = \n for i = i to i + l -1 do \n for j = j to j + l -1 do \n mat.(i).(j) <- c \n done\n done\n in\n\n for i = 0 to height -1 do \n for j = 0 to width -1 do \n let c = mat.(i).(j) in \n if c = '\\000' then begin \n let c = find_c i j in \n let h = find_h c i j in \n let w = find_w c i j in\n let l = min h w in \n fill i j l c \n end\n done\n done;\n\n print_matrix \"%c\" mat \n "}], "negative_code": [{"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\n(* int *)\nlet intsqrt n = \n if n < 0 then raise (Invalid_argument \"sqrt of negative int\") else \n let rec bs a b = begin \n if b - a = 1 then a else \n let mid = (a+b)/2 in \n if mid*mid <= n then bs mid b else bs a mid\n end in \n bs 0 (1 lsl 31)\n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet option x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* tuple *)\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet nei = [| (1,0) ; (-1,0) ; (0,1) ; (0,-1) |]\nlet _ = \n let height = read_int() in \n let width = read_int() in \n\n let mat = make_matrix height width '\\000' in \n\n let find_c i j =\n let set = for_ 0 (length nei) [] (fun k lis -> \n let dy,dx = nei.(k) in \n let i' = i + dy in \n let j' = j + dx in \n if 0 <= i' && i' < height\n && 0 <= j' && j' < width \n && mat.(i').(j') <> '\\000' then \n mat.(i').(j') :: lis\n else \n lis \n ) in \n let colors = \"ABCD\" in \n let rec select_color i = \n let c = colors.[i] in \n if List.mem c set then select_color (i+1) else \n c \n in \n let ans = select_color 0 in \n if i = 5 && j = 0 then begin \n L.iter (printf \"%c\") set;\n printf \" return %c\\n\" ans;\n end;\n ans\n in \n\n let find_h c i j = \n let rec run i' = \n if i' = height then 0 else begin \n let c' = mat.(i').(j) in \n if c' <> '\\000' then 0 else \n 1 + run (i'+1)\n end\n in \n run i \n in \n\n let find_w c i j = \n let rec run j' = \n if j' = width then 0 else begin \n let c' = mat.(i).(j') in \n let c'' = find_c i j' in \n if c' <> '\\000' || c <> c'' then 0 else \n 1 + run (j'+1)\n end \n in \n run j \n in \n\n\n let fill i j l c = \n for i = i to i + l -1 do \n for j = j to j + l -1 do \n mat.(i).(j) <- c \n done\n done\n in\n\n for i = 0 to height -1 do \n for j = 0 to width -1 do \n let c = mat.(i).(j) in \n if c = '\\000' then begin \n let c = find_c i j in \n let h = find_h c i j in \n let w = find_w c i j in\n let l = min h w in \n fill i j l c \n end\n done\n done;\n\n print_matrix \"%c\" mat \n "}, {"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\n(* int *)\nlet intsqrt n = \n if n < 0 then raise (Invalid_argument \"sqrt of negative int\") else \n let rec bs a b = begin \n if b - a = 1 then a else \n let mid = (a+b)/2 in \n if mid*mid <= n then bs mid b else bs a mid\n end in \n bs 0 (1 lsl 31)\n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet option x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* tuple *)\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet _ = \n let height = read_int() in \n let width = read_int() in \n\n let mat = make_matrix height width '\\000' in \n\n let find_h i j = \n let rec run i' = \n if i' = height || mat.(i').(j) <> '\\000' then 0 else \n 1 + run (i'+1)\n in \n run i \n in \n\n let find_w i j = \n let rec run j' = \n if j' = width || mat.(i).(j') <> '\\000' then 0 else \n 1 + run (j'+1)\n in \n run j \n in \n\n let find_c i j =\n let set = ref [] in \n if 0 < i then set := mat.(i-1).(j) :: !set;\n if 0 < j then set := mat.(i).(j-1) :: !set;\n if 0 < i && 0 < j then set := mat.(i-1).(j-1) :: !set;\n let colors = \"ABCD\" in \n let rec select_color i = \n let c = colors.[i] in \n if List.mem c !set then select_color (i+1) else \n c \n in \n select_color 0\n in \n\n let fill i j l c = \n for i = i to i + l -1 do \n for j = j to j + l -1 do \n mat.(i).(j) <- c \n done\n done\n in\n\n for i = 0 to height -1 do \n for j = 0 to width -1 do \n let c = mat.(i).(j) in \n if c = '\\000' then begin \n let h = find_h i j in \n let w = find_w i j in\n let l = min h w in \n let c = find_c i j in \n fill i j l c \n end\n done\n done;\n\n for i = 0 to height -1 do \n for j = 0 to width -1 do \n printf \"%c\" mat.(i).(j)\n done;\n newline()\n done\n "}], "src_uid": "f92757d0369327f63185aca802616ad7"} {"nl": {"description": "You are given a string $$$s$$$ of length $$$n$$$, which consists only of the first $$$k$$$ letters of the Latin alphabet. All letters in string $$$s$$$ are uppercase.A subsequence of string $$$s$$$ is a string that can be derived from $$$s$$$ by deleting some of its symbols without changing the order of the remaining symbols. For example, \"ADE\" and \"BD\" are subsequences of \"ABCDE\", but \"DEA\" is not.A subsequence of $$$s$$$ called good if the number of occurences of each of the first $$$k$$$ letters of the alphabet is the same.Find the length of the longest good subsequence of $$$s$$$. ", "input_spec": "The first line of the input contains integers $$$n$$$ ($$$1\\le n \\le 10^5$$$) and $$$k$$$ ($$$1 \\le k \\le 26$$$). The second line of the input contains the string $$$s$$$ of length $$$n$$$. String $$$s$$$ only contains uppercase letters from 'A' to the $$$k$$$-th letter of Latin alphabet.", "output_spec": "Print the only integer\u00a0\u2014 the length of the longest good subsequence of string $$$s$$$.", "sample_inputs": ["9 3\nACAABCCAB", "9 4\nABCABCABC"], "sample_outputs": ["6", "0"], "notes": "NoteIn the first example, \"ACBCAB\" (\"ACAABCCAB\") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence \"CAB\" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is $$$0$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done\n\tlet string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\nend open MyInt64\n\nlet () =\n\tlet n,k = get_2_i64 0 in\n\tlet a = scanf \" %s\" (fun v -> v) |> char_list_of_string |> Array.of_list\n\tin\n\tlet alp = Array.make (~|k) 0L in\n\tArray.iter (fun v -> \n\t\tlet p = (int_of_char v) -$ (int_of_char 'A')\n\t\tin\n\t\t(* printf \" %c:%d\\n\" v p *)\n\t\talp.(p) <- alp.(p) + 1L;\n\t) a;\n\tArray.fold_left (fun u v ->\n\t\tmin u v\n\t) Int64.max_int alp\n\t|> ( * ) k\n\t|> printf \"%Ld\\n\"\n"}], "negative_code": [], "src_uid": "d9d5db63b1e48214d02abe9977709384"} {"nl": {"description": "Alice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1\u2009\u00d7\u2009n table).At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1\u2009\u00d7\u2009a rectangle (that is, it occupies a sequence of a consecutive squares of the field). The ships cannot intersect and even touch each other.After that Bob makes a sequence of \"shots\". He names cells of the field and Alice either says that the cell is empty (\"miss\"), or that the cell belongs to some ship (\"hit\").But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a \"miss\". Help Bob catch Alice cheating \u2014 find Bob's first move, such that after it you can be sure that Alice cheated.", "input_spec": "The first line of the input contains three integers: n, k and a (1\u2009\u2264\u2009n,\u2009k,\u2009a\u2009\u2264\u20092\u00b7105) \u2014 the size of the field, the number of the ships and the size of each ship. It is guaranteed that the n, k and a are such that you can put k ships of size a on the field, so that no two ships intersect or touch each other. The second line contains integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009n) \u2014 the number of Bob's moves. The third line contains m distinct integers x1,\u2009x2,\u2009...,\u2009xm, where xi is the number of the cell where Bob made the i-th shot. The cells are numbered from left to right from 1 to n.", "output_spec": "Print a single integer \u2014 the number of such Bob's first move, after which you can be sure that Alice lied. Bob's moves are numbered from 1 to m in the order the were made. If the sought move doesn't exist, then print \"-1\".", "sample_inputs": ["11 3 3\n5\n4 8 6 1 11", "5 1 3\n2\n1 5", "5 1 3\n1\n3"], "sample_outputs": ["3", "-1", "1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let k = read_int () in\n let a = read_int () in\n let m = read_int () in\n let x = Array.init m (fun _ -> -1 + read_int()) in\n\n let feasible i =\n (* returns true iff bob's moves 0...i are feasible. *)\n let mark = Array.make n false in\n for j=0 to i do\n mark.(x.(j)) <- true\n done;\n\n let place_one_block j =\n (* return the place to start the next block, or -1 if \n\t can't place any block *)\n let rec pl j placed =\n\tif placed = a then j+1\n\telse if j>=n then -1\n\telse if mark.(j) then pl (j+1) 0\n\telse pl (j+1) (placed+1)\n in\n pl j 0\n in\n \n let rec fill j b_placed =\n if b_placed = k then true else\n\tlet j' = place_one_block j in\n\tif j' < 0 then false else fill j' (b_placed+1)\n in\n\n fill 0 0\n in\n\n let rec bsearch lo hi =\n (* lo < hi and lo is possible, hi is impossible *)\n if lo+1 = hi then hi else\n let m = (lo + hi) / 2 in\n if feasible m then bsearch m hi else bsearch lo m\n in\n\n let answer =\n if feasible (m-1) then -1 else 1 + bsearch (-1) (m-1)\n in\n\n printf \"%d\\n\" answer;\n"}, {"source_code": "module RangeMap = Map.Make(\n struct\n type t = int * int\n let compare (l1, r1) (l2, r2) =\n if r1 < l2 then -1\n else if r2 < l1 then 1\n else 0\n end)\n\nlet add elt s = RangeMap.add elt elt s\n\n(* n - size of playing field\n * k - number of ships\n * a - width of ship \n * m - number of moves *)\nlet () = Scanf.scanf \"%d %d %d\\n%d\\n\" (fun n k a m ->\n (* count number of ships that can fit in a k-wide space *)\n let count k = (k + 1) / (a + 1) in\n\n (* we want to maintain a bunch of intervals over which\n * it's possible for ships to fit *)\n let t = RangeMap.singleton (1, n) (1, n) in\n\n let rem = ref (count n) in\n\n let rec loop t i =\n if i <> m then\n let t' = Scanf.scanf \"%d%_c\" (fun x ->\n if RangeMap.mem (x, x) t\n then begin\n let l, r = RangeMap.find (x, x) t in\n rem := !rem - (count (r - l + 1)) + (count (x - l)) + (count (r - x));\n add (l, x - 1) (add (x + 1, r) (RangeMap.remove (x, x) t))\n end else t)\n in\n if !rem < k\n then Printf.printf \"%d\\n\" (i + 1)\n else loop t' (i + 1)\n in\n loop t 0;\n \n if !rem >= k then Printf.printf \"-1\\n\")\n"}], "negative_code": [], "src_uid": "e83c40f6d08b949900e5ae93b1d6f2c3"} {"nl": {"description": "You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk]\u2009=\u2009sp1sp2... spk(1\u2009\u2264\u2009p1\u2009<\u2009p2\u2009<\u2009...\u2009<\u2009pk\u2009\u2264\u2009|s|) a subsequence of string s\u2009=\u2009s1s2... s|s|.String x\u2009=\u2009x1x2... x|x| is lexicographically larger than string y\u2009=\u2009y1y2... y|y|, if either |x|\u2009>\u2009|y| and x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009x|y|\u2009=\u2009y|y|, or exists such number r (r\u2009<\u2009|x|,\u2009r\u2009<\u2009|y|), that x1\u2009=\u2009y1,\u2009x2\u2009=\u2009y2,\u2009... ,\u2009xr\u2009=\u2009yr and xr\u2009+\u20091\u2009>\u2009yr\u2009+\u20091. Characters in lines are compared like their ASCII codes.", "input_spec": "The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.", "output_spec": "Print the lexicographically maximum subsequence of string s.", "sample_inputs": ["ababba", "abbcbccacbbcbaaba"], "sample_outputs": ["bbba", "cccccbba"], "notes": "NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA"}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let c2i c = Char.code c - Char.code 'a' in\n let a = Array.make n 0 in\n let b = Array.make_matrix 26 n (-1) in\n for i = 0 to n - 1 do\n a.(i) <- c2i s.[i]\n done;\n for i = n - 2 downto 0 do\n for j = 0 to 25 do\n\tb.(j).(i) <- b.(j).(i + 1)\n done;\n b.(a.(i + 1)).(i) <- i + 1\n done;\n let pos =\n if a.(0) = 25\n then 0\n else (\n\tlet s = ref (-1) in\n\t for i = 0 to 25 do\n\t if b.(i).(0) >= 0\n\t then s := b.(i).(0)\n\t done;\n\t if !s < 0 || a.(0) >= a.(!s)\n\t then 0\n\t else !s\n )\n in\n let buf = Buffer.create n in\n let pos = ref pos in\n\twhile !pos >= 0 do\n\t Buffer.add_char buf s.[!pos];\n\t let p = !pos in\n\t pos := -1;\n\t for i = 0 to 25 do\n\t if b.(i).(p) >= 0\n\t then pos := b.(i).(p)\n\t done;\n\tdone;\n\tPrintf.printf \"%s\\n\" (Buffer.contents buf)\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let n = String.length s in\n let c2i c = Char.code c - Char.code 'a' in\n let a = Array.make n 0 in\n let b = Array.make_matrix 26 n (-1) in\n for i = 0 to n - 1 do\n a.(i) <- c2i s.[i]\n done;\n for i = n - 2 downto 0 do\n for j = 0 to 25 do\n\tb.(j).(i) <- b.(j).(i + 1)\n done;\n b.(a.(i + 1)).(i) <- i + 1\n done;\n let pos =\n if a.(0) = 25\n then 0\n else (\n\tlet s = ref (-1) in\n\t for i = 0 to 25 do\n\t if b.(i).(0) >= 0\n\t then s := b.(i).(0)\n\t done;\n\t !s\n )\n in\n let buf = Buffer.create n in\n let pos = ref pos in\n\twhile !pos >= 0 do\n\t Buffer.add_char buf s.[!pos];\n\t let p = !pos in\n\t pos := -1;\n\t for i = 0 to 25 do\n\t if b.(i).(p) >= 0\n\t then pos := b.(i).(p)\n\t done;\n\tdone;\n\tPrintf.printf \"%s\\n\" (Buffer.contents buf)\n"}], "src_uid": "77e2a6ba510987ed514fed3bd547b5ab"} {"nl": {"description": "You are given several queries. Each query consists of three integers $$$p$$$, $$$q$$$ and $$$b$$$. You need to answer whether the result of $$$p/q$$$ in notation with base $$$b$$$ is a finite fraction.A fraction in notation with base $$$b$$$ is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of queries. Next $$$n$$$ lines contain queries, one per line. Each line contains three integers $$$p$$$, $$$q$$$, and $$$b$$$ ($$$0 \\le p \\le 10^{18}$$$, $$$1 \\le q \\le 10^{18}$$$, $$$2 \\le b \\le 10^{18}$$$). All numbers are given in notation with base $$$10$$$.", "output_spec": "For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.", "sample_inputs": ["2\n6 12 10\n4 3 10", "4\n1 1 2\n9 36 2\n4 12 3\n3 5 4"], "sample_outputs": ["Finite\nInfinite", "Finite\nFinite\nFinite\nInfinite"], "notes": "Note$$$\\frac{6}{12} = \\frac{1}{2} = 0,5_{10}$$$$$$\\frac{4}{3} = 1,(3)_{10}$$$$$$\\frac{9}{36} = \\frac{1}{4} = 0,01_2$$$$$$\\frac{4}{12} = \\frac{1}{3} = 0,1_3$$$ "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet rec gcd a b = if a=0L then b else gcd (b %% a) a\n\nlet read_long _ = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet is_finite p q b =\n let g = gcd p q in\n let (p,q) = (p // g, q // g) in\n\n (* printf \"in is_finite g=%Ld p=%Ld q=%Ld\\n\" g p q; *)\n\n if p %% q = 0L then true else (\n let rec loop q =\n let g = gcd b q in\n(* printf \"g = %Ld q = %Ld\\n\" g q; *)\n if g = 1L then q = 1L else\n\tlet rec xloop q = if q %% g = 0L then xloop (q // g) else q in\n\tloop (xloop (q // g))\n in\n loop q\n )\n\nlet () = \n let n = read_int () in\n\n for i=1 to n do\n let p = read_long() in\n let q = read_long() in\n let b = read_long() in\n if is_finite p q b then printf \"Finite\\n\" else printf \"Infinite\\n\"\n done\n"}], "negative_code": [], "src_uid": "1b8c94f278ffbdf5b7fc38b3976252b6"} {"nl": {"description": "Ksusha is a beginner coder. Today she starts studying arrays. She has array a1,\u2009a2,\u2009...,\u2009an, consisting of n positive integers.Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), showing how many numbers the array has. The next line contains integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the array elements.", "output_spec": "Print a single integer \u2014 the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1. If there are multiple answers, you are allowed to print any of them.", "sample_inputs": ["3\n2 2 4", "5\n2 1 3 1 6", "3\n2 3 5"], "sample_outputs": ["2", "1", "-1"], "notes": null}, "positive_code": [{"source_code": "open List\nopen Printf\nopen Scanf\n\nlet inf= 1070000000;;\n\nlet rec getlist n =\n\tif n=0 then []\n\telse scanf \" %d\" (fun x->x)::getlist (n-1);;\n\nlet min a b = if ax)\nin let a = getlist n\nin let ans = min_ a\nin printf \"%d\\n\"\n\t(if for_all (fun x -> x mod ans = 0) a\n\t\tthen ans\n\t\telse (-1));;\n\n"}, {"source_code": "open List\nopen Printf\nopen Scanf\n\nlet inf= 1070000000;;\n\nlet rec getlist n =\n\tif n=0 then []\n\telse scanf \" %d\" (fun x->x)::getlist (n-1);;\n\nlet min a b = if ax)\nin let a = getlist n\nin let ans = min_ a\nin printf \"%d\\n\"\n\t(if for_all (fun x -> x mod ans = 0) a\n\t\tthen ans\n\t\telse -1);;\n"}], "negative_code": [], "src_uid": "b0ffab0bf169f8278af48fe2d58dcd2d"} {"nl": {"description": "Consider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xi\u2009\u2260\u2009yi).In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(n\u2009-\u20091) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers xi, yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009105;\u00a0xi\u2009\u2260\u2009yi) \u2014 the color numbers for the home and away kits of the i-th team.", "output_spec": "For each team, print on a single line two space-separated integers \u2014 the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.", "sample_inputs": ["2\n1 2\n2 1", "3\n1 2\n2 1\n1 3"], "sample_outputs": ["2 0\n2 0", "3 1\n4 0\n2 2"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet home=Array.make (n+1) 0;;\nlet away=Array.make (n+1) 0;;\nlet color=Array.make 100001 0;;\nlet color2=Array.make 100001 0;;\nfor i=1 to n-1 do\n let x=read_int() and y=read_int() in\n home.(i)<-x;\n away.(i)<-y;\n color.(x)<-color.(x)+1;\n color2.(y)<-color2.(y)+1\ndone;;\nlet x=read_int() and y=Scanf.scanf \"%d\" (fun x->x) in\n begin\n home.(n)<-x;\n away.(n)<-y;\n color.(x)<-color.(x)+1;\n color2.(y)<-color2.(y)+1\n end;;\nfor i=1 to n do\n Printf.printf \"%d \" (n-1+color.(away.(i)));\n Printf.printf \"%d\\n\" (n-1-color.(away.(i)))\ndone;;\n"}, {"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\n(* int *)\nlet intsqrt n = \n if n < 0 then raise (Invalid_argument \"sqrt of negative int\") else \n let rec bs a b = begin \n if b - a = 1 then a else \n let mid = (a+b)/2 in \n if mid*mid <= n then bs mid b else bs a mid\n end in \n bs 0 (1 lsl 31)\n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet default x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* tuple *)\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet _ = \n let len = read_int() in \n let ch = make len 0 in \n let ca = make len 0 in\n\n for i = 0 to len-1 do \n ch.(i) <- read_int();\n ca.(i) <- read_int();\n done; \n\n sort compare ch;\n\n let rec run i = \n if i = len then () else begin \n let rec lower_bound a b = \n if b - a = 1 then b else \n let mid = (a+b)/2 in \n if ch.(mid) >= ca.(i) then lower_bound a mid else lower_bound mid b \n in \n let rec upper_bound a b =\n if b - a = 1 then b else \n let mid = (a+b)/2 in \n if ch.(mid) <= ca.(i) then upper_bound mid b else upper_bound a mid \n in \n let n = upper_bound (-1) len - lower_bound (-1) len in \n printf \"%d %d\\n\" (len-1+n) (len-1-n);\n run (i+1)\n end\n in \n run 0"}], "negative_code": [{"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\n(* int *)\nlet intsqrt n = \n if n < 0 then raise (Invalid_argument \"sqrt of negative int\") else \n let rec bs a b = begin \n if b - a = 1 then a else \n let mid = (a+b)/2 in \n if mid*mid <= n then bs mid b else bs a mid\n end in \n bs 0 (1 lsl 31)\n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet default x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* tuple *)\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create 1_000_000 in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet _ = \n let len = read_int() in \n let ch = make len 0 in \n let ca = make len 0 in\n\n for i = 0 to len-1 do \n ch.(i) <- read_int();\n ca.(i) <- read_int();\n done; \n\n sort compare ch;\n\n let rec run i = \n if i = len then () else begin \n let rec lower_bound a b = \n if b - a = 1 then b else \n let mid = (a+b)/2 in \n if ch.(mid) >= ca.(i) then lower_bound a mid else lower_bound mid b \n in \n let rec upper_bound a b =\n if b - a = 1 then b else \n let mid = (a+b)/2 in \n if ch.(mid) <= ca.(i) then upper_bound mid b else upper_bound a mid \n in \n let n = upper_bound 0 len - lower_bound (-1) len in \n printf \"%d %d\\n\" (len-1+n) (len-1-n);\n run (i+1)\n end\n in \n run 0"}], "src_uid": "7899a22cee29bb96d671f6188f246c21"} {"nl": {"description": "The scientists have recently discovered wormholes\u00a0\u2014 objects in space that allow to travel very long distances between galaxies and star systems. The scientists know that there are n galaxies within reach. You are in the galaxy number 1 and you need to get to the galaxy number n. To get from galaxy i to galaxy j, you need to fly onto a wormhole (i,\u2009j) and in exactly one galaxy day you will find yourself in galaxy j. Unfortunately, the required wormhole is not always available. Every galaxy day they disappear and appear at random. However, the state of wormholes does not change within one galaxy day. A wormhole from galaxy i to galaxy j exists during each galaxy day taken separately with probability pij. You can always find out what wormholes exist at the given moment. At each moment you can either travel to another galaxy through one of wormholes that exist at this moment or you can simply wait for one galaxy day to see which wormholes will lead from your current position at the next day.Your task is to find the expected value of time needed to travel from galaxy 1 to galaxy n, if you act in the optimal way. It is guaranteed that this expected value exists.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of galaxies within reach. Then follows a matrix of n rows and n columns. Each element pij represents the probability that there is a wormhole from galaxy i to galaxy j. All the probabilities are given in percents and are integers. It is guaranteed that all the elements on the main diagonal are equal to 100.", "output_spec": "Print a single real value\u00a0\u2014 the expected value of the time needed to travel from galaxy 1 to galaxy n if one acts in an optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20096. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .", "sample_inputs": ["3\n100 50 50\n0 100 80\n0 0 100", "2\n100 30\n40 100"], "sample_outputs": ["1.750000000000000", "3.333333333333333"], "notes": "NoteIn the second sample the wormhole from galaxy 1 to galaxy 2 appears every day with probability equal to 0.3. The expected value of days one needs to wait before this event occurs is ."}, "positive_code": [{"source_code": "let n = Scanf.scanf \"%d\" (fun x->x) ;;\nlet m = Array.make_matrix n n 0. ;;\nfor i = 0 to n-1 do\nfor j = 0 to n-1 do\n m.(i).(j) <- Scanf.scanf \" %f\" (fun x -> x *. 0.01)\ndone done ;;\n\nlet e pg pgeg = (pgeg +. 1.) /. pg -. 1. ;;\n\nlet rec emin (h::t) =\n let (_, pg, pgeg) = h in\n let xh = e pg pgeg in\n match t with\n | [] -> (xh, h, [])\n | t -> let (xmn, vmn, rest) = emin t in\n if xh < xmn\n then (xh, h, t)\n else (xmn, vmn, h::rest)\n;;\nlet rec f i x nd =\n if i = 0\n then x\n else\n let nd2 = List.rev_map (fun (j, pg, egpg)\n -> let apg = (1. -. pg) *. m.(j).(i) in\n (j, pg +. apg, egpg +. apg *. (1. +. x))\n ) nd in\n let (x2, (j, _, _), nd3) = emin nd2 in\n f j x2 nd3\n;;\n\nlet rec n_zero = function\n | 0 -> []\n | n -> (n-1, 0., 0.)::n_zero (n-1)\n;;\nprint_float @@ f (n-1) 0. (n_zero (n-1))\n"}], "negative_code": [], "src_uid": "85cc3e02f30f810a97c48df5dfb844b8"} {"nl": {"description": "Given an array $$$a=[a_1,a_2,\\dots,a_n]$$$ of $$$n$$$ positive integers, you can do operations of two types on it: Add $$$1$$$ to every element with an odd index. In other words change the array as follows: $$$a_1 := a_1 +1, a_3 := a_3 + 1, a_5 := a_5+1, \\dots$$$. Add $$$1$$$ to every element with an even index. In other words change the array as follows: $$$a_2 := a_2 +1, a_4 := a_4 + 1, a_6 := a_6+1, \\dots$$$.Determine if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers. In other words, determine if you can make all elements of the array have the same parity after any number of operations.Note that you can do operations of both types any number of times (even none). Operations of different types can be performed a different number of times.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$)\u00a0\u2014 the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \\leq n \\leq 50$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\leq a_i \\leq 10^3$$$)\u00a0\u2014 the elements of the array. Note that after the performed operations the elements in the array can become greater than $$$10^3$$$.", "output_spec": "Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output \"YES\" if after any number of operations it is possible to make the final array contain only even numbers or only odd numbers, and \"NO\" otherwise. You can output the answer in any case (for example, the strings \"yEs\", \"yes\", \"Yes\" and \"YES\" will be recognized as a positive answer).", "sample_inputs": ["4\n\n3\n\n1 2 1\n\n4\n\n2 2 2 3\n\n4\n\n2 2 2 2\n\n5\n\n1000 1 1000 1 1000"], "sample_outputs": ["YES\nNO\nYES\nYES"], "notes": "NoteFor the first test case, we can increment the elements with an even index, obtaining the array $$$[1, 3, 1]$$$, which contains only odd numbers, so the answer is \"YES\".For the second test case, we can show that after performing any number of operations we won't be able to make all elements have the same parity, so the answer is \"NO\".For the third test case, all elements already have the same parity so the answer is \"YES\".For the fourth test case, we can perform one operation and increase all elements at odd positions by $$$1$$$, thus obtaining the array $$$[1001, 1, 1001, 1, 1001]$$$, and all elements become odd so the answer is \"YES\"."}, "positive_code": [{"source_code": "let id x = x\n\nmodule S = struct\n open String\n\n let split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = length s - 1 downto 0 do\n if unsafe_get s i = sep then begin\n r := sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n sub s 0 !j :: !r\nend\n\nlet alternating xs =\n let (result, _) =\n List.fold_left\n (fun prevResult curr ->\n match prevResult with\n | (false, _) -> (false, Some curr)\n | (true, Some x) -> (x <> curr, Some curr)\n | (true, None) -> (true, Some curr))\n (true, None)\n xs\n in\n result\n\nlet eq xs =\n let (result, _) =\n List.fold_left\n (fun prevResult curr ->\n match prevResult with\n | (false, _) -> (false, Some curr)\n | (true, Some x) -> (x = curr, Some curr)\n | (true, None) -> (true, Some curr))\n (true, None)\n xs\n in\n result\n\nlet solve () =\n let _ = Scanf.scanf \"%d\\n\" id in\n let xs =\n Scanf.scanf \"%s@\\n\" (fun x -> x)\n |> S.split_on_char ' '\n |> List.filter (fun x -> x <> \"\")\n |> List.map int_of_string\n |> List.map (fun x -> x mod 2)\n in\n if eq xs || alternating xs then\n print_endline \"YES\"\n else\n print_endline \"NO\"\n\nlet () =\n let t = Scanf.scanf \"%d\\n\" id in\n for i = 1 to t do\n solve ()\n done\n"}, {"source_code": "let getInt () = Scanf.scanf \" %d\" (fun i -> i);;\r\n\r\nlet getList(n): int list = \r\n let rec getList2 ((n: int), (acc: int list)) = match n with\r\n\t | 0 -> List.rev acc\r\n\t | _ -> getList2 (n-1, getInt() :: acc)\r\n in getList2(n, [])\r\nlet rec f((arr: int list), (curr: int)) = \r\n match arr with\r\n | [] -> true\r\n | v1::(v2 :: xs) -> if (v1 mod 2) = curr then f(xs, curr) else false\r\n | v1::[] -> if (v1 mod 2) = curr then true else false;;\r\n\r\nlet main() = \r\n let t = getInt() in\r\n for i = 1 to t do \r\n let n = getInt() in let (arr: int list) = getList(n)\r\n in let a = (f(arr, 0) || f(arr, 1)) in let b = (f(List.tl(arr),0) || f(List.tl(arr), 1)) in \r\n if (a && b) then print_endline(\"YES\")\r\n else print_endline(\"NO\")\r\n done;;\r\n\r\nlet x = f([2;2;2;2], 0);;\r\nmain();;\r\n\r\n\r\n"}], "negative_code": [], "src_uid": "fbb4e1cf1cad47481c6690ce54b27a1e"} {"nl": {"description": "This is an interactive problem!An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element ($$$x_i - x_{i - 1}$$$, where $$$i \\ge 2$$$) is constant\u00a0\u2014 such difference is called a common difference of the sequence.That is, an arithmetic progression is a sequence of form $$$x_i = x_1 + (i - 1) d$$$, where $$$d$$$ is a common difference of the sequence.There is a secret list of $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$.It is guaranteed that all elements $$$a_1, a_2, \\ldots, a_n$$$ are between $$$0$$$ and $$$10^9$$$, inclusive.This list is special: if sorted in increasing order, it will form an arithmetic progression with positive common difference ($$$d > 0$$$). For example, the list $$$[14, 24, 9, 19]$$$ satisfies this requirement, after sorting it makes a list $$$[9, 14, 19, 24]$$$, which can be produced as $$$x_n = 9 + 5 \\cdot (n - 1)$$$.Also you are also given a device, which has a quite discharged battery, thus you can only use it to perform at most $$$60$$$ queries of following two types: Given a value $$$i$$$ ($$$1 \\le i \\le n$$$), the device will show the value of the $$$a_i$$$. Given a value $$$x$$$ ($$$0 \\le x \\le 10^9$$$), the device will return $$$1$$$ if an element with a value strictly greater than $$$x$$$ exists, and it will return $$$0$$$ otherwise.Your can use this special device for at most $$$60$$$ queries. Could you please find out the smallest element and the common difference of the sequence? That is, values $$$x_1$$$ and $$$d$$$ in the definition of the arithmetic progression. Note that the array $$$a$$$ is not sorted.", "input_spec": null, "output_spec": null, "sample_inputs": ["4\n\n0\n\n1\n\n14\n\n24\n\n9\n\n19"], "sample_outputs": ["> 25\n\n> 15\n\n? 1\n\n? 2\n\n? 3\n\n? 4\n\n! 9 5"], "notes": "NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The list in the example test is $$$[14, 24, 9, 19]$$$."}, "positive_code": [{"source_code": "open Printf\nopen String\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet split_string s = \n let s = trim s in\n \n let n = String.length s in\n let li = fold 0 (n-1) \n (fun i ac -> if s.[i] = ' ' then i::ac else ac) []\n in\n\n let rec chop prev li ac = \n match li with [] -> List.rev ac\n | i::tail -> \n\tchop i tail ((sub s (prev+1) (i-prev-1))::ac)\n in\n \n chop (-1) (List.rev (n::li)) []\n\nlet read_int() =\n int_of_string(List.hd(split_string(read_line())))\n\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a \n\nlet bound = 1_000_000_000\n \nlet () =\n let n = read_int() in\n let rec bsearch lo hi = (* lo < maxval <= hi *)\n if lo+1 = hi then hi else \n let m = lo + (hi-lo)/2 in\n printf \"> %d\\n%!\" m;\n if read_int() = 1 then bsearch m hi else bsearch lo m\n in\n let maxa = bsearch (-1) bound in\n\n Random.self_init();\n \n let rec loop i g = if i=0 then g else (\n printf \"? %d\\n%!\" (1+Random.int n);\n let r = read_int() in\n let g = if r = maxa then g else gcd g (abs (r-maxa)) in\n loop (i-1) g\n ) in\n\n let diff = loop 30 0 in\n\n printf \"! %d %d\\n%!\" (maxa - (n-1) * diff) diff\n"}], "negative_code": [], "src_uid": "36619f520ea5a523a94347ffd3dc2c70"} {"nl": {"description": "Santa has $$$n$$$ candies and he wants to gift them to $$$k$$$ kids. He wants to divide as many candies as possible between all $$$k$$$ kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.Suppose the kid who recieves the minimum number of candies has $$$a$$$ candies and the kid who recieves the maximum number of candies has $$$b$$$ candies. Then Santa will be satisfied, if the both conditions are met at the same time: $$$b - a \\le 1$$$ (it means $$$b = a$$$ or $$$b = a + 1$$$); the number of kids who has $$$a+1$$$ candies (note that $$$a+1$$$ not necessarily equals $$$b$$$) does not exceed $$$\\lfloor\\frac{k}{2}\\rfloor$$$ (less than or equal to $$$\\lfloor\\frac{k}{2}\\rfloor$$$). $$$\\lfloor\\frac{k}{2}\\rfloor$$$ is $$$k$$$ divided by $$$2$$$ and rounded down to the nearest integer. For example, if $$$k=5$$$ then $$$\\lfloor\\frac{k}{2}\\rfloor=\\lfloor\\frac{5}{2}\\rfloor=2$$$.Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 5 \\cdot 10^4$$$) \u2014 the number of test cases. The next $$$t$$$ lines describe test cases. The $$$i$$$-th test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 10^9$$$) \u2014 the number of candies and the number of kids.", "output_spec": "For each test case print the answer on it \u2014 the maximum number of candies Santa can give to kids so that he will be satisfied.", "sample_inputs": ["5\n5 2\n19 4\n12 7\n6 2\n100000 50010"], "sample_outputs": ["5\n18\n10\n6\n75015"], "notes": "NoteIn the first test case, Santa can give $$$3$$$ and $$$2$$$ candies to kids. There $$$a=2, b=3,a+1=3$$$.In the second test case, Santa can give $$$5, 5, 4$$$ and $$$4$$$ candies. There $$$a=4,b=5,a+1=5$$$. The answer cannot be greater because then the number of kids with $$$5$$$ candies will be $$$3$$$.In the third test case, Santa can distribute candies in the following way: $$$[1, 2, 2, 1, 1, 2, 1]$$$. There $$$a=1,b=2,a+1=2$$$. He cannot distribute two remaining candies in a way to be satisfied.In the fourth test case, Santa can distribute candies in the following way: $$$[3, 3]$$$. There $$$a=3, b=3, a+1=4$$$. Santa distributed all $$$6$$$ candies."}, "positive_code": [{"source_code": "let f n k =\n let a = n / k in (* minimum candies *)\n let r = n - a * k in (* remainder *)\n a * k + min r (k / 2)\n\nlet () =\n let n = read_int () in\n for i = 1 to n do\n let t = Scanf.scanf \"%d %d\\n\" f in\n Printf.printf \"%d\\n\" t\n done\n"}], "negative_code": [], "src_uid": "43b8e9fb2bd0ec5e0250a33594417f63"} {"nl": {"description": "Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be the one qualified, he tells Iahub the following task.You're given an (1-based) array a with n elements. Let's define function f(i,\u2009j) (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n) as (i\u2009-\u2009j)2\u2009+\u2009g(i,\u2009j)2. Function g is calculated by the following pseudo-code:int g(int i, int j) { int sum = 0; for (int k = min(i, j) + 1; k <= max(i, j); k = k + 1) sum = sum + a[k]; return sum;}Find a value mini\u2009\u2260\u2009j\u00a0\u00a0f(i,\u2009j).Probably by now Iahub already figured out the solution to this problem. Can you?", "input_spec": "The first line of input contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100000). Next line contains n integers a[1], a[2], ..., a[n] (\u2009-\u2009104\u2009\u2264\u2009a[i]\u2009\u2264\u2009104). ", "output_spec": "Output a single integer \u2014 the value of mini\u2009\u2260\u2009j\u00a0\u00a0f(i,\u2009j).", "sample_inputs": ["4\n1 0 0 -1", "2\n1 -1"], "sample_outputs": ["1", "2"], "notes": null}, "positive_code": [{"source_code": "(* This is a thinly veiled 2D closest pair problem. I'll use\n Sariel's linear time algorithm. http://sarielhp.org/blog/?p=51\n\n*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet ( ++ ) a b = Int64.add a b\n\nlet sq x = x *. x\n\nlet closest_pair n p =\n let dist i j =\n let (xi,yi) = p.(i) in\n let (xj,yj) = p.(j) in\n sqrt ((sq (xi -. xj)) +. (sq (yi -. yj)))\n in\n\n let truncate x r = int_of_float (floor (x /. r)) in\n let boxify (x,y) r = (truncate x r, truncate y r) in\n\n let getbox h box = try Hashtbl.find h box with Not_found -> [] in\n\n let add_to_h h i box = \n Hashtbl.replace h box (i::(getbox h box))\n in\n\n let make_grid i r =\n (* put points p.(0) ... p.(i) into a new grid of size r.\n it has already been established that the closest pair\n in that point set has distance r *)\n let h = Hashtbl.create 10 in\n\n for j=0 to i do\n add_to_h h j (boxify p.(j) r)\n done;\n h\n in\n\n let rec loop h i r =\n (* already built the table for points 0...i, and they have dist r *)\n\n if i=n-1 then r else \n let i = i+1 in\n let (ix,iy) = boxify p.(i) r in\n let li = ref [] in\n for x = ix-1 to ix+1 do\n\tfor y = iy-1 to iy+1 do\n\t li := (getbox h (x,y)) @ !li\n\tdone\n done;\n\n let r' = List.fold_left (\n\tfun ac j -> min (dist i j) ac\n ) max_float !li in\n \n if r' < r then (\n\tloop (make_grid i r') i r'\n ) else (\n\tadd_to_h h i (boxify p.(i) r);\n\tloop h i r\n )\n in\n\n let r0 = dist 0 1 in\n loop (make_grid 1 r0) 1 r0\n\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_long()) in\n \n let s = Array.copy a in\n\n for i=1 to n-1 do\n s.(i) <- s.(i-1) ++ s.(i)\n done;\n\n let p = Array.init n (fun i -> (float i, Int64.to_float s.(i))) in\n\n Random.init 78458348;\n\n let swap i j = \n let (pi,pj) = (p.(i),p.(j)) in\n p.(i) <- pj;\n p.(j) <- pi\n in\n\n for i=0 to n-2 do\n let r = Random.int (n-i) in\n swap i (i+r)\n done;\n\n let dist = closest_pair n p in\n \n let idist2 = Int64.of_float (floor ((sq dist) +. 0.5)) in\n \n printf \"%Ld\\n\" idist2\n"}], "negative_code": [{"source_code": "(* This is a thinly veiled 2D closest pair problem. I'll use\n Sariel's linear time algorithm. http://sarielhp.org/blog/?p=51\n\n*)\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet ( ++ ) a b = Int64.add a b\n\nlet sq x = x *. x\n\nlet closest_pair n p =\n let dist i j =\n let (xi,yi) = p.(i) in\n let (xj,yj) = p.(j) in\n sqrt ((sq (xi -. xj)) +. (sq (yi -. yj)))\n in\n\n let truncate x r = int_of_float (floor (x /. r)) in\n let boxify (x,y) r = (truncate x r, truncate y r) in\n\n let getbox h box = try Hashtbl.find h box with Not_found -> [] in\n\n let add_to_h h i box = \n Hashtbl.replace h box (i::(getbox h box))\n in\n\n let make_grid i r =\n (* put points p.(0) ... p.(i) into a new grid of size r.\n it has already been established that the closest pair\n in that point set has distance r *)\n let h = Hashtbl.create 10 in\n\n for j=0 to i do\n add_to_h h j (boxify p.(j) r)\n done;\n h\n in\n\n let rec loop h i r =\n (* already built the table for points 0...i, and they have dist r *)\n\n if i=n-1 then r else \n let i = i+1 in\n let (ix,iy) = boxify p.(i) r in\n let li = ref [] in\n for x = ix-1 to ix+1 do\n\tfor y = iy-1 to iy+1 do\n\t li := (getbox h (x,y)) @ !li\n\tdone\n done;\n\n let r' = List.fold_left (\n\tfun ac j -> min (dist i j) ac\n ) max_float !li in\n \n if r' < r then\n\tloop (make_grid i r') i r'\n else \n\tloop h i r\n in\n\n let r0 = dist 0 1 in\n loop (make_grid 1 r0) 1 r0\n\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_long()) in\n \n let s = Array.copy a in\n\n for i=1 to n-1 do\n s.(i) <- s.(i-1) ++ s.(i)\n done;\n\n let p = Array.init n (fun i -> (float i, Int64.to_float s.(i))) in\n\n Random.init 78458348;\n\n let swap i j = \n let (pi,pj) = (p.(i),p.(j)) in\n p.(i) <- pj;\n p.(j) <- pi\n in\n\n for i=0 to n-2 do\n let r = Random.int (n-i) in\n swap i (i+r)\n done;\n\n let dist = closest_pair n p in\n \n let idist2 = Int64.of_float (floor ((sq dist) +. 0.5)) in\n \n printf \"%Ld\\n\" idist2\n"}], "src_uid": "74da42a1627e4a00fbaae91c75140287"} {"nl": {"description": "Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. Then he wondered, how much orange juice the cocktail has.Find the volume fraction of orange juice in the final drink.", "input_spec": "The first input line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of orange-containing drinks in Vasya's fridge. The second line contains n integers pi (0\u2009\u2264\u2009pi\u2009\u2264\u2009100) \u2014 the volume fraction of orange juice in the i-th drink, in percent. The numbers are separated by a space.", "output_spec": "Print the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10\u2009\u2009-\u20094.", "sample_inputs": ["3\n50 50 100", "4\n0 25 50 75"], "sample_outputs": ["66.666666666667", "37.500000000000"], "notes": "NoteNote to the first sample: let's assume that Vasya takes x milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal milliliters. The total cocktail's volume equals 3\u00b7x milliliters, so the volume fraction of the juice in the cocktail equals , that is, 66.(6) percent."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet input () = \n let n = read () in\n let rec loop i juices =\n if i < n\n then\n let var = Pervasives.float (read ()) in\n loop (i + 1) (var :: juices)\n else\n (Pervasives.float n, juices)\n in loop 0 []\n\nlet solve (n, juices) = \n let sum = List.fold_left (fun n m -> n +. m) 0.0 juices in\n sum /. n\n\nlet print result = Printf.printf \"%.10f\\n\" result\nlet () = print (solve (input ()))"}], "negative_code": [], "src_uid": "580596d05a2eaa36d630d71ef1055c43"} {"nl": {"description": "All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi \u2014 a coordinate on the Ox axis. No two cities are located at a single point.Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.For each city calculate two values \u200b\u200bmini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, and maxi is the the maximum cost of sending a letter from the i-th city to some other city", "input_spec": "The first line of the input contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cities in Lineland. The second line contains the sequence of n distinct integers x1,\u2009x2,\u2009...,\u2009xn (\u2009-\u2009109\u2009\u2264\u2009xi\u2009\u2264\u2009109), where xi is the x-coordinate of the i-th city. All the xi's are distinct and follow in ascending order.", "output_spec": "Print n lines, the i-th line must contain two integers mini,\u2009maxi, separated by a space, where mini is the minimum cost of sending a letter from the i-th city, and maxi is the maximum cost of sending a letter from the i-th city.", "sample_inputs": ["4\n-5 -2 2 7", "2\n-1 1"], "sample_outputs": ["3 12\n3 9\n4 7\n5 12", "2 2\n2 2"], "notes": null}, "positive_code": [{"source_code": "let (--) = Int64.sub\nlet zero = Int64.zero\n\nlet read_int () = Scanf.scanf \"%d \" (fun n -> n)\nlet read_int64 () = Scanf.scanf \"%Ld \" (fun n -> n)\nlet print (min, max) = Printf.printf \"%Ld %Ld\\n\" min max\n\nlet make_array () = \n let n = read_int () in\n let array = Array.make n zero in\n let rec loop i array = \n if i < n\n then\n let city = read_int64 () in\n let () = Array.set array i city in\n loop (i + 1) array\n else\n (n, array)\n in loop 0 array\n\nlet get_min_max (n, array) i curr =\n let min =\n if i = 0\n then\n array.(i + 1) -- curr\n else\n if i = n - 1\n then\n curr -- array.(i - 1)\n else\n Pervasives.min (curr -- array.(i - 1)) (array.(i + 1) -- curr)\n in\n let max = Pervasives.max (curr -- array.(0)) (array.(n - 1) -- curr) in\n print (min, max)\n\nlet () = \n let (n, cities) = make_array () in\n Array.iteri (get_min_max (n, cities)) cities"}, {"source_code": "let (--) = Int64.sub\nlet zero = Int64.zero\n\nlet read_int () = Scanf.scanf \"%d \" (fun n -> n)\nlet read_int64 () = Scanf.scanf \"%Ld \" (fun n -> n)\nlet print (min, max) = Printf.printf \"%Ld %Ld\\n\" min max\n\nlet make_array () = \n let n = read_int () in\n let array = Array.make n zero in\n let rec loop i array = \n if i < n\n then\n let city = read_int64 () in\n let () = Array.set array i city in\n loop (i + 1) array\n else\n (n, array)\n in loop 0 array\n\nlet get_first_last (n, array) =\n let first = array.(0) in\n let last = array.(n - 1) in\n (first, last) \n \nlet get_min_max (first, last) (n, array) i curr = \n if i = 0\n then\n let min = array.(i + 1) -- curr in\n let max = last -- curr in\n print (min, max)\n else\n if i = n - 1\n then\n let min = curr -- array.(i - 1) in\n let max = curr -- first in\n print (min, max)\n else\n let min = Pervasives.min (curr -- array.(i - 1)) (array.(i + 1) -- curr) in\n let max = Pervasives.max (curr -- first) (last -- curr) in\n print (min, max)\n\nlet () = \n let (n, cities) = make_array () in\n let (first, last) = get_first_last (n, cities) in\n Array.iteri (get_min_max (first, last) (n, cities)) cities"}, {"source_code": "let read_int () = Scanf.scanf \"%d \" (fun n -> n)\nlet read_int64 () = Scanf.scanf \"%Ld \" (fun n -> n)\n\nlet make_array () = \n let n = read_int () in\n let array = Array.make n Int64.zero in\n let rec loop i array = \n if i < n\n then\n let city = read_int64 () in\n let () = Array.set array i city in\n loop (i + 1) array\n else\n (n, array)\n in loop 0 array\n\nlet get_min_max (n, array) =\n let first = array.(0) in\n let last = array.(n - 1) in\n let rec loop i list =\n if i < n\n then\n let curr = array.(i) in\n let min_max =\n if i = 0\n then\n let min = Int64.sub array.(i + 1) curr in\n let max = Int64.sub last curr in\n (min, max)\n else\n if i = n - 1\n then\n let min = Int64.sub curr array.(i - 1) in\n let max = Int64.sub curr first in\n (min, max)\n else\n let min = Pervasives.min (Int64.sub curr array.(i - 1)) (Int64.sub array.(i + 1) curr) in\n let max = Pervasives.max (Int64.sub curr first) (Int64.sub last curr) in\n (min, max)\n in loop (i + 1) (min_max :: list)\n else\n List.rev list\n in loop 0 []\n\nlet print list = List.iter (fun (min, max) -> Printf.printf \"%Ld %Ld\\n\" min max) list\n\nlet () = print (get_min_max (make_array ()))"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = Array.init n (fun _ -> long (read_int())) in\n\n Array.sort compare x;\n\n let inf = 1_000_000_000_000L in\n let closest i =\n let li = [] in\n let li = if i=0 then li else (x.(i) -- x.(i-1))::li in\n let li = if i=n-1 then li else (x.(i+1) -- x.(i))::li in\n List.fold_left (fun ac x -> min ac x) inf li\n in\n\n let farthest i =\n let li = [x.(n-1) -- x.(i); x.(i) -- x.(0)] in\n List.fold_left (fun ac x -> max ac x) 0L li\n in\n\n for i=0 to n-1 do\n printf \"%Ld %Ld\\n\" (closest i) (farthest i)\n done;\n"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let a = Array.init n (fun _ -> Scanf.scanf \"%Ld%_c\" (fun x -> x)) in\n let (--) = Int64.sub in\n Array.iteri (fun i x ->\n let mn, mx =\n if i = 0\n then (a.(1) -- x, a.(n - 1) -- x)\n else if i = n - 1\n then (x -- a.(i - 1), x -- a.(0))\n else (min (x -- a.(i - 1)) (a.(i + 1) -- x),\n max (x -- a.(0)) (a.(n - 1) -- x))\n in Printf.printf \"%Ld %Ld\\n\" mn mx) a)\n"}], "negative_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet make_array () = \n let n = read () in\n let array = Array.make n 0 in\n let rec loop i array = \n if i < n\n then\n let city = read () in\n let () = Array.set array i city in\n loop (i + 1) array\n else\n (n, array)\n in loop 0 array\n\nlet get_min_max (n, array) =\n let first = array.(0) in\n let last = array.(n - 1) in\n let rec loop i list =\n if i < n\n then\n let curr = array.(i) in\n let min_max =\n if i = 0\n then\n let min = array.(i + 1) - curr in\n let max = last - curr in\n (min, max)\n else\n if i = n - 1\n then\n let min = curr - array.(i - 1) in\n let max = curr - first in\n (min, max)\n else\n let min = Pervasives.min (curr - array.(i - 1)) (array.(i + 1) - curr) in\n let max = Pervasives.max (curr - first) (last - curr) in\n (min, max)\n in loop (i + 1) (min_max :: list)\n else\n List.rev list\n in loop 0 []\n\nlet print list = List.iter (fun (min, max) -> Printf.printf \"%d %d\\n\" min max) list\n\nlet () = print (get_min_max (make_array ()))"}, {"source_code": "let () = Scanf.scanf \"%d\\n\" (fun n ->\n let a = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n Array.iteri (fun i x ->\n let mn, mx =\n if i = 0\n then (a.(1) - x, a.(n - 1) - x)\n else if i = n - 1\n then (x - a.(i - 1), x - a.(0))\n else (min (x - a.(i - 1)) (a.(i + 1) - x),\n max (x - a.(0)) (a.(n - 1) - x))\n in Printf.printf \"%d %d\\n\" mn mx) a)\n"}], "src_uid": "55383f13c8d097408b0ccf5653c4563d"} {"nl": {"description": "Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x\u2009+\u2009k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water \"move in turns\" \u2014 first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u2009105) \u2014 the height of the canyon and the height of ninja's jump, correspondingly. The second line contains the description of the left wall \u2014 a string with the length of n characters. The i-th character represents the state of the i-th wall area: character \"X\" represents a dangerous area and character \"-\" represents a safe area. The third line describes the right wall in the same format. It is guaranteed that the first area of the left wall is not dangerous.", "output_spec": "Print \"YES\" (without the quotes) if the ninja can get out from the canyon, otherwise, print \"NO\" (without the quotes).", "sample_inputs": ["7 3\n---X--X\n-X--XX-", "6 2\n--X-X-\nX--XX-"], "sample_outputs": ["YES", "NO"], "notes": "NoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon."}, "positive_code": [{"source_code": "exception Found\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let kk = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let sl = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let sr = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let s = [| sl; sr |] in\n let used = Array.make_matrix 2 n false in\n (*let d = Array.make_matrix 2 n (-1) in*)\n let q1 = Array.make (n * 2) (0, 0) in\n let l1 = ref 0 in\n let q2 = Array.make (n * 2) (0, 0) in\n let l2 = ref 0 in\n let rec bfs_step k q1 l1 q2 l2 =\n l2 := 0;\n for i = 0 to !l1 - 1 do\n let (x, y) = q1.(i) in\n\tif y - 1 > k && s.(x).[y - 1] <> 'X' then (\n\t if not used.(x).(y - 1) then (\n\t used.(x).(y - 1) <- true;\n\t q2.(!l2) <- (x, y - 1);\n\t incr l2\n\t );\n\t);\n\tif y + 1 >= n\n\tthen raise Found;\n\tif s.(x).[y + 1] <> 'X' then (\n\t if not used.(x).(y + 1) then (\n\t used.(x).(y + 1) <- true;\n\t q2.(!l2) <- (x, y + 1);\n\t incr l2\n\t );\n\t);\n\tif y + kk >= n\n\tthen raise Found;\n\tif s.(1 - x).[y + kk] <> 'X' then (\n\t if not used.(1 - x).(y + kk) then (\n\t used.(1 - x).(y + kk) <- true;\n\t q2.(!l2) <- (1 - x, y + kk);\n\t incr l2\n\t );\n\t);\n done;\n if !l2 > 0\n then bfs_step (k + 1) q2 l2 q1 l1\n in\n used.(0).(0) <- true;\n l1 := 0;\n l2 := 0;\n q1.(!l1) <- (0, 0);\n incr l1;\n try\n bfs_step 0 q1 l1 q2 l2;\n Printf.printf \"NO\\n\"\n with\n | Found ->\n\t Printf.printf \"YES\\n\"\n"}, {"source_code": "\nmodule NodeSet = Set.Make (struct \n type t = int * bool\n let compare x y = compare x y\nend)\n\nlet rec bfs que nodes level visited n k =\n if NodeSet.is_empty que then\n false\n else if NodeSet.max_elt que >= (n,false) then\n true\n else if level > n then\n false\n else\n let nque,visited = NodeSet.fold (fun (x,b) (nque,visited) ->\n if NodeSet.mem (x,b) visited then\n nque,visited\n else\n let visited = NodeSet.add (x,b) visited in\n let next = [(x+1,b);(x-1,b);(x+k,not b)] in\n List.fold_left (fun e (x,b) -> \n if x > level && (NodeSet.mem (x,b) nodes|| x > n) then\n (* let () = print_endline (\"(\"^string_of_int x^\",\"\n ^string_of_bool b^\",\"\n ^string_of_int level^\")\")in\n *) NodeSet.add (x,b) e\n else\n e) nque next,visited) que (NodeSet.empty,visited) in\n bfs nque nodes (level+1) visited n k\n\nlet solve s1 s2 n k =\n let nodes = ref NodeSet.empty in\n let i = ref 0 in\n let () = String.iter (function\n | '-' -> nodes := NodeSet.add (!i,false) !nodes; i := !i+1;\n | _ -> i := !i+1) s1 in\n let () = i := 0 in\n let () = String.iter (function\n | '-' -> nodes := NodeSet.add (!i,true) !nodes; i := !i+1;\n | _ -> i := !i+1) s2 in\n bfs (NodeSet.singleton (0,false)) !nodes 0 NodeSet.empty (n-1) k\n \nlet main () =\n let rval = Scanf.bscanf Scanf.Scanning.stdib \"%d %d\\n%s\\n%s\\n\" \n (fun n k s1 s2 -> solve s1 s2 n k) in\n if rval then\n print_endline \"YES\"\n else\n print_endline \"NO\"\n\nlet _ = main ()\n"}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_char _ = bscanf Scanning.stdib \" %c \" (fun x -> x)\n\nlet () =\n let n = read_int () and k = read_int () in\n let a = Array.make_matrix n 2 ' ' in\n for i = 0 to n - 1 do\n a.(i).(0) <- read_char ()\n done;\n for i = 0 to n - 1 do\n a.(i).(1) <- read_char ()\n done;\n let bfs start =\n let visited = Array.make_matrix n 2 false\n and time = Array.make_matrix n 2 0\n and q = Queue.create ()\n and ans = ref false in\n visited.(fst start).(snd start) <- true;\n Queue.push start q;\n while not (Queue.is_empty q) do\n let (v, side) = Queue.pop q in\n if time.(v).(side) <= v then begin\n if v + k >= n then ans := true;\n let go i j =\n 0 <= i && i <= n - 1 && a.(i).(j) <> 'X' && not visited.(i).(j) in\n if go (v - 1) side then begin\n visited.(v- 1).(side) <- true;\n time.(v - 1).(side) <- time.(v).(side) + 1;\n Queue.push ((v - 1), side) q\n end;\n if go (v + 1) side then begin\n visited.(v + 1).(side) <- true;\n time.(v + 1).(side) <- time.(v).(side) + 1;\n Queue.push ((v + 1), side) q\n end;\n if go (v + k) ((side + 1) mod 2) then begin\n visited.(v + k).((side + 1) mod 2) <- true;\n time.(v + k).((side + 1) mod 2) <- time.(v).(side) + 1;\n Queue.push ((v + k), ((side + 1) mod 2)) q\n end;\n end\n done;\n !ans in\n if bfs (0, 0) then printf \"YES\\n\"\n else printf \"NO\""}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_char _ = bscanf Scanning.stdib \" %c \" (fun x -> x)\n\nlet () =\n let n = read_int () and k = read_int () in\n let a = Array.make_matrix n 2 ' ' in\n for i = 0 to n - 1 do\n a.(i).(0) <- read_char ()\n done;\n for i = 0 to n - 1 do\n a.(i).(1) <- read_char ()\n done;\n let bfs start =\n let queue = Array.make (2 * n) (0, 0) and front = ref 0 and back = ref 0 in\n let push w =\n queue.(!back) <- w;\n back := !back + 1 in\n let pop () =\n let x = queue.(!front) in\n front := !front + 1;\n x in\n let visited = Array.make_matrix n 2 false\n and time = Array.make_matrix n 2 0 in\n let ans = ref false in\n visited.(fst start).(snd start) <- true;\n push start;\n while not (!back = !front) do\n let (v, side) = pop () in\n if time.(v).(side) <= v then begin\n if v + k >= n then ans := true;\n let go i j =\n 0 <= i && i <= n - 1 && a.(i).(j) <> 'X' && not visited.(i).(j) in\n if go (v - 1) side then begin\n visited.(v - 1).(side) <- true;\n time.(v - 1).(side) <- time.(v).(side) + 1;\n push ((v - 1), side)\n end;\n if go (v + 1) side then begin\n visited.(v + 1).(side) <- true;\n time.(v + 1).(side) <- time.(v).(side) + 1;\n push ((v + 1), side)\n end;\n if go (v + k) ((side + 1) mod 2) then begin\n visited.(v + k).((side + 1) mod 2) <- true;\n time.(v + k).((side + 1) mod 2) <- time.(v).(side) + 1;\n push ((v + k), ((side + 1) mod 2))\n end;\n end\n done;\n !ans in\n if bfs (0, 0) then printf \"YES\\n\"\n else printf \"NO\""}, {"source_code": "module NodeSet = Set.Make (struct \n type t = int * bool\n let compare x y = compare x y\nend)\n\nlet rec bfs que nodes level visited n k =\n if NodeSet.is_empty que then\n false\n else if NodeSet.max_elt que >= (n,false) then\n true\n else if level > n then\n false\n else\n let nque,visited = NodeSet.fold (fun (x,b) (nque,visited) ->\n if NodeSet.mem (x,b) visited then\n nque,visited\n else\n let visited = NodeSet.add (x,b) visited in\n let next = [(x+1,b);(x-1,b);(x+k,not b)] in\n List.fold_left (fun e (x,b) -> \n if x > level && (NodeSet.mem (x,b) nodes|| x > n) then\n (* let () = print_endline (\"(\"^string_of_int x^\",\"\n ^string_of_bool b^\",\"\n ^string_of_int level^\")\")in\n *) NodeSet.add (x,b) e\n else\n e) nque next,visited) que (NodeSet.empty,visited) in\n bfs nque nodes (level+1) visited n k\n\nlet solve s1 s2 n k =\n let nodes = ref NodeSet.empty in\n let i = ref 0 in\n let () = String.iter (function\n | '-' -> nodes := NodeSet.add (!i,false) !nodes; i := !i+1;\n | _ -> i := !i+1) s1 in\n let () = i := 0 in\n let () = String.iter (function\n | '-' -> nodes := NodeSet.add (!i,true) !nodes; i := !i+1;\n | _ -> i := !i+1) s2 in\n bfs (NodeSet.singleton (0,false)) !nodes 0 NodeSet.empty (n-1) k\n \nlet main () =\n let rval = Scanf.bscanf Scanf.Scanning.stdib \"%d %d\\n%s\\n%s\\n\" \n (fun n k s1 s2 -> solve s1 s2 n k) in\n if rval then\n print_endline \"YES\"\n else\n print_endline \"NO\"\n\nlet _ = main ()"}], "negative_code": [], "src_uid": "e95bde11483e05751ee7da91a6b4ede1"} {"nl": {"description": "Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.Jzzhu wonders how to get the maximum possible number of groups. Can you help him?", "input_spec": "A single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of the apples.", "output_spec": "The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers \u2014 the numbers of apples in the current group. If there are several optimal answers you can print any of them.", "sample_inputs": ["6", "9", "2"], "sample_outputs": ["2\n6 3\n2 4", "3\n9 3\n2 4\n6 8", "0"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\n\nlet sieve n =\n let group = Array.make (n+1) [] in\n let sieve = Array.make (n+1) true in\n \n for i=2 to n do\n if sieve.(i) then ( (* is a prime *)\n let rec loop j = if j > n then () else (\n\tif sieve.(j) then (\n\t group.(i) <- j::group.(i);\n\t sieve.(j) <- false;\n\t);\n\tloop (j+i)\n ) in\n loop i\n )\n done;\n group\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n if n<3 then printf \"0\\n\" else\n let group = sieve n in\n let mark = Array.init (n+1) (fun i -> i land 1 = 0) in\n let m = n/2 in (* no group beyond m need be considered *)\n\n for i=3 to m do\n if (List.length group.(i)) land 1 = 1 then (\n\tgroup.(i) <- (2*i) :: group.(i);\n\tmark.(2*i) <- false;\n )\n done;\n \n let g2 = fold 2 n (fun i ac -> if mark.(i) then i::ac else ac) [] in\n group.(2) <- if List.length g2 land 1 = 0 then g2 else List.tl g2;\n\n let size = fold 2 m (fun i ac -> ac + List.length group.(i)) 0 in\n printf \"%d\\n\" (size/2);\n\n for i=2 to m do\n let rec loop li = match li with [] -> ()\n\t| a::(b::tail) ->\n\t printf \"%d %d\\n\" a b;\n\t loop tail\n\t| _ -> failwith \"odd-length list\"\n in\n loop group.(i)\n done\n"}], "negative_code": [], "src_uid": "72d70a1c2e579bf81954ff932a9bc16e"} {"nl": {"description": "During the quarantine, Sicromoft has more free time to create the new functions in \"Celex-2021\". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows: The cell with coordinates $$$(x, y)$$$ is at the intersection of $$$x$$$-th row and $$$y$$$-th column. Upper left cell $$$(1,1)$$$ contains an integer $$$1$$$.The developers of the SUM function don't sleep either. Because of the boredom, they teamed up with the developers of the RAND function, so they added the ability to calculate the sum on an arbitrary path from one cell to another, moving down or right. Formally, from the cell $$$(x,y)$$$ in one step you can move to the cell $$$(x+1, y)$$$ or $$$(x, y+1)$$$. After another Dinwows update, Levian started to study \"Celex-2021\" (because he wants to be an accountant!). After filling in the table with the GAZ-GIZ function, he asked you to calculate the quantity of possible different amounts on the path from a given cell $$$(x_1, y_1)$$$ to another given cell $$$(x_2, y_2$$$), if you can only move one cell down or right.Formally, consider all the paths from the cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ such that each next cell in the path is located either to the down or to the right of the previous one. Calculate the number of different sums of elements for all such paths.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 57179$$$) \u2014 the number of test cases. Each of the following $$$t$$$ lines contains four natural numbers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \\le x_1 \\le x_2 \\le 10^9$$$, $$$1 \\le y_1 \\le y_2 \\le 10^9$$$) \u2014 coordinates of the start and the end cells. ", "output_spec": "For each test case, in a separate line, print the number of possible different sums on the way from the start cell to the end cell.", "sample_inputs": ["4\n1 1 2 2\n1 2 2 4\n179 1 179 100000\n5 7 5 7"], "sample_outputs": ["2\n3\n1\n1"], "notes": "NoteIn the first test case there are two possible sums: $$$1+2+5=8$$$ and $$$1+3+5=9$$$. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %Ld %Ld \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let (x1,y1) = read_pair () in\n let (x2,y2) = read_pair () in \n\n let max_min_diff = (x2 -- x1) ** (y2 -- y1) in\n printf \"%Ld\\n\" (max_min_diff ++ 1L)\n done\n"}], "negative_code": [], "src_uid": "1b13c9d9fa0c5a44d035bcf6d70e1a60"} {"nl": {"description": "Ramesses came to university to algorithms practice, and his professor, who is a fairly known programmer, gave him the following task.You are given two matrices $$$A$$$ and $$$B$$$ of size $$$n \\times m$$$, each of which consists of $$$0$$$ and $$$1$$$ only. You can apply the following operation to the matrix $$$A$$$ arbitrary number of times: take any submatrix of the matrix $$$A$$$ that has at least two rows and two columns, and invert the values in its corners (i.e. all corners of the submatrix that contain $$$0$$$, will be replaced by $$$1$$$, and all corners of the submatrix that contain $$$1$$$, will be replaced by $$$0$$$). You have to answer whether you can obtain the matrix $$$B$$$ from the matrix $$$A$$$. An example of the operation. The chosen submatrix is shown in blue and yellow, its corners are shown in yellow. Ramesses don't want to perform these operations by himself, so he asks you to answer this question.A submatrix of matrix $$$M$$$ is a matrix which consist of all elements which come from one of the rows with indices $$$x_1, x_1+1, \\ldots, x_2$$$ of matrix $$$M$$$ and one of the columns with indices $$$y_1, y_1+1, \\ldots, y_2$$$ of matrix $$$M$$$, where $$$x_1, x_2, y_1, y_2$$$ are the edge rows and columns of the submatrix. In other words, a submatrix is a set of elements of source matrix which form a solid rectangle (i.e. without holes) with sides parallel to the sides of the original matrix. The corners of the submatrix are cells $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$, where the cell $$$(i,j)$$$ denotes the cell on the intersection of the $$$i$$$-th row and the $$$j$$$-th column.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 500$$$)\u00a0\u2014 the number of rows and the number of columns in matrices $$$A$$$ and $$$B$$$. Each of the next $$$n$$$ lines contain $$$m$$$ integers: the $$$j$$$-th integer in the $$$i$$$-th line is the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$0 \\leq A_{ij} \\leq 1$$$). Each of the next $$$n$$$ lines contain $$$m$$$ integers: the $$$j$$$-th integer in the $$$i$$$-th line is the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$0 \\leq B_{ij} \\leq 1$$$). ", "output_spec": "Print \"Yes\" (without quotes) if it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$ using the operations described above, and \"No\" (without quotes), if it is not possible. You can print each letter in any case (upper or lower).", "sample_inputs": ["3 3\n0 1 0\n0 1 0\n1 0 0\n1 0 0\n1 0 0\n1 0 0", "6 7\n0 0 1 1 0 0 1\n0 1 0 0 1 0 1\n0 0 0 1 0 0 1\n1 0 1 0 1 0 0\n0 1 0 0 1 0 1\n0 1 0 1 0 0 1\n1 1 0 1 0 1 1\n0 1 1 0 1 0 0\n1 1 0 1 0 0 1\n1 0 1 0 0 1 0\n0 1 1 0 1 0 0\n0 1 1 1 1 0 1", "3 4\n0 1 0 1\n1 0 1 0\n0 1 0 1\n1 1 1 1\n1 1 1 1\n1 1 1 1"], "sample_outputs": ["Yes", "Yes", "No"], "notes": "NoteThe examples are explained below. Example 1. Example 2. Example 3. "}, "positive_code": [{"source_code": "let () =\n let n, m = Scanf.scanf \"%d %d\\n\" (fun x y -> (x, y)) in\n let a =\n Array.init n\n (fun _ ->\n Array.init m\n (fun _ -> Scanf.scanf \"%d \" (fun x -> x))\n )\n in\n let diff =\n Array.init n\n (fun i ->\n Array.init m\n (fun j ->\n let x = Scanf.scanf \"%d \" (fun x -> x) in\n x = a.(i).(j)\n )\n )\n in\n let acc = ref true in\n for i = 0 to n-2 do\n let n_f = Array.fold_left (fun acc x -> if x then acc else acc + 1) 0 diff.(i) in\n if n_f mod 2 = 0 then\n Array.iteri (fun j x -> if not x then diff.(i+1).(j) <- not diff.(i+1).(j)) diff.(i)\n else acc := false\n done;\n if Array.fold_left (&&) !acc diff.(n-1) then Printf.printf \"Yes\" else Printf.printf \"No\"\n;;"}], "negative_code": [], "src_uid": "068e6bbfe590f4485528e85fa991ff24"} {"nl": {"description": "There are two infinite sources of water: hot water of temperature $$$h$$$; cold water of temperature $$$c$$$ ($$$c < h$$$). You perform the following procedure of alternating moves: take one cup of the hot water and pour it into an infinitely deep barrel; take one cup of the cold water and pour it into an infinitely deep barrel; take one cup of the hot water $$$\\dots$$$ and so on $$$\\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 3 \\cdot 10^4$$$)\u00a0\u2014 the number of testcases. Each of the next $$$T$$$ lines contains three integers $$$h$$$, $$$c$$$ and $$$t$$$ ($$$1 \\le c < h \\le 10^6$$$; $$$c \\le t \\le h$$$)\u00a0\u2014 the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.", "output_spec": "For each testcase print a single positive integer\u00a0\u2014 the minimum number of cups required to be poured into the barrel to achieve the closest temperature to $$$t$$$.", "sample_inputs": ["3\n30 10 20\n41 15 30\n18 13 18"], "sample_outputs": ["2\n7\n1"], "notes": "NoteIn the first testcase the temperature after $$$2$$$ poured cups: $$$1$$$ hot and $$$1$$$ cold is exactly $$$20$$$. So that is the closest we can achieve.In the second testcase the temperature after $$$7$$$ poured cups: $$$4$$$ hot and $$$3$$$ cold is about $$$29.857$$$. Pouring more water won't get us closer to $$$t$$$ than that.In the third testcase the temperature after $$$1$$$ poured cup: $$$1$$$ hot is $$$18$$$. That's exactly equal to $$$t$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \n\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let h = read_long() in\n let c = read_long() in\n let t = read_long() in\n\n let solve () =\n let condition ell =\n\tell ** h ++ (ell -- 1L) ** c <= (2L ** ell -- 1L) ** t\n in\n\n let score ell =\n\tlet numerator = Int64.to_float (ell ** h ++ (ell -- 1L) ** c) in\n\tlet denom = Int64.to_float (2L ** ell -- 1L) in\n\tlet tee = Int64.to_float t in\n\tabs_float (tee -. numerator /. denom)\n in\n \n let rec bsearch lo hi =\n (* the condtion holds for hi, does not hold for lo *)\n\tif lo ++ 1L = hi then hi else \n\t let m = (lo ++ hi)//2L in\n\t if condition m then bsearch lo m else bsearch m hi \n in\n \n let rec findhi hi = if condition hi then hi else findhi (hi ++ hi) in\n \n if t = h then 1L\n else if 2L ** t <= h ++ c then 2L\n else (\n\tlet ell = bsearch 0L (findhi 1L) in\n\tlet ell = if score (ell -- 1L) <= score ell then (ell -- 1L) else ell in\n\t2L ** ell -- 1L\n )\n in\n\n printf \"%Ld\\n\" (solve())\n \n done\n"}], "negative_code": [], "src_uid": "ca157773d06c7d192589218e2aad6431"} {"nl": {"description": "Kawashiro Nitori is a girl who loves competitive programming.One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.Given a string $$$s$$$ and a parameter $$$k$$$, you need to check if there exist $$$k+1$$$ non-empty strings $$$a_1,a_2...,a_{k+1}$$$, such that $$$$$$s=a_1+a_2+\\ldots +a_k+a_{k+1}+R(a_k)+R(a_{k-1})+\\ldots+R(a_{1}).$$$$$$ Here $$$+$$$ represents concatenation. We define $$$R(x)$$$ as a reversed string $$$x$$$. For example $$$R(abcd) = dcba$$$. Note that in the formula above the part $$$R(a_{k+1})$$$ is intentionally skipped.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\\le t\\le 100$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The first line of each test case description contains two integers $$$n$$$, $$$k$$$ ($$$1\\le n\\le 100$$$, $$$0\\le k\\le \\lfloor \\frac{n}{2} \\rfloor$$$) \u00a0\u2014 the length of the string $$$s$$$ and the parameter $$$k$$$. The second line of each test case description contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase English letters.", "output_spec": "For each test case, print \"YES\" (without quotes), if it is possible to find $$$a_1,a_2,\\ldots,a_{k+1}$$$, and \"NO\" (without quotes) otherwise. You can print letters in any case (upper or lower).", "sample_inputs": ["7\n5 1\nqwqwq\n2 1\nab\n3 1\nioi\n4 2\nicpc\n22 0\ndokidokiliteratureclub\n19 8\nimteamshanghaialice\n6 3\naaaaaa"], "sample_outputs": ["YES\nNO\nYES\nNO\nYES\nNO\nNO"], "notes": "NoteIn the first test case, one possible solution is $$$a_1=qw$$$ and $$$a_2=q$$$.In the third test case, one possible solution is $$$a_1=i$$$ and $$$a_2=o$$$.In the fifth test case, one possible solution is $$$a_1=dokidokiliteratureclub$$$."}, "positive_code": [{"source_code": "let solution len str k = \n let rec helper i =\n if i = k\n then true\n else if str.[i] = str.[len-i-1]\n then helper (i+1)\n else false in\n if k * 2 = len\n then false\n else helper 0\n\nlet test_case () =\n let len::k::_ =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n let str = read_line () in\n (if solution len str k then \"YES\" else \"NO\")\n |> print_endline\n\nlet () =\n let nb_cases = read_int () in\n for i = 1 to nb_cases do\n test_case ()\n done\n"}], "negative_code": [], "src_uid": "6fbf41dc32d1c28351d78a9ec5fc0026"} {"nl": {"description": "Little X has n distinct integers: p1,\u2009p2,\u2009...,\u2009pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied: If number x belongs to set A, then number a\u2009-\u2009x must also belong to set A. If number x belongs to set B, then number b\u2009-\u2009x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible.", "input_spec": "The first line contains three space-separated integers n,\u2009a,\u2009b (1\u2009\u2264\u2009n\u2009\u2264\u2009105;\u00a01\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009109). The next line contains n space-separated distinct integers p1,\u2009p2,\u2009...,\u2009pn\u00a0(1\u2009\u2264\u2009pi\u2009\u2264\u2009109).", "output_spec": "If there is a way to divide the numbers into two sets, then print \"YES\" in the first line. Then print n integers: b1,\u2009b2,\u2009...,\u2009bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print \"NO\" (without the quotes).", "sample_inputs": ["4 5 9\n2 3 4 5", "3 3 4\n1 2 4"], "sample_outputs": ["YES\n0 0 1 1", "NO"], "notes": "NoteIt's OK if all the numbers are in the same set, and the other one is empty."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = read_long () in\n let b = read_long () in\n\n let h = Hashtbl.create 10 in\n\n let ps = Array.make n 0L in\n\n for i=0 to n-1 do\n let p = read_long() in\n ps.(i) <- p;\n Hashtbl.replace h p i\n done;\n\n let lookup x = try Hashtbl.find h x with Not_found -> -1 in\n\n let pair = Array.make_matrix n 2 (-1) in\n\n for i=0 to n-1 do\n pair.(i).(0) <- lookup (a -- ps.(i));\n pair.(i).(1) <- lookup (b -- ps.(i));\n done;\n\n let compat i color = pair.(i).(color) >= 0 in\n let degree i = (if compat i 0 then 1 else 0) + (if compat i 1 then 1 else 0) in\n \n let color = Array.make n (-1) in\n \n let rec dfs v col parity = if color.(v) >= 0 then true else (\n color.(v) <- col;\n let next = pair.(v).(parity) in\n if degree next = 1 then (\n if compat next col then (\n\tcolor.(next) <- col;\n\ttrue;\n ) else false\n ) else (\n dfs next col (1-parity)\n )\n )\n in\n\n if forall 0 (n-1) \n (fun v -> match (compat v 0, compat v 1) with | (true,true) -> true | _ -> false) then (\n Array.fill color 0 n 0\n );\n\n let answer = forall 0 (n-1) (fun v ->\n match (compat v 0, compat v 1) with\n | (true,true) -> true\n | (true,false) -> dfs v 0 0\n | (false,true) -> dfs v 1 1\n | (false,false) -> false\n ) in\n\n if answer then (\n printf \"YES\\n\";\n for i=0 to n-1 do \n printf \"%s%d\" (if i>0 then \" \" else \"\") color.(i)\n done;\n print_newline();\n ) else printf \"NO\\n\"\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = read_long () in\n let b = read_long () in\n\n let h = Hashtbl.create 10 in\n\n let ps = Array.make n 0L in\n\n for i=0 to n-1 do\n let p = read_long() in\n ps.(i) <- p;\n Hashtbl.replace h p i\n done;\n\n let lookup x = try Hashtbl.find h x with Not_found -> -1 in\n\n let apair = Array.make n (-1) in\n let bpair = Array.make n (-1) in\n\n for i=0 to n-1 do\n apair.(i) <- lookup (a -- ps.(i));\n bpair.(i) <- lookup (b -- ps.(i));\n done;\n\n let all_paired = forall 0 (n-1) (fun i -> apair.(i)>=0 && bpair.(i)>=0) in\n\n if all_paired then (\n printf \"YES\\n\";\n for i=0 to n-1 do \n if i>0 then printf \" \";\n printf \"1\"\n done;\n print_newline()\n ) else (\n if exists 0 (n-1) (fun i -> apair.(i)<0 && bpair.(i)<0) then printf \"NO\\n\" else (\n\n let rec loop i = if i=n then () else\n\t (\n\t if apair.(i) >=0 && bpair.(i) >=0 then ()\n\t else if apair.(i) <0 && bpair.(i) >=0 then\n\t apair.(bpair.(i)) <- -1\n\t else if apair.(i) >=0 && bpair.(i) < 0 then\n\t bpair.(apair.(i)) <- -1\n\t else ();\n\t loop (i+1)\n\t )\n in\n\n loop 0;\n\n if exists 0 (n-1) (fun i -> apair.(i)<0 && bpair.(i)<0) then printf \"NO\\n\" else (\n \n\tprintf \"YES\\n\";\n\tfor i=0 to n-1 do \n\t if i>0 then printf \" \";\n\t printf \"%d\" (if apair.(i)>=0 then 0 else 1)\n\tdone;\n\tprint_newline()\n )\n )\n )\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = read_long () in\n let b = read_long () in\n\n let h = Hashtbl.create 10 in\n\n let ps = Array.make n 0L in\n\n for i=0 to n-1 do\n let p = read_long() in\n ps.(i) <- p;\n Hashtbl.replace h p i\n done;\n\n let lookup x = try Hashtbl.find h x with Not_found -> -1 in\n\n let pair = Array.make_matrix n 2 (-1) in\n\n for i=0 to n-1 do\n pair.(i).(0) <- lookup (a -- ps.(i));\n pair.(i).(1) <- lookup (b -- ps.(i));\n done;\n\n let compat i color = pair.(i).(color) >= 0 in\n \n let visited = Array.make n false in\n \n let rec dfs v color parity = if visited.(v) then true else (\n visited.(v) <- true;\n if compat v color && compat v parity then (\n let next = pair.(v).(parity) in\n pair.(v).(1-color) <- -1;\n dfs next color (1-parity)\n ) else false\n )\n in\n let answer = forall 0 (n-1) (fun v ->\n match (compat v 0, compat v 1) with\n | (true,true) -> true\n | (true,false) -> dfs v 0 0\n | (false,true) -> dfs v 1 1\n | (false,false) -> false\n ) in\n\n if answer then (\n printf \"YES\\n\";\n for i=0 to n-1 do \n printf \"%s%d\" (if i>0 then \" \" else \"\") (if compat i 0 then 0 else 1)\n done;\n print_newline();\n ) else printf \"NO\\n\"\n"}], "src_uid": "1a46737540d253583234193a026008e3"} {"nl": {"description": "Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds: \"Are you kidding me?\", asks Chris.For example, consider a case where s\u2009=\u20098 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1\u2009-\u20091)\u2009+\u2009(4\u2009-\u20091)\u2009+\u2009(5\u2009-\u20091)\u2009=\u2009(8\u2009-\u20093)\u2009+\u2009(8\u2009-\u20096)\u2009=\u20097. However, now Chris has exactly s\u2009=\u2009106 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!", "input_spec": "The first line of input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105), the number of blocks in the set X. The next line contains n distinct space-separated integers x1, x2, ..., xn (1\u2009\u2264\u2009xi\u2009\u2264\u2009106), the numbers of the blocks in X. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.", "output_spec": "In the first line of output print a single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009106\u2009-\u2009n), the number of blocks in the set Y. In the next line output m distinct space-separated integers y1, y2, ..., ym (1\u2009\u2264\u2009yi\u2009\u2264\u2009106), such that the required equality holds. The sets X and Y should not intersect, i.e. xi\u2009\u2260\u2009yj for all i, j (1\u2009\u2264\u2009i\u2009\u2264\u2009n; 1\u2009\u2264\u2009j\u2009\u2264\u2009m). It is guaranteed that at least one solution always exists. If there are multiple solutions, output any of them.", "sample_inputs": ["3\n1 4 5", "1\n1"], "sample_outputs": ["2\n999993 1000000", "1\n1000000"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let s = 1_000_000 in\n let n = read_int () in\n\n let comp x = s+1-x in\n let usedx = Array.make (s+1) false in\n \n for i=0 to n-1 do\n usedx.(read_int ()) <- true;\n done;\n\n printf \"%d\\n\" n;\n\n let count = ref 0 in\n\n for i=1 to s do\n if (not usedx.(i)) && usedx.(comp i) then (\n usedx.(i) <- true;\n printf \"%s%d\" (if !count=0 then \"\" else \" \") i;\n count := !count+1\n )\n done;\n\n let pairs = (n - !count)/2 in\n \n let rec loop y j = if j=0 then () else\n if not usedx.(y) then (\n\tprintf \"%s%d %d\" (if !count=0 then \"\" else \" \") y (comp y);\n\tcount := !count + 2;\n\tloop (y+1) (j-1)\n ) else loop (y+1) j\n in\n\n loop 1 pairs;\n print_newline()\n \n \n\n\n \n \n\n"}, {"source_code": "\nopen Printf\nopen Scanf\n\nlet (@@) f x = f x;;\nlet (@.) f g x = f (g x);;\n\nlet read_int () = scanf \" %d\" (fun x -> x);;\n\nlet n = read_int();;\n\nlet a = Array.make 1000000 false;;\nmodule IntSet = Set.Make(struct type t = int;; let compare = Pervasives.compare;; end);;\n\nlet () = \n for i = 0 to n-1 do\n a.(read_int() - 1) <- true;\n done;\n;;\n\nlet rec f (i : int) (count : int) (set : IntSet.t) : int * IntSet.t =\n if i = 500000 then (count, set)\n else if a.(i) then\n if a.(1000000-i-1) then f (i+1) (count+1) set\n else f (i+1) count @@ IntSet.add (1000000-i) set\n else\n if a.(1000000-i-1) then f (i+1) count @@ IntSet.add (i+1) set\n else f (i+1) count set\n;;\n\nlet (count, set) = f 0 0 IntSet.empty;;\n\nlet rec g (i : int) (count : int) (set : IntSet.t) : int * IntSet.t = \n if i = 500000 then (count, set)\n else if count = 0 then (0, set)\n else if (not a.(i)) && (not a.(1000000-i-1)) then g (i+1) (count-1) @@ IntSet.add (i+1) @@ IntSet.add (1000000-i) set\n else g (i+1) count set\n;;\n\nlet (count, set) = g 0 count set;;\n\nprintf \"%d\\n\" @@ IntSet.cardinal set;\nIntSet.iter (fun x -> printf \"%d \" x) set;\nprint_newline();"}], "negative_code": [{"source_code": "\nopen Printf\nopen Scanf\n\nlet (@@) f x = f x;;\nlet (@.) f g x = f (g x);;\n\nlet read_int () = scanf \" %d\" (fun x -> x);;\n\nlet n = read_int();;\n\nlet a = Array.make 1000000 false;;\nmodule IntSet = Set.Make(struct type t = int;; let compare = Pervasives.compare;; end);;\n\nlet () = \n for i = 0 to n-1 do\n a.(read_int() - 1) <- true;\n done;\n;;\n\nlet rec f (i : int) (count : int) (set : IntSet.t) : int * IntSet.t =\n if i = 500000 then (count, set)\n else if a.(i) then\n if a.(1000000-i-1) then f (i+1) (count+1) set\n else f (i+1) count @@ IntSet.add (1000000-i) set\n else\n if a.(1000000-i-1) then f (i+1) count @@ IntSet.add (i+1) set\n else f (i+1) count set\n;;\n\nlet (count, set) = f 0 0 IntSet.empty;;\n\nlet rec g (i : int) (count : int) (set : IntSet.t) : int * IntSet.t = \n if i = 500000 then (count, set)\n else if count = 0 then (0, set)\n else if (not a.(i)) && (not a.(1000000-i-1)) then g (i+1) (count-1) @@ IntSet.add (i+1) @@ IntSet.add (1000000-i-1) set\n else g (i+1) count set\n;;\n\nlet (count, set) = g 0 count set;;\n\nIntSet.iter (fun x -> printf \"%d \" x) set;\nprint_newline();"}, {"source_code": "\nopen Printf\nopen Scanf\n\nlet (@@) f x = f x;;\nlet (@.) f g x = f (g x);;\n\nlet read_int () = scanf \" %d\" (fun x -> x);;\n\nlet n = read_int();;\n\nlet a = Array.make 1000000 false;;\nmodule IntSet = Set.Make(struct type t = int;; let compare = Pervasives.compare;; end);;\n\nlet () = \n for i = 0 to n-1 do\n a.(read_int() - 1) <- true;\n done;\n;;\n\nlet rec f (i : int) (count : int) (set : IntSet.t) : int * IntSet.t =\n if i = 500000 then (count, set)\n else if a.(i) then\n if a.(1000000-i-1) then f (i+1) (count+1) set\n else f (i+1) count @@ IntSet.add (1000000-i) set\n else\n if a.(1000000-i-1) then f (i+1) count @@ IntSet.add (i+1) set\n else f (i+1) count set\n;;\n\nlet (count, set) = f 0 0 IntSet.empty;;\n\nlet rec g (i : int) (count : int) (set : IntSet.t) : int * IntSet.t = \n if i = 500000 then (count, set)\n else if count = 0 then (0, set)\n else if (not a.(i)) && (not a.(1000000-i-1)) then g (i+1) (count-1) @@ IntSet.add (i+1) @@ IntSet.add (1000000-i-1) set\n else g (i+1) count set\n;;\n\nlet (count, set) = g 0 count set;;\n\nprintf \"%d\\n\" @@ IntSet.cardinal set;\nIntSet.iter (fun x -> printf \"%d \" x) set;\nprint_newline();"}], "src_uid": "4143caa25fcc2f4d400d169f9697be01"} {"nl": {"description": "There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated: Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting). When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end. When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements. The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction. You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009200\u2009000)\u00a0\u2014 the number of employees. The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.", "output_spec": "Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.", "sample_inputs": ["5\nDDRRR", "6\nDDRRRR"], "sample_outputs": ["D", "R"], "notes": "NoteConsider one of the voting scenarios for the first sample: Employee 1 denies employee 5 to vote. Employee 2 denies employee 3 to vote. Employee 3 has no right to vote and skips his turn (he was denied by employee 2). Employee 4 denies employee 2 to vote. Employee 5 has no right to vote and skips his turn (he was denied by employee 1). Employee 1 denies employee 4. Only employee 1 now has the right to vote so the voting ends with the victory of depublicans. "}, "positive_code": [{"source_code": "let vote_result (s : string) : char =\n let d = Queue.create () in\n let r = Queue.create () in\n begin\n String.iteri\n (fun i c ->\n match c with\n | 'D' -> Queue.push i d\n | 'R' -> Queue.push i r\n | _ -> failwith \"input not consists of just D and R\")\n s;\n \n let n = ref (String.length s) in\n let rec loop () =\n match (Queue.is_empty d, Queue.is_empty r) with\n | false, false ->\n Queue.push (!n)\n (if Queue.pop d < Queue.pop r then d else r);\n incr n;\n loop ()\n | true, false -> 'R'\n | false, true -> 'D'\n | true, true -> failwith \"impossible\"\n in loop ()\n end\n\n\nlet main () =\n let n = read_int () in\n let s = really_input_string stdin n in\n print_char (vote_result s)\n\n\nlet () = main ()\n"}], "negative_code": [{"source_code": "let vote_result (s : string) : char =\n let n = ref (String.length s) in\n let bs = Bytes.unsafe_of_string s in\n let prev_n = ref 1 in\n while (!n) <> (!prev_n) do\n let l = !n in\n prev_n := l;\n begin\n let d = ref 0 in\n let r = ref 0 in\n for i = 0 to l-1 do\n match Bytes.get bs i with\n 'D' ->\n begin\n while ((!r) < l) && (Bytes.get bs (!r) <> 'R') do incr r done;\n if (!r) < l then Bytes.set bs (!r) ' ' else ()\n end\n | 'R' ->\n begin\n while ((!d) < l) && (Bytes.get bs (!d) <> 'D') do incr d done;\n if (!d) < l then Bytes.set bs (!d) ' ' else ()\n end\n | _ -> ()\n done\n end;\n begin\n n := 0;\n for i = 0 to l-1 do\n match Bytes.get bs i with\n 'D' -> (Bytes.set bs (!n) 'D'; incr n)\n | 'R' -> (Bytes.set bs (!n) 'R'; incr n)\n | _ -> ()\n done\n end\n done;\n Bytes.get bs 0\n\n\nlet main () =\n let _ = read_int () in\n let s = read_line () in\n print_char (vote_result s)\n\n\nlet () = main ()\n"}, {"source_code": "let vote_result (s : string) : char =\n let n = ref (String.length s) in\n let bs = Bytes.unsafe_of_string s in\n let prev_n = ref 1 in\n while (!n) <> (!prev_n) do\n let l = !n in\n prev_n := l;\n begin\n let d = ref 0 in\n let r = ref 0 in\n for i = 0 to l-1 do\n match Bytes.get bs i with\n 'D' ->\n begin\n if (!r) <= i then r := i+1;\n while ((!r) < l) && (Bytes.get bs (!r) <> 'R') do incr r done;\n if (!r) < l then Bytes.set bs (!r) ' ' else ()\n end\n | 'R' ->\n begin\n if (!d) <= i then d := i+1;\n while ((!d) < l) && (Bytes.get bs (!d) <> 'D') do incr d done;\n if (!d) < l then Bytes.set bs (!d) ' ' else ()\n end\n | _ -> ()\n done\n end;\n begin\n n := 0;\n for i = 0 to l-1 do\n match Bytes.get bs i with\n 'D' -> (Bytes.set bs (!n) 'D'; incr n)\n | 'R' -> (Bytes.set bs (!n) 'R'; incr n)\n | _ -> ()\n done\n end\n done;\n Bytes.get bs 0\n\n\nlet main () =\n let _ = read_int () in\n let s = read_line () in\n print_char (vote_result s)\n\n\nlet () = main ()\n"}], "src_uid": "cc50eef15726d429cfc2e76f0aa8cd19"} {"nl": {"description": "One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the \"Goldbach's conjecture\". It says: \"each even number no less than four can be expressed as the sum of two primes\". Let's modify it. How about a statement like that: \"each integer no less than 12 can be expressed as the sum of two composite numbers.\" Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.", "input_spec": "The only line contains an integer n (12\u2009\u2264\u2009n\u2009\u2264\u2009106).", "output_spec": "Output two composite integers x and y (1\u2009<\u2009x,\u2009y\u2009<\u2009n) such that x\u2009+\u2009y\u2009=\u2009n. If there are multiple solutions, you can output any of them.", "sample_inputs": ["12", "15", "23", "1000000"], "sample_outputs": ["4 8", "6 9", "8 15", "500000 500000"], "notes": "NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output \"6 6\" or \"8 4\" as well.In the second example, 15 = 6 + 9. Note that you can't output \"1 14\" because 1 is not a composite number."}, "positive_code": [{"source_code": "let input () = Scanf.scanf \"%d\" (fun n -> n)\n\nlet solve int = \n let rec loop n =\n if n < int / 2\n then\n let div = 2 * n in\n let rest = int - div in\n if rest mod 2 = 0\n then\n (div, rest)\n else\n if rest mod 3 = 0\n then\n (div, rest)\n else\n loop (n + 1)\n else\n failwith \"Bad number\"\n in loop 2\n\nlet print (a, b) = Printf.printf \"%d %d\\n\" a b\n\nlet () = print (solve (input ()))"}, {"source_code": "open Printf\n\nlet order a b =\n if a < b then (a, b) else (b, a)\n\nlet () =\n let n = int_of_string @@ input_line stdin in\n if n mod 2 = 0 then\n printf \"4 %d\\n\" (n - 4)\n else\n let (a, b) = order 9 (n - 9) in\n printf \"%d %d\\n\" a b \n"}], "negative_code": [], "src_uid": "3ea971165088fae130d866180c6c868b"} {"nl": {"description": "Luntik has decided to try singing. He has $$$a$$$ one-minute songs, $$$b$$$ two-minute songs and $$$c$$$ three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.He wants to make the absolute difference of durations of the concerts as small as possible. The duration of the concert is the sum of durations of all songs in that concert.Please help Luntik and find the minimal possible difference in minutes between the concerts durations.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$)\u00a0\u2014 the number of test cases. Each test case consists of one line containing three integers $$$a, b, c$$$ $$$(1 \\le a, b, c \\le 10^9)$$$\u00a0\u2014 the number of one-minute, two-minute and three-minute songs.", "output_spec": "For each test case print the minimal possible difference in minutes between the concerts durations.", "sample_inputs": ["4\n1 1 1\n2 1 3\n5 5 5\n1 1 2"], "sample_outputs": ["0\n1\n0\n1"], "notes": "NoteIn the first test case, Luntik can include a one-minute song and a two-minute song into the first concert, and a three-minute song into the second concert. Then the difference will be equal to $$$0$$$.In the second test case, Luntik can include two one-minute songs and a two-minute song and a three-minute song into the first concert, and two three-minute songs into the second concert. The duration of the first concert will be $$$1 + 1 + 2 + 3 = 7$$$, the duration of the second concert will be $$$6$$$. The difference of them is $$$|7-6| = 1$$$."}, "positive_code": [{"source_code": "let solve3 a b =\r\n match b with\r\n | 0 -> ( match a with\r\n | 0 -> 3\r\n | 1 -> 2\r\n | 2 -> 1\r\n | _ -> (a - 3) mod 2 )\r\n | _ -> ( match a with\r\n | 0 -> 1\r\n | _ -> (a - 1) mod 2)\r\n\r\n\r\n\r\nlet solve0 a b =\r\n match (b mod 2) with\r\n | 0 -> (a mod 2)\r\n | _ -> ( match a with \r\n | 0 -> 2\r\n | _ -> (a mod 2)\r\n )\r\n\r\nlet solve6 a b =\r\n match b with\r\n | 0 -> if (a < 6) then 6 - a else (a - 6) mod 2\r\n | 1 -> if (a < 4) then 4 - a else (a - 4) mod 2\r\n | 2 -> if (a < 2) then 2 - a else (a - 2) mod 2 \r\n | _ -> solve0 a (b - 3)\r\n\r\nlet solve a b c =\r\n match (c mod 2) with\r\n | 0 -> solve0 a b\r\n | _ -> solve3 a b\r\n\r\nlet solve_ a b c =\r\n match c with\r\n | 0 -> solve0 a b\r\n | _ -> if (c mod 2) == 1\r\n then solve3 a b\r\n else min (solve0 a b) (solve6 a b)\r\n \r\n\r\n\r\nlet () = \r\n let tc = Scanf.scanf \" %d\" (fun x -> x) in\r\n let rec loop tc =\r\n if tc == 0 then\r\n ()\r\n else\r\n (let a, b, c = Scanf.scanf \" %d %d %d\" (fun a b c -> (a, b, c)) in\r\n Printf.printf \"%d\\n\" (min\r\n (solve a b c)\r\n (solve_ a b c)\r\n );\r\n loop (tc - 1) \r\n )\r\n in loop tc\r\n\r\n"}], "negative_code": [], "src_uid": "4322861935ca727b0de8556849bc5982"} {"nl": {"description": "You have $$$n$$$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $$$i$$$-th gift consists of $$$a_i$$$ candies and $$$b_i$$$ oranges.During one move, you can choose some gift $$$1 \\le i \\le n$$$ and do one of the following operations: eat exactly one candy from this gift (decrease $$$a_i$$$ by one); eat exactly one orange from this gift (decrease $$$b_i$$$ by one); eat exactly one candy and exactly one orange from this gift (decrease both $$$a_i$$$ and $$$b_i$$$ by one). Of course, you can not eat a candy or orange if it's not present in the gift (so neither $$$a_i$$$ nor $$$b_i$$$ can become less than zero).As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: $$$a_1 = a_2 = \\dots = a_n$$$ and $$$b_1 = b_2 = \\dots = b_n$$$ (and $$$a_i$$$ equals $$$b_i$$$ is not necessary).Your task is to find the minimum number of moves required to equalize all the given gifts.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the number of gifts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$), where $$$a_i$$$ is the number of candies in the $$$i$$$-th gift. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \\dots, b_n$$$ ($$$1 \\le b_i \\le 10^9$$$), where $$$b_i$$$ is the number of oranges in the $$$i$$$-th gift.", "output_spec": "For each test case, print one integer: the minimum number of moves required to equalize all the given gifts.", "sample_inputs": ["5\n3\n3 5 6\n3 2 3\n5\n1 2 3 4 5\n5 4 3 2 1\n3\n1 1 1\n2 2 2\n6\n1 1000000000 1000000000 1000000000 1000000000 1000000000\n1 1 1 1 1 1\n3\n10 12 8\n7 5 4"], "sample_outputs": ["6\n16\n0\n4999999995\n7"], "notes": "NoteIn the first test case of the example, we can perform the following sequence of moves: choose the first gift and eat one orange from it, so $$$a = [3, 5, 6]$$$ and $$$b = [2, 2, 3]$$$; choose the second gift and eat one candy from it, so $$$a = [3, 4, 6]$$$ and $$$b = [2, 2, 3]$$$; choose the second gift and eat one candy from it, so $$$a = [3, 3, 6]$$$ and $$$b = [2, 2, 3]$$$; choose the third gift and eat one candy and one orange from it, so $$$a = [3, 3, 5]$$$ and $$$b = [2, 2, 2]$$$; choose the third gift and eat one candy from it, so $$$a = [3, 3, 4]$$$ and $$$b = [2, 2, 2]$$$; choose the third gift and eat one candy from it, so $$$a = [3, 3, 3]$$$ and $$$b = [2, 2, 2]$$$. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\n\nlet solve () =\n let n = read_int() in\n let arr_a = Array.init n read_int in\n let arr_b = Array.init n read_int in\n let _min a b = \n if a > b then b\n else a\n in\n let rec min_element ind arr =\n if Array.length arr = (ind + 1) then (\n arr.(ind)\n ) else (\n min (arr.(ind)) (min_element (ind + 1) arr)\n )\n in\n let min_a = min_element 0 arr_a in\n let min_b = min_element 0 arr_b in\n let rec get_answer ind = \n let x = Int64.of_int (max (arr_a.(ind) - min_a) (arr_b.(ind) - min_b)) in\n if n = (ind + 1) then (\n x\n ) else (\n Int64.add x (get_answer (ind + 1))\n )\n in\n let answer = get_answer 0 in\n printf \"%Ld\\n\" answer\n \nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}], "negative_code": [], "src_uid": "35368cefc5ce46a9f41a15734826a151"} {"nl": {"description": "Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity \u2014 origami, but remembered the puzzle that she could not solve. The tree is a non-oriented connected graph without cycles. In particular, there always are n\u2009-\u20091 edges in a tree with n vertices.The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane.It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u200930) \u2014 the number of vertices in the tree. Each of next n\u2009-\u20091 lines contains two integers ui, vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree.", "output_spec": "If the puzzle doesn't have a solution then in the only line print \"NO\". Otherwise, the first line should contain \"YES\". The next n lines should contain the pair of integers xi, yi (|xi|,\u2009|yi|\u2009\u2264\u20091018) \u2014 the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them. ", "sample_inputs": ["7\n1 2\n1 3\n2 4\n2 5\n3 6\n3 7", "6\n1 2\n2 3\n2 4\n2 5\n2 6", "4\n1 2\n2 3\n3 4"], "sample_outputs": ["YES\n0 0\n1 0\n0 1\n2 0\n1 -1\n-1 1\n0 2", "NO", "YES\n3 3\n4 3\n5 3\n6 3"], "notes": "NoteIn the first sample one of the possible positions of tree is: "}, "positive_code": [{"source_code": "let ( ++ ) = Int64.add\nlet ( -- ) = Int64.sub\nlet ( ** ) = Int64.mul\nlet ( // ) = Int64.div\n\nlet read_int _ = Scanf.scanf \" %d \" (fun n -> n)\nlet read_int64 _ = Scanf.scanf \" %Ld \" (fun n -> n)\n\nlet rec dfs res g v p x0 y0 l =\n if List.length g.(v) > 4 then raise Not_found;\n let neighbors = List.filter (fun x -> x <> p) g.(v) in\n let prev = let (x, y) = res.(p) in ((x--x0)//2L, (y--y0)//2L) in\n let deltas = List.filter (fun x -> x <> prev) [(l,0L);(0L--l,0L);(0L,l);(0L,0L--l)] in\n res.(v) <- (x0,y0);\n List.iteri (fun i w -> let (dx,dy) = List.nth deltas i in\n dfs res g w v (x0 ++ dx) (y0 ++ dy) (l//2L)) neighbors\n (* List.iter (fun w -> dfs res g w v (len//2L)) neighbors; *)\n\nlet () =\n let n = read_int () in\n let edges = Array.init (n-1)\n (fun _ -> let v = read_int () and w = read_int () in (v,w)) in\n let add_edge graph (v,w) = (graph.(v) <- w :: graph.(v);\n graph.(w) <- v :: graph.(w);) in\n let graph = Array.make (n+1) [] in\n Array.iter (add_edge graph) edges;\n let res = Array.make (n+1) (0L,0L) in\n try\n dfs res graph 1 0 0L 0L (Int64.shift_left 1L 40);\n print_endline \"YES\";\n for i=1 to n do\n let (x,y) = res.(i) in\n Printf.printf \"%Ld %Ld\\n\" x y\n done\n with\n Not_found -> print_endline \"NO\"\n"}], "negative_code": [], "src_uid": "1ee7ec135d957db2fca0aa591fc44b16"} {"nl": {"description": "Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex $$$1$$$ is the root of this tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $$$0$$$.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $$$2$$$ rounding down. More formally, during one move, you choose some edge $$$i$$$ and divide its weight by $$$2$$$ rounding down ($$$w_i := \\left\\lfloor\\frac{w_i}{2}\\right\\rfloor$$$).Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$. In other words, if $$$w(i, j)$$$ is the weight of the path from the vertex $$$i$$$ to the vertex $$$j$$$, then you have to make $$$\\sum\\limits_{v \\in leaves} w(root, v) \\le S$$$, where $$$leaves$$$ is the list of all leaves.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$S$$$ ($$$2 \\le n \\le 10^5; 1 \\le S \\le 10^{16}$$$) \u2014 the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next $$$n-1$$$ lines describe edges of the tree. The edge $$$i$$$ is described as three integers $$$v_i$$$, $$$u_i$$$ and $$$w_i$$$ ($$$1 \\le v_i, u_i \\le n; 1 \\le w_i \\le 10^6$$$), where $$$v_i$$$ and $$$u_i$$$ are vertices the edge $$$i$$$ connects and $$$w_i$$$ is the weight of this edge. It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$ ($$$\\sum n \\le 10^5$$$).", "output_spec": "For each test case, print the answer: the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$.", "sample_inputs": ["3\n3 20\n2 1 8\n3 1 7\n5 50\n1 3 100\n1 5 10\n2 3 123\n5 4 55\n2 100\n1 2 409"], "sample_outputs": ["0\n8\n3"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Pair = struct \n type t = int64 * int \n let compare = compare\nend\n\nmodule SS = Set.Make(Pair)\n \nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n\nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n\nlet solve() =\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n\n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n g.(u) <- ((v, w) :: g.(u));\n g.(v) <- ((u, w) :: g.(v))\n done;\n\n let edges = Array.make n (0L, 0) in\n\n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n\n let upd_cnt new_vert cost =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n edges.(new_vert) <- (cost, add)\n )\n in\n\n List.iter (fun (new_vert, cost) -> upd_cnt new_vert cost) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n\n let sum = ref 0L in\n\n let rec calc_set ind =\n if ind = n then SS.empty\n else (\n let set_now = calc_set (ind + 1) in\n let (cost, cnt) = edges.(ind) in\n let mult = Int64.mul cost (Int64.of_int cnt) in\n sum := Int64.add !sum mult;\n let mult = Int64.mul (div2 cost) (Int64.of_int cnt) in\n SS.add (mult, ind) set_now\n )\n in\n\n let answer = ref 0 in\n \n let set = Array.make 1 (calc_set 0) in\n\n while !sum > s do\n answer := !answer + 1;\n let (del_value, del_id) = SS.max_elt set.(0) in\n let new_set = SS.remove (del_value, del_id) set.(0) in\n let (cost_edge, cnt_edge) = edges.(del_id) in\n edges.(del_id) <- (Int64.div cost_edge 2L, cnt_edge);\n let cost_edge = Int64.div cost_edge 2L in\n let new_cost_edge = div2 cost_edge in\n let new_set = SS.add (Int64.mul new_cost_edge (Int64.of_int cnt_edge), del_id) new_set in\n sum := Int64.add !sum (Int64.mul (Int64.of_int (-1)) del_value);\n set.(0) <- new_set\n done;\n \n printf \"%d\\n\" !answer\n;;\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}, {"source_code": "open Printf\nopen Scanf\n \nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n \nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n \nlet solve() =\n let t = Sys.time() in\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n \n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n let c = 1 in\n g.(u) <- ((v, w, c) :: g.(u));\n g.(v) <- ((u, w, c) :: g.(v))\n done;\n \n let list_1 = ref [] in\n let list_2 = ref [] in\n let sum = ref 0L in\n \n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n \n let upd_cnt new_vert cost t =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n \n let mult = Int64.mul cost (Int64.of_int add) in\n sum := Int64.add !sum mult;\n let c = ref cost in\n while !c > 0L do\n let mult = Int64.mul (div2 !c) (Int64.of_int add) in\n if t = 1 then (\n list_1 := mult :: !list_1\n ) \n else (\n list_2 := mult :: !list_2\n );\n c := Int64.div !c 2L\n done \n )\n in\n \n List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n \n let answer = ref 0 in\n \n list_1 := List.sort compare !list_1;\n list_2 := List.sort compare !list_2;\n list_1 := List.rev !list_1;\n list_2 := List.rev !list_2;\n \n while !sum > s do\n if t -. Sys.time() > 2.5 then (\n sum := 0L\n )\n else (\n if List.length !list_2 = 0 then (\n sum := Int64.sub !sum (List.hd !list_1);\n list_1 := List.tl !list_1\n ) else if List.length !list_1 = 0 then (\n sum := Int64.sub !sum (List.hd !list_2);\n list_2 := List.tl !list_2;\n answer := !answer + 1\n ) else (\n let cost_1 = List.hd !list_1 in\n let cost_2 = List.hd !list_2 in\n if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in\n if (Int64.add cost_1 cost_3) >= cost_2 then (\n list_1 := List.tl !list_1;\n sum := Int64.sub !sum cost_1\n ) else (\n list_2 := List.tl !list_2;\n sum := Int64.sub !sum cost_2;\n answer := !answer + 1\n )\n )\n )\n );\n \n answer := !answer + 1\n done;\n \n printf \"%d\\n\" !answer\n;;\n \nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Pair = struct \n type t = int64 * int \n let compare = compare\nend\n\nmodule SS = Set.Make(Pair)\n \nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\nlet read_lint _ = bscanf Scanning.stdin \"%Ld \" (fun x -> x)\n\nlet div2 a =\n Int64.div (Int64.add a 1L) 2L\n;;\n\nlet solve() =\n let n = read_int() in\n let s = read_lint() in\n let g = Array.make n [] in\n\n for i = 0 to n - 2 do\n let u = read_int() - 1 in\n let v = read_int() - 1 in\n let w = read_lint() in\n g.(u) <- ((v, w) :: g.(u));\n g.(v) <- ((u, w) :: g.(v))\n done;\n\n let edges = Array.make n (0L, 0) in\n\n let rec dfs vert parent =\n let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in\n\n let upd_cnt new_vert cost =\n if new_vert = parent then ()\n else (\n let add = dfs new_vert vert in\n cnt_leaves := !cnt_leaves + add;\n edges.(new_vert) <- (cost, add)\n )\n in\n\n List.iter (fun (new_vert, cost) -> upd_cnt new_vert cost) g.(vert);\n \n !cnt_leaves\n in\n \n dfs 0 0;\n\n let sum = ref 0L in\n\n let rec calc_set ind =\n if ind = n then SS.empty\n else (\n let set_now = calc_set (ind + 1) in\n let (cost, cnt) = edges.(ind) in\n let mult = Int64.mul cost (Int64.of_int cnt) in\n sum := Int64.add !sum mult;\n let mult = Int64.mul (div2 cost) (Int64.of_int cnt) in\n SS.add (mult, ind) set_now\n )\n in\n\n if n = 100000 then printf \"not runtime\"\n else (\n let rec greed priority_set now_cost = \n if now_cost <= s then 0\n else (\n let (del_value, del_id) = SS.max_elt priority_set in\n let new_set = SS.remove (del_value, del_id) priority_set in\n let (cost_edge, cnt_edge) = edges.(del_id) in\n edges.(del_id) <- (Int64.div cost_edge 2L, cnt_edge);\n let cost_edge = Int64.div cost_edge 2L in\n let new_cost_edge = div2 cost_edge in\n let new_set = SS.add (Int64.mul new_cost_edge (Int64.of_int cnt_edge), del_id) new_set in\n 1 + (greed new_set (Int64.add now_cost (Int64.mul (Int64.of_int (-1)) del_value)))\n )\n in\n\n let set = calc_set 0 in\n \n printf \"%d\\n\" (greed set !sum)\n )\n;;\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done"}], "src_uid": "9cd7f058d4671b12b67babd38293a3fc"} {"nl": {"description": "A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it? ", "input_spec": "The first line contains 26 integers xa,\u2009xb,\u2009...,\u2009xz (\u2009-\u2009105\u2009\u2264\u2009xi\u2009\u2264\u2009105) \u2014 the value assigned to letters a,\u2009b,\u2009c,\u2009...,\u2009z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters\u2014 the string for which you need to calculate the answer. ", "output_spec": "Print the answer to the problem. ", "sample_inputs": ["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"], "sample_outputs": ["2", "2"], "notes": "NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\nlet n2l n = char_of_int ((int_of_char 'a') + n)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let x = Array.init 26 (fun _ -> read_int()) in\n let s = read_string () in\n let n = String.length s in\n let score = Array.init n (fun i -> x.(l2n s.[i])) in\n\n let acc = Array.make (n+1) 0L in\n\n for i=1 to n do\n acc.(i) <- acc.(i-1) ++ (long score.(i-1))\n done;\n\n let h = Hashtbl.create 1000 in\n\n let acval = Hashtbl.create 1000 in\n\n for i=0 to n do\n Hashtbl.replace acval acc.(i) true;\n if i>0 then (\n let c = s.[i-1] in\n let li = try Hashtbl.find h (c,acc.(i)) with Not_found -> [] in\n Hashtbl.replace h (c,acc.(i)) (0::li)\n );\n if i [] in\n Hashtbl.replace h (c,acc.(i)) (1::li)\n )\n done;\n\n let total = ref 0L in\n\n let count_list li =\n let rec loop li nzeros ac =\n match li with [] -> ac\n\t| 0::tail -> loop tail (nzeros++1L) ac\n\t| 1::tail -> loop tail nzeros (ac++nzeros)\n\t| _ -> failwith \"bad list\"\n in\n loop (List.rev li) 0L 0L\n in\n \n Hashtbl.iter (\n fun ac _ ->\n for i=0 to 25 do\n\tlet li = try Hashtbl.find h ((n2l i),ac) with Not_found -> [] in\n\ttotal := !total ++ (count_list li)\n done\n ) acval;\n\n printf \"%Ld\\n\" !total\n"}], "negative_code": [], "src_uid": "0dd2758f432542fa82ff949d19496346"} {"nl": {"description": "You are given one integer number $$$n$$$. Find three distinct integers $$$a, b, c$$$ such that $$$2 \\le a, b, c$$$ and $$$a \\cdot b \\cdot c = n$$$ or say that it is impossible to do it.If there are several answers, you can print any.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. The next $$$n$$$ lines describe test cases. The $$$i$$$-th test case is given on a new line as one integer $$$n$$$ ($$$2 \\le n \\le 10^9$$$).", "output_spec": "For each test case, print the answer on it. Print \"NO\" if it is impossible to represent $$$n$$$ as $$$a \\cdot b \\cdot c$$$ for some distinct integers $$$a, b, c$$$ such that $$$2 \\le a, b, c$$$. Otherwise, print \"YES\" and any possible such representation.", "sample_inputs": ["5\n64\n32\n97\n2\n12345"], "sample_outputs": ["YES\n2 4 8 \nNO\nNO\nNO\nYES\n3 5 823"], "notes": null}, "positive_code": [{"source_code": "open! Printf;;\n\nmodule String = struct\n\tinclude String\n\tlet split c str =\n\t\tlet str = String.concat \"\" [str; String.make 1 c] in\n\t\tlet cur = ref [] in\n\t\tlet res = ref [] in\n\t\tString.iter (fun a ->\n\t\t\tmatch a = c with\n\t\t\t| false -> cur := (String.make 1 a) :: !cur\n\t\t\t| true -> \n\t\t\t\tlet char_list = List.rev (!cur) in\n\t\t\t\tres := (String.concat \"\" char_list) :: !res;\n\t\t\t\tcur := []) str ;\n\t\t\tList.rev !res \n\t;;\nend;;\n\nlet read_int_list () = \n\tread_line () |> String.split ' ' |> List.map int_of_string\n;;\n\nlet read_2_ints () =\n\tmatch read_int_list () with \n\t| [a; b] -> a, b\n\t| _ -> assert false\n;; \n\nlet t = read_int () in \nfor _ = 1 to t do\n\tlet n = read_int () in\n\tlet a = ref 2 in\n\twhile (!a)*(!a)*(!a) < n && (n mod (!a) <> 0) do\n\t\ta := !a + 1\n\tdone;\n\tlet b = ref (!a + 1) in\n\twhile (!b)*(!b) < n / (!a) && ((n / (!a)) mod (!b) <> 0) do\n\t\tb := !b + 1\n\tdone;\n\tlet a, b, c = !a, !b, (n / !a) / !b in\n\tif a * b * c == n && (a < b) && (b < c) then printf \"YES\\n%d %d %d\\n\" a b c\n\telse print_endline \"NO\"\ndone \n"}], "negative_code": [], "src_uid": "0f7ceecdffe11f45d0c1d618ef3c6469"} {"nl": {"description": "100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet.The following game was chosen for the fights: initially there is a polynomial P(x)\u2009=\u2009anxn\u2009+\u2009an\u2009-\u20091xn\u2009-\u20091\u2009+\u2009...\u2009+\u2009a1x\u2009+\u2009a0,\u2009 with yet undefined coefficients and the integer k. Players alternate their turns. At each turn, a player pick some index j, such that coefficient aj that stay near xj is not determined yet and sets it to any value (integer or real, positive or negative, 0 is also allowed). Computer moves first. The human will be declared the winner if and only if the resulting polynomial will be divisible by Q(x)\u2009=\u2009x\u2009-\u2009k.Polynomial P(x) is said to be divisible by polynomial Q(x) if there exists a representation P(x)\u2009=\u2009B(x)Q(x), where B(x) is also some polynomial.Some moves have been made already and now you wonder, is it true that human can guarantee the victory if he plays optimally?", "input_spec": "The first line of the input contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u2009|k|\u2009\u2264\u200910\u2009000)\u00a0\u2014 the size of the polynomial and the integer k. The i-th of the following n\u2009+\u20091 lines contain character '?' if the coefficient near xi\u2009-\u20091 is yet undefined or the integer value ai, if the coefficient is already known (\u2009-\u200910\u2009000\u2009\u2264\u2009ai\u2009\u2264\u200910\u2009000). Each of integers ai (and even an) may be equal to 0. Please note, that it's not guaranteed that you are given the position of the game where it's computer's turn to move.", "output_spec": "Print \"Yes\" (without quotes) if the human has winning strategy, or \"No\" (without quotes) otherwise.", "sample_inputs": ["1 2\n-1\n?", "2 100\n-10000\n0\n1", "4 5\n?\n1\n?\n1\n?"], "sample_outputs": ["Yes", "Yes", "No"], "notes": "NoteIn the first sample, computer set a0 to \u2009-\u20091 on the first move, so if human can set coefficient a1 to 0.5 and win.In the second sample, all coefficients are already set and the resulting polynomial is divisible by x\u2009-\u2009100, so the human has won."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\nlet long x = Int64.of_int x\n \nlet next_prime_up n = \n let isprime n = \n let rec loop i = \n if (i*i > n) then true \n else if n mod i = 0 then false \n else loop (i+2) in\n loop 3 in\n let rec search i = if isprime i then i else search (i+2) in\n if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)\n \nlet value_at_k_is_zero a n k =\n let a = Array.init (n+1) (\n fun i -> match a.(i) with None -> failwith \"no\" | Some x -> long x\n ) in\n let k = long k in\n \n Random.init 374;\n\n let eval p =\n let ( %% ) x n = let y = Int64.rem x n in if y<0L then Int64.add y n else y in\n let ( ** ) a b = (Int64.mul a b) %% p in\n let ( ++ ) a b = (Int64.add a b) %% p in\n\n let (answer,_) = fold 0 n (fun i (ac,kpowi) ->\n (ac ++ a.(i) ** kpowi, k ** kpowi)\n ) (0L, 1L) in\n answer\n in\n \n forall 1 20 (fun _ ->\n let p = long (next_prime_up (10_000_000 + (Random.int 10_000_000))) in\n eval p = 0L\n )\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let k = read_int () in\n let a = Array.init (n+1) (\n fun _ ->\n let s = read_string() in\n if s = \"?\" then None else Some (int_of_string s)\n ) in\n\n let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in\n let my_turn = (n+1 - moves_remaining) land 1 = 1 in\n let a0_not_used = a.(0) = None in\n let a0_is_zero = a.(0) = Some 0 in\n let i_get_last_move = (n+1) land 1 = 0 in\n \n let answer =\n if moves_remaining = 0 then (\n value_at_k_is_zero a n k\n ) else if k=0 then (\n (my_turn && a0_not_used) || a0_is_zero\n ) else (\n i_get_last_move\n )\n in\n\n match answer with true -> printf \"Yes\\n\" | false -> printf \"No\\n\"\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n \nlet next_prime_up n = \n let isprime n = \n let rec loop i = \n if (i*i > n) then true \n else if n mod i = 0 then false \n else loop (i+2) in\n loop 3 in\n let rec search i = if isprime i then i else search (i+2) in\n if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)\n \nlet value_at_k_is_zero a n k =\n let a = Array.init (n+1) (\n fun i -> match a.(i) with None -> failwith \"no\" | Some x -> x\n ) in\n\n Random.init 374;\n\n let eval p =\n let ( %% ) x n = let y = x mod n in if y<0 then y+n else y in\n let ( ** ) a b = (a * b) %% p in\n let ( ++ ) a b = (a + b) %% p in\n let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i)) in\n\n let rec ( ^ ) e pow = \n if pow=0 then 1 else\n\tlet a = e^(pow/2) in\n\tif (pow land 1)=0 then a**a else e**a**a\n in\n\n sum 0 n (fun i -> a.(i) ** (k ^ i)) 0\n in\n \n forall 1 20 (fun _ ->\n let p = next_prime_up (4000 + (Random.int 4000)) in\n eval p = 0\n )\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let k = read_int () in\n let a = Array.init (n+1) (\n fun _ ->\n let s = read_string() in\n if s = \"?\" then None else Some (int_of_string s)\n ) in\n\n let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in\n let my_turn = (n+1 - moves_remaining) land 1 = 1 in\n let a0_not_used = a.(0) = None in\n let a0_is_zero = a.(0) = Some 0 in\n let i_get_last_move = (n+1) land 1 = 0 in\n \n let answer =\n if moves_remaining = 0 then (\n value_at_k_is_zero a n k\n ) else if k=0 then (\n (my_turn && a0_not_used) || a0_is_zero\n ) else (\n i_get_last_move\n )\n in\n\n match answer with true -> printf \"Yes\\n\" | false -> printf \"No\\n\"\n\n\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n \nlet next_prime_up n = \n let isprime n = \n let rec loop i = \n if (i*i > n) then true \n else if n mod i = 0 then false \n else loop (i+2) in\n loop 3 in\n let rec search i = if isprime i then i else search (i+2) in\n if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)\n \nlet value_at_k_is_zero a n k =\n let a = Array.init (n+1) (\n fun i -> match a.(i) with None -> failwith \"no\" | Some x -> x\n ) in\n\n Random.init 374;\n\n let eval p =\n let ( %% ) x n = let y = x mod n in if y<0 then y+n else y in\n let ( ** ) a b = (a * b) %% p in\n let ( ++ ) a b = (a + b) %% p in\n let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i)) in\n\n let rec ( ^ ) e pow = \n if pow=0 then 1 else\n\tlet a = e^(pow/2) in\n\tif (pow land 1)=0 then a**a else e**a**a\n in\n\n sum 0 n (fun i -> a.(i) ** (k ^ i)) 0\n in\n \n forall 1 20 (fun _ ->\n let p = next_prime_up (4000 + (Random.int 4000)) in\n eval p = 0\n )\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let k = read_int () in\n let a = Array.init (n+1) (\n fun _ ->\n let s = read_string() in\n if s = \"?\" then None else Some (int_of_string s)\n ) in\n\n let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in\n let my_turn = (n+1 - moves_remaining) land 1 = 1 in\n let a0_used = a.(0) = None in\n let i_get_last_move = (n+1) land 1 = 0 in\n \n let answer =\n if moves_remaining = 0 then (\n value_at_k_is_zero a n k\n ) else if k=0 then (\n my_turn && (not a0_used)\n ) else (\n i_get_last_move\n )\n in\n\n match answer with true -> printf \"Yes\\n\" | false -> printf \"No\\n\"\n\n\n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n \nlet next_prime_up n = \n let isprime n = \n let rec loop i = \n if (i*i > n) then true \n else if n mod i = 0 then false \n else loop (i+2) in\n loop 3 in\n let rec search i = if isprime i then i else search (i+2) in\n if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)\n \nlet value_at_k_is_zero a n k =\n let a = Array.init (n+1) (\n fun i -> match a.(i) with None -> failwith \"no\" | Some x -> x\n ) in\n\n Random.init 374;\n\n let eval p =\n let ( %% ) x n = let y = x mod n in if y<0 then y+n else y in\n let ( ** ) a b = (a * b) %% p in\n let ( ++ ) a b = (a + b) %% p in\n let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i)) in\n\n let rec ( ^ ) e pow = \n if pow=0 then 1 else\n\tlet a = e^(pow/2) in\n\tif (pow land 1)=0 then a**a else e**a**a\n in\n\n sum 0 n (fun i -> a.(i) ** (k ^ i)) 0\n in\n \n forall 1 20 (fun _ ->\n let p = next_prime_up (2 + (Random.int 8000)) in\n eval p = 0\n )\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let k = read_int () in\n let a = Array.init (n+1) (\n fun _ ->\n let s = read_string() in\n if s = \"?\" then None else Some (int_of_string s)\n ) in\n\n let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in\n let my_turn = (n+1 - moves_remaining) land 1 = 1 in\n let a0_not_used = a.(0) = None in\n let a0_is_zero = a.(0) = Some 0 in\n let i_get_last_move = (n+1) land 1 = 0 in\n \n let answer =\n if moves_remaining = 0 then (\n value_at_k_is_zero a n k\n ) else if k=0 then (\n (my_turn && a0_not_used) || a0_is_zero\n ) else (\n if n=9999 && k=10000 then failwith \"test 85\";\n i_get_last_move\n )\n in\n\n match answer with true -> printf \"Yes\\n\" | false -> printf \"No\\n\"\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n \nlet next_prime_up n = \n let isprime n = \n let rec loop i = \n if (i*i > n) then true \n else if n mod i = 0 then false \n else loop (i+2) in\n loop 3 in\n let rec search i = if isprime i then i else search (i+2) in\n if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)\n \nlet value_at_k_is_zero a n k =\n let a = Array.init (n+1) (\n fun i -> match a.(i) with None -> failwith \"no\" | Some x -> x\n ) in\n\n Random.init 374;\n\n let eval p =\n let ( %% ) x n = let y = x mod n in if y<0 then y+n else y in\n let ( ** ) a b = (a * b) %% p in\n let ( ++ ) a b = (a + b) %% p in\n let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i)) in\n\n let rec ( ^ ) e pow = \n if pow=0 then 1 else\n\tlet a = e^(pow/2) in\n\tif (pow land 1)=0 then a**a else e**a**a\n in\n\n sum 0 n (fun i -> a.(i) ** (k ^ i)) 0\n in\n \n forall 1 20 (fun _ ->\n let p = next_prime_up (4000 + (Random.int 4000)) in\n eval p = 0\n )\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let k = read_int () in\n let a = Array.init (n+1) (\n fun _ ->\n let s = read_string() in\n if s = \"?\" then None else Some (int_of_string s)\n ) in\n\n let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in\n let my_turn = (n+1 - moves_remaining) land 1 = 1 in\n let a0_used = a.(0) = None in\n let a0_is_zero = a.(0) = Some 0 in\n let i_get_last_move = (n+1) land 1 = 0 in\n \n let answer =\n if moves_remaining = 0 then (\n value_at_k_is_zero a n k\n ) else if k=0 then (\n (my_turn && (not a0_used)) || a0_is_zero\n ) else (\n i_get_last_move\n )\n in\n\n match answer with true -> printf \"Yes\\n\" | false -> printf \"No\\n\"\n\n\n\n"}], "src_uid": "c0c7b1900e6be6d14695477355e4d87b"} {"nl": {"description": "PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?", "input_spec": "The first input line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009103)\u00a0\u2014 number of words PolandBall and EnemyBall know, respectively. Then n strings follow, one per line\u00a0\u2014 words familiar to PolandBall. Then m strings follow, one per line\u00a0\u2014 words familiar to EnemyBall. Note that one Ball cannot know a word more than once (strings are unique), but some words can be known by both players. Each word is non-empty and consists of no more than 500 lowercase English alphabet letters.", "output_spec": "In a single line of print the answer\u00a0\u2014 \"YES\" if PolandBall wins and \"NO\" otherwise. Both Balls play optimally.", "sample_inputs": ["5 1\npolandball\nis\na\ncool\ncharacter\nnope", "2 2\nkremowka\nwadowicka\nkremowka\nwiedenska", "1 2\na\na\nb"], "sample_outputs": ["YES", "YES", "NO"], "notes": "NoteIn the first example PolandBall knows much more words and wins effortlessly.In the second example if PolandBall says kremowka first, then EnemyBall cannot use that word anymore. EnemyBall can only say wiedenska. PolandBall says wadowicka and wins."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x)\nlet read_string () = Scanf.scanf \" %s \" (fun x -> x)\nlet read_list read_func size =\n let rec aux lst rf sz =\n if sz = 0 then lst\n else aux (rf () :: lst) rf (sz - 1)\n in\n aux [] read_func size\n (*List.rev (aux [] read_func size)*)\nlet is_even num = num land 1 = 0\nlet is_odd num = num land 1 = 1\n\nlet () =\n let n = read_int () in\n let m = read_int () in\n let wordlist = read_list read_string (n + m) in\n (*List.iter (Printf.printf \"%s d\\n\") wordlist*)\n let uniqsorted = List.sort_uniq compare wordlist in\n let uslen = List.length uniqsorted in\n let isodd = if is_odd uslen then 1 else 0 in\n if isodd + n > m then print_string \"YES\\n\" else print_string \"NO\\n\"\n\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let ht = Hashtbl.create 10 in\n let c = ref 0 in\n for i = 1 to n do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tHashtbl.replace ht s ()\n done;\n for i = 1 to m do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tif Hashtbl.mem ht s\n\tthen incr c;\n done;\n if !c mod 2 = 0 && n > m || !c mod 2 = 1 && n >= m\n then Printf.printf \"YES\\n\"\n else Printf.printf \"NO\\n\"\n"}], "negative_code": [], "src_uid": "4b352854008a9378551db60b76d33cfa"} {"nl": {"description": "Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k\u2009>\u20091 Pokemon with strengths {s1,\u2009s2,\u2009s3,\u2009...,\u2009sk} tend to fight among each other if gcd(s1,\u2009s2,\u2009s3,\u2009...,\u2009sk)\u2009=\u20091 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.", "input_spec": "The input consists of two lines. The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1\u2009\u2264\u2009si\u2009\u2264\u2009105), the strength of the i-th Pokemon.", "output_spec": "Print single integer\u00a0\u2014 the maximum number of Pokemons Bash can take.", "sample_inputs": ["3\n2 3 4", "5\n2 3 4 6 7"], "sample_outputs": ["2", "3"], "notes": "Notegcd (greatest common divisor) of positive integers set {a1,\u2009a2,\u2009...,\u2009an} is the maximum positive integer that divides all the integers {a1,\u2009a2,\u2009...,\u2009an}.In the first sample, we can take Pokemons with strengths {2,\u20094} since gcd(2,\u20094)\u2009=\u20092.In the second sample, we can take Pokemons with strengths {2,\u20094,\u20096}, and there is no larger group with gcd\u2009\u2260\u20091."}, "positive_code": [{"source_code": "let _ =\n let n2 = 100000 in\n let prime = Array.make (n2 + 1) true in\n let p = Array.make (n2 + 1) 0 in\n let pd = Array.init (n2 + 1) (fun i -> i) in\n let pk = ref 0 in\n let () =\n for i = 2 to n2 do\n if prime.(i) then (\n\tp.(!pk) <- i;\n\tincr pk;\n\tpd.(i) <- i;\n\tlet j = ref (2 * i) in\n while !j <= n2 do\n\t let jj = !j in\n prime.(jj) <- false;\n\t pd.(jj) <- i;\n j := jj + i\n done\n )\n done;\n prime.(1) <- false;\n in\n let pk = !pk - 1 in\n let fp = Array.make 20 0 in\n let fd = Array.make 20 0 in\n let ff = Array.make 20 0 in\n let factor x =\n let r = ref 0 in\n let x = ref x in\n while !x > 1 && not (pd.(!x) = !x) do\n\tlet pr = pd.(!x) in\n\t let d = ref 0 in\n\t ff.(!r) <- 1;\n\t while !x mod pr = 0 do\n\t incr d;\n\t x := !x / pr;\n\t ff.(!r) <- ff.(!r) * pr;\n\t done;\n\t fp.(!r) <- pr;\n\t fd.(!r) <- !d;\n\t incr r;\n done;\n if !x > 1 then (\n\tfp.(!r) <- !x;\n\tfd.(!r) <- 1;\n\tff.(!r) <- !x;\n\tincr r;\n );\n !r\n in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let c = Array.make (n2 + 1) 0 in\n let _ =\n for i = 0 to n - 1 do\n let t = factor a.(i) in\n\tfor j = 0 to t - 1 do\n\t c.(fp.(j)) <- c.(fp.(j)) + 1\n\tdone;\n done;\n in\n let res = ref 1 in\n for i = 0 to n2 do\n res := max !res c.(i)\n done;\n Printf.printf \"%d\\n\" !res\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet factor n = \n let rec loop n p ac = \n if n=1 then ac\n else if p*p > n then (n::ac)\n else if n mod p = 0 then loop (n/p) p (p::ac)\n else loop n (p+1) ac\n in\n List.rev (loop n 2 [])\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x) \nlet () = \n let n = read_int () in\n let s = Array.init n (fun i -> read_int()) in\n\n let maxs = 100_000 in\n \n let pcount = Array.make maxs 0 in\n\n for i=0 to n-1 do\n let lf = factor s.(i) in\n let lf = List.sort_uniq compare lf in\n List.iter (fun f -> pcount.(f) <- pcount.(f) + 1) lf;\n done;\n\n let answer = maxf 0 (maxs-1) (fun i -> pcount.(i)) in\n\n printf \"%d\\n\" (max answer 1)\n"}], "negative_code": [{"source_code": "let _ =\n let n2 = 100000 in\n let prime = Array.make (n2 + 1) true in\n let p = Array.make (n2 + 1) 0 in\n let pd = Array.init (n2 + 1) (fun i -> i) in\n let pk = ref 0 in\n let () =\n for i = 2 to n2 do\n if prime.(i) then (\n\tp.(!pk) <- i;\n\tincr pk;\n\tpd.(i) <- i;\n\tlet j = ref (2 * i) in\n while !j <= n2 do\n\t let jj = !j in\n prime.(jj) <- false;\n\t pd.(jj) <- i;\n j := jj + i\n done\n )\n done;\n prime.(1) <- false;\n in\n let pk = !pk - 1 in\n let fp = Array.make 20 0 in\n let fd = Array.make 20 0 in\n let ff = Array.make 20 0 in\n let factor x =\n let r = ref 0 in\n let x = ref x in\n while !x > 1 && not (pd.(!x) = !x) do\n\tlet pr = pd.(!x) in\n\t let d = ref 0 in\n\t ff.(!r) <- 1;\n\t while !x mod pr = 0 do\n\t incr d;\n\t x := !x / pr;\n\t ff.(!r) <- ff.(!r) * pr;\n\t done;\n\t fp.(!r) <- pr;\n\t fd.(!r) <- !d;\n\t incr r;\n done;\n if !x > 1 then (\n\tfp.(!r) <- !x;\n\tfd.(!r) <- 1;\n\tff.(!r) <- !x;\n\tincr r;\n );\n !r\n in\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let c = Array.make (n2 + 1) 0 in\n let _ =\n for i = 0 to n - 1 do\n let t = factor a.(i) in\n\tfor j = 0 to t - 1 do\n\t c.(fp.(j)) <- c.(fp.(j)) + 1\n\tdone;\n done;\n in\n let res = ref 0 in\n for i = 0 to n2 do\n res := max !res c.(i)\n done;\n Printf.printf \"%d\\n\" !res\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet factor n = \n let rec loop n p ac = \n if n=1 then ac\n else if p*p > n then (n::ac)\n else if n mod p = 0 then loop (n/p) p (p::ac)\n else loop n (p+1) ac\n in\n List.rev (loop n 2 [])\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x) \nlet () = \n let n = read_int () in\n let s = Array.init n (fun i -> read_int()) in\n\n let maxs = 100_000 in\n \n let pcount = Array.make maxs 0 in\n\n for i=0 to n-1 do\n let lf = factor s.(i) in\n let lf = List.sort_uniq compare lf in\n List.iter (fun f -> pcount.(f) <- pcount.(f) + 1) lf;\n done;\n\n let answer = maxf 0 (maxs-1) (fun i -> pcount.(i)) in\n\n printf \"%d\\n\" (min answer 1)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet factor n = \n let rec loop n p ac = \n if n=1 then ac\n else if p*p > n then (n::ac)\n else if n mod p = 0 then loop (n/p) p (p::ac)\n else loop n (p+1) ac\n in\n List.rev (loop n 2 [])\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x) \nlet () = \n let n = read_int () in\n let s = Array.init n (fun i -> read_int()) in\n\n let maxs = 100_000 in\n \n let pcount = Array.make maxs 0 in\n\n for i=0 to n-1 do\n let lf = factor s.(i) in\n let lf = List.sort_uniq compare lf in\n List.iter (fun f -> pcount.(f) <- pcount.(f) + 1) lf;\n done;\n\n let answer = maxf 0 (maxs-1) (fun i -> pcount.(i)) in\n\n printf \"%d\\n\" answer\n"}], "src_uid": "eea7860e6bbbe5f399b9123ebd663e3e"} {"nl": {"description": "The School \u21160 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: ti\u2009=\u20091, if the i-th child is good at programming, ti\u2009=\u20092, if the i-th child is good at maths, ti\u2009=\u20093, if the i-th child is good at PE Each child happens to be good at exactly one of these three subjects.The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095000) \u2014 the number of children in the school. The second line contains n integers t1,\u2009t2,\u2009...,\u2009tn (1\u2009\u2264\u2009ti\u2009\u2264\u20093), where ti describes the skill of the i-th child.", "output_spec": "In the first line output integer w \u2014 the largest possible number of teams. Then print w lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to n in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them. If no teams can be compiled, print the only line with value w equal to 0.", "sample_inputs": ["7\n1 3 1 3 2 1 2", "4\n2 1 1 2"], "sample_outputs": ["2\n3 5 2\n6 7 4", "0"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet divide () = \n let n = read () in\n let rec loop i one two three =\n if i <= n\n then\n match read () with\n | 1 -> loop (i + 1) (i :: one) two three\n | 2 -> loop (i + 1) one (i :: two) three\n | 3 -> loop (i + 1) one two (i :: three)\n else\n (one, two, three)\n in loop 1 [] [] []\n\nlet combine (one, two, three) = \n let rec loop one two three list =\n match one, two, three with\n | (coder :: one), (mather :: two), (boxer :: three) -> \n loop one two three ((coder :: mather :: boxer :: []) :: list)\n | _ -> list\n in loop one two three []\n\nlet solve () = \n let teams = combine (divide ()) in\n let total = List.length teams in\n (total, teams)\n\nlet print (n, teams) = \n Printf.printf \"%d\\n\" n;\n List.iter (fun [a; b; c] -> Printf.printf \"%d %d %d\\n\" a b c) teams\n\nlet () = print (solve())"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet divide () = \n let n = read () in\n let rec loop i one two three =\n if i <= n\n then\n match read () with\n | 1 -> loop (i + 1) (i :: one) two three\n | 2 -> loop (i + 1) one (i :: two) three\n | 3 -> loop (i + 1) one two (i :: three)\n else\n (one, two, three)\n in loop 1 [] [] []\n\nlet combine (one, two, three) = \n let rec loop one two three list =\n match one, two, three with\n | (coder :: one), (mather :: two), (boxer :: three) -> \n loop one two three ((coder :: mather :: boxer :: []) :: list)\n | _ -> list\n in loop one two three []\n\nlet solve () = \n let teams = combine (divide ()) in\n let total = List.length teams in\n (total, teams)\n\nlet print (n, teams) = \n Printf.printf \"%d\\n\" n;\n let rec loop list =\n match list with\n | ((coder :: mather :: boxer :: []) :: list) -> \n Printf.printf \"%d %d %d\\n\" coder mather boxer;\n loop list\n | _ -> ()\n in loop teams\n \nlet () = print (solve())\n"}, {"source_code": "let _ = read_line () |> int_of_string and\n ts = read_line () |> Str.split (Str.regexp \" +\") |> List.map int_of_string in \nlet ones = List.mapi (fun i a -> if a = 1 then i + 1 else 0) ts and\n twos = List.mapi (fun i a -> if a = 2 then i + 1 else 0) ts and\n threes = List.mapi (fun i a -> if a = 3 then i + 1 else 0) ts in\nlet rec map3 a b c acc = \n match (a,b,c) with\n | ([], _, _) -> acc \n | (_, [], _) -> acc \n | (_, _, []) -> acc \n | ((0::ax), (b::bx), (c::cx)) -> map3 ax (b::bx) (c::cx) acc\n | ((a::ax), (0::bx), (c::cx)) -> map3 (a::ax) bx (c::cx) acc\n | ((a::ax), (b::bx), (0::cx)) -> map3 (a::ax) (b::bx) cx acc\n | ((a::ax), (b::bx), (c::cx)) -> map3 ax bx cx ([a;b;c]::acc) in\nlet print_list ls = \nbegin\nList.length ls |> Printf.printf \"%d\\n\";\nList.iter (fun l -> Printf.printf \"%d %d %d\\n\" (List.nth l 0) (List.nth l 1) (List.nth l 2)) ls\nend in\nmap3 ones twos threes [] |> print_list\n \n\n"}], "negative_code": [{"source_code": "let _ = read_line () |> int_of_string and\n ts = read_line () |> Str.split (Str.regexp \" +\") |> List.map int_of_string in \nlet ones = List.mapi (fun i a -> if a = 1 then i + 1 else 0) ts and\n twos = List.mapi (fun i a -> if a = 2 then i + 1 else 0) ts and\n threes = List.mapi (fun i a -> if a = 3 then i + 1 else 0) ts in\nlet rec map3 a b c acc = \n match (a,b,c) with\n | ([], _, _) -> acc \n | (_, [], _) -> acc \n | (_, _, []) -> acc \n | ((0::ax), (b::bx), (c::cx)) -> map3 ax (b::bx) (c::cx) acc\n | ((a::ax), (0::bx), (c::cx)) -> map3 (a::ax) bx (c::cx) acc\n | ((a::ax), (b::bx), (0::cx)) -> map3 (a::ax) (b::bx) cx acc\n | ((a::ax), (b::bx), (c::cx)) -> map3 ax bx cx ([a;b;c]::acc) in\nlet print_list = List.iter (fun l -> Printf.printf \"%d %d %d\\n\" (List.nth l 0) (List.nth l 1) (List.nth l 2))\nin map3 ones twos threes [] |> print_list\n \n\n"}], "src_uid": "c014861f27edf35990cc065399697b10"} {"nl": {"description": "A tree is a connected undirected graph consisting of n vertices and n\u2009\u2009-\u2009\u20091 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree\u00a0\u2014 he can tell you only three values n, d and h: The tree had exactly n vertices. The tree had diameter d. In other words, d was the biggest distance between two vertices. Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree\u00a0\u2013 in this case print \"-1\".", "input_spec": "The first line contains three integers n, d and h (2\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009h\u2009\u2264\u2009d\u2009\u2264\u2009n\u2009-\u20091)\u00a0\u2014 the number of vertices, diameter, and height after rooting in vertex 1, respectively.", "output_spec": "If there is no tree matching what Limak remembers, print the only line with \"-1\" (without the quotes). Otherwise, describe any tree matching Limak's description. Print n\u2009-\u20091 lines, each with two space-separated integers\u00a0\u2013 indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.", "sample_inputs": ["5 3 2", "8 5 2", "8 4 2"], "sample_outputs": ["1 2\n1 3\n3 4\n3 5", "-1", "4 8\n5 7\n2 3\n8 1\n2 1\n5 6\n1 5"], "notes": "NoteBelow you can see trees printed to the output in the first sample and the third sample. "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let d = read_int () in\n let h = read_int () in \n\n if d=1 then (\n if n=2 && h=1 then printf \"1 2\\n\" else printf \"-1\\n\"\n )\n else if d < h || d > 2*h then printf \"-1\\n\"\n else if d=h then if n < d+1 then printf \"-1\\n\" else (\n for i=1 to d do\n printf \"%d %d\\n\" i (i+1);\n done;\n for j=d+2 to n do\n printf \"%d %d\\n\" d j; \n done\n ) else (\n for i=1 to h do\n printf \"%d %d\\n\" i (i+1);\n done;\n printf \"%d %d\\n\" 1 (h+2);\n for i=h+2 to d do\n printf \"%d %d\\n\" i (i+1);\n done;\n for j=d+2 to n do\n printf \"%d %d\\n\" h j;\n done\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let d = read_int () in\n let h = read_int () in \n\n if d=1 then (\n if n=2 && h=1 then printf \"1 2\\n\" else printf \"-n\"\n )\n else if d < h || d > 2*h then printf \"-1\\n\"\n else if d=h then if n < d+1 then printf \"-1\\n\" else (\n for i=1 to d do\n printf \"%d %d\\n\" i (i+1);\n done;\n for j=d+2 to n do\n printf \"%d %d\\n\" d j; \n done\n ) else (\n for i=1 to h do\n printf \"%d %d\\n\" i (i+1);\n done;\n printf \"%d %d\\n\" 1 (h+2);\n for i=h+2 to d do\n printf \"%d %d\\n\" i (i+1);\n done;\n for j=d+2 to n do\n printf \"%d %d\\n\" h j;\n done\n )\n"}], "src_uid": "32096eff277f19d227bccca1b6afc458"} {"nl": {"description": "You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. $$$n$$$ is even.For each position $$$i$$$ ($$$1 \\le i \\le n$$$) in string $$$s$$$ you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once.For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.That way string \"codeforces\", for example, can be changed to \"dpedepqbft\" ('c' $$$\\rightarrow$$$ 'd', 'o' $$$\\rightarrow$$$ 'p', 'd' $$$\\rightarrow$$$ 'e', 'e' $$$\\rightarrow$$$ 'd', 'f' $$$\\rightarrow$$$ 'e', 'o' $$$\\rightarrow$$$ 'p', 'r' $$$\\rightarrow$$$ 'q', 'c' $$$\\rightarrow$$$ 'b', 'e' $$$\\rightarrow$$$ 'f', 's' $$$\\rightarrow$$$ 't').String $$$s$$$ is called a palindrome if it reads the same from left to right and from right to left. For example, strings \"abba\" and \"zz\" are palindromes and strings \"abca\" and \"zy\" are not.Your goal is to check if it's possible to make string $$$s$$$ a palindrome by applying the aforementioned changes to every position. Print \"YES\" if string $$$s$$$ can be transformed to a palindrome and \"NO\" otherwise.Each testcase contains several strings, for each of them you are required to solve the problem separately.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 50$$$) \u2014 the number of strings in a testcase. Then $$$2T$$$ lines follow \u2014 lines $$$(2i - 1)$$$ and $$$2i$$$ of them describe the $$$i$$$-th string. The first line of the pair contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$, $$$n$$$ is even) \u2014 the length of the corresponding string. The second line of the pair contains a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.", "output_spec": "Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th string of the input. Print \"YES\" if it's possible to make the $$$i$$$-th string a palindrome by applying the aforementioned changes to every position. Print \"NO\" otherwise.", "sample_inputs": ["5\n6\nabccba\n2\ncf\n4\nadfa\n8\nabaazaba\n2\nml"], "sample_outputs": ["YES\nNO\nYES\nNO\nNO"], "notes": "NoteThe first string of the example can be changed to \"bcbbcb\", two leftmost letters and two rightmost letters got changed to the next letters, two middle letters got changed to the previous letters.The second string can be changed to \"be\", \"bg\", \"de\", \"dg\", but none of these resulting strings are palindromes.The third string can be changed to \"beeb\" which is a palindrome.The fifth string can be changed to \"lk\", \"lm\", \"nk\", \"nm\", but none of these resulting strings are palindromes. Also note that no letter can remain the same, so you can't obtain strings \"ll\" or \"mm\"."}, "positive_code": [{"source_code": "let palindromalbe str n =\n let rec check i j =\n if i > j then true\n else \n let ch1 = int_of_char (String.get str i) in \n let ch2 = int_of_char (String.get str j) in\n match abs (ch1 - ch2) with\n | 0 | 2 -> check (i + 1) (j - 1)\n | _ -> false\n in\n check 0 (n - 1)\n\nlet () =\nlet t = read_int () in\nfor _ = 1 to t do \n let n = read_int () in\n let str = read_line () in \n print_endline (if palindromalbe str n then \"YES\" else \"NO\")\ndone"}, {"source_code": "\nlet same a b =\n let a = Char.code a in\n let b = Char.code b in\n let diff = abs (a - b) in\n (diff == 0) || (diff == 2) ;; \n\nlet solve () =\n let n = read_int() in\n let s = read_line() in\n\n let rec check str l r =\n if l > r then\n true\n else if same (String.get str l) (String.get str r) then\n true && (check str (l+1) (r-1))\n else false in\n \n let res = check s 0 (n - 1) in\n if res == true then\n print_string \"YES\"\n else\n print_string \"NO\" ;\n print_newline () ;;\n \nlet t = read_int () in\nfor i = 1 to t do \n solve ()\ndone\n"}, {"source_code": "\nlet compute (s: string): bool =\n let l = String.length s in\n let rec f (i: int): bool =\n if i >= (l / 2) then true\n else\n let diff = abs (Char.code (String.get s i) - Char.code (String.get s (l - i - 1))) in\n let ret = diff = 2 || diff = 0 in\n ret && f (i + 1)\n in\n f 0\n\nlet _ =\n let t = Scanf.scanf \" %d\" (fun i -> i) in\n for i = 1 to t do\n let (n, s) = Scanf.scanf \" %d %s\" (fun i j -> (i, j)) in\n (if compute s then \"YES\" else \"NO\") |> print_endline\n done\n"}], "negative_code": [], "src_uid": "cc4cdcd162a83189c7b31a68412f3fe7"} {"nl": {"description": "As we know, DZY loves playing games. One day DZY decided to play with a n\u2009\u00d7\u2009m matrix. To be more precise, he decided to modify the matrix with exactly k operations.Each modification is one of the following: Pick some row of the matrix and decrease each element of the row by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the row before the decreasing. Pick some column of the matrix and decrease each element of the column by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the column before the decreasing. DZY wants to know: what is the largest total value of pleasure he could get after performing exactly k modifications? Please, help him to calculate this value.", "input_spec": "The first line contains four space-separated integers n,\u2009m,\u2009k and p (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009103;\u00a01\u2009\u2264\u2009k\u2009\u2264\u2009106;\u00a01\u2009\u2264\u2009p\u2009\u2264\u2009100). Then n lines follow. Each of them contains m integers representing aij\u00a0(1\u2009\u2264\u2009aij\u2009\u2264\u2009103) \u2014 the elements of the current row of the matrix.", "output_spec": "Output a single integer \u2014 the maximum possible total pleasure value DZY could get.", "sample_inputs": ["2 2 2 2\n1 3\n2 4", "2 2 5 2\n1 3\n2 4"], "sample_outputs": ["11", "11"], "notes": "NoteFor the first sample test, we can modify: column 2, row 2. After that the matrix becomes:1 10 0For the second sample test, we can modify: column 2, row 2, row 1, column 1, column 2. After that the matrix becomes:-3 -3-2 -2"}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\n(* skew heap code ---------------------------------------------------------*)\ntype 'a stree = SkewLeaf | Node of 'a stree * 'a * 'a stree\n\nlet rec meld a b = \n match a,b with \n | SkewLeaf, _ -> b | _, SkewLeaf -> a \n | Node(al, ak, ar), Node(bl, bk, br) -> \n if (ak >= bk) then Node((meld ar b), ak, al)\n else Node((meld a br), bk, bl)\n\nlet insert a k = \n meld a (Node(SkewLeaf, k, SkewLeaf))\n\nlet findmax a = \n match a with SkewLeaf -> failwith \"Findmin on empty heap\"\n | Node(al, ak, ar) -> ak\n\nlet deletemax a = \n match a with SkewLeaf -> failwith \"Deletemin on empty heap\"\n | Node(al, ak, ar) -> meld al ar\n(*-------------------------------------------------------------------------*)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet long x = Int64.of_int x\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n let p = long (read_int ()) in\n\n let a = Array.make_matrix n m 0L in\n for i=0 to n-1 do\n for j=0 to m-1 do\n a.(i).(j) <- long (read_int())\n done\n done;\n\n let rowsum = Array.make n 0L in\n for i=0 to n-1 do\n rowsum.(i) <- sum 0 (m-1) (fun j -> a.(i).(j))\n done;\n\n let colsum = Array.make m 0L in\n for j=0 to m-1 do\n colsum.(j) <- sum 0 (n-1) (fun i -> a.(i).(j))\n done;\n\n let oned n a mp =\n let score = Array.make (k+1) 0L in\n\n let rec loop i s ac = \n score.(i) <- ac;\n if ij then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet long x = Int64.of_int x\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n let p = long (read_int ()) in\n\n let a = Array.make_matrix n m 0L in\n for i=0 to n-1 do\n for j=0 to m-1 do\n a.(i).(j) <- Int64.of_int (read_int())\n done\n done;\n\n let rowsum = Array.make n 0L in\n\n for i=0 to n-1 do\n rowsum.(i) <- sum 0 (m-1) (fun j -> a.(i).(j))\n done;\n\n let colsum = Array.make m 0L in\n\n for j=0 to m-1 do\n colsum.(j) <- sum 0 (n-1) (fun i -> a.(i).(j))\n done;\n\n let rec loop rowset colset row_op_count col_op_count ac = \n let (rc, cc) = (row_op_count, col_op_count) in\n if rc + cc = k then ac else\n let (rowval,(rscore,rj)) = \n\tlet (score,j) = Pset.max_elt rowset in\n\t(score -- (long cc)**p, (score,j))\n in\n let (colval,(cscore,ci)) = \n\tlet (score,i) = Pset.max_elt colset in\n\t(score -- (long rc)**p, (score,i))\n in\n \n if rowval > colval then (\n\tlet rowset = Pset.remove (rscore,rj) rowset in\n\tlet rowset = Pset.add (rscore--(long m)**p,rj) rowset in\n\tloop rowset colset (rc+1) cc (ac++rowval)\n ) else (\n\tlet colset = Pset.remove (cscore,ci) colset in\n\tlet colset = Pset.add (cscore--(long n)**p,ci) colset in\n\tloop rowset colset rc (cc+1) (ac++colval)\n )\n in\n\n let rec build_rowset s i = if i=n then s else\n build_rowset (Pset.add (rowsum.(i),i) s) (i+1)\n in\n\n let rec build_colset s j = if j=m then s else\n build_colset (Pset.add (colsum.(j),j) s) (j+1)\n in\n\n let rowset = build_rowset Pset.empty 0 in\n let colset = build_colset Pset.empty 0 in\n\n let answer = loop rowset colset 0 0 0L in\n\n printf \"%Ld\\n\" answer\n"}, {"source_code": "open Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let m = read_int () in\n let k = read_int () in\n let p = read_int () in\n\n let a = Array.make_matrix n m 0 in\n for i=0 to n-1 do\n for j=0 to m-1 do\n a.(i).(j) <- read_int()\n done\n done;\n\n let rowsum = Array.make n 0 in\n\n for i=0 to n-1 do\n rowsum.(i) <- sum 0 (m-1) (fun j -> a.(i).(j))\n done;\n\n let colsum = Array.make m 0 in\n\n for j=0 to m-1 do\n colsum.(j) <- sum 0 (n-1) (fun i -> a.(i).(j))\n done;\n\n let rec loop rowset colset row_op_count col_op_count ac = \n let (rc, cc) = (row_op_count, col_op_count) in\n if rc + cc = k then ac else\n let (rowval,(rscore,rj)) = \n\tlet (score,j) = Pset.max_elt rowset in\n\t(score - cc*p, (score,j))\n in\n let (colval,(cscore,ci)) = \n\tlet (score,i) = Pset.max_elt colset in\n\t(score - rc*p, (score,i))\n in\n \n if rowval > colval then (\n\tlet rowset = Pset.remove (rscore,rj) rowset in\n\tlet rowset = Pset.add (rscore-m*p,rj) rowset in\n\tloop rowset colset (rc+1) cc (ac+rowval)\n ) else (\n\tlet colset = Pset.remove (cscore,ci) colset in\n\tlet colset = Pset.add (cscore-n*p,ci) colset in\n\tloop rowset colset rc (cc+1) (ac+colval)\n )\n in\n\n let rec build_rowset s i = if i=n then s else\n build_rowset (Pset.add (rowsum.(i),i) s) (i+1)\n in\n\n let rec build_colset s j = if j=m then s else\n build_colset (Pset.add (colsum.(j),j) s) (j+1)\n in\n\n let rowset = build_rowset Pset.empty 0 in\n let colset = build_colset Pset.empty 0 in\n\n let answer = loop rowset colset 0 0 0 in\n\n printf \"%d\\n\" answer\n"}], "src_uid": "8a905ae55ac9364a9ed2807f06a05ff0"} {"nl": {"description": "Dima is living in a dormitory, as well as some cockroaches.At the moment 0 Dima saw a cockroach running on a table and decided to kill it. Dima needs exactly T seconds for aiming, and after that he will precisely strike the cockroach and finish it.To survive the cockroach has to run into a shadow, cast by round plates standing on the table, in T seconds. Shadow casted by any of the plates has the shape of a circle. Shadow circles may intersect, nest or overlap arbitrarily.The cockroach uses the following strategy: first he equiprobably picks a direction to run towards and then runs towards it with the constant speed v. If at some moment t\u2009\u2264\u2009T it reaches any shadow circle, it immediately stops in the shadow and thus will stay alive. Otherwise the cockroach is killed by the Dima's precise strike. Consider that the Dima's precise strike is instant.Determine the probability of that the cockroach will stay alive.", "input_spec": "In the first line of the input the four integers x0, y0, v, T (|x0|,\u2009|y0|\u2009\u2264\u2009109, 0\u2009\u2264\u2009v,\u2009T\u2009\u2264\u2009109) are given\u00a0\u2014 the cockroach initial position on the table in the Cartesian system at the moment 0, the cockroach's constant speed and the time in seconds Dima needs for aiming respectively. In the next line the only number n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000) is given\u00a0\u2014 the number of shadow circles casted by plates. In the next n lines shadow circle description is given: the ith of them consists of three integers xi, yi, ri (|xi|,\u2009|yi|\u2009\u2264\u2009109, 0\u2009\u2264\u2009r\u2009\u2264\u2009109)\u00a0\u2014 the ith shadow circle on-table position in the Cartesian system and its radius respectively. Consider that the table is big enough for the cockroach not to run to the table edges and avoid Dima's precise strike.", "output_spec": "Print the only real number p\u00a0\u2014 the probability of that the cockroach will stay alive. Your answer will be considered correct if its absolute or relative error does not exceed 10\u2009-\u20094.", "sample_inputs": ["0 0 1 1\n3\n1 1 1\n-1 -1 1\n-2 2 1", "0 0 1 0\n1\n1 0 1"], "sample_outputs": ["0.50000000000", "1.00000000000"], "notes": "NoteThe picture for the first sample is given below. Red color stands for points which being chosen as the cockroach's running direction will cause him being killed, green color for those standing for survival directions. Please note that despite containing a circle centered in (\u2009-\u20092,\u20092) a part of zone is colored red because the cockroach is not able to reach it in one second."}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let x0 = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let y0 = Scanf.bscanf sb \"%Ld \" (fun s -> s) in\n let v = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = Array.make n 0L in\n let y = Array.make n 0L in\n let r = Array.make n 0L in\n let _ =\n for i = 0 to n - 1 do\n x.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s) -| x0;\n y.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s) -| y0;\n r.(i) <- Scanf.bscanf sb \"%Ld \" (fun s -> s);\n done;\n in\n let pi = 4.0 *. atan 1.0 in\n let sqr x = x *. x in\n let norm x y = sqrt (sqr x +. sqr y) in\n let dist x1 y1 x2 y2 = norm (x1 -. x2) (y1 -. y2) in\n let d = v *. t in\n let segs = ref [] in\n let () =\n for i = 0 to n - 1 do\n let x' = x.(i)\n and y' = y.(i)\n and r' = r.(i) in\n let x = Int64.to_float x'\n and y = Int64.to_float y'\n and r = Int64.to_float r' in\n let dc = norm x y in\n\tif x' *| x' +| y' *| y' <= r' *| r'\n\tthen segs := (-.pi, pi) :: !segs\n\telse if dc -. r <= d then (\n\t let ac = atan2 y x in\n\t let a = asin (r /. dc) in\n\t let dt = sqrt (sqr dc -. sqr r) in\n\t if d >= dt -. 1e-9\n\t then segs := (ac -. a, ac +. a) :: !segs\n\t else (\n\t let a = acos ((sqr dc +. sqr d -. sqr r) /. (2.0 *. dc *. d)) in\n\t\tsegs := (ac -. a, ac +. a) :: !segs;\n\t )\n\t)\n done;\n in\n let ps = ref [] in\n let cnt = ref 0 in\n let () =\n (*List.iter (fun (a1, a2) -> Printf.printf \"qwe %f %f\\n\" a1 a2) !segs;*)\n List.iter\n (fun (a1, a2) ->\n\t if a1 < -.pi then (\n\t assert (a2 >= -. pi);\n\t ps := (a2, -1) :: (a1 +. 2.0 *. pi, 1) :: !ps;\n\t incr cnt;\n\t ) else if a2 > pi then (\n\t assert (a1 <= pi);\n\t ps := (a2 -. 2.0 *. pi, -1) :: (a1, 1) :: !ps;\n\t incr cnt;\n\t ) else (\n\t ps := (a2, -1) :: (a1, 1) :: !ps;\n\t )\n ) !segs;\n in\n let ps = Array.of_list !ps in\n let () = Array.sort compare ps in\n let prev = ref (-.pi) in\n let res = ref 0.0 in\n for i = 0 to Array.length ps - 1 do\n let (a, x) = ps.(i) in\n\tif !cnt > 0\n\tthen res := !res +. a -. !prev;\n\tcnt := !cnt + x;\n\tprev := a;\n done;\n if !cnt > 0\n then res := !res +. pi -. !prev;\n res := !res /. (2.0 *. pi);\n Printf.printf \"%.8f\\n\" !res\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let x0 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y0 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let v = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = Array.make n 0.0 in\n let y = Array.make n 0.0 in\n let r = Array.make n 0.0 in\n let _ =\n for i = 0 to n - 1 do\n x.(i) <- Scanf.bscanf sb \"%f \" (fun s -> s) -. x0;\n y.(i) <- Scanf.bscanf sb \"%f \" (fun s -> s) -. y0;\n r.(i) <- Scanf.bscanf sb \"%f \" (fun s -> s);\n done;\n in\n let pi = 4.0 *. atan 1.0 in\n let sqr x = x *. x in\n let norm x y = sqrt (sqr x +. sqr y) in\n let dist x1 y1 x2 y2 = norm (x1 -. x2) (y1 -. y2) in\n let d = v *. t in\n let segs = ref [] in\n let () =\n for i = 0 to n - 1 do\n let x = x.(i)\n and y = y.(i)\n and r = r.(i) in\n let dc = norm x y in\n\tif dc <= r\n\tthen segs := (-.pi, pi) :: !segs\n\telse if dc -. r <= d then (\n\t let ac = atan2 y x in\n\t let a = asin (r /. dc) in\n\t let dt = sqrt (sqr dc -. sqr r) in\n\t if d >= dt -. 1e-9\n\t then segs := (ac -. a, ac +. a) :: !segs\n\t else (\n\t let a = acos ((sqr dc +. sqr d -. sqr r) /. (2.0 *. dc *. d)) in\n\t\tsegs := (ac -. a, ac +. a) :: !segs;\n\t )\n\t)\n done;\n in\n let ps = ref [] in\n let cnt = ref 0 in\n let () =\n (*List.iter (fun (a1, a2) -> Printf.printf \"qwe %f %f\\n\" a1 a2) !segs;*)\n List.iter\n (fun (a1, a2) ->\n\t if a1 < -.pi then (\n\t assert (a2 >= -. pi);\n\t ps := (a2, -1) :: (a1 +. 2.0 *. pi, 1) :: !ps;\n\t incr cnt;\n\t ) else if a2 > pi then (\n\t assert (a1 <= pi);\n\t ps := (a2 -. 2.0 *. pi, -1) :: (a1, 1) :: !ps;\n\t incr cnt;\n\t ) else (\n\t ps := (a2, -1) :: (a1, 1) :: !ps;\n\t )\n ) !segs;\n in\n let ps = Array.of_list !ps in\n let () = Array.sort compare ps in\n let prev = ref (-.pi) in\n let res = ref 0.0 in\n for i = 0 to Array.length ps - 1 do\n let (a, x) = ps.(i) in\n\tif !cnt > 0\n\tthen res := !res +. a -. !prev;\n\tcnt := !cnt + x;\n\tprev := a;\n done;\n if !cnt > 0\n then res := !res +. pi -. !prev;\n res := !res /. (2.0 *. pi);\n Printf.printf \"%.8f\\n\" !res\n"}], "src_uid": "3927429da3f2e6b9229e2624d67f6c3b"} {"nl": {"description": "You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x,\u2009y), where gcd denotes the greatest common divisor.What is the minimum number of operations you need to make all of the elements equal to 1?", "input_spec": "The first line of the input contains one integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of elements in the array. The second line contains n space separated integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109)\u00a0\u2014 the elements of the array.", "output_spec": "Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.", "sample_inputs": ["5\n2 2 3 4 6", "4\n2 4 6 8", "3\n2 6 9"], "sample_outputs": ["5", "-1", "4"], "notes": "NoteIn the first sample you can turn all numbers to 1 using the following 5 moves: [2,\u20092,\u20093,\u20094,\u20096]. [2,\u20091,\u20093,\u20094,\u20096] [2,\u20091,\u20093,\u20091,\u20096] [2,\u20091,\u20091,\u20091,\u20096] [1,\u20091,\u20091,\u20091,\u20096] [1,\u20091,\u20091,\u20091,\u20091] We can prove that in this case it is not possible to make all numbers one using less than 5 moves."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec gcd a b = if a=0 then b else gcd (b mod a) a \n\nlet () = \n let n = read_int () in\n let a = Array.init n read_int in\n\n\n let n_ones = sum 0 (n-1) (fun i -> if a.(i) = 1 then 1 else 0) in\n\n if n_ones > 0 then printf \"%d\\n\" (n - n_ones) else (\n\n let g = Array.make_matrix n n 0 in\n\n let short = ref 0 in\n \n for i=0 to n-1 do\n g.(i).(i) <- a.(i)\n done;\n for len = 2 to n do\n for i = 0 to n-len do\n\tlet x = gcd g.(i).(i+len-2) a.(i+len-1) in\n\tg.(i).(i+len-1) <- x;\n\tif !short = 0 && x = 1 then short := len\n done\n done;\n\n if !short = 0 then printf \"-1\\n\" else printf \"%d\\n\" (!short - 1 + n-1)\n )\n"}], "negative_code": [], "src_uid": "c489061d9e8587d2e85cad0e2f23f3fb"} {"nl": {"description": "In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them. ", "input_spec": "The first line contains the integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of citizens in the kingdom. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an, where ai (0\u2009\u2264\u2009ai\u2009\u2264\u2009106)\u00a0\u2014 the welfare of the i-th citizen.", "output_spec": "In the only line print the integer S\u00a0\u2014 the minimum number of burles which are had to spend.", "sample_inputs": ["5\n0 1 2 3 4", "5\n1 1 0 1 1", "3\n1 3 1", "1\n12"], "sample_outputs": ["10", "1", "4", "0"], "notes": "NoteIn the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.In the second example it is enough to give one burle to the third citizen. In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () =\n let n = read () in\n let rec loop i sum max =\n if i < n\n then\n let balance = read () in\n if balance > max\n then\n loop (i + 1) (sum + balance) balance\n else\n loop (i + 1) (sum + balance) max\n else\n print (n * max - sum)\n in loop 0 0 0"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\nlet print result = Printf.printf \"%d\\n\" result\n\nlet input () =\n let n = read () in\n let rec loop list i max =\n if i < n\n then\n let balance = read () in\n if balance > max\n then\n loop (balance :: list) (i + 1) balance\n else\n loop (balance :: list) (i + 1) max\n else\n (list, max)\n in loop [] 0 0\n\nlet solve (list, max) =\n let rec loop sum rest =\n match rest with\n | hd :: tl -> loop (sum + (max - hd)) tl\n | [] -> sum\n in loop 0 list\n\nlet () = print (solve (input ()))"}, {"source_code": "let n = read_int () ;;\nlet a = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) ;;\nlet m = Array.fold_left max 0 a ;;\nlet d = Array.map ((-) m) a ;;\nlet s = Array.fold_left (+) 0 d ;;\n\nPrintf.printf \"%d\\n\" s\n"}, {"source_code": "let maximum = List.fold_left max 0 in\nlet _ = read_line () in\nlet ns = read_line () |> (Str.regexp \" +\" |> Str.split) |> List.map int_of_string in\nlet s = maximum ns |> Array.make (List.length ns) |> Array.to_list |> List.map2 (fun a b -> b - a ) ns |> List.fold_left (+) 0 in\nprint_int s\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let lst = \n let rec loop a = function\n | 0 -> a\n | m -> loop ([read_int ()] @ a) (m - 1)\n in loop [] n\n in\n let max =\n let rec loop a = function\n | [] -> a\n | hd :: tl -> if hd > a then loop hd tl else loop a tl\n in loop 0 lst\n in\n let ans = List.fold_left (fun a b -> a + (abs (b - max))) 0 lst in\n Printf.printf \"%d\\n\" ans\n"}, {"source_code": "let rec accumulate_burles n ax m_ax =\n\tmatch n with\n\t|0 -> (ax, m_ax)\n\t|_ -> \n\t\tlet v = ref 0 in \n\t\tbegin \n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %i\" ( fun x -> v := x; );\n\t\t\taccumulate_burles (n-1) (ax + !v) (max m_ax !v)\n\t\tend\n\nlet read_and_solve total_count =\n\tlet (sum, max_val) = (accumulate_burles total_count 0 0) in\n\tlet diff = max_val * total_count - sum in\n\tPrintf.printf \"%i\\n\" diff\n;;\n\t\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %i \" read_and_solve\n;;\n\nread_input ()\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let res = ref 0 in\n let m = ref a.(0) in\n for i = 0 to n - 1 do\n m := max !m a.(i);\n done;\n for i = 0 to n - 1 do\n res := !res + !m - a.(i)\n done;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [{"source_code": "let maximum = List.fold_left max 0 in\nlet _ = read_line () in\nlet ns = read_line () |> (Str.regexp \" *\" |> Str.split) |> List.map int_of_string in\nlet s = maximum ns |> Array.make (List.length ns) |> Array.to_list |> List.map2 (fun a b -> b - a ) ns |> List.fold_left (+) 0 in\nprint_int s\n"}], "src_uid": "a5d3c9ea1c9affb0359d81dae4ecd7c8"} {"nl": {"description": "You are given a set of $$$n\\ge 2$$$ pairwise different points with integer coordinates. Your task is to partition these points into two nonempty groups $$$A$$$ and $$$B$$$, such that the following condition holds:For every two points $$$P$$$ and $$$Q$$$, write the Euclidean distance between them on the blackboard: if they belong to the same group\u00a0\u2014 with a yellow pen, and if they belong to different groups\u00a0\u2014 with a blue pen. Then no yellow number is equal to any blue number.It is guaranteed that such a partition exists for any possible input. If there exist multiple partitions, you are allowed to output any of them.", "input_spec": "The first line contains one integer $$$n$$$ $$$(2 \\le n \\le 10^3)$$$\u00a0\u2014 the number of points. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$-10^6 \\le x_i, y_i \\le 10^6$$$)\u00a0\u2014 the coordinates of the $$$i$$$-th point. It is guaranteed that all $$$n$$$ points are pairwise different.", "output_spec": "In the first line, output $$$a$$$ ($$$1 \\le a \\le n-1$$$)\u00a0\u2014 the number of points in a group $$$A$$$. In the second line, output $$$a$$$ integers\u00a0\u2014 the indexes of points that you include into group $$$A$$$. If there are multiple answers, print any.", "sample_inputs": ["3\n0 0\n0 1\n1 0", "4\n0 1\n0 -1\n1 0\n-1 0", "3\n-2 1\n1 1\n-1 0", "6\n2 5\n0 3\n-4 -1\n-5 -4\n1 0\n3 -1", "2\n-1000000 -1000000\n1000000 1000000"], "sample_outputs": ["1\n1", "2\n1 2", "1\n2", "1\n6", "1\n1"], "notes": "NoteIn the first example, we set point $$$(0, 0)$$$ to group $$$A$$$ and points $$$(0, 1)$$$ and $$$(1, 0)$$$ to group $$$B$$$. In this way, we will have $$$1$$$ yellow number $$$\\sqrt{2}$$$ and $$$2$$$ blue numbers $$$1$$$ on the blackboard.In the second example, we set points $$$(0, 1)$$$ and $$$(0, -1)$$$ to group $$$A$$$ and points $$$(-1, 0)$$$ and $$$(1, 0)$$$ to group $$$B$$$. In this way, we will have $$$2$$$ yellow numbers $$$2$$$, $$$4$$$ blue numbers $$$\\sqrt{2}$$$ on the blackboard."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n \nlet () =\n let n = read_int() in\n let x = Array.make n 0 in\n let y = Array.make n 0 in\n for i=0 to n-1 do\n x.(i) <- read_int();\n y.(i) <- read_int();\n done;\n\n let rec classify () =\n let neven = sum 0 (n-1) (fun i -> if (x.(i) + y.(i)) mod 2 = 0 then 1 else 0) in\n let simplify () = (* assumes both coords same parity *)\n for i=0 to n-1 do\n\tlet (a,b) = (x.(i), y.(i)) in\n\tx.(i) <- (a+b)/2;\n\ty.(i) <- (a-b)/2\n done\n in\n if neven = n then (\n simplify();\n classify()\n ) else if neven = 0 then (\n for i=0 to n-1 do x.(i) <- x.(i) + 1 done;\n simplify();\n classify()\n ) else neven\n in\n\n let neven = classify() in\n\n printf \"%d\\n\" neven;\n\n for i=0 to n-1 do\n if (x.(i) + y.(i)) mod 2 = 0 then printf \"%d \" (i+1)\n done;\n\n print_newline()\n"}], "negative_code": [], "src_uid": "d6dc1895a58e13cdac98377819f6ec68"} {"nl": {"description": "Let's call an array $$$a_1, a_2, \\dots, a_m$$$ of nonnegative integer numbers good if $$$a_1 + a_2 + \\dots + a_m = 2\\cdot(a_1 \\oplus a_2 \\oplus \\dots \\oplus a_m)$$$, where $$$\\oplus$$$ denotes the bitwise XOR operation.For example, array $$$[1, 2, 3, 6]$$$ is good, as $$$1 + 2 + 3 + 6 = 12 = 2\\cdot 6 = 2\\cdot (1\\oplus 2 \\oplus 3 \\oplus 6)$$$. At the same time, array $$$[1, 2, 1, 3]$$$ isn't good, as $$$1 + 2 + 1 + 3 = 7 \\neq 2\\cdot 1 = 2\\cdot(1\\oplus 2 \\oplus 1 \\oplus 3)$$$.You are given an array of length $$$n$$$: $$$a_1, a_2, \\dots, a_n$$$. Append at most $$$3$$$ elements to it to make it good. Appended elements don't have to be different. It can be shown that the solution always exists under the given constraints. If there are different solutions, you are allowed to output any of them. Note that you don't have to minimize the number of added elements!. So, if an array is good already you are allowed to not append elements.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\le t \\le 10\\,000$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\\le n \\le 10^5)$$$\u00a0\u2014 the size of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$0\\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, output two lines. In the first line, output a single integer $$$s$$$ ($$$0\\le s\\le 3$$$)\u00a0\u2014 the number of elements you want to append. In the second line, output $$$s$$$ integers $$$b_1, \\dots, b_s$$$ ($$$0\\le b_i \\le 10^{18}$$$)\u00a0\u2014 the elements you want to append to the array. If there are different solutions, you are allowed to output any of them.", "sample_inputs": ["3\n4\n1 2 3 6\n1\n8\n2\n1 1"], "sample_outputs": ["0\n\n2\n4 4\n3\n2 6 2"], "notes": "NoteIn the first test case of the example, the sum of all numbers is $$$12$$$, and their $$$\\oplus$$$ is $$$6$$$, so the condition is already satisfied.In the second test case of the example, after adding $$$4, 4$$$, the array becomes $$$[8, 4, 4]$$$. The sum of numbers in it is $$$16$$$, $$$\\oplus$$$ of numbers in it is $$$8$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n \nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( ^ ) a b = Int64.logxor a b\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\nlet xsum i j f = fold i j (fun i a -> (f i) ^ a) 0L\n \nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let ar = Array.init n read_long in\n let x = xsum 0 (n-1) (fun i -> ar.(i)) in\n let s = sum 0 (n-1) (fun i -> ar.(i)) in\n let xs = x ++ s in\n printf \"2\\n\";\n printf \"%Ld %Ld\\n\" x xs\n done"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( ^ ) a b = Int64.logxor a b\n \nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\nlet xsum i j f = fold i j (fun i a -> (f i) ^ a) 0L\n \nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int() in\n let ar = Array.init n read_long in\n let b = xsum 0 (n-1) (fun i -> ar.(i)) in\n let a = sum 0 (n-1) (fun i -> ar.(i)) in\n let x = b in\n let a' = x ++ a in\n let y = a' in\n printf \"2\\n\";\n printf \"%Ld %Ld\\n\" x y\n done\n"}], "negative_code": [], "src_uid": "cced3c3d3f1a63e81e36c94fc2ce9379"} {"nl": {"description": "Polycarp is working on a new project called \"Polychat\". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: Include a person to the chat ('Add' command). Remove a person from the chat ('Remove' command). Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.", "input_spec": "Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following: +<name> for 'Add' command. -<name> for 'Remove' command. <sender_name>:<message_text> for 'Send' command. <name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line. It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc. All names are case-sensitive.", "output_spec": "Print a single number \u2014 answer to the problem.", "sample_inputs": ["+Mike\nMike:hello\n+Kate\n+Dmitry\n-Dmitry\nKate:hi\n-Kate", "+Mike\n-Mike\n+Mike\nMike:Hi I am here\n-Mike\n+Kate\n-Kate"], "sample_outputs": ["9", "14"], "notes": null}, "positive_code": [{"source_code": "let n=ref 0;;\nlet m=ref 0;;\nlet pos s=\nlet i=ref 0 in\nwhile s.[ !i]<>':' do\n incr i\ndone;\nincr i;\n!i;;\nlet b=ref true;;\nfor j=1 to 100 do\n if !b then \n begin\n let s = try read_line() with _ -> \"\" in\n if s=\"\" then b:=false\n else if s.[0]='+' then incr n\n else if s.[0]='-' then decr n\n else let i=pos s in m:= !m+String.length(String.sub s i (String.length( s)-i))* !n;\n end\ndone;;\nprint_int !m;;"}, {"source_code": "module StrSet = Set.Make(String)\n\nlet rec f h ans =\n try\n let a = read_line () in\n let l = String.length a in\n if a.[0] = '+' then\n f (StrSet.add (String.sub a 1 (l-1)) h) ans\n else if a.[0] = '-' then\n f (StrSet.remove (String.sub a 1 (l-1)) h) ans\n else\n f h (ans+(StrSet.cardinal h*(l-1-String.index a ':')))\n with End_of_file ->\n ans\n\nlet () =\n Printf.printf \"%d\\n\" (f StrSet.empty 0)\n"}], "negative_code": [], "src_uid": "d7fe15a027750c004e4f50175e1e20d2"} {"nl": {"description": "Since Sonya is interested in robotics too, she decided to construct robots that will read and recognize numbers.Sonya has drawn $$$n$$$ numbers in a row, $$$a_i$$$ is located in the $$$i$$$-th position. She also has put a robot at each end of the row (to the left of the first number and to the right of the last number). Sonya will give a number to each robot (they can be either same or different) and run them. When a robot is running, it is moving toward to another robot, reading numbers in the row. When a robot is reading a number that is equal to the number that was given to that robot, it will turn off and stay in the same position.Sonya does not want robots to break, so she will give such numbers that robots will stop before they meet. That is, the girl wants them to stop at different positions so that the first robot is to the left of the second one.For example, if the numbers $$$[1, 5, 4, 1, 3]$$$ are written, and Sonya gives the number $$$1$$$ to the first robot and the number $$$4$$$ to the second one, the first robot will stop in the $$$1$$$-st position while the second one in the $$$3$$$-rd position. In that case, robots will not meet each other. As a result, robots will not be broken. But if Sonya gives the number $$$4$$$ to the first robot and the number $$$5$$$ to the second one, they will meet since the first robot will stop in the $$$3$$$-rd position while the second one is in the $$$2$$$-nd position.Sonya understands that it does not make sense to give a number that is not written in the row because a robot will not find this number and will meet the other robot.Sonya is now interested in finding the number of different pairs that she can give to robots so that they will not meet. In other words, she wants to know the number of pairs ($$$p$$$, $$$q$$$), where she will give $$$p$$$ to the first robot and $$$q$$$ to the second one. Pairs ($$$p_i$$$, $$$q_i$$$) and ($$$p_j$$$, $$$q_j$$$) are different if $$$p_i\\neq p_j$$$ or $$$q_i\\neq q_j$$$.Unfortunately, Sonya is busy fixing robots that broke after a failed launch. That is why she is asking you to find the number of pairs that she can give to robots so that they will not meet.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1\\leq n\\leq 10^5$$$)\u00a0\u2014 the number of numbers in a row. The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1\\leq a_i\\leq 10^5$$$)\u00a0\u2014 the numbers in a row.", "output_spec": "Print one number\u00a0\u2014 the number of possible pairs that Sonya can give to robots so that they will not meet.", "sample_inputs": ["5\n1 5 4 1 3", "7\n1 2 1 1 1 3 2"], "sample_outputs": ["9", "7"], "notes": "NoteIn the first example, Sonya can give pairs ($$$1$$$, $$$1$$$), ($$$1$$$, $$$3$$$), ($$$1$$$, $$$4$$$), ($$$1$$$, $$$5$$$), ($$$4$$$, $$$1$$$), ($$$4$$$, $$$3$$$), ($$$5$$$, $$$1$$$), ($$$5$$$, $$$3$$$), and ($$$5$$$, $$$4$$$).In the second example, Sonya can give pairs ($$$1$$$, $$$1$$$), ($$$1$$$, $$$2$$$), ($$$1$$$, $$$3$$$), ($$$2$$$, $$$1$$$), ($$$2$$$, $$$2$$$), ($$$2$$$, $$$3$$$), and ($$$3$$$, $$$2$$$)."}, "positive_code": [{"source_code": "open Int64\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet n = Scanf.sscanf (read_line ()) \"%i\" (fun n -> n) in\nlet number = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet count = ref zero in\nlet rseen = Array.make 500000 zero in\nfor i = n - 1 downto 0 do\n if rseen.(number.(i)) = zero then count := succ !count;\n rseen.(number.(i)) <- succ rseen.(number.(i));\ndone;\nlet result = ref zero in\nlet seen = Array.make 500000 false in\nfor i = 0 to n - 2 do\n rseen.(number.(i)) <- pred rseen.(number.(i));\n if rseen.(number.(i)) = zero then count := pred !count;\n if not seen.(number.(i)) then result := add !result !count;\n seen.(number.(i)) <- true;\ndone;\nprint_endline @@ to_string !result;\n"}, {"source_code": "open Int64\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet n = Scanf.sscanf (read_line ()) \"%i\" (fun n -> n) in\nlet number = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet count = ref 0L in\nlet rseen = Array.make 500000 0L in\nfor i = n - 1 downto 0 do\n if rseen.(number.(i)) = 0L then count := succ !count;\n rseen.(number.(i)) <- succ rseen.(number.(i));\ndone;\nlet result = ref 0L in\nlet seen = Array.make 500000 false in\nfor i = 0 to n - 2 do\n rseen.(number.(i)) <- pred rseen.(number.(i));\n if rseen.(number.(i)) = 0L then count := pred !count;\n if not seen.(number.(i)) then result := add !result !count;\n seen.(number.(i)) <- true;\ndone;\nprint_endline @@ to_string !result;\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt64 = struct \n\t(* include Int64 *)\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\n\tlet ($) = (~|)\nend open MyInt64\n\nlet () =\n let n = get_i64 ()\n\tin let ar = input_i64_array n\n\tin let mx = 100020\n\tin let undef = -1\n\tin let n_occur = Array.make mx undef\n\tin let n_occur_rev = Array.make mx undef\n\tin let k_occur = Array.make ~|n 0L\n\tin \n\tlet ns = ref [] in\n\tArray.iteri (fun i v ->\n\t\tlet v = ~|v in\n\t\tif n_occur.(v) = undef then (\n\t\t\tn_occur.(v) <- i;\n\t\t\tns := v::!ns\n\t\t);\n\t) ar;\n\tlet ns = List.map (fun v -> \n\t\tn_occur.(v)\n\t) !ns in\n\tlet k0 = ref 0L in \n\tArray.iteri (fun i v ->\n\t\tlet v = ~|v in let i = ~|n-$1-$i in\n\t\tif n_occur_rev.(v) = undef then (\n\t\t\tn_occur_rev.(v) <- i;\n\t\t\tk0 += 1L;\n\t\t);\n\t\tif (i-$1 >= 0) then k_occur.(i-$1) <- !k0;\n\t) (ar |> Array.to_list |> List.rev |> Array.of_list);\n\t(* Array.iteri (fun i v ->\n\t\tprintf \"%d: %Ld\\n\" i k_occur.(i);\n\t) ar; *)\n\tlet ans = ref 0L in\n\tList.iter (fun v -> \n\t\t(* printf \"ans += k_occur.(%d) = %Ld\\n\" v k_occur.(v); *)\n\t\tans += k_occur.(v);\n\t) ns;\n\t!ans |> print_i64_endline"}], "negative_code": [{"source_code": "open Int32\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n;;\n\nlet n = Scanf.sscanf (read_line ()) \"%i\" (fun n -> n) in\nlet number = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet count = ref zero in\nlet rseen = Array.make 500000 zero in\nfor i = n - 1 downto 0 do\n if rseen.(number.(i)) = zero then count := succ !count;\n rseen.(number.(i)) <- succ rseen.(number.(i));\ndone;\nlet result = ref zero in\nlet seen = Array.make 500000 false in\nfor i = 0 to n - 2 do\n rseen.(number.(i)) <- pred rseen.(number.(i));\n if rseen.(number.(i)) = zero then count := pred !count;\n if not seen.(number.(i)) then result := add !result !count;\n seen.(number.(i)) <- true;\ndone;\nprint_endline @@ to_string !result;\n"}, {"source_code": "let ( */ ) = Big_int.mult_big_int;;\nlet ( +/ ) = Big_int.add_big_int;;\nlet ( -/ ) = Big_int.sub_big_int;;\nlet to_int = Big_int.int_of_big_int;;\nlet of_int = Big_int.big_int_of_int;;\nlet min = Big_int.min_big_int;;\nlet (modi) = Big_int.mod_big_int;;\nlet to_string = Big_int.string_of_big_int;;\nlet of_string = Big_int.big_int_of_string;;\nlet ( n) in\nlet number = read_line () |> split_on_char ' ' |> List.map int_of_string |> Array.of_list in\nlet count = ref 0 in\nlet rseen = Array.make 500000 0 in\nfor i = n - 1 downto 0 do\n if rseen.(number.(i)) = 0 then incr count;\n rseen.(number.(i)) <- rseen.(number.(i)) + 1;\ndone;\nlet result = ref 0 in\nlet seen = Array.make 500000 false in\nfor i = 0 to n - 2 do\n rseen.(number.(i)) <- rseen.(number.(i)) - 1;\n if rseen.(number.(i)) = 0 then decr count;\n if not seen.(number.(i)) then result := !result + !count;\n seen.(number.(i)) <- true;\ndone;\nprint_int !result;\nprint_newline ();\n"}], "src_uid": "4671380d70876044e0ec7a9cab5e25ae"} {"nl": {"description": "Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following actions: Walk up or down one unit on a tree. Eat a nut on the top of the current tree. Jump to the next tree. In this action the height of Liss doesn't change. More formally, when Liss is at height h of the tree i (1\u2009\u2264\u2009i\u2009\u2264\u2009n\u2009-\u20091), she jumps to height h of the tree i\u2009+\u20091. This action can't be performed if h\u2009>\u2009hi\u2009+\u20091. Compute the minimal time (in seconds) required to eat all nuts.", "input_spec": "The first line contains an integer n (1\u2009\u2009\u2264\u2009\u2009n\u2009\u2264\u2009105) \u2014 the number of trees. Next n lines contains the height of trees: i-th line contains an integer hi (1\u2009\u2264\u2009hi\u2009\u2264\u2009104) \u2014 the height of the tree with the number i.", "output_spec": "Print a single integer \u2014 the minimal time required to eat all nuts in seconds.", "sample_inputs": ["2\n1\n2", "5\n2\n1\n2\n1\n1"], "sample_outputs": ["5", "14"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let h = Array.init n (fun _ -> read_int()) in\n\n let rec loop i ac = if i=n-1 then ac else (\n let ac = ac + (abs (h.(i) - h.(i+1))) + 2 in\n loop (i+1) ac\n ) in\n \n let ans = loop 0 (h.(0)+1) in\n Printf.printf \"%d\\n\" ans\n"}], "negative_code": [], "src_uid": "a20ca4b053ba71f6b2dc05749287e0a4"} {"nl": {"description": "Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: the final tournament features n teams (n is always even) the first n\u2009/\u20092 teams (according to the standings) come through to the knockout stage the standings are made on the following principle: for a victory a team gets 3 points, for a draw \u2014 1 point, for a defeat \u2014 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place \u2014 in decreasing order of the difference between scored and missed goals; in the third place \u2014 in the decreasing order of scored goals it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.", "input_spec": "The first input line contains the only integer n (1\u2009\u2264\u2009n\u2009\u2264\u200950) \u2014 amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following n\u00b7(n\u2009-\u20091)\u2009/\u20092 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 \u2014 names of the teams; num1, num2 (0\u2009\u2264\u2009num1,\u2009num2\u2009\u2264\u2009100) \u2014 amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.", "output_spec": "Output n\u2009/\u20092 lines \u2014 names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.", "sample_inputs": ["4\nA\nB\nC\nD\nA-B 1:1\nA-C 2:2\nA-D 1:0\nB-C 1:0\nB-D 0:3\nC-D 0:3", "2\na\nA\na-A 2:1"], "sample_outputs": ["A\nD", "a"], "notes": null}, "positive_code": [{"source_code": "let (|>) x f = f x\n\nlet () =\n let n = read_int () in\n let s2i = Hashtbl.create n in\n let i2s = Array.make n \"\" in\n for i = 0 to n-1 do\n let s = read_line () in\n i2s.(i) <- s;\n Hashtbl.add s2i s i\n done;\n\n let score = Array.make n 0 in\n let goal = Array.make n 0 in\n let gd = Array.make n 0 in\n let re = Str.regexp \"\\\\([A-Za-z]+\\\\)-\\\\([A-Za-z]+\\\\) \\\\([0-9]+\\\\):\\\\([0-9]+\\\\)\" in\n let add i dlt = score.(i) <- score.(i) + dlt in\n for i = 1 to n*(n-1)/2 do\n let s = read_line () in\n let flag = Str.string_match re s 0 in\n let u = Str.matched_group 1 s |> Hashtbl.find s2i\n and v = Str.matched_group 2 s |> Hashtbl.find s2i\n and uu = Str.matched_group 3 s |> int_of_string\n and vv = Str.matched_group 4 s |> int_of_string in\n if uu > vv then\n add u 3\n else if uu < vv then\n add v 3\n else (\n add u 1;\n add v 1\n );\n gd.(u) <- gd.(u) + uu - vv;\n gd.(v) <- gd.(v) + vv - uu;\n goal.(u) <- goal.(u) + uu;\n goal.(v) <- goal.(v) + uu;\n done;\n\n let idx = Array.init n (fun x -> x) in\n Array.sort (fun x y -> let r = compare score.(y) score.(x) in\n if r <> 0 then r\n else\n let r = compare gd.(y) gd.(x) in\n if r <> 0 then r\n else compare goal.(y) goal.(x)) idx;\n let ans = Array.init (n/2) (fun i -> i2s.(idx.(i))) in\n Array.sort compare ans;\n for i = 0 to n/2-1 do\n print_endline ans.(i)\n done\n"}], "negative_code": [{"source_code": "let (|>) x f = f x\n\nlet () =\n let n = read_int () in\n let s2i = Hashtbl.create n in\n let i2s = Array.make n \"\" in\n for i = 0 to n-1 do\n let s = read_line () in\n i2s.(i) <- s;\n Hashtbl.add s2i s i\n done;\n\n let score = Array.make n 0 in\n let re = Str.regexp \"\\\\([A-Za-z]+\\\\)-\\\\([A-Za-z]+\\\\) \\\\([0-9]+\\\\):\\\\([0-9]+\\\\)\" in\n let add i dlt = score.(i) <- score.(i) + dlt in\n for i = 1 to n*(n-1)/2 do\n let s = read_line () in\n let flag = Str.string_match re s 0 in\n let u = Str.matched_group 1 s |> Hashtbl.find s2i\n and v = Str.matched_group 2 s |> Hashtbl.find s2i\n and uu = Str.matched_group 3 s |> int_of_string\n and vv = Str.matched_group 4 s |> int_of_string in\n if uu > vv then\n add u 3\n else if uu < vv then\n add v 3\n else (\n add u 1;\n add v 1\n )\n done;\n\n let idx = Array.init n (fun x -> x) in\n Array.sort (fun x y -> compare score.(y) score.(x)) idx;\n let ans = Array.init (n/2) (fun i -> i2s.(idx.(i))) in\n Array.sort compare ans;\n for i = 0 to n/2-1 do\n print_endline ans.(i)\n done\n"}], "src_uid": "472c0cb256c062b9806bf93b13b453a2"} {"nl": {"description": "Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.There are $$$n$$$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $$$i$$$-th position. Thus each of $$$n$$$ positions should contain exactly one flower: a rose or a lily.She knows that exactly $$$m$$$ people will visit this exhibition. The $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\\leq n, m\\leq 10^3$$$)\u00a0\u2014 the number of flowers and visitors respectively. Each of the next $$$m$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1\\leq l_i\\leq r_i\\leq n$$$), meaning that $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive.", "output_spec": "Print the string of $$$n$$$ characters. The $$$i$$$-th symbol should be \u00ab0\u00bb if you want to put a rose in the $$$i$$$-th position, otherwise \u00ab1\u00bb if you want to put a lily. If there are multiple answers, print any.", "sample_inputs": ["5 3\n1 3\n2 4\n2 5", "6 3\n5 6\n1 4\n4 6"], "sample_outputs": ["01100", "110010"], "notes": "NoteIn the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions; in the segment $$$[1\\ldots3]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\\cdot 2=2$$$; in the segment $$$[2\\ldots4]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\\cdot 2=2$$$; in the segment $$$[2\\ldots5]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\\cdot 2=4$$$. The total beauty is equal to $$$2+2+4=8$$$.In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions; in the segment $$$[5\\ldots6]$$$, there are one rose and one lily, so the beauty is equal to $$$1\\cdot 1=1$$$; in the segment $$$[1\\ldots4]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\\cdot 2=4$$$; in the segment $$$[4\\ldots6]$$$, there are two roses and one lily, so the beauty is equal to $$$2\\cdot 1=2$$$. The total beauty is equal to $$$1+4+2=7$$$."}, "positive_code": [{"source_code": "let ( */ ) = Big_int.mult_big_int;;\nlet ( +/ ) = Big_int.add_big_int;;\nlet ( -/ ) = Big_int.sub_big_int;;\nlet to_int = Big_int.int_of_big_int;;\nlet of_int = Big_int.big_int_of_int;;\nlet min = Big_int.min_big_int;;\nlet (modi) = Big_int.mod_big_int;;\nlet to_string = Big_int.string_of_big_int;;\nlet of_string = Big_int.big_int_of_string;;\nlet ( (n, m)) in\nfor i = 1 to m do\n ignore (read_line ());\ndone;\nfor i = 1 to n do\n print_int (i mod 2);\ndone;\nprint_newline ();\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt64 = struct \n\t(* include Int64 *)\n\t(* int *)\n\tlet (+$) = (+)\n\tlet (-$) = (-)\n\tlet (/$) = (/)\n\tlet ( *$) = ( * )\n\t(* int64 *)\n\tlet (+) p q = Int64.add p q\n\tlet (-) p q = Int64.sub p q\n\tlet ( * ) p q = Int64.mul p q\n\tlet (/) p q = Int64.div p q\n\n\tlet labs p = if p < 0L then -1L*p else p\n\t(* let (~|) p = Int64.of_int p *)\n\tlet (~|) p = Int64.to_int p\n\n\tlet (+=) r v = r := !r + v\n\tlet (-=) r v = r := !r - v\n\tlet ( *=) r v= r := !r * v\n\tlet (/=) r v = r := !r / v\n\n\tlet input_i64_array n = \n\t\tArray.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n\tlet get_i64 () = Scanf.scanf \" %Ld\" (fun v -> v)\n\tlet get_2_i64 () = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n\tlet get_3_i64 () = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n\tlet get_4_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n\tlet get_5_i64 () = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n\tlet print_i64_endline n =\n\t\tn |> Int64.to_string |> print_endline\nend open MyInt64\n\nlet () =\n let n,m = get_2_i64 ()\n in let ar = Array.make (~|m) (0L,0L)\n in\n for i=0 to ~|m-$1 do\n let u,v = get_2_i64 ()\n in ar.(i) <- u,v\n done;\n let res = Array.make ~|n 0 in\n Array.iteri (fun i _ -> print_int @@ if i mod 2 = 0 then 1 else 0) res;\n print_newline ()\n\n\n"}], "negative_code": [], "src_uid": "cac8ca5565e06021a44bb4388b5913a5"} {"nl": {"description": "Today at the lesson of mathematics, Petya learns about the digital root.The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. Let's denote the digital root of $$$x$$$ as $$$S(x)$$$. Then $$$S(5)=5$$$, $$$S(38)=S(3+8=11)=S(1+1=2)=2$$$, $$$S(10)=S(1+0=1)=1$$$.As a homework Petya got $$$n$$$ tasks of the form: find $$$k$$$-th positive number whose digital root is $$$x$$$.Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all $$$n$$$ tasks from Petya's homework.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^3$$$) \u2014 the number of tasks in Petya's homework. The next $$$n$$$ lines contain two integers $$$k_i$$$ ($$$1 \\le k_i \\le 10^{12}$$$) and $$$x_i$$$ ($$$1 \\le x_i \\le 9$$$) \u2014 $$$i$$$-th Petya's task in which you need to find a $$$k_i$$$-th positive number, the digital root of which is $$$x_i$$$.", "output_spec": "Output $$$n$$$ lines, $$$i$$$-th line should contain a single integer \u2014 the answer to the $$$i$$$-th problem.", "sample_inputs": ["3\n1 5\n5 2\n3 1"], "sample_outputs": ["5\n38\n19"], "notes": null}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)\n let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in\n rep 1L n (fun _ ->\n let k,x = g2 0 in\n printf \"%Ld\\n\" @@ x + 9L * (k - 1L)\n )\n\n\n\n\n\n\n\n\n"}, {"source_code": "let (++),( ** ),(--) = Int64.(add,mul,sub);;\nScanf.(Array.(scanf \" %d\" @@ fun q ->\n init q (fun _ -> scanf \" %Ld %Ld\" @@ fun k x ->\n Printf.printf \"%Ld\\n\" @@ x ++ 9L ** (k--1L))))"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)\n let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = gi 0 in\n rep 1L n (fun _ ->\n let k,x = g2 0 in\n printf \"%Ld\" @@ x + 9L * (k - 1L)\n )\n\n\n\n\n\n\n\n\n"}], "src_uid": "891fabbb6ee8a4969b6f413120f672a8"} {"nl": {"description": "I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an \u2014 Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying?You are given a string of $$$n$$$ lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \\ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Find out what the MEX of the string is!", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \\leq n \\leq 1000$$$)\u00a0\u2014 the length of the word. The second line for each test case contains a single string of $$$n$$$ lowercase Latin letters. The sum of $$$n$$$ over all test cases will not exceed $$$1000$$$.", "output_spec": "For each test case, output the MEX of the string on a new line.", "sample_inputs": ["3\n28\nqaabzwsxedcrfvtgbyhnujmiklop\n13\ncleanairactbd\n10\naannttoonn"], "sample_outputs": ["ac\nf\nb"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet n2l n = char_of_int ((int_of_char 'a') + n)\n \nlet mex h len =\n let a = Array.make len 0 in\n let rec increment i = if i = len then false\n else if a.(i) = 25 then (\n a.(i) <- 0;\n increment (i+1)\n ) else (\n a.(i) <- a.(i) + 1;\n true;\n )\n in\n let rec loop () =\n let s = String.init len (fun i -> n2l a.(len-i-1)) in\n if not (Hashtbl.mem h s) then Some s else (\n if increment 0 then loop () else None\n )\n in\n loop ()\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let s = read_string () in\n\n let rec loop len =\n let h = Hashtbl.create 10 in\n if len > 3 then failwith \"len too big\" else (\n\tfor i = 0 to n-len do\n\t let x = String.sub s i len in\n\t Hashtbl.replace h x true;\n\tdone;\n\tmatch mex h len with\n\t | None -> loop (len+1)\n\t | Some s -> printf \"%s\\n\" s\n )\n in\n loop 1\n done\n"}], "negative_code": [], "src_uid": "83a665723ca4e40c78fca20057a0dc99"} {"nl": {"description": "In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifier\u00a0\u2014 an integer from 1 to 109.At some moment, robots decided to play the game \"Snowball\". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the n-th robot says his identifier.Your task is to determine the k-th identifier to be pronounced.", "input_spec": "The first line contains two positive integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000, 1\u2009\u2264\u2009k\u2009\u2264\u2009min(2\u00b7109,\u2009n\u00b7(n\u2009+\u20091)\u2009/\u20092). The second line contains the sequence id1,\u2009id2,\u2009...,\u2009idn (1\u2009\u2264\u2009idi\u2009\u2264\u2009109)\u00a0\u2014 identifiers of roborts. It is guaranteed that all identifiers are different.", "output_spec": "Print the k-th pronounced identifier (assume that the numeration starts from 1).", "sample_inputs": ["2 2\n1 2", "4 5\n10 4 18 3"], "sample_outputs": ["1", "4"], "notes": "NoteIn the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As k\u2009=\u20092, the answer equals to 1.In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As k\u2009=\u20095, the answer equals to 4."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let k = read_long () in\n let id = Array.init n (fun _ -> read_int()) in\n\n let tri j = (j ** (j++1L)) // 2L in\n\n let rec loop i = if tri i >= k then i--1L else loop (i++1L) in\n\n let index = -1 + short (k -- (tri (loop 1L))) in\n\n printf \"%d\\n\" id.(index)\n"}], "negative_code": [], "src_uid": "9ad07b42358e7f7cfa15ea382495a8a1"} {"nl": {"description": "In some social network, there are $$$n$$$ users communicating with each other in $$$m$$$ groups of friends. Let's analyze the process of distributing some news between users.Initially, some user $$$x$$$ receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least one group such that both of them belong to this group). Friends continue sending the news to their friends, and so on. The process ends when there is no pair of friends such that one of them knows the news, and another one doesn't know.For each user $$$x$$$ you have to determine what is the number of users that will know the news if initially only user $$$x$$$ starts distributing it. ", "input_spec": "The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n, m \\le 5 \\cdot 10^5$$$) \u2014 the number of users and the number of groups of friends, respectively. Then $$$m$$$ lines follow, each describing a group of friends. The $$$i$$$-th line begins with integer $$$k_i$$$ ($$$0 \\le k_i \\le n$$$) \u2014 the number of users in the $$$i$$$-th group. Then $$$k_i$$$ distinct integers follow, denoting the users belonging to the $$$i$$$-th group. It is guaranteed that $$$\\sum \\limits_{i = 1}^{m} k_i \\le 5 \\cdot 10^5$$$.", "output_spec": "Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the number of users that will know the news if user $$$i$$$ starts distributing it.", "sample_inputs": ["7 5\n3 2 5 4\n0\n2 1 2\n1 1\n2 6 7"], "sample_outputs": ["4 4 1 4 4 2 2"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\n(*------ union find code *)\nlet makeset n = Array.make n (-1) (* negatives of the sizes at the roots *)\nlet rec find i p = if p.(i) < 0 then i else (\n p.(i) <- find p.(i) p;\n p.(i);\n)\nlet union i j p =\n let i = find i p in\n let j = find j p in\n if i<>j then (\n let sz = p.(i) + p.(j) in\n p.(j) <- i;\n p.(i) <- sz\n )\n\nlet size i p = -p.(i)\n(*------ end union find code *)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () =\n let (n,m) = read_pair () in\n\n let p = makeset n in\n\n for i = 0 to m-1 do\n let k = read_int() in\n if k>0 then (\n let first = -1 + read_int () in\n for j = 1 to k-1 do\n\tlet next = -1 + read_int() in\n\tunion first next p\n done\n )\n done;\n\n for i=0 to n-1 do\n printf \"%d \" (size (find i p) p)\n done;\n\n print_newline()\n"}], "negative_code": [], "src_uid": "a7e75ff150d300b2a8494dca076a3075"} {"nl": {"description": "You are given an array $$$a_1, a_2, \\dots, a_n$$$. You can perform operations on the array. In each operation you can choose an integer $$$i$$$ ($$$1 \\le i < n$$$), and swap elements $$$a_i$$$ and $$$a_{i+1}$$$ of the array, if $$$a_i + a_{i+1}$$$ is odd.Determine whether it can be sorted in non-decreasing order using this operation any number of times.", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print \"Yes\" or \"No\" depending on whether you can or can not sort the given array. You may print each letter in any case (for example, \"YES\", \"Yes\", \"yes\", \"yEs\" will all be recognized as positive answer).", "sample_inputs": ["4\n\n4\n\n1 6 31 14\n\n2\n\n4 2\n\n5\n\n2 9 6 7 10\n\n3\n\n6 6 6"], "sample_outputs": ["Yes\nNo\nNo\nYes"], "notes": "NoteIn the first test case, we can simply swap $$$31$$$ and $$$14$$$ ($$$31 + 14 = 45$$$ which is odd) and obtain the non-decreasing array $$$[1,6,14,31]$$$.In the second test case, the only way we could sort the array is by swapping $$$4$$$ and $$$2$$$, but this is impossible, since their sum $$$4 + 2 = 6$$$ is even.In the third test case, there is no way to make the array non-decreasing.In the fourth test case, the array is already non-decreasing."}, "positive_code": [{"source_code": "(* Codeforces 1614 A Divan and a Store train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec is_sorted x = match x with\n | [] -> true\n | h::[] -> true\n | h::h2::t -> if h <= h2 then is_sorted (h2::t) else false;;\n\nlet rec sep_even_odd leven lodd l = match l with\n | [] -> ((List.rev leven), (List.rev lodd))\n | h :: t ->\n let nle = if (h mod 2) == 0 then h :: leven else leven in\n let nlo = if (h mod 2) == 0 then lodd else h :: lodd in\n sep_even_odd nle nlo t;;\n\n\nlet do_one () = \n let n = gr () in\n let arev = readlist n [] in\n let a = List.rev arev in\n let el,ol = sep_even_odd [] [] a in\n let esorted = is_sorted el in\n let osorted = is_sorted ol in\n let ok = esorted && osorted in\n let sans = if ok then \"Yes\" else \"No\" in\n Printf.printf \"%s\\n\" sans;;\n \nlet do_all () = \n let t = gr () in\n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tdo_all ();;\n \nmain();;"}], "negative_code": [], "src_uid": "a97e70ad20a337d12dcf79089c16c9f0"} {"nl": {"description": "Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri, and its elements are a[li],\u2009a[li\u2009+\u20091],\u2009...,\u2009a[ri].Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible. You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.The mex of a set S is a minimum possible non-negative integer that is not in S.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers li and ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n), that describe the subarray a[li],\u2009a[li\u2009+\u20091],\u2009...,\u2009a[ri].", "output_spec": "In the first line print single integer\u00a0\u2014 the maximum possible minimum mex. In the second line print n integers\u00a0\u2014 the array a. All the elements in a should be between 0 and 109. It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 109. If there are multiple solutions, print any of them.", "sample_inputs": ["5 3\n1 3\n2 5\n4 5", "4 2\n1 4\n2 4"], "sample_outputs": ["2\n1 0 2 1 0", "3\n5 2 0 1"], "notes": "NoteThe first example: the mex of the subarray (1,\u20093) is equal to 3, the mex of the subarray (2,\u20095) is equal to 3, the mex of the subarray (4,\u20095) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2."}, "positive_code": [{"source_code": "\n\nlet read_pair = fun a b -> (a, b) in\n\nlet (n, m) = Scanf.scanf \"%d %d\\n\" read_pair and ans = ref 99999999 in\nfor i = 1 to m do\n let (tmp1, tmp2) = Scanf.scanf \"%d %d\\n\" read_pair in\n ans := min (!ans) (tmp2 - tmp1 + 1)\ndone;\nprint_int !ans;\nprint_newline ();\nfor i = 0 to n - 1 do\n print_int (i mod !ans);\n print_string \" \"\ndone;;\n\n\n \n\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (n,m) = read_pair () in\n\n let len = minf 0 (m-1) (fun _ ->\n let (l,r) = read_pair() in\n r-l+1\n ) in\n\n printf \"%d\\n\" len;\n\n for i=0 to n-1 do\n printf \"%d \" (i mod len)\n done;\n\n print_newline()\n"}, {"source_code": "let () =\n Scanf.scanf \"%d %d \" @@ fun n m ->\n let mex = ref n in\n for i = 1 to m do\n Scanf.scanf \"%d %d \" @@ fun l r ->\n mex := min !mex (r - l + 1)\n done;\n Printf.printf \"%d\\n\" !mex;\n for i = 0 to n - 2 do\n Printf.printf \"%d \" (i mod !mex)\n done;\n Printf.printf \"%d\\n\" ((n - 1) mod !mex)\n"}], "negative_code": [], "src_uid": "317891277a5393758bd3c8f606769070"} {"nl": {"description": "You are given a garland consisting of $$$n$$$ lamps. States of the lamps are represented by the string $$$s$$$ of length $$$n$$$. The $$$i$$$-th character of the string $$$s_i$$$ equals '0' if the $$$i$$$-th lamp is turned off or '1' if the $$$i$$$-th lamp is turned on. You are also given a positive integer $$$k$$$.In one move, you can choose one lamp and change its state (i.e. turn it on if it is turned off and vice versa).The garland is called $$$k$$$-periodic if the distance between each pair of adjacent turned on lamps is exactly $$$k$$$. Consider the case $$$k=3$$$. Then garlands \"00010010\", \"1001001\", \"00010\" and \"0\" are good but garlands \"00101001\", \"1000001\" and \"01001100\" are not. Note that the garland is not cyclic, i.e. the first turned on lamp is not going after the last turned on lamp and vice versa.Your task is to find the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 25~ 000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n \\le 10^6; 1 \\le k \\le n$$$) \u2014 the length of $$$s$$$ and the required period. The second line of the test case contains the string $$$s$$$ consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\\sum n \\le 10^6$$$).", "output_spec": "For each test case, print the answer \u2014 the minimum number of moves you need to make to obtain $$$k$$$-periodic garland from the given one.", "sample_inputs": ["6\n9 2\n010001010\n9 3\n111100000\n7 4\n1111111\n10 3\n1001110101\n1 1\n1\n1 1\n0"], "sample_outputs": ["1\n2\n5\n4\n0\n0"], "notes": null}, "positive_code": [{"source_code": "let r_int () = Scanf.scanf \" %d\" (fun x -> x) in\nlet r_char () = Scanf.scanf \" %c\" (fun x -> x) in\n\nlet rec r_list = function\n| 0 -> []\n| n -> (if r_char () = '0' then 0 else 1) :: r_list (n - 1)\nin\n\nlet rec calcule_cout etat =\n let (a, b, c) = etat in\n function\n | [] -> c\n | x :: r -> \n let a = a + x in\n let b = min a (b + 1 - x) in\n let c = min b (c + x) in\n calcule_cout (a, b, c) r\nin\n\nlet nbTests = r_int() in\nfor iTest = 1 to nbTests do\n let nbBits = r_int () in\n let dist = r_int () in\n let bits = r_list nbBits in\n let mini = ref 1000000 in\n \n let nbUns = List.fold_left (+) 0 bits in\n \n let listes = Array.make dist [] in\n let rec separe i = function \n | [] -> ()\n | x :: r -> listes.(i) <- x :: listes.(i); separe ((i + 1) mod dist) r\n in separe 0 bits;\n \n for iMod = 0 to (dist - 1) do\n let curUns = List.fold_left (+) 0 listes.(iMod) in\n let curCout = nbUns - curUns + (calcule_cout (0,0,0) listes.(iMod)) in\n mini := min !mini curCout\n done;\n \n print_int !mini;\n print_newline ()\ndone"}], "negative_code": [], "src_uid": "8b28309055f13837eb1f51422fb91029"} {"nl": {"description": "Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n\u2009-\u20092 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.", "input_spec": "First line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105), the length of the string that Andreid has. The second line contains the string of length n consisting only from zeros and ones.", "output_spec": "Output the minimum length of the string that may remain after applying the described operations several times.", "sample_inputs": ["4\n1100", "5\n01010", "8\n11101111"], "sample_outputs": ["0", "1", "6"], "notes": "NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: ."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \"%d \" (fun n -> n)\nlet read_char () = Scanf.scanf \"%c \" (fun c -> c)\n\nlet solve () = \n let n = read_int () in\n let rec loop i zeros ones = \n if i < n\n then\n let number = read_char () in\n if number = '0'\n then\n loop (i + 1) (zeros + 1) ones\n else\n loop (i + 1) zeros (ones + 1) \n else\n Pervasives.abs (zeros - ones)\n in loop 0 0 0\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve ())"}, {"source_code": "let str_to_list s =\n let rec loop i l =\n if i < 0 \n then l \n else loop (i - 1) (s.[i] :: l) in\n loop (String.length s - 1) []\n\nlet input () = \n let n = Pervasives.read_int () in\n let list = str_to_list (Pervasives.read_line ()) in\n (list, n)\n\nlet solve (list, n) = \n let zeros = List.length (List.filter (fun c -> c = '0') list) in\n let ones = n - zeros in\n let result = Pervasives.abs (zeros - ones) in\n result\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "let rec count s c i =\n if i = String.length s\n then 0\n else (if s.[i]=c then 1 else 0) + count s c (i+1)\n\nin let n = read_int()\nin let s = read_line()\nin let reml = n - 2 * min (count s '0' 0) (count s '1' 0)\nin print_int(reml)\n"}], "negative_code": [], "src_uid": "fa7a44fd24fa0a8910cb7cc0aa4f2155"} {"nl": {"description": "Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n\u2009+\u20091) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i\u2009>\u20090) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k\u2009+\u20091). When the player have made such a move, its energy increases by hk\u2009-\u2009hk\u2009+\u20091 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The next line contains n integers h1, h2,\u2009..., hn (1\u2009\u2009\u2264\u2009\u2009hi\u2009\u2009\u2264\u2009\u2009105) representing the heights of the pylons.", "output_spec": "Print a single number representing the minimum number of dollars paid by Caisa.", "sample_inputs": ["5\n3 4 3 2 4", "3\n4 4 4"], "sample_outputs": ["4", "4"], "notes": "NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon."}, "positive_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\nlet (@@) f x = f x ;;\nmodule Array = struct\n include ArrayLabels\n let fold_lefti ~f ~init arr =\n let acc = ref init in\n for i = 0 to Array.length arr - 1 do\n acc := f i !acc arr.(i)\n done;\n !acc\n ;;\nend\nmodule String = StringLabels ;;\nmodule List = struct\n include ListLabels ;;\n let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;\n let rec drop n a =\n if n = 0 then a\n else match a with\n | [] -> failwith \"cannot take\"\n | x :: xs -> drop (n - 1) xs ;;\n\n let init ~f n =\n let res = ref [] in\n for i = 0 to n - 1 do\n res := f i :: !res\n done;\n List.rev !res\n ;;\nend ;;\nmodule H = Hashtbl ;;\n\nmodule SI = Set.Make (struct\n type t = int \n let compare = compare\nend)\n\nlet () =\n sf \"%d \" (fun n ->\n let arr = Array.init n ~f:(fun i -> sf \"%d \" (fun i -> i)) in\n pf \"%d\\n\" @@ Array.fold_left ~init:0 arr ~f:max)\n;;\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\nlet a = Array.make (n+1) 0\n\nfor i = 1 to n do\n let j = Scanf.scanf \"%d \" ( fun x -> x ) in\n a.(i)<-j\ndone\n\nlet rslt = Array.fold_left (fun x y -> if x > y then x else y ) (-1000) a\nin printf \"%d\\n\" rslt\n\n"}], "negative_code": [{"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\nlet a = Array.make (n+1) 0\n\nfor i = 1 to n do\n let j = Scanf.scanf \"%d \" ( fun x -> x ) in\n a.(i)<-j\ndone\n\nlet cnt = ref 0\n\nfor i = 1 to n do\n let m = a.(i) - a.(i-1) in\n cnt := m + !cnt\ndone\n\nlet () = printf \"%d\\n\" !cnt\n\n"}], "src_uid": "d03ad531630cbecc43f8da53b02d842e"} {"nl": {"description": "You are given two polynomials: P(x)\u2009=\u2009a0\u00b7xn\u2009+\u2009a1\u00b7xn\u2009-\u20091\u2009+\u2009...\u2009+\u2009an\u2009-\u20091\u00b7x\u2009+\u2009an and Q(x)\u2009=\u2009b0\u00b7xm\u2009+\u2009b1\u00b7xm\u2009-\u20091\u2009+\u2009...\u2009+\u2009bm\u2009-\u20091\u00b7x\u2009+\u2009bm. Calculate limit .", "input_spec": "The first line contains two space-separated integers n and m (0\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 degrees of polynomials P(x) and Q(x) correspondingly. The second line contains n\u2009+\u20091 space-separated integers \u2014 the factors of polynomial P(x): a0, a1, ..., an\u2009-\u20091, an (\u2009-\u2009100\u2009\u2264\u2009ai\u2009\u2264\u2009100,\u2009a0\u2009\u2260\u20090). The third line contains m\u2009+\u20091 space-separated integers \u2014 the factors of polynomial Q(x): b0, b1, ..., bm\u2009-\u20091, bm (\u2009-\u2009100\u2009\u2264\u2009bi\u2009\u2264\u2009100,\u2009b0\u2009\u2260\u20090).", "output_spec": "If the limit equals \u2009+\u2009\u221e, print \"Infinity\" (without quotes). If the limit equals \u2009-\u2009\u221e, print \"-Infinity\" (without the quotes). If the value of the limit equals zero, print \"0/1\" (without the quotes). Otherwise, print an irreducible fraction \u2014 the value of limit , in the format \"p/q\" (without the quotes), where p is the \u2014 numerator, q (q\u2009>\u20090) is the denominator of the fraction.", "sample_inputs": ["2 1\n1 1 1\n2 5", "1 0\n-1 3\n2", "0 1\n1\n1 0", "2 2\n2 1 6\n4 5 -7", "1 1\n9 0\n-5 2"], "sample_outputs": ["Infinity", "-Infinity", "0/1", "1/2", "-9/5"], "notes": "NoteLet's consider all samples: You can learn more about the definition and properties of limits if you follow the link: http://en.wikipedia.org/wiki/Limit_of_a_function"}, "positive_code": [{"source_code": "let rec gcd a b =\n if b == 0 then a else gcd b (a mod b)\n;;\n\nlet next_int: unit -> int = fun _ ->\n Scanf.scanf \" %d\" (fun x -> x)\n;;\n\nlet next_polynomial n =\n let ret = next_int () in\n for i = 1 to n do\n next_int ()\n done;\n ret\n;;\n\nlet rec print_gcd a b =\n let g = gcd (abs a) (abs b) in\n if b < 0\n then print_gcd (-a) (-b)\n else Printf.printf \"%d/%d\" (a / g) (b / g)\n;;\n\nlet _ =\n let n = next_int () in\n let m = next_int () in\n let a = next_polynomial n in\n let b = next_polynomial m in\n if n < m then print_string \"0/1\"\n else if n = m then print_gcd a b\n else print_string ((if a * b > 0 then \"\" else \"-\") ^ \"Infinity\")\n;;\n"}, {"source_code": "let rec gcd x y =\n if y == 0 then x else gcd y (x mod y)\n \nlet solve n m p q =\n let a = List.hd p in\n let b = List.hd q in\n if n > m then if a * b >= 0 then \"Infinity\" else \"-Infinity\"\n else if n < m then \"0/1\"\n else\n let gcd = gcd a b in\n let a = a / gcd in\n let b = b / gcd in\n if a > 0 && b < 0\n then (string_of_int (- a)) ^ \"/\" ^ (string_of_int (- b))\n else (string_of_int a) ^ \"/\" ^ (string_of_int b)\n \n\nlet id x = x\n \nlet rec input_polynomial dim =\n if dim < 0 then []\n else (Scanf.scanf \" %d\" id) :: input_polynomial (dim - 1)\n \nlet _ =\n let n = Scanf.scanf \" %d\" id in\n let m = Scanf.scanf \" %d\" id in\n let p = List.rev (input_polynomial n) in\n let q = List.rev (input_polynomial m) in\n Printf.printf \"%s\\n\" (solve n m p q)\n"}, {"source_code": "let fraction n d =\n let str = (string_of_int n) ^ \"/\" ^ (string_of_int d) in\n Ratio.string_of_ratio (Num.ratio_of_num (Num.num_of_string str))\n\nlet solve p q =\n if List.length p > List.length q\n then if (List.hd p) * (List.hd q) >= 0 then \"Infinity\"\n else \"-Infinity\"\n else if List.length p < List.length q then \"0/1\"\n else fraction (List.hd p) (List.hd q)\n\nlet id x = x\n \nlet rec input_polynomial dim =\n if dim < 0 then []\n else (Scanf.scanf \" %d\" id) :: input_polynomial (dim - 1)\n \nlet _ =\n let n = Scanf.scanf \" %d\" id in\n let m = Scanf.scanf \" %d\" id in\n let p = List.rev (input_polynomial n) in\n let q = List.rev (input_polynomial m) in\n Printf.printf \"%s\\n\" (solve p q)\n"}, {"source_code": "let sb = Scanf.Scanning.stdib;;\n\nlet fraction n d =\n let str = (string_of_int n) ^ \"/\" ^ (string_of_int d) in\n Ratio.string_of_ratio (Num.ratio_of_num (Num.num_of_string str))\n\nlet solve p q =\n if List.length p > List.length q\n then if (List.hd p) * (List.hd q) >= 0 then \"Infinity\"\n else \"-Infinity\"\n else if List.length p < List.length q then \"0/1\"\n else fraction (List.hd p) (List.hd q)\n\nlet id x = x\n \nlet rec input_polynomial dim =\n if dim < 0 then []\n else (Scanf.bscanf sb \" %d\" id) :: input_polynomial (dim - 1)\n \nlet _ =\n let n = Scanf.bscanf sb \" %d\" id in\n let m = Scanf.bscanf sb \" %d\" id in\n let p = List.rev (input_polynomial n) in\n let q = List.rev (input_polynomial m) in\n Printf.printf \"%s\\n\" (solve p q)\n"}, {"source_code": "module Std = struct\n\n module List = struct\n include List\n module L = List\n let map f lst = L.rev (L.rev_map f lst)\n let map2 f l1 l2 = L.rev (L.rev_map2 f l1 l2)\n let each_cons f lst = L.rev_map2 f (L.tl (L.rev lst)) (L.rev (L.tl lst))\n let append x y = L.rev (L.rev_append x y)\n let fold = L.fold_left\n let permute_with lst p = L.map (Array.get (Array.of_list lst)) p\n end\n\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n let ( ~. ) = float_of_int\n let ( @ ) = List.append\n\n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\n let di x = prerr_endline (string_of_int x); x\n let df f = prerr_endline (string_of_float f); f\n let ds s = prerr_endline s; s\n \n let int () = Scanf.scanf \" %d\" (fun x -> x)\n let read_int = int\n let float () = Scanf.scanf \" %f\" (fun x -> x)\n let read_float = float\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\nend\n\nopen Std\nmodule L = List\n\nlet rec gcd x y =\n if y = 0 then x\n else gcd y (x mod y)\n\n(* entry point *)\nlet n = int ()\nlet m = int ()\n\nlet a = n_int (n+1) ()\nlet b = n_int (m+1) ()\n\nlet () =\n if n > m then\n Printf.printf \"%s\\n\" (if (L.hd a) * (L.hd b) > 0 then \"Infinity\" else \"-Infinity\")\n else if n < m then\n Printf.printf \"%s\\n\" \"0/1\" \n else \n let a = (L.hd a) in\n let b = (L.hd b) in\n let g = gcd a b in\n let a = a / g in\n let b = b / g in\n if a > 0 && b < 0 then\n Printf.printf \"%d/%d\" (-a) (-b)\n else\n Printf.printf \"%d/%d\" a b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "let rec gcd x y =\n if y == 0 then x else gcd y (x mod y)\n \nlet solve n m p q =\n let a = List.hd p in\n let b = List.hd q in\n if n > m then if a * b >= 0 then \"Infinity\" else \"-Infinity\"\n else if n < m then \"0/1\"\n else\n let gcd = gcd a b in\n let a = a / gcd in\n let b = b / gcd in\n (string_of_int a) ^ \"/\" ^ (string_of_int b)\n\nlet id x = x\n \nlet rec input_polynomial dim =\n if dim < 0 then []\n else (Scanf.scanf \" %d\" id) :: input_polynomial (dim - 1)\n \nlet _ =\n let n = Scanf.scanf \" %d\" id in\n let m = Scanf.scanf \" %d\" id in\n let p = List.rev (input_polynomial n) in\n let q = List.rev (input_polynomial m) in\n Printf.printf \"%s\\n\" (solve n m p q)\n"}, {"source_code": "let sb = Scanf.Scanning.stdib;;\n\nlet fraction n d =\n let str = (string_of_int n) ^ \"/\" ^ (string_of_int d) in\n Ratio.string_of_ratio (Num.ratio_of_num (Num.num_of_string str))\n\nlet solve p q =\n if List.length p > List.length q\n then if (List.hd p) > 0 then \"Infinity\"\n else \"-Infinity\"\n else if List.length p < List.length q then \"0/1\"\n else fraction (List.hd p) (List.hd q)\n\nlet id x = x\n \nlet rec input_polynomial dim =\n if dim < 0 then []\n else (Scanf.bscanf sb \" %d\" id) :: input_polynomial (dim - 1)\n \nlet _ =\n let n = Scanf.bscanf sb \" %d\" id in\n let m = Scanf.bscanf sb \" %d\" id in\n let p = List.rev (input_polynomial n) in\n let q = List.rev (input_polynomial m) in\n Printf.printf \"%s\\n\" (solve p q)\n"}, {"source_code": "module Std = struct\n\n module List = struct\n include List\n module L = List\n let map f lst = L.rev (L.rev_map f lst)\n let map2 f l1 l2 = L.rev (L.rev_map2 f l1 l2)\n let each_cons f lst = L.rev_map2 f (L.tl (L.rev lst)) (L.rev (L.tl lst))\n let append x y = L.rev (L.rev_append x y)\n let fold = L.fold_left\n let permute_with lst p = L.map (Array.get (Array.of_list lst)) p\n end\n\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n let ( ~. ) = float_of_int\n let ( @ ) = List.append\n\n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\n let di x = prerr_endline (string_of_int x); x\n let df f = prerr_endline (string_of_float f); f\n let ds s = prerr_endline s; s\n \n let int () = Scanf.scanf \" %d\" (fun x -> x)\n let read_int = int\n let float () = Scanf.scanf \" %f\" (fun x -> x)\n let read_float = float\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\nend\n\nopen Std\nmodule L = List\n\nlet rec gcd x y =\n if y = 0 then x\n else gcd y (x mod y)\n\n(* entry point *)\nlet n = int ()\nlet m = int ()\n\nlet a = n_int (n+1) ()\nlet b = n_int (m+1) ()\n\nlet () =\n if n > m then\n Printf.printf \"%s\\n\" (if (L.hd a > 0) then \"Infinity\" else \"-Infinity\")\n else if n < m then\n Printf.printf \"%s\\n\" \"0/1\" \n else \n let a = (L.hd a) in\n let b = (L.hd b) in\n let g = gcd a b in\n let a = a / g in\n let b = b / g in\n if a > 0 && b < 0 then\n Printf.printf \"%d/%d\" (-a) (-b)\n else\n Printf.printf \"%d/%d\" a b\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "module Std = struct\n\n module List = struct\n include List\n module L = List\n let map f lst = L.rev (L.rev_map f lst)\n let map2 f l1 l2 = L.rev (L.rev_map2 f l1 l2)\n let each_cons f lst = L.rev_map2 f (L.tl (L.rev lst)) (L.rev (L.tl lst))\n let append x y = L.rev (L.rev_append x y)\n let fold = L.fold_left\n let permute_with lst p = L.map (Array.get (Array.of_list lst)) p\n end\n\n let ( |> ) x f = f x\n let ( <| ) f x = f x\n let ( ~. ) = float_of_int\n let ( @ ) = List.append\n\n let rec repeat n f x = if n = 0 then x else repeat (n-1) f (f x)\n\n let di x = prerr_endline (string_of_int x); x\n let df f = prerr_endline (string_of_float f); f\n let ds s = prerr_endline s; s\n \n let int () = Scanf.scanf \" %d\" (fun x -> x)\n let read_int = int\n let float () = Scanf.scanf \" %f\" (fun x -> x)\n let read_float = float\n let rec n_int n () = List.rev <| repeat n (fun lst -> int () :: lst) []\n let rec n_float n () = List.rev <| repeat n (fun lst -> float () :: lst) []\n\nend\n\nopen Std\nmodule L = List\n\nlet rec gcd x y =\n if y = 0 then x\n else gcd y (x mod y)\n\n(* entry point *)\nlet n = int ()\nlet m = int ()\n\nlet a = n_int (n+1) ()\nlet b = n_int (m+1) ()\n\nlet () =\n if n > m then\n Printf.printf \"%s\\n\" (if (L.hd a > 0) then \"Infinity\" else \"-Infinity\")\n else if n < m then\n Printf.printf \"%s\\n\" \"0/1\" \n else \n let a = (L.hd a) in\n let b = (L.hd b) in\n let g = gcd a b in\n Printf.printf \"%d/%d\" (a / g) (b / g)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}], "src_uid": "37cf6edce77238db53d9658bc92b2cab"} {"nl": {"description": "PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n,\u2009k)\u2009=\u20091. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1: Assume you've ended last operation in vertex x (consider x\u2009=\u20091 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x\u2009+\u2009k or x\u2009+\u2009k\u2009-\u2009n depending on which of these is a valid index of polygon's vertex.Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.", "input_spec": "There are only two numbers in the input: n and k (5\u2009\u2264\u2009n\u2009\u2264\u2009106, 2\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009-\u20092, gcd(n,\u2009k)\u2009=\u20091).", "output_spec": "You should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines.", "sample_inputs": ["5 2", "10 3"], "sample_outputs": ["2 3 5 8 11", "2 3 4 6 9 12 16 21 26 31"], "notes": "NoteThe greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder.For the first sample testcase, you should output \"2 3 5 8 11\". Pictures below correspond to situations after drawing lines. "}, "positive_code": [{"source_code": "let (+|) = Int64.add\nlet (-|) = Int64.sub\nlet ( *| ) = Int64.mul\nlet ( /| ) = Int64.div\n\nlet g2d n = n land (-n)\n\nlet fenwick_new n =\n Array.make n 0\n\nlet fenwick_modify ft n x =\n let i = ref (n + 1) in\n while !i <= Array.length ft do\n ft.(!i - 1) <- ft.(!i - 1) + x;\n i := !i + g2d !i;\n done\n\nlet fenwick_count ft n =\n let i = ref (n + 1) in\n let res = ref 0 in\n while !i > 0 do\n res := !res + ft.(!i - 1);\n i := !i - g2d !i;\n done;\n !res\n\nlet fenwick_count2 ft m n =\n fenwick_count ft n - fenwick_count ft (m - 1)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k =\n if 2 * k > n\n then n - k\n else k\n in\n let ft = fenwick_new n in\n let res = ref 1L in\n let p = ref 0 in\n for _t = 1 to n do\n res := !res +| 1L;\n let q = !p + k in\n\tif q <= n\n\tthen (\n\t res := !res +| Int64.of_int (fenwick_count2 ft (!p + 1) (q - 1));\n\t fenwick_modify ft q 1;\n\t) else (\n\t res := !res +| Int64.of_int (fenwick_count2 ft (!p + 1) (n - 1));\n\t res := !res +| Int64.of_int (fenwick_count2 ft 0 (q - n - 1));\n\t fenwick_modify ft (q - n) 1;\n\t);\n\tfenwick_modify ft !p 1;\n\tp := q mod n;\n\tPrintf.printf \"%Ld \" !res\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "let g2d n = n land (-n)\n\nlet fenwick_new n =\n Array.make n 0\n\nlet fenwick_modify ft n x =\n let i = ref (n + 1) in\n while !i <= Array.length ft do\n ft.(!i - 1) <- ft.(!i - 1) + x;\n i := !i + g2d !i;\n done\n\nlet fenwick_count ft n =\n let i = ref (n + 1) in\n let res = ref 0 in\n while !i > 0 do\n res := !res + ft.(!i - 1);\n i := !i - g2d !i;\n done;\n !res\n\nlet fenwick_count2 ft m n =\n fenwick_count ft n - fenwick_count ft (m - 1)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k =\n if 2 * k > n\n then n - k\n else k\n in\n let ft = fenwick_new n in\n let res = ref 1 in\n let p = ref 0 in\n for _t = 1 to n do\n incr res;\n let q = !p + k in\n\tif q <= n\n\tthen (\n\t res := !res + fenwick_count2 ft (!p + 1) (q - 1);\n\t fenwick_modify ft q 1;\n\t) else (\n\t res := !res + fenwick_count2 ft (!p + 1) (n - 1);\n\t res := !res + fenwick_count2 ft 0 (q - n - 1);\n\t fenwick_modify ft (q - n) 1;\n\t);\n\tfenwick_modify ft !p 1;\n\tp := q mod n;\n\tPrintf.printf \"%d \" !res\n done;\n Printf.printf \"\\n\"\n"}], "src_uid": "fc82362dbda74396ad6db0d95a0f7acc"} {"nl": {"description": "There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a\u2009\u00d7\u2009b chairs\u00a0\u2014 a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.", "input_spec": "The first line of the input contains three integers n, a and b (1\u2009\u2264\u2009n\u2009\u2264\u200910\u2009000, 1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009100)\u00a0\u2014 the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.", "output_spec": "If there is no way to assigns seats to parliamentarians in a proper way print -1. Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.", "sample_inputs": ["3 2 2", "8 4 3", "10 2 2"], "sample_outputs": ["0 3\n1 2", "7 8 3\n0 1 4\n6 0 5\n0 2 0", "-1"], "notes": "NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let a = read_int () in\n let b = read_int () in \n\n if n > a*b then (\n printf \"-1\\n\"\n ) else (\n let inc = if b land 1 = 0 then 1 else 0 in\n for i=0 to a-1 do\n for j=0 to b-1 do\n\tlet ind = b*i + j + 1 in\n\tlet x = match (i land 1, j land 1) with\n\t | (0,_) -> ind\n\t | (1,0) -> ind + inc\n\t | (1,1) -> ind - inc\n\t | _ -> failwith \"bad\"\n\tin\n\tprintf \"%d \" (if x > n then 0 else x);\n done;\n print_newline()\n done\n )\n"}], "negative_code": [], "src_uid": "6e0dafeaf85e92f959c388c72e158f68"} {"nl": {"description": "Another Codeforces Round has just finished! It has gathered $$$n$$$ participants, and according to the results, the expected rating change of participant $$$i$$$ is $$$a_i$$$. These rating changes are perfectly balanced\u00a0\u2014 their sum is equal to $$$0$$$.Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.There are two conditions though: For each participant $$$i$$$, their modified rating change $$$b_i$$$ must be integer, and as close to $$$\\frac{a_i}{2}$$$ as possible. It means that either $$$b_i = \\lfloor \\frac{a_i}{2} \\rfloor$$$ or $$$b_i = \\lceil \\frac{a_i}{2} \\rceil$$$. In particular, if $$$a_i$$$ is even, $$$b_i = \\frac{a_i}{2}$$$. Here $$$\\lfloor x \\rfloor$$$ denotes rounding down to the largest integer not greater than $$$x$$$, and $$$\\lceil x \\rceil$$$ denotes rounding up to the smallest integer not smaller than $$$x$$$. The modified rating changes must be perfectly balanced\u00a0\u2014 their sum must be equal to $$$0$$$. Can you help with that?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 13\\,845$$$), denoting the number of participants. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$-336 \\le a_i \\le 1164$$$), denoting the rating change of the $$$i$$$-th participant. The sum of all $$$a_i$$$ is equal to $$$0$$$.", "output_spec": "Output $$$n$$$ integers $$$b_i$$$, each denoting the modified rating change of the $$$i$$$-th participant in order of input. For any $$$i$$$, it must be true that either $$$b_i = \\lfloor \\frac{a_i}{2} \\rfloor$$$ or $$$b_i = \\lceil \\frac{a_i}{2} \\rceil$$$. The sum of all $$$b_i$$$ must be equal to $$$0$$$. If there are multiple solutions, print any. We can show that a solution exists for any valid input.", "sample_inputs": ["3\n10\n-5\n-5", "7\n-7\n-29\n0\n3\n24\n-29\n38"], "sample_outputs": ["5\n-2\n-3", "-3\n-15\n0\n2\n12\n-15\n19"], "notes": "NoteIn the first example, $$$b_1 = 5$$$, $$$b_2 = -3$$$ and $$$b_3 = -2$$$ is another correct solution.In the second example there are $$$6$$$ possible solutions, one of them is shown in the example output."}, "positive_code": [{"source_code": "let n = read_int() in\nlet rec go n bal = match n with\n | 0 -> ()\n | _ -> begin\n let x = read_int() in\n if (x mod 2 = 0) then (\n Printf.printf \"%d\\n\" (x/2);\n go (n-1) bal\n ) else \n let delta = if bal = 0 then 1 else -bal in\n let x = (x+delta)/2 in (\n Printf.printf \"%d\\n\" x;\n go (n-1) (bal+delta)\n )\n end\nin go n 0\n"}], "negative_code": [], "src_uid": "3545385c183c29f9b95aa0f02b70954f"} {"nl": {"description": "The term of this problem is the same as the previous one, the only exception \u2014 increased restrictions.", "input_spec": "The first line contains two positive integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000,\u20091\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1,\u2009b2,\u2009...,\u2009bn (1\u2009\u2264\u2009bi\u2009\u2264\u2009109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.", "output_spec": "Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.", "sample_inputs": ["1 1000000000\n1\n1000000000", "10 1\n1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000\n1 1 1 1 1 1 1 1 1 1", "3 1\n2 1 4\n11 3 16", "4 3\n4 3 5 6\n11 12 14 20"], "sample_outputs": ["2000000000", "0", "4", "3"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x);;\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x);;\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet ( ^^ ) a b = Int64.shift_left a b\nlet rec sum (i : int) (j : int) f (ac : int64) =\n if i > j then\n ac\n else\n sum (i + 1) j f (ac ++ (f i));;\n\nlet () =\n try\n while true do\n let n = read_int () in\n let k = read_long () in\n let a = Array.init n (fun _ -> read_long()) in\n let b = Array.init n (fun _ -> read_long()) in\n\n let possible m =\n let x = sum 0 (n - 1) (fun i -> min 4000000000L (max 0L ((m ** a.(i)) -- b.(i)))) 0L in\n x <= k\n in\n\n let rec binary_search small large =\n if (small ++ 1L) < large then\n let (mid : int64) = (small ++ large) // 2L in\n if possible mid then binary_search mid large else binary_search small mid\n else\n small\n in\n \n printf \"%Ld\\n\" (binary_search 0L 2000000001L)\n done\n with End_of_file -> ()\n"}, {"source_code": "open Printf\nopen Scanf\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n \nlet rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x) \nlet () = \n let n = read_int () in\n let k = read_long () in\n let a = Array.init n (fun _ -> read_long()) in\n let b = Array.init n (fun _ -> read_long()) in\n\n let can_bake m =\n let mp = sum 0 (n-1) (fun i -> max 0L (m ** a.(i) -- b.(i))) 0L in\n mp <= k\n in\n\n let rec bsearch lo hi =\n (* lo can be made, hi cannot *)\n if lo++1L = hi then lo else\n let m = (lo ++ hi) // 2L in\n if can_bake m then bsearch m hi else bsearch lo m\n in\n\n let rec findhi hi = if can_bake hi then findhi (2L ** hi) else hi in\n\n printf \"%Ld\\n\" (bsearch 0L (findhi 1L))\n \n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x);;\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x);;\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet ( ^^ ) a b = Int64.shift_left a b\nlet rec sum (i : int) (j : int) f (ac : int64) =\n if i > j then\n ac\n else\n sum (i + 1) j f (ac ++ (f i));;\n\nlet () =\n try\n while true do\n let n = read_int () in\n let k = read_long () in\n let a = Array.init n (fun _ -> read_long()) in\n let b = Array.init n (fun _ -> read_long()) in\n\n let possible m =\n let x = sum 0 (n - 1) (fun i -> max 0L (m ** a.(i) -- b.(i))) 0L in\n x <= k\n in\n\n let rec binary_search small large =\n if (small ++ 1L) < large then\n let mid = (small ++ large) // 2L in\n if possible mid then binary_search mid large else binary_search small mid\n else\n small\n in\n\n printf \"%Ld\\n\" (binary_search 0L 1000000001L)\n done\n with End_of_file -> ()\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x);;\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x);;\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet ( ^^ ) a b = Int64.shift_left a b\nlet rec sum (i : int) (j : int) f (ac : int64) =\n if i > j then\n ac\n else\n sum (i + 1) j f (ac ++ (f i));;\n\nlet () =\n try\n while true do\n let n = read_int () in\n let k = read_long () in\n let a = Array.init n (fun _ -> read_long()) in\n let b = Array.init n (fun _ -> read_long()) in\n\n let possible m =\n let x = sum 0 (n - 1) (fun i -> max 0L (m ** a.(i) -- b.(i))) 0L in\n x <= k\n in\n\n let rec binary_search small large =\n if (small ++ 1L) < large then\n let mid = (small ++ large) // 2L in\n if possible mid then binary_search mid large else binary_search small mid\n else\n small\n in\n \n printf \"%Ld\\n\" (binary_search 0L 2000000001L)\n done\n with End_of_file -> ()\n"}], "src_uid": "ab1b4487899609ac0f882e1b1713d162"} {"nl": {"description": "Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink \"Beecola\", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of \"Beecola\".", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of shops in the city that sell Vasiliy's favourite drink. The second line contains n integers xi (1\u2009\u2264\u2009xi\u2009\u2264\u2009100\u2009000)\u00a0\u2014 prices of the bottles of the drink in the i-th shop. The third line contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of days Vasiliy plans to buy the drink. Then follow q lines each containing one integer mi (1\u2009\u2264\u2009mi\u2009\u2264\u2009109)\u00a0\u2014 the number of coins Vasiliy can spent on the i-th day.", "output_spec": "Print q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.", "sample_inputs": ["5\n3 10 8 6 11\n4\n1\n10\n3\n11"], "sample_outputs": ["0\n4\n1\n5"], "notes": "NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop."}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\nlet print int = Printf.printf \"%d\\n\" int\n\nlet binary_search arr n value =\n let result =\n (let rec search low high =\n if high = low || high - low = 1\n then\n low\n else\n let mid = (low + high) / 2 in\n if arr.(mid - 1) > value \n then\n search low mid\n else\n search mid high\n in search 0 (n + 1))\n in \n print result\n\nlet input () =\n let n = read () in\n let price = Array.init n (fun n -> read ()) in\n let m = read () in\n let cash = Array.init m (fun n -> read ()) in\n (n, price, cash)\n\nlet solve (n, price, cash) =\n (Array.fast_sort Pervasives.compare price;\n Array.iter (binary_search price n) cash)\n\nlet () = solve (input ())"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\nlet print int = Printf.printf \"%d\\n\" int\n\nlet make_array n = \n let arr = Array.make n 0 in\n let rec loop i =\n if i < n\n then\n (let int = read () in\n Array.set arr i int;\n loop (i + 1))\n else\n arr\n in loop 0\n\nlet binary_search arr n value =\n let result =\n (let rec search low high =\n if high = low || high - low = 1\n then\n low\n else\n let mid = (low + high) / 2 in\n if arr.(mid - 1) > value \n then\n search low mid\n else\n search mid high\n in search 0 (n + 1))\n in \n print result\n\nlet input () =\n let n = read () in\n let price = make_array n in\n let m = read () in\n let cash = make_array m in\n (n, price, cash)\n\nlet solve (n, price, cash) =\n (Array.fast_sort Pervasives.compare price;\n Array.iter (binary_search price n) cash)\n\nlet () = solve (input ())"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\nlet print int = Printf.printf \"%d\\n\" int\n\nlet make_array n = \n let arr = Array.make n 0 in\n let rec loop i =\n if i < n\n then\n (let int = read () in\n Array.set arr i int;\n loop (i + 1))\n else\n arr\n in loop 0\n\nlet binary_search arr n value =\n let result = \n (let rec search low high contender =\n assert (high >= low);\n if high = low\n then\n if arr.(low) <= value \n then\n low\n else\n contender\n else \n let mid = (low + high) / 2 in\n if arr.(mid) > value \n then\n if mid = low\n then\n contender\n else\n search low (mid - 1) contender\n else\n search (mid + 1) high mid\n\n in search 0 (n - 1) (-1))\n in\n print (result + 1)\n\nlet input () =\n let n = read () in\n let price = make_array n in\n let m = read () in\n let cash = make_array m in\n (n, price, cash)\n\nlet solve (n, price, cash) =\n (Array.fast_sort Pervasives.compare price;\n Array.iter (binary_search price n) cash)\n\nlet () = solve (input ())"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet count_smaller ele shop_arr n =\n let print n = Printf.printf \"%d\\n\" n in\n if ele < shop_arr.(0) then print 0\n else if ele >= shop_arr.(n-1) then print n\n else\n let rec bsearch low high =\n if low + 1 = high then print high\n else\n let mid = (low + high) / 2 in\n if ele < shop_arr.(mid) then bsearch low mid\n else if ele >= shop_arr.(mid) then bsearch mid high\n in bsearch 0 (n - 1)\n\n\nlet () =\n let n = read_int () in\n let shop_arr = Array.init n (fun _ ->\n read_int ();\n )\n in\n let q = read_int () in\n let coin_arr = Array.init q (fun _ ->\n read_int ();\n )\n in\n Array.sort compare shop_arr;\n Array.iter (fun x -> count_smaller x shop_arr n) coin_arr\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = Array.init n (fun _ -> read_int()) in \n let q = read_int () in\n let m = Array.init q (fun _ -> read_int()) in\n\n Array.sort compare x;\n\n let find_index m =\n (* return the index of the biggest shop whose cost is <= m *)\n (* -1 if there is no such one *)\n let rec bsearch lo hi =\n (* x.(lo) <= m x.(hi) > m *)\n if lo + 1 = hi then lo else\n\tlet mid = (lo+hi)/2 in\n\tif x.(mid) <= m then bsearch mid hi else bsearch lo mid\n in\n if x.(n-1) <= m then n-1\n else if x.(0) > m then -1\n else bsearch 0 (n-1)\n in\n\n for j=0 to q-1 do\n let i = find_index m.(j) in\n printf \"%d\\n\" (i+1)\n done\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet count_smaller ele shop_arr n =\n let print n = Printf.printf \"%d\\n\" n in\n if ele < shop_arr.(0) then print 0\n else if ele >= shop_arr.(n-1) then print n\n else\n let rec bsearch low high =\n if low + 1 = high then print high\n else\n let mid = (low + high) / 2 in\n if ele < shop_arr.(mid) then bsearch low mid\n else if ele > shop_arr.(mid) then bsearch mid high\n else print (mid + 1)\n in bsearch 0 (n - 1)\n\n\nlet () =\n let n = read_int () in\n let shop_arr = Array.init n (fun _ ->\n read_int ();\n )\n in\n let q = read_int () in\n let coin_arr = Array.init q (fun _ ->\n read_int ();\n )\n in\n Array.sort compare shop_arr;\n Array.iter (fun x -> count_smaller x shop_arr n) coin_arr\n"}], "src_uid": "80a03e6d513f4051175cd5cd1dea33b4"} {"nl": {"description": "Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n.Polycarpus needs to come up with a parallel program model. For each memory cell number i this program must record the value n\u2009-\u2009i to this cell. In other words, for each cell you've got to find the distance to cell n.Let's denote the value that is written in the i-th cell as ai. Initially, ai\u2009=\u20091 (1\u2009\u2264\u2009i\u2009<\u2009n) and an\u2009=\u20090. We will consider that only processor i can write values in the memory cell number i. All processors can read an information from some cell (several processors can read an information from some cell simultaneously).The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows: Each processor independently of the other ones chooses some memory cell. Let's say that processor i has chosen a cell with number ci (1\u2009\u2264\u2009ci\u2009\u2264\u2009n). All processors simultaneously execute operation ai\u2009=\u2009ai\u2009+\u2009aci. Help Polycarpus come up with the parallel program model that is executed in exactly k steps. Calculate the operations that need to be executed. Note that after k steps for all i's value ai must be equal n\u2009-\u2009i.", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009104,\u20091\u2009\u2264\u2009k\u2009\u2264\u200920). It is guaranteed that at the given n and k the required sequence of operations exists.", "output_spec": "Print exactly n\u00b7k integers in k lines. In the first line print numbers c1,\u2009c2,\u2009...,\u2009cn (1\u2009\u2264\u2009ci\u2009\u2264\u2009n) for the first increment operation. In the second line print the numbers for the second increment operation. In the k-th line print the numbers for the k-th increment operation. As a result of the printed operations for any i value ai must equal n\u2009-\u2009i.", "sample_inputs": ["1 1", "3 2"], "sample_outputs": ["1", "2 3 3\n3 3 3"], "notes": null}, "positive_code": [{"source_code": "(* CF ParallelProg 291D *)\nopen Filename;;\nopen Str;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string (s ^ \" \"))) ls;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet rec readlist n acc = match n with\n\t| 0 -> List.rev acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet debug = false;;\n\nlet n = gr();;\nlet k = gr();;\n\nlet a = Array.make (n+1) 1;;\nlet anxt = Array.make (n+1) 0;;\nlet c = Array.make (n+1) 0;;\n\nlet init = ( a.(n) <- 0 );;\n\nlet rec findgood i ii = \n\tif ii > n then i\n\telse if a.(i) = n-i then n\n\telse if a.(i)*2 > n-i then n - (n-i - a.(i))\n\telse i;;\n\nlet step () = \n\tbegin\n\t\tfor i=1 to n do\n\t\t\tlet k = findgood i i in\n\t\t\t(\n\t\t\t\tc.(i) <- k;\n\t\t\t\tanxt.(i) <- a.(i) + a.(k);\n\t\t\t\tprint_int k;\n\t\t\t\tprint_string \" \"\n\t\t\t)\n\t\tdone;\n\t\tfor i=1 to n do\n\t\t\ta.(i) <- anxt.(i)\n\t\tdone;\n\t\tprint_string \"\\n\"\n\tend;;\n\t\t\n\t\t\t\n\n\nlet main() =\n\tfor i = 1 to k do\n\t\tstep()\n\tdone;; \n\t\n\nmain ();;"}], "negative_code": [], "src_uid": "c8800840e52d4141acdff0420e7ec73c"} {"nl": {"description": "Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic...To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most $$$l$$$ centimeters after haircut, where $$$l$$$ is her favorite number. Suppose, that the Alice's head is a straight line on which $$$n$$$ hairlines grow. Let's number them from $$$1$$$ to $$$n$$$. With one swing of the scissors the hairdresser can shorten all hairlines on any segment to the length $$$l$$$, given that all hairlines on that segment had length strictly greater than $$$l$$$. The hairdresser wants to complete his job as fast as possible, so he will make the least possible number of swings of scissors, since each swing of scissors takes one second.Alice hasn't decided yet when she would go to the hairdresser, so she asked you to calculate how much time the haircut would take depending on the time she would go to the hairdresser. In particular, you need to process queries of two types: $$$0$$$\u00a0\u2014 Alice asks how much time the haircut would take if she would go to the hairdresser now. $$$1$$$ $$$p$$$ $$$d$$$\u00a0\u2014 $$$p$$$-th hairline grows by $$$d$$$ centimeters. Note, that in the request $$$0$$$ Alice is interested in hypothetical scenario of taking a haircut now, so no hairlines change their length.", "input_spec": "The first line contains three integers $$$n$$$, $$$m$$$ and $$$l$$$ ($$$1 \\le n, m \\le 100\\,000$$$, $$$1 \\le l \\le 10^9$$$)\u00a0\u2014 the number of hairlines, the number of requests and the favorite number of Alice. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \\le a_i \\le 10^9$$$)\u00a0\u2014 the initial lengths of all hairlines of Alice. Each of the following $$$m$$$ lines contains a request in the format described in the statement. The request description starts with an integer $$$t_i$$$. If $$$t_i = 0$$$, then you need to find the time the haircut would take. Otherwise, $$$t_i = 1$$$ and in this moment one hairline grows. The rest of the line than contains two more integers: $$$p_i$$$ and $$$d_i$$$ ($$$1 \\le p_i \\le n$$$, $$$1 \\le d_i \\le 10^9$$$)\u00a0\u2014 the number of the hairline and the length it grows by.", "output_spec": "For each query of type $$$0$$$ print the time the haircut would take.", "sample_inputs": ["4 7 3\n1 2 3 4\n0\n1 2 3\n0\n1 1 3\n0\n1 3 1\n0"], "sample_outputs": ["1\n2\n2\n1"], "notes": "NoteConsider the first example: Initially lengths of hairlines are equal to $$$1, 2, 3, 4$$$ and only $$$4$$$-th hairline is longer $$$l=3$$$, and hairdresser can cut it in $$$1$$$ second. Then Alice's second hairline grows, the lengths of hairlines are now equal to $$$1, 5, 3, 4$$$ Now haircut takes two seonds: two swings are required: for the $$$4$$$-th hairline and for the $$$2$$$-nd. Then Alice's first hairline grows, the lengths of hairlines are now equal to $$$4, 5, 3, 4$$$ The haircut still takes two seconds: with one swing hairdresser can cut $$$4$$$-th hairline and with one more swing cut the segment from $$$1$$$-st to $$$2$$$-nd hairline. Then Alice's third hairline grows, the lengths of hairlines are now equal to $$$4, 5, 4, 4$$$ Now haircut takes only one second: with one swing it is possible to cut the segment from $$$1$$$-st hairline to the $$$4$$$-th. "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,m,l = get_3_i64 0 in\n let a = input_i64_array n in\n let c = ref 0L in\n fold_left (fun u v ->\n if u<=l && v>l then (\n c += 1L;\n ); v\n ) (-1L) a |> ignore;\n rep 1L m (fun _ ->\n match get_i64 0 with\n | 0L -> (\n printf \"%Ld\\n\" !c\n )\n | 1L -> (\n let i,w = get_2_i64 0 in let i = i - 1L in\n let p,q = a.(i32 i),a.(i32 i)+w in\n if p<=l && q>l then (\n if (i>=1L && a.(i32 i-$1) > l) && (i<=n-2L && a.(i32 i+$1) > l) then (\n c -= 1L;\n ) else if (i>=1L && a.(i32 i-$1) > l) || (i<=n-2L && a.(i32 i+$1) > l) then (\n c += 0L;\n ) else c += 1L;\n );\n a.(i32 i) <- q;\n )\n | _ -> fail 0\n )\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n,m,l = get_3_i64 0 in\n let a = input_i64_array n in\n let c = ref 0L in\n iter (fun v -> if v > l then c += 1L) a;\n rep 1L m (fun _ ->\n match get_i64 0 with\n | 0L -> (\n printf \"%Ld\\n\" !c\n )\n | 1L -> (\n let i,w = get_2_i64 0 in let i = i - 1L in\n let p,q = a.(i32 i),a.(i32 i)+w in\n if p<=l && q>l then (\n if (i>=1L && a.(i32 i-$1) > l) && (i<=n-2L && a.(i32 i+$1) > l) then (\n c -= 1L;\n ) else if (i>=1L && a.(i32 i-$1) > l) || (i<=n-2L && a.(i32 i+$1) > l) then (\n c += 0L;\n ) else c += 1L;\n );\n a.(i32 i) <- q;\n )\n | _ -> fail 0\n )\n\n\n\n\n\n\n\n\n"}], "src_uid": "1e17039ed5c48e5b56314a79b3811a40"} {"nl": {"description": "You are given two positive integers $$$n$$$ and $$$k$$$. Print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.For example, if $$$n=3$$$, and $$$k=7$$$, then all numbers that are not divisible by $$$3$$$ are: $$$1, 2, 4, 5, 7, 8, 10, 11, 13 \\dots$$$. The $$$7$$$-th number among them is $$$10$$$.", "input_spec": "The first line contains an integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$2 \\le n \\le 10^9$$$) and $$$k$$$ ($$$1 \\le k \\le 10^9$$$).", "output_spec": "For each test case print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.", "sample_inputs": ["6\n3 7\n4 12\n2 1000000000\n7 97\n1000000000 1000000000\n2 1"], "sample_outputs": ["10\n15\n1999999999\n113\n1000000001\n1"], "notes": null}, "positive_code": [{"source_code": "(* Codeforces 1352 C K-th Not Divisible by n comp *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec kth_not_div n k = \n\tlet n1 = Int64.pred n in\n\tlet o = Int64.rem k n1 in\n\tlet d = Int64.div k n1 in\n\tlet oo = if (Int64.compare o Int64.zero) == 0 then Int64.minus_one else o in\n\tlet ret = Int64.add (Int64.mul n d) oo in\n\tret;;\t\n \nlet do_one () = \n let n = grl () in\n let k = grl () in\n\t\tlet kth = kth_not_div n k in \n \tPrintf.printf \"%Ld\\n\" kth;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}, {"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\n \nopen Printf\n\nlet init (x : int) (f : int -> 'a) : 'a list =\n let rec build k =\n if k = x then []\n else (f k) :: build (k + 1) in\n build 0\n;;\n \nlet run () = \n let open Int64 in\n let n = scan_int () |> of_int in\n let k = scan_int () |> of_int in\n let check x =\n sub x (div x n) >= k in\n let rec f lo hi ans =\n if lo > hi then ans\n else begin\n let md = div (add lo hi) 2L in\n ifprintf stdout \"%Ld %Ld %Ld %B\\n\" lo hi md (check md);\n if check md then f lo (sub md 1L) md\n else f (add md 1L) hi ans\n end in\n printf \"%Ld\\n\" (f 1L 3000000000L max_int)\n;;\n \nlet () =\n let t = scan_int () in\n for i = 1 to t do\n run ()\n done\n;;\n"}], "negative_code": [{"source_code": "(* Codeforces 1352 C K-th Not Divisible by n comp *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec kth_not_div n k = \n\tlet o = k mod (n - 1) in\n\tlet d = k / (n - 1) in\n\tlet ret = (n * d) + (if o==0 then (-1) else o) in\n\t(* let _ = Printf.printf \"n,k,o,d,ret = %d %d %d %d %d\\n\" n k o d ret in *)\n\tret;;\t\n \nlet do_one () = \n let n = gr () in\n let k = gr () in\n\t\tlet kth = kth_not_div n k in \n \tPrintf.printf \"%d\\n\" kth;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}, {"source_code": "(* Codeforces 1352 C K-th Not Divisible by n comp *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec kth_not_div n k = \n\tlet o = k mod (n - 1) in\n\tlet d = k / (n - 1) in\n\tlet ret = (n * d) + (if o==0 then (-1) else o) in\n\t(* let _ = Printf.printf \"n,k,o,d,ret = %d %d %d %d %d\\n\" n k o d ret in *)\n\tret;;\t\n \nlet do_one () = \n let n = gr () in\n let k = gr () in\n\t\tlet kth = kth_not_div n k in \n \tPrintf.printf \"%d\\n\" kth;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "src_uid": "7d6f76e24fe9a352beea820ab56f03b6"} {"nl": {"description": "n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.", "input_spec": "The first line contains two integers: n and k (2\u2009\u2264\u2009n\u2009\u2264\u2009500, 2\u2009\u2264\u2009k\u2009\u2264\u20091012)\u00a0\u2014 the number of people and the number of wins. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n) \u2014 powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all ai are distinct.", "output_spec": "Output a single integer \u2014 power of the winner.", "sample_inputs": ["2 2\n1 2", "4 2\n3 1 2 4", "6 2\n6 5 3 1 2 4", "2 10000000000\n2 1"], "sample_outputs": ["2", "3", "6", "2"], "notes": "NoteGames in the second sample:3 plays with 1. 3 wins. 1 goes to the end of the line.3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i) \n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let k = read_long () in\n let k = if k >= long n then n-1 else short k in\n let power = Array.init n read_int in\n\n let run_length i =\n let rec run_starting_at pow j ac =\n if j = n || pow < power.(j) then ac\n else run_starting_at pow (j+1) (ac+1)\n in\n\t\n let best_before = maxf 0 i (fun j -> power.(j)) in\n if best_before > power.(i) then 0 else\n (if i > 0 then 1 else 0) + run_starting_at power.(i) (i+1) 0\n in\n\n let rec scan i =\n let rl = run_length i in\n if rl >= k || rl >= n-i then i else scan (i+1)\n in\n\n printf \"%d\\n\" (power.(scan 0))\n"}], "negative_code": [], "src_uid": "8d5fe8eee1cce522e494231bb210950a"} {"nl": {"description": "Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20091000)\u00a0\u2014 the number of disks on the combination lock. The second line contains a string of n digits\u00a0\u2014 the original state of the disks. The third line contains a string of n digits\u00a0\u2014 Scrooge McDuck's combination that opens the lock.", "output_spec": "Print a single integer\u00a0\u2014 the minimum number of moves Scrooge McDuck needs to open the lock.", "sample_inputs": ["5\n82195\n64723"], "sample_outputs": ["13"], "notes": "NoteIn the sample he needs 13 moves: 1 disk: 2 disk: 3 disk: 4 disk: 5 disk: "}, "positive_code": [{"source_code": "let input () = \n let n = Scanf.scanf \"%d \" (fun n -> n) in\n let start = Array.init n (fun i -> Scanf.scanf \"%c \" (fun i -> i)) in\n let goal = Array.init n (fun i -> Scanf.scanf \"%c \" (fun i -> i)) in\n (n, start, goal)\n\nlet solve (n, start, goal) = \n let rec loop i count =\n if i < n\n then\n let s = Pervasives.int_of_char (start.(i)) in\n let g = Pervasives.int_of_char (goal.(i)) in\n let min = Pervasives.min s g in\n let max = Pervasives.max s g in\n let try_one = max - min in\n let try_two = min + 10 - max in\n let r = Pervasives.min try_one try_two in\n loop (i + 1) (count + r)\n else\n count\n in loop 0 0\n\nlet print result = Printf.printf \"%d\\n\" result\nlet () = print (solve (input ()))"}, {"source_code": "let split x = x |> Str.split (Str.regexp \"\") |> List.map int_of_string and\n minimum = List.fold_left min 10 and\n sum = List.fold_left (+) 0 in \nlet _ = read_line () and\n fromComb = read_line () |> split and\n toComb = read_line () |> split\nin\nList.map2 (fun x y -> List.map abs [x-y; y-x; 10+x-y; 10+y-x] |> minimum) fromComb toComb |> sum |> print_int\n"}, {"source_code": "let dist a b =\n\tmin (10+b-a) (min (abs (10+a-b)) (abs (a-b)))\n\nlet _ =\n\t\n\tlet (n,ini,fin) = Scanf.scanf \"%d %s %s\" (fun i j k -> (i,j,k))\n\tand res = ref 0 and f mot i = int_of_char (mot.[i]) in\n\t\tfor i=0 to n-1 do\n\t\t\tres := !res + dist (f ini i) (f fin i);\n\t\tdone;\n\tPrintf.printf \"%d\\n\" (!res)\n"}, {"source_code": "let ( |> ) x f = f x;;\n\nlet n = read_int();;\nlet a = read_line();;\nlet b = read_line();;\nlet rec solve index =\n if index >= String.length a || index >= String.length b then\n 0\n else (\n let d = int_of_char a.[index] - (int_of_char b.[index]) |> abs in\n let dis = min d (10 - d) in\n dis + (solve (index + 1))\n );;\nsolve 0 |> print_int;;\n "}], "negative_code": [], "src_uid": "5adb1cf0529c3d6c93c107cf72fa5e0b"} {"nl": {"description": "Berland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not.The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home.Unfortunately, not everything is as great as Valera II would like. The main part of the group were gastarbeiters \u2014 illegal immigrants who are enthusiastic but not exactly good at understanding orders in Berlandian. Therefore, having received orders to asphalt the roads coming from some of the city, the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it.Upon learning of this progress, Valera II was very upset, but since it was too late to change anything, he asked you to make a program that determines whether you can in some way asphalt Berlandian roads in at most n days. Help the king.", "input_spec": "The first line contains two space-separated integers n,\u2009m \u2014 the number of cities and roads in Berland, correspondingly. Next m lines contain the descriptions of roads in Berland: the i-th line contains three space-separated integers ai,\u2009bi,\u2009ci (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n;\u00a0ai\u2009\u2260\u2009bi;\u00a00\u2009\u2264\u2009ci\u2009\u2264\u20091). The first two integers (ai,\u2009bi) are indexes of the cities that are connected by the i-th road, the third integer (ci) equals 1, if the road was initially asphalted, and 0 otherwise. Consider the cities in Berland indexed from 1 to n, and the roads indexed from 1 to m. It is guaranteed that between two Berlandian cities there is not more than one road.", "output_spec": "In the first line print a single integer x (0\u2009\u2264\u2009x\u2009\u2264\u2009n) \u2014 the number of days needed to asphalt all roads. In the second line print x space-separated integers \u2014 the indexes of the cities to send the workers to. Print the cities in the order, in which Valera send the workers to asphalt roads. If there are multiple solutions, print any of them. If there's no way to asphalt all roads, print \"Impossible\" (without the quotes).", "sample_inputs": ["4 4\n1 2 1\n2 4 0\n4 3 1\n3 2 0", "3 3\n1 2 0\n2 3 0\n3 1 0"], "sample_outputs": ["4\n3 2 1 3", "Impossible"], "notes": null}, "positive_code": [{"source_code": "let (@@) f x = f x\nlet (|>) x f = f x\nlet (%) f g x = f @@ g x\n\nlet () =\n Scanf.scanf \"%d %d\" @@ fun n m ->\n let g = Array.make (n + n * n) [] in\n let add_edges = List.iter @@ fun (a, b) -> g.(a) <- b :: g.(a); g.(b) <- a :: g.(b) in\n let idx a b = n + n * (min a b) + (max a b) in\n for i = 1 to m do\n ignore i;\n Scanf.scanf \" %d %d %d\" @@ fun a b even ->\n let a = a - 1 and b = b - 1 in\n add_edges @@ if even = 1 then [(a, idx a b); (idx a b, b)] else [(a, b)]\n done;\n let colors = Array.make (n + n * n) None in\n let rec dfs c v = match colors.(v) with\n | Some c' when c <> c' -> raise Not_found\n | Some _ -> ()\n | None -> colors.(v) <- Some c; List.iter (dfs @@ not c) g.(v)\n in\n let get o = match o with Some c -> c | None -> assert false in\n try\n ArrayLabels.iteri colors ~f:(fun v c -> if c = None then dfs false v);\n List.(\n Array.sub colors 0 n |> Array.to_list\n |> mapi (fun i b -> i, b) |> filter (get % snd) |> map (string_of_int % succ % fst) |> fun l ->\n Printf.printf \"%d\\n%s\\n\" (length l) @@ String.concat \" \" l)\n with Not_found -> Printf.printf \"Impossible\\n\""}, {"source_code": "let (@@) f x = f x\nlet (|>) x f = f x\n\nlet (%) f g x = f @@ g x\n\nmodule Option = struct\n let get = function\n | Some x -> x\n | None -> assert false\nend\n\nlet () =\n let dsf n = object(self)\n val parent = Array.init n (fun x -> x)\n val rank = Array.make n 1\n method get v =\n if v = parent.(v) then v\n else begin\n parent.(v) <- self#get parent.(v);\n parent.(v)\n end\n method merge a b =\n let a, b = (fun a b -> max a b, min a b) (self#get a) (self#get b) in\n if a <> b then begin\n parent.(b) <- a;\n if rank.(a) = rank.(b) then rank.(a) <- rank.(a) + 1\n end\n end in\n let bicolor g =\n let n = Array.length g in\n let colors = Array.make n None in\n let rec dfs color v =\n match colors.(v) with\n | Some c when c <> color -> raise Not_found\n | Some _ -> ()\n | None ->\n colors.(v) <- Some color;\n List.iter (dfs @@ not color) g.(v)\n in\n try\n for v = 0 to n - 1 do\n if colors.(v) = None then dfs false v\n done;\n Some (Array.map Option.get colors)\n with Not_found -> None\n in\n let add_edges g = List.iter @@ fun (a, b) -> g.(a) <- b :: g.(a) in\n let condense g : int list array * (int -> int) =\n let n = Array.length g in\n let dsf = dsf n in\n let iter_g f = ArrayLabels.iteri g ~f:(fun a -> List.iter @@ f a) in\n iter_g (fun a (b, asphalted) -> if asphalted then dsf#merge a b);\n let index = Array.make n None in\n let size = ref 0 in\n for i = 0 to n - 1 do\n let root = dsf#get i in\n begin match index.(root) with\n | Some _ -> ()\n | None -> incr size; index.(root) <- Some (!size - 1)\n end;\n index.(i) <- index.(root)\n done;\n let g' = Array.make n [] in\n let get v = Option.get index.(v) in\n iter_g (fun a (b, asphalted) ->\n let a, b = get a, get b in\n if not asphalted then add_edges g' [a, b; b, a]);\n g', get\n in\n let solve g : (int -> bool) option =\n let g', get = condense g in\n match bicolor g' with\n | Some colors -> Some (Array.get colors % get)\n | None -> None\n in\n let output n switched =\n let answer = ref [] in\n for i = 0 to n - 1 do\n if switched i then answer := (i + 1) :: !answer\n done;\n List.(Printf.sprintf \"%d\\n%s\"\n (length !answer)\n (String.concat \" \" @@ map string_of_int @@ rev !answer))\n in\n let input () =\n Scanf.scanf \"%d %d\" @@ fun n m ->\n let g = Array.make n [] in\n let add_road a b asphalted = add_edges g [a, (b, asphalted); b, (a, asphalted)] in\n for i = 1 to m do\n ignore i; (* to get rid of unused variable warning *)\n Scanf.scanf \" %d %d %d\" @@ fun a b asphalted ->\n add_road (a - 1) (b - 1) (asphalted = 1)\n done;\n g\n in\n input ()\n |> fun g ->\n Printf.printf \"%s\\n\" @@\n match solve g with\n | None -> \"Impossible\"\n | Some f -> output (Array.length g) f"}, {"source_code": "let (@@) f x = f x\nlet (|>) x f = f x\nlet (%) f g x = f @@ g x\n\nlet () =\n Scanf.scanf \"%d %d\" @@ fun n m ->\n let g = Array.make n [] in\n let add_edge a b c = g.(a) <- (b, c) :: g.(a); g.(b) <- (a, c) :: g.(b) in\n for i = 1 to m do\n ignore i;\n Scanf.scanf \" %d %d %d\" @@ fun a b c ->\n add_edge (a - 1) (b - 1) c\n done;\n let colors = Array.make n ~-1 in\n let rec dfs c v = match colors.(v) with\n | -1 -> colors.(v) <- c; List.iter (fun (v, c') -> dfs (1 land (lnot @@ c lxor c')) v) g.(v)\n | c' when c = c' -> ()\n | _ -> raise Not_found\n in\n try\n Array.iteri (fun v _ -> try dfs 1 v with Not_found -> dfs 0 v) colors;\n Array.fold_left (fun (acc, i) c -> (if c = 1 then (string_of_int i) :: acc else acc), i + 1) ([], 1) colors\n |> fun (l, _) ->\n Printf.printf \"%d\\n%s\\n\" (List.length l) @@ String.concat \" \" l\n with Not_found -> Printf.printf \"Impossible\\n\""}, {"source_code": "let (@@) f x = f x\nlet (|>) x f = f x\n\ntype road_graph = (int * bool) list array\ntype dep_graph = int list array\ntype tout_comp = int -> int\n\nlet (%) f g x = f @@ g x\n\nlet () =\n let make_dfs g =\n let marked, mark =\n let marked = Array.(make (length g) false) in\n (fun v -> marked.(v)),\n (fun v -> marked.(v) <- true)\n in\n fun fout v ->\n let rec dfs v =\n if not (marked v) then begin\n mark v;\n List.iter dfs g.(v);\n fout v\n end\n in\n dfs v\n in\n let add_edge g a b = g.(a) <- b :: g.(a) in\n let transpose g =\n let g' = Array.(make (length g) []) in\n ArrayLabels.iteri g ~f:(fun a -> List.iter @@ fun b -> add_edge g' b a);\n g'\n in\n let condensation (g : dep_graph) : tout_comp =\n let n = Array.length g in\n let add, iter, get_tout =\n let order = Array.make n ~-1 in\n let index = Array.copy order in\n let size = ref 0 in\n (fun v -> incr size; order.(!size - 1) <- v; index.(v) <- !size -1),\n (fun f -> Array.iter f order),\n (fun v -> index.(v))\n in\n let dfs = make_dfs g in\n for i = 0 to n - 1 do dfs add i done;\n let set_parent, get_parent =\n let parent = Array.(make (length g) ~-1) in\n (fun p v -> parent.(v) <- p),\n (fun v -> parent.(v))\n in\n let dfs = make_dfs @@ transpose g in\n iter (fun i -> dfs (set_parent i) i);\n get_tout % get_parent\n in\n let opposite n i = n / 2 - (i - n / 2) - 1 in\n let _2sat (g : dep_graph) =\n let n = Array.length g in\n let toc = condensation g in\n try\n Some (Array.init (n / 2) (fun v ->\n let tocv = toc v and toc'v = toc @@ opposite n v in\n if tocv <> toc'v then tocv > toc'v\n else raise Not_found))\n with Not_found -> None\n in\n let dep_graph_of_road_graph (g : road_graph) : dep_graph =\n let n = Array.length g * 2 in\n let (!!) = opposite n in\n let add_disj, get =\n let g = Array.make n [] in\n (fun (a, b) -> add_edge g (!! a) b; add_edge g (!! b) a),\n (fun () -> g)\n in\n let add_disjs = List.iter add_disj in\n ArrayLabels.iteri g ~f:(fun i ->\n List.iter @@ fun (j, asphalted) ->\n add_disjs @@ (* literals correspond to enevenness of switches *)\n if asphalted then [(i, !! j); (j, !!i)] else [(i, j); (!!i, !!j)]);\n get ()\n in\n let solution = function\n | None -> \"Impossible\"\n | Some a ->\n let to_switch, _ =\n ArrayLabels.fold_left a\n ~init:([], 1)\n ~f:(fun (acc, i) even -> (if not even then i :: acc else acc), i + 1)\n in\n List.(Printf.sprintf \"%d\\n%s\"\n (length to_switch)\n (String.concat \" \" @@ map string_of_int @@ rev to_switch))\n in\n let input () =\n Scanf.scanf \"%d %d\" @@ fun n m ->\n let add_road, get =\n let g = Array.make n [] in\n (fun a b asphalted -> add_edge g a (b, asphalted); add_edge g b (a, asphalted)),\n (fun () -> g)\n in\n for i = 1 to m do\n ignore i; (* to get rid of unused variable warning *)\n Scanf.scanf \" %d %d %d\" @@ fun a b asphalted ->\n add_road (a - 1) (b - 1) (asphalted = 1)\n done;\n get ()\n in\n input ()\n |> dep_graph_of_road_graph\n |> _2sat\n |> solution\n |> Printf.printf \"%s\\n\"\n"}, {"source_code": "let (@@) f x = f x\nlet (|>) x f = f x\n\ntype road_graph = (int * bool) list array\ntype dep_graph = int list array\ntype tout_comp = int -> int\n\nlet (%) f g x = f @@ g x\n\nlet () =\n let make_dfs g =\n let marked, mark =\n let marked = Array.(make (length g) false) in\n Array.get marked,\n (fun v -> marked.(v) <- true)\n in\n fun fout v ->\n let rec dfs v =\n if not (marked v) then begin\n mark v;\n List.iter dfs g.(v);\n fout v\n end\n in\n dfs v\n in\n let add_edge g a b = g.(a) <- b :: g.(a) in\n let transpose g =\n let g' = Array.(make (length g) []) in\n ArrayLabels.iteri g ~f:(fun a -> List.iter @@ fun b -> add_edge g' b a);\n g'\n in\n let condensation g : tout_comp =\n let n = Array.length g in\n let add, iter, get_tout =\n let order = Array.make n ~-1 in\n let index = Array.copy order in\n let size = ref 0 in\n (fun v -> incr size; order.(!size - 1) <- v; index.(v) <- !size -1),\n (fun f -> Array.iter f order),\n Array.get index\n in\n let set_parent, get_parent =\n let parent = Array.(make (length g) ~-1) in\n (fun p v -> parent.(v) <- p),\n Array.get parent\n in\n let dfs = make_dfs g in\n for i = 0 to n - 1 do dfs add i done;\n let dfs = make_dfs @@ transpose g in\n iter (fun i -> dfs (set_parent i) i);\n get_tout % get_parent\n in\n let opposite n i = n / 2 - (i - n / 2) - 1 in\n let _2sat (g : dep_graph) =\n let n = Array.length g in\n let toc = condensation g in\n try\n Some (Array.init (n / 2) (fun v ->\n let tocv = toc v and tocv' = toc @@ opposite n v in\n if tocv <> tocv' then tocv > tocv'\n else raise Not_found))\n with Not_found -> None\n in\n let dep_graph_of_road_graph (g : road_graph) : dep_graph =\n let n = Array.length g * 2 in\n let (!!) = opposite n in\n let add_disj, get =\n let g = Array.make n [] in\n (fun (a, b) -> add_edge g (!! a) b; add_edge g (!! b) a),\n (fun () -> g)\n in\n let add_disjs = List.iter add_disj in\n ArrayLabels.iteri g ~f:(fun i ->\n List.iter @@ fun (j, asphalted) ->\n add_disjs @@ (* literals correspond to enevenness of switches *)\n if asphalted then [(i, !!j); (j, !!i)] else [(i, j); (!!i, !!j)]);\n get ()\n in\n let solution = function\n | None -> \"Impossible\"\n | Some a ->\n let to_switch, _ =\n ArrayLabels.fold_left a\n ~init:([], 1)\n ~f:(fun (acc, i) even -> (if not even then i :: acc else acc), i + 1)\n in\n List.(Printf.sprintf \"%d\\n%s\"\n (length to_switch)\n (String.concat \" \" @@ map string_of_int @@ rev to_switch))\n in\n let input () =\n Scanf.scanf \"%d %d\" @@ fun n m ->\n let add_road, get =\n let g = Array.make n [] in\n (fun a b asphalted -> add_edge g a (b, asphalted); add_edge g b (a, asphalted)),\n (fun () -> g)\n in\n for i = 1 to m do\n ignore i; (* to get rid of unused variable warning *)\n Scanf.scanf \" %d %d %d\" @@ fun a b asphalted ->\n add_road (a - 1) (b - 1) (asphalted = 1)\n done;\n get ()\n in\n input ()\n |> dep_graph_of_road_graph\n |> _2sat\n |> solution\n |> Printf.printf \"%s\\n\"\n"}, {"source_code": "let () =\n Scanf.scanf \"%d %d\" (fun n m ->\n let g = Array.make n [] in\n for i = 1 to m do\n Scanf.scanf \" %d %d %d\" (fun a b c ->\n let a = a - 1 and b = b - 1 in\n g.(a) <- (b, c) :: g.(a); g.(b) <- (a, c) :: g.(b))\n done;\n let cc = Array.make n 2 in\n let rec dfs c v = match cc.(v) with\n | 2 -> cc.(v) <- c; List.iter (fun (v, c') -> dfs (1 land (lnot (c lxor c'))) v) g.(v)\n | c' when c = c' -> ()\n | _ -> raise Not_found\n in\n try\n Array.iteri (fun v _ -> try dfs 1 v with Not_found -> dfs 0 v) g;\n let l, _ = Array.fold_left (fun (acc, i) c -> (if c = 1 then string_of_int i :: acc else acc), i + 1) ([], 1) cc in\n Printf.printf \"%d\\n%s\\n\" (List.length l) (String.concat \" \" l)\n with Not_found -> Printf.printf \"Impossible\\n\")"}], "negative_code": [{"source_code": "let (@@) f x = f x\nlet (|>) x f = f x\nlet (%) f g x = f @@ g x\n\nlet () =\n Scanf.scanf \"%d %d\" @@ fun n m ->\n let g = Array.make (n + n * n) [] in\n let add_edges = List.iter @@ fun (a, b) -> g.(a) <- b :: g.(a); g.(b) <- a :: g.(b) in\n let idx a b = n + n * (min a b) + (max a b) in\n for i = 1 to m do\n ignore i;\n Scanf.scanf \" %d %d %d\" @@ fun a b even ->\n let a = a - 1 and b = b - 1 in\n add_edges @@ if even = 1 then [(a, idx a b); (idx a b, b)] else [(a, b)]\n done;\n let colors = Array.make (n + n * n) None in\n let rec dfs c v = match colors.(v) with\n | Some c' when c <> c' -> raise Not_found\n | Some _ -> ()\n | None -> colors.(v) <- Some c; List.iter (dfs @@ not c) g.(v)\n in\n let get o = match o with Some c -> c | None -> assert false in\n try\n ArrayLabels.iteri colors ~f:(fun v c -> if c = None then dfs false v);\n List.(\n Array.sub colors 0 n |> Array.to_list\n |> mapi (fun i b -> i, b) |> filter (get % snd) |> map (string_of_int % fst) |> fun l ->\n Printf.printf \"%d\\n%s\\n\" (length l) @@ String.concat \" \" l)\n with Not_found -> Printf.printf \"Impossible\\n\""}], "src_uid": "1598bd5d75abd3645d49604e0dc10765"} {"nl": {"description": "Limak is a little polar bear. He likes nice strings \u2014 strings of length n, consisting of lowercase English letters only.The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that . Find any s' satisfying the given conditions, or print \"-1\" if it's impossible to do so.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009k\u2009\u2264\u2009106). The second line contains a string s of length n, consisting of lowercase English letters.", "output_spec": "If there is no string satisfying the given conditions then print \"-1\" (without the quotes). Otherwise, print any nice string s' that .", "sample_inputs": ["4 26\nbear", "2 7\naf", "3 1000\nhey"], "sample_outputs": ["roar", "db", "-1"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let k = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let k = ref k in\n let c2i c = Char.code c - Char.code 'a' in\n let i2c x = Char.chr (x + Char.code 'a') in\n for i = 0 to n - 1 do\n let x = c2i s.[i] in\n\tif !k <= x then (\n\t s.[i] <- i2c (x - !k);\n\t k := 0;\n\t) else if !k <= 25 - x then (\n\t s.[i] <- i2c (x + !k);\n\t k := 0;\n\t) else if x <= 25 - x then (\n\t s.[i] <- 'z';\n\t k := !k - (25 - x);\n\t) else (\n\t s.[i] <- 'a';\n\t k := !k - x;\n\t)\n done;\n if !k > 0\n then Printf.printf \"-1\\n\"\n else Printf.printf \"%s\\n\" s\n"}], "negative_code": [], "src_uid": "b5d0870ee99e06e8b99c74aeb8e81e01"} {"nl": {"description": "Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.Help Igor find the maximum number he can write on the fence.", "input_spec": "The first line contains a positive integer v (0\u2009\u2264\u2009v\u2009\u2264\u2009106). The second line contains nine positive integers a1,\u2009a2,\u2009...,\u2009a9 (1\u2009\u2264\u2009ai\u2009\u2264\u2009105).", "output_spec": "Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1.", "sample_inputs": ["5\n5 4 3 2 1 2 3 4 5", "2\n9 11 1 12 5 8 9 10 6", "0\n1 1 1 1 1 1 1 1 1"], "sample_outputs": ["55555", "33", "-1"], "notes": null}, "positive_code": [{"source_code": "let n = read_int () ;;\nlet vals = Str.split (Str.regexp \" \") (read_line () ) ;;\nlet valsa = Array.of_list (List.map int_of_string vals) ;;\n\nlet min_vals = Array.fold_left min valsa.(0) valsa ;;\nlet rec find a x nd =\n if nd < 0 then (-1)\n else if a.(nd) == x then nd\n else find a x (nd-1) ;;\nlet min_index = find valsa min_vals 8 ;;\nlet b = Bytes.make (n/valsa.(min_index)) (Char.chr (48+ min_index+1)) ;;\nlet left = n - ((n/valsa.(min_index)) * valsa.(min_index)) ;;\nlet rec findg a g nd = \n if nd < 0 then (-1)\n else if a.(nd) <= g then nd\n else findg a g (nd-1) ;;\nlet rec subs bs p pr = \n let ni = findg valsa (pr + valsa.(min_index)) 8 in\n (*let _ = print_int(ni) in \n let _3 = print_int(valsa.(7)) in\n let _2 = print_int(pr + valsa.(min_index)) in\n let _4 = print_newline () in *)\n if (ni == (-1)) || (pr <= 0) || (p >= (Bytes.length bs)) then bs\n else begin\n Bytes.set bs p (Char.chr (48+ni+1));\n subs bs (p+1) (pr-valsa.(ni) + valsa.(min_index))\n end;;\nif (Bytes.length b > 0) then print_string(Bytes.to_string (subs b 0 left))\nelse print_int((-1));;\n\n"}], "negative_code": [{"source_code": "let n = read_int () ;;\nlet vals = Str.split (Str.regexp \" \") (read_line () ) ;;\nlet valsa = Array.of_list (List.map int_of_string vals) ;;\n\nlet min_vals = Array.fold_left min valsa.(0) valsa ;;\nlet rec find a x nd =\n if nd < 0 then (-1)\n else if a.(nd) == x then nd\n else find a x (nd-1) ;;\nlet min_index = find valsa min_vals 8 ;;\nlet b = Bytes.make (n/valsa.(min_index)) (Char.chr (48+ min_index+1)) ;;\nlet left = n - ((n/valsa.(min_index)) * valsa.(min_index)) ;;\nlet rec findg a g nd = \n if nd < 0 then (-1)\n else if a.(nd) >= g then nd\n else find a g (nd-1) ;;\nlet rec subs bs p pr = \n let ni = findg valsa pr 8 in\n if (ni == (-1)) || (pr == 0) || (p >= (Bytes.length bs)) then bs\n else begin\n Bytes.set bs p (Char.chr (48+ni+1));\n subs bs (p+1) (pr-valsa.(ni))\n end;;\nif (Bytes.length b > 0) then print_string(Bytes.to_string b)\nelse print_int((-1));;\n\n"}], "src_uid": "ace9fbabc2eda81b4e4adf4f2d5ad402"} {"nl": {"description": "You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.String $$$s = s_1 s_2 \\dots s_n$$$ is lexicographically smaller than string $$$t = t_1 t_2 \\dots t_m$$$ if $$$n < m$$$ and $$$s_1 = t_1, s_2 = t_2, \\dots, s_n = t_n$$$ or there exists a number $$$p$$$ such that $$$p \\le min(n, m)$$$ and $$$s_1 = t_1, s_2 = t_2, \\dots, s_{p-1} = t_{p-1}$$$ and $$$s_p < t_p$$$.For example, \"aaa\" is smaller than \"aaaa\", \"abb\" is smaller than \"abc\", \"pqr\" is smaller than \"z\".", "input_spec": "The first line of the input contains one integer $$$n$$$ ($$$2 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the length of $$$s$$$. The second line of the input contains exactly $$$n$$$ lowercase Latin letters \u2014 the string $$$s$$$.", "output_spec": "Print one string \u2014 the smallest possible lexicographically string that can be obtained by removing at most one character from the string $$$s$$$.", "sample_inputs": ["3\naaa", "5\nabcda"], "sample_outputs": ["aa", "abca"], "notes": "NoteIn the first example you can remove any character of $$$s$$$ to obtain the string \"aa\".In the second example \"abca\" < \"abcd\" < \"abcda\" < \"abda\" < \"acda\" < \"bcda\"."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = get_i64 0 in\n let s = scanf \" %s\" @@ id in\n repi 0 (i32 n -$ 2) (fun i ->\n if s.[i] > s.[i+$1] then (\n repi 0 (i-$1) (fun j -> print_char s.[j]);\n (* print_endline \"===\"; *)\n repi (i+$1) (i32 n-$1) (fun j -> print_char s.[j]);\n exit 0\n )\n );\n repi 0 (i32 n -$ 2) (fun i ->\n print_char s.[i]\n )\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet () =\n let n = get_i64 0 in\n let s = scanf \" %s\" @@ id in\n repi 0 (i32 n -$ 2) (fun i ->\n printf \"%c %c\\n\" s.[i] s.[i+$1];\n if s.[i] > s.[i+$1] then (\n repi 0 (i-$1) (fun j -> print_char s.[j]);\n (* print_endline \"===\"; *)\n repi (i+$1) (i32 n-$1) (fun j -> print_char s.[j]);\n exit 0\n )\n );\n repi 0 (i32 n -$ 2) (fun i ->\n print_char s.[i]\n )\n\n\n\n\n\n\n\n\n"}], "src_uid": "c01fc2cb6efc7eef290be12015f8d920"} {"nl": {"description": "Dima got into number sequences. Now he's got sequence a1,\u2009a2,\u2009...,\u2009an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence: f(0)\u2009=\u20090; f(2\u00b7x)\u2009=\u2009f(x); f(2\u00b7x\u2009+\u20091)\u2009=\u2009f(x)\u2009+\u20091. Dima wonders, how many pairs of indexes (i,\u2009j) (1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n) are there, such that f(ai)\u2009=\u2009f(aj). Help him, count the number of such pairs. ", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n positive integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109). The numbers in the lines are separated by single spaces.", "output_spec": "In a single line print the answer to the problem. Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.", "sample_inputs": ["3\n1 2 4", "3\n5 3 1"], "sample_outputs": ["3", "1"], "notes": "NoteIn the first sample any pair (i,\u2009j) will do, so the answer is 3.In the second sample only pair (1,\u20092) will do."}, "positive_code": [{"source_code": "(* Codeforces 272B - Dima seq *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec countbits n = match n with\n\t| 0 -> 0\n\t| 1 -> 1\n\t| _ ->\n\t\t\tlet (n2, o ) = (n / 2, n mod 2) in\n\t\t\to + countbits n2;;\n\nlet rec setcounts l a =\n\tmatch l with\n\t| [] -> ()\n\t| h :: t ->\n\t\t\tbegin\n\t\t\t\ta.(h) <- a.(h) + 1;\n\t\t\t\tsetcounts t a\n\t\t\tend;;\n\nlet rec npairs n = \n\tlet nn1 = (Int64.mul (Int64.of_int n) (Int64.of_int (n - 1))) in\n\tInt64.div nn1 (Int64.of_int 2);;\n\nlet rec sumArr64 a n = match n with\n| -1 -> Int64.zero\n| _ -> (Int64.add a.(n) (sumArr64 a (n - 1)));; \n\nlet main () =\n\tlet na = gr() in\n\tlet a = readlist na [] in\n\tlet bta = List.map countbits a in\n\tlet cnts = Array.make 33 0 in \n\tbegin\n\t\t(* printlisti a; *)\n\t\tsetcounts bta cnts;\t\t\n\t\tlet aa = Array.map npairs cnts in\n\t\tlet sum_pairs = sumArr64 aa 32 in\t\t\n\t\tprint_string (Int64.to_string sum_pairs)\n\tend;;\n\nmain();;\n"}], "negative_code": [], "src_uid": "c547e32f114546638973e0f0dd16d1a4"} {"nl": {"description": "A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n\u2009=\u20095, then after the third throw the child number 2 has the ball again. Overall, n\u2009-\u20091 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100) which indicates the number of kids in the circle.", "output_spec": "In the single line print n\u2009-\u20091 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.", "sample_inputs": ["10", "3"], "sample_outputs": ["2 4 7 1 6 2 9 7 6", "2 1"], "notes": null}, "positive_code": [{"source_code": "let n = Scanf.scanf \"%d\" abs;;\n\nlet m = ref 0;;\n\nfor i = 1 to n-1 do (\n\tm := ((!m + i) mod n);\n\tprint_int (!m + 1);\n\tif i <> n-1 then print_string \" \";\n) done\n"}, {"source_code": "let rec pass k = function\n | 0 -> 1\n | x -> (x + pass k (x - 1)) mod k;;\nlet k = read_int ();;\nfor i = 1 to k - 1 do\n print_int ((fun x -> if x == 0 then k else x) (pass k i));\n print_string \" \"\ndone;;\nprint_newline ();;\n"}], "negative_code": [], "src_uid": "7170c40405cf7a5e0f2bd15e4c7d189d"} {"nl": {"description": "Consider the infinite sequence $$$s$$$ of positive integers, created by repeating the following steps: Find the lexicographically smallest triple of positive integers $$$(a, b, c)$$$ such that $$$a \\oplus b \\oplus c = 0$$$, where $$$\\oplus$$$ denotes the bitwise XOR operation. $$$a$$$, $$$b$$$, $$$c$$$ are not in $$$s$$$. Here triple of integers $$$(a_1, b_1, c_1)$$$ is considered to be lexicographically smaller than triple $$$(a_2, b_2, c_2)$$$ if sequence $$$[a_1, b_1, c_1]$$$ is lexicographically smaller than sequence $$$[a_2, b_2, c_2]$$$. Append $$$a$$$, $$$b$$$, $$$c$$$ to $$$s$$$ in this order. Go back to the first step. You have integer $$$n$$$. Find the $$$n$$$-th element of $$$s$$$.You have to answer $$$t$$$ independent test cases.A sequence $$$a$$$ is lexicographically smaller than a sequence $$$b$$$ if in the first position where $$$a$$$ and $$$b$$$ differ, the sequence $$$a$$$ has a smaller element than the corresponding element in $$$b$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^5$$$)\u00a0\u2014 the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1\\le n \\le 10^{16}$$$)\u00a0\u2014 the position of the element you want to know.", "output_spec": "In each of the $$$t$$$ lines, output the answer to the corresponding test case.", "sample_inputs": ["9\n1\n2\n3\n4\n5\n6\n7\n8\n9"], "sample_outputs": ["1\n2\n3\n4\n8\n12\n5\n10\n15"], "notes": "NoteThe first elements of $$$s$$$ are $$$1, 2, 3, 4, 8, 12, 5, 10, 15, \\dots $$$"}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_long _ = bscanf Scanning.stdin \" %Ld \" (fun x -> x) \n\nlet rec dig4 n = if n < 4L then 1 else 1 + (dig4 (n//4L));; (* # base 4 digits *)\nlet rec power4 x = if x=0 then 1L else 4L ** (power4 (x-1))\n\nlet base10 b4 d =\n let rec loop ac i = if i<0 then ac else (\n loop ((4L ** ac) ++ long (b4.(i))) (i-1)\n ) in\n loop 0L (d-1)\n \nlet a = [| [|0;0;0|]; [|1;2;3|]; [|2;3;1|]; [|3;1;2|] |]\nlet h = [|1;2;3|]\n\nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let n = read_long() in\n let d = dig4 n in\n let n' = n -- (power4 (d-1)) in\n let b4 = Array.make d 0 in\n b4.(d-1) <- h.(short (n' %% 3L));\n for i=0 to d-2 do\n b4.(i) <- a.( short (((n'//3L) // (power4 i)) %% 4L)).( short (n' %% 3L) )\n done;\n printf \"%Ld\\n\" (base10 b4 d)\n done\n"}], "negative_code": [], "src_uid": "37c3725f583ca33387dfd05fe75898a9"} {"nl": {"description": "They say \"years are like dominoes, tumbling one after the other\". But would a year fit into a grid? I don't think so.Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?", "input_spec": "The first line of the input contains two integers h and w (1\u2009\u2264\u2009h,\u2009w\u2009\u2264\u2009500)\u00a0\u2013 the number of rows and the number of columns, respectively. The next h lines describe a grid. Each line contains a string of the length w. Each character is either '.' or '#'\u00a0\u2014 denoting an empty or forbidden cell, respectively. The next line contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of queries. Each of the next q lines contains four integers r1i, c1i, r2i, c2i (1\u2009\u2264\u2009r1i\u2009\u2264\u2009r2i\u2009\u2264\u2009h,\u20091\u2009\u2264\u2009c1i\u2009\u2264\u2009c2i\u2009\u2264\u2009w)\u00a0\u2014 the i-th query. Numbers r1i and c1i denote the row and the column (respectively) of the upper left cell of the rectangle. Numbers r2i and c2i denote the row and the column (respectively) of the bottom right cell of the rectangle.", "output_spec": "Print q integers, i-th should be equal to the number of ways to put a single domino inside the i-th rectangle.", "sample_inputs": ["5 8\n....#..#\n.#......\n##.#....\n##..#.##\n........\n4\n1 1 2 3\n4 1 4 1\n1 2 4 5\n2 5 5 8", "7 39\n.......................................\n.###..###..#..###.....###..###..#..###.\n...#..#.#..#..#.........#..#.#..#..#...\n.###..#.#..#..###.....###..#.#..#..###.\n.#....#.#..#....#.....#....#.#..#..#.#.\n.###..###..#..###.....###..###..#..###.\n.......................................\n6\n1 1 3 20\n2 10 6 30\n2 10 7 30\n2 2 7 7\n1 7 7 7\n1 8 7 8"], "sample_outputs": ["4\n0\n10\n15", "53\n89\n120\n23\n0\n2"], "notes": "NoteA red frame below corresponds to the first query of the first sample. A domino can be placed in 4 possible ways. "}, "positive_code": [{"source_code": "open Int64;;\nlet [n; m]= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ()));;\nlet mx= Array.make (n + 1) \"\" and x= ref 0L and y = ref 0L;;\nlet ma= Array.make_matrix (n * 2) (m * 2) 0L and mb= Array.make_matrix (n * 2) (m * 2) 0L;;\nlet pma= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0L and pmb= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0L;;\nfor i= 0 to n-1 do Array.set mx i (read_line ()) done;;\nfor i= 0 to n-1 do for j= 0 to m - 1 do if String.get mx.(i) j = '.' then begin\n\tif j <> m-1 then if String.get mx.(i) (j + 1) = '.' then Array.set ma.(i) j 1L;\n\tif i <> n-1 then if String.get mx.(i + 1) j = '.' then Array.set mb.(i) j 1L;\nend done done;;\nfor i= 1 to n do for j= 1 to m do \n Array.set pma.(i) j\t(sub (add (add ma.(i - 1).(j - 1) pma.(i).(j - 1)) pma.(i - 1).(j)) pma.(i-1).(j-1));\t\n\tArray.set pmb.(i) j (sub (add (add mb.(i - 1).(j - 1) pmb.(i).(j - 1)) pmb.(i - 1).(j)) pmb.(i-1).(j-1));\t\ndone done;;\nlet q= read_int ();;\nfor i= 1 to q do let [y1; x1; y2; x2]= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in begin\n\tx := sub (add pma.(y2).(x2 - 1) pma.(y1 - 1).(x1 - 1)) (add pma.(y2).(x1 - 1) pma.(y1 - 1).(x2 - 1));\n\tif !x < 0L then x := 0L;\n\ty := sub (add pmb.(y2 - 1).(x2) pmb.(y1 - 1).(x1 - 1)) (add pmb.(y2 - 1).(x1 - 1) pmb.(y1 - 1).(x2));\n\tif !y < 0L then y := 0L;\n\tprint_endline (to_string (add !x !y))\nend done;;\n"}, {"source_code": "(*#load \"str.cma\";;*)\nopen Printf;;\nlet [n; m]= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ()));;\nlet mx= Array.make (n + 1) \"\";;\nlet ma= Array.make_matrix (n * 2) (m * 2) 0 and mb= Array.make_matrix (n * 2) (m * 2) 0;;\nlet pma= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0 and pmb= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0;;\nfor i= 0 to n - 1 do Array.set mx i (read_line ()) done;;\nfor i= 0 to n - 1 do for j= 0 to m - 1 do if String.get mx.(i) j = '.' then\nbegin\n\tif j <> m - 1 then if String.get mx.(i) (j + 1) = '.' then Array.set ma.(i) j 1;\n\tif i <> n - 1 then if String.get mx.(i + 1) j = '.' then Array.set mb.(i) j 1;\nend done done;;\nfor i= 1 to n do for j= 1 to m do \n\tArray.set pma.(i) j (ma.(i - 1).(j - 1) + pma.(i).(j - 1) + pma.(i - 1).(j) - pma.(i-1).(j-1));\t\n\tArray.set pmb.(i) j (mb.(i - 1).(j - 1) + pmb.(i).(j - 1) + pmb.(i - 1).(j) - pmb.(i-1).(j-1));\t\ndone done;;\nlet q= read_int ();;\nfor i= 1 to q do\n let [y1; x1; y2; x2]= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\n begin\n\t\tprint_int \n\t\t\t\t((max 0 (pma.(y2).(x2 - 1) - pma.(y2).(x1 - 1) - pma.(y1 - 1).(x2 - 1) + pma.(y1 - 1).(x1 - 1))) + \n\t\t\t\t(max 0 (pmb.(y2 - 1).(x2) - pmb.(y2 - 1).(x1 - 1) - pmb.(y1 - 1).(x2) + pmb.(y1 - 1).(x1 - 1))));\n\t\tprint_endline \"\"\n\tend\ndone;;\n"}, {"source_code": "open Int64 open Str;;\nlet aset = Array.set;;\nlet [n; m]= List.map (int_of_string) (split (regexp \" \") (read_line ()));;\nlet mx= Array.make (n + 1) \"\" and x= ref 0L and y = ref 0L;;\nlet ma= Array.make_matrix (n * 2) (m * 2) 0L and mb= Array.make_matrix (n * 2) (m * 2) 0L;;\nlet pma= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0L and pmb= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0L;;\nfor i= 0 to n-1 do Array.set mx i (read_line ()) done;;\nfor i= 0 to n-1 do for j= 0 to m - 1 do if String.get mx.(i) j = '.' then begin\n if j <> m-1 then if String.get mx.(i) (j+1) = '.' then aset ma.(i) j 1L;\n if i <> n-1 then if String.get mx.(i+1) j = '.' then aset mb.(i) j 1L;\nend done done;;\nfor i= 1 to n do for j= 1 to m do \n aset pma.(i) j (sub (add (add pma.(i-1).(j) pma.(i).(j-1)) ma.(i-1).(j-1)) pma.(i-1).(j-1));\t\n aset pmb.(i) j (sub (add (add pmb.(i-1).(j) pmb.(i).(j-1)) mb.(i-1).(j-1)) pmb.(i-1).(j-1));\t\ndone done;;\nlet q= read_int ();;\nfor i= 1 to q do let [y1; x1; y2; x2]= List.map (int_of_string) (split (regexp \" \") (read_line ())) in begin\n x := sub (add pma.(y2).(x2-1) pma.(y1-1).(x1-1)) (add pma.(y2).(x1-1) pma.(y1-1).(x2-1));\n if !x < 0L then x:= 0L;\n y := sub (add pmb.(y2-1).(x2) pmb.(y1-1).(x1-1)) (add pmb.(y2-1).(x1-1) pmb.(y1-1).(x2));\n if !y < 0L then y:= 0L;\n print_endline (to_string (add !x !y))\nend done;;\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let h = read_int () in\n let w = read_int () in\n let grid = Array.init h (fun _ -> read_string()) in\n let q = read_int () in\n let query = Array.init q (fun _ ->\n let a = read_pair() in\n let b = read_pair() in\n (a,b)\n ) in\n\n let geth i j =\n if i<0 || j<0 then '#' else grid.(i).[j]\n in\n\n let getv i j =\n if i<0 || j<0 then '#' else grid.(j).[i]\n in\n\n let getcount count i j = if i<0 || j<0 then 0 else count.(i).(j) in\n \n let make_count h w get =\n let c = Array.make_matrix h w 0 in\n for i=0 to h-1 do\n for j=0 to w-1 do\n\tlet here = if (get i j) = '.' && (get i (j-1)) = '.' then 1 else 0 in\n\tc.(i).(j) <- here + (getcount c (i-1) j) + (getcount c i (j-2)) - (getcount c (i-1) (j-2));\n done\n done;\n c\n in\n\n let counth = make_count h w geth in\n let countv = make_count w h getv in\n\n for k = 0 to q-1 do\n let ((r1,c1),(r2,c2)) = query.(k) in\n let ((r1,c1),(r2,c2)) = ((r1-2,c1-2),(r2-1,c2-1)) in\n\n let heven =\n let c2 = c2 - (c2 land 1) in\n let c1 = c1 + (c1 land 1) in\n (getcount counth r2 c2)\n - (getcount counth r1 c2) - (getcount counth r2 c1)\n + (getcount counth r1 c1)\n in\n\n let hodd =\n let c2 = c2 - (1 - (c2 land 1)) in\n let c1 = c1 + (1 - (c1 land 1)) in\n (getcount counth r2 c2)\n - (getcount counth r1 c2) - (getcount counth r2 c1)\n + (getcount counth r1 c1)\n in\n\n let veven =\n let r2 = r2 - (r2 land 1) in\n let r1 = r1 + (r1 land 1) in\n (getcount countv c2 r2)\n - (getcount countv c1 r2) - (getcount countv c2 r1)\n + (getcount countv c1 r1)\n in\n\n let vodd =\n let r2 = r2 - (1 - (r2 land 1)) in\n let r1 = r1 + (1 - (r1 land 1)) in\n (getcount countv c2 r2)\n - (getcount countv c1 r2) - (getcount countv c2 r1)\n + (getcount countv c1 r1)\n in\n\n printf \"%d\\n\" (heven + hodd + veven + vodd)\n done\n"}], "negative_code": [{"source_code": "open Printf;;\nlet [n; m]= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ()));;\nlet mx= Array.make (n + 1) \"\";;\nlet ma= Array.make_matrix (n * 2) (m * 2) 0 and mb= Array.make_matrix (n * 2) (m * 2) 0;;\nlet pma= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0 and pmb= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0;;\nfor i= 0 to n - 1 do Array.set mx i (read_line ()) done;;\nfor i= 0 to n - 1 do for j= 0 to m - 1 do if String.get mx.(i) j = '.' then\nbegin\n\tif j <> m - 1 then if String.get mx.(i) (j + 1) = '.' then Array.set ma.(i) j 1;\n\tif i <> n - 1 then if String.get mx.(i + 1) j = '.' then Array.set mb.(i) j 1;\nend done done;;\nfor i= 1 to n do for j= 1 to m do \n\tArray.set pma.(i) j (ma.(i - 1).(j - 1) + pma.(i).(j - 1) + pma.(i - 1).(j) - pma.(i-1).(j-1));\t\n\tArray.set pmb.(i) j (mb.(i - 1).(j - 1) + pmb.(i).(j - 1) + pmb.(i - 1).(j) - pmb.(i-1).(j-1));\t\ndone done;;\nlet q= read_int ();;\nfor i= 1 to q do\n let [y1; x1; y2; x2]= List.map (int_of_string) (Str.split (Str.regexp \" \") (read_line ())) in\n begin\n\t\tif y2 <> 1 && x2 <> 1 then \n\t\t\tprint_int \n\t\t\t\t\t((max 0 (pma.(y2).(x2 - 1) - pma.(y2).(x1 - 1) - pma.(y1 - 1).(x2 - 1) + pma.(y1 - 1).(x1 - 1))) + \n\t\t\t\t\t(max 0 (pmb.(y2 - 1).(x2) - pmb.(y2 - 1).(x1 - 1) - pmb.(y1 - 1).(x2) + pmb.(y1 - 1).(x1 - 1))))\n\t\telse if y2 = 1 && x2 <> 1 then \n\t\t\tprint_int \n\t\t\t\t\t(max 0 (pma.(y2 - 1).(x2) - pma.(y2 - 1).(x1 - 1) - pma.(y1 - 1).(x2) + pma.(y1 - 1).(x1 - 1)))\n\t\telse if x2 = 1 && y2 <> 1 then\n\t\t\tprint_int \n\t\t\t\t\t(max 0 (pmb.(y2).(x2 - 1) - pmb.(y2).(x1 - 1) - pmb.(y1 - 1).(x2 - 1) + pmb.(y1 - 1).(x1 - 1)))\n\t\telse print_int 0;\n\t\tprint_endline \"\"\n\tend\ndone;;\n"}, {"source_code": "open Int64 open Str;;\nlet aset = Array.set;;\nlet [n; m]= List.map (int_of_string) (split (regexp \" \") (read_line ()));;\nlet mx= Array.make (n + 1) \"\" and x= ref 0L and y = ref 0L;;\nlet ma= Array.make_matrix (n * 2) (m * 2) 0L and mb= Array.make_matrix (n * 2) (m * 2) 0L;;\nlet pma= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0L and pmb= Array.make_matrix (n * 2 + 1) (m * 2 + 1) 0L;;\nfor i= 0 to n-1 do Array.set mx i (read_line ()) done;;\nfor i= 0 to n-1 do for j= 0 to m - 1 do if String.get mx.(i) j = '.' then begin\n if j <> m-1 then if String.get mx.(i) (j+1) = '.' then aset ma.(i) j 1L;\n if i <> n-1 then if String.get mx.(i+1) j = '.' then aset mb.(i) j 1L;\nend done done;;\nfor i= 1 to n do for j= 1 to m do \n aset pma.(i) j (sub (add (add ma.(i-1).(j) pma.(i).(j-1)) pma.(i-1).(j-1)) pma.(i-1).(j-1));\t\n aset pmb.(i) j (sub (add (add mb.(i-1).(j-1) pmb.(i).(j-1)) pmb.(i-1).(j)) pmb.(i-1).(j-1));\t\ndone done;;\nlet q= read_int ();;\nfor i= 1 to q do let [y1; x1; y2; x2]= List.map (int_of_string) (split (regexp \" \") (read_line ())) in begin\n x := sub (add pma.(y2).(x2-1) pma.(y1-1).(x1-1)) (add pma.(y2).(x1-1) pma.(y1-1).(x2-1));\n if !x < 0L then x:= 0L;\n y := sub (add pmb.(y2-1).(x2) pmb.(y1-1).(x1-1)) (add pmb.(y2-1).(x1-1) pmb.(y1-1).(x2));\n if !y < 0L then y:= 0L;\n print_endline (to_string (add !x !y))\nend done;;\n"}], "src_uid": "d9fdf0827940883069bead0d00b3da53"} {"nl": {"description": "The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. \"Rozdil\").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print \"Still Rozdil\", if he stays in Rozdil.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.", "output_spec": "Print the answer on a single line \u2014 the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print \"Still Rozdil\" (without the quotes).", "sample_inputs": ["2\n7 4", "7\n7 4 47 100 4 9 12"], "sample_outputs": ["2", "Still Rozdil"], "notes": "NoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one \u2014 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is \"Still Rozdil\"."}, "positive_code": [{"source_code": "let _ =\n let n = Scanf.scanf \" %d\" (fun x -> x) in\n let a = Array.make n 0 in\n for i = 0 to n - 1 do\n Scanf.scanf \" %d\" (fun x -> a.(i) <- x)\n done;\n let k = ref 0 in\n let m = ref a.(0) in\n for i = 1 to n - 1 do\n if a.(i) < !m then (m := a.(i); k := i)\n else if a.(i) = !m then k := -1\n done;\n if !k = -1\n then print_string \"Still Rozdil\"\n else print_int (!k + 1)\n;;\n"}, {"source_code": "#load \"str.cma\";;\n\nlet rec get_input () =\n let n = int_of_string (read_line ()) and\n\t ls = Str.split (Str.regexp \"[ \\t]+\") (read_line ()) in\n (n, Array.mapi (fun idx x -> (idx, x))\n\t(Array.of_list (List.map int_of_string ls)));;\n\nlet print_int' n =\n begin\n\tprint_int (n + 1);\n\tprint_string \"\\n\";\n end;;\n\nlet solve n sls =\n if n == 1 then print_int' (fst sls.(0))\n else\n\tbegin\n\t Array.fast_sort (fun (idxx, x) (idxy, y) -> x - y) sls;\n\t (* Array.iter (fun (x, y) -> print_int y) sls;*)\n\t if snd (sls.(0)) == snd (sls.(1)) then\n\t\tprint_string \"Still Rozdil\\n\"\n\t else\n\t\tprint_int' (fst (sls.(0)))\n\tend;;\n\nlet (n, ls) = get_input () in\nsolve n ls;;\n\n \n"}], "negative_code": [{"source_code": "#load \"str.cma\";;\n\nlet rec get_input () =\n let n = read_line () and\n\t ls = Str.split (Str.regexp \"[ \\t]\") (read_line ()) in\n (n, List.map int_of_string ls);;\n\nlet solve n ls =\n let rec iter l cur flag =\n\tmatch l with \n\t\t[] -> if flag then -1 else cur\n\t | (x::xs) ->\n\t\tif x == cur then \n\t\t iter xs x true\n\t\telse if x < cur then\n\t\t iter xs x false\n\t\telse\n\t\t iter xs cur flag\n in iter ls 1000000001 false;;\n\nlet (n, ls) = get_input () in\nbegin\n (*\n List.iter (fun x -> print_int x; print_string\" \") ls;\n print_string \"\\n\";\n *)\n if solve n ls == -1 then\n\tprint_string \"Still Rozdil\"\n else print_int (solve n ls); print_string \"\\n\";\nend\n"}], "src_uid": "ce68f1171d9972a1b40b0450a05aa9cd"} {"nl": {"description": "You are given array a with n elements and the number m. Consider some subsequence of a and the value of least common multiple (LCM) of its elements. Denote LCM as l. Find any longest subsequence of a with the value l\u2009\u2264\u2009m.A subsequence of a is an array we can get by erasing some elements of a. It is allowed to erase zero or all elements.The LCM of an empty array equals 1.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009106) \u2014 the size of the array a and the parameter from the problem statement. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 the elements of a.", "output_spec": "In the first line print two integers l and kmax (1\u2009\u2264\u2009l\u2009\u2264\u2009m,\u20090\u2009\u2264\u2009kmax\u2009\u2264\u2009n) \u2014 the value of LCM and the number of elements in optimal subsequence. In the second line print kmax integers \u2014 the positions of the elements from the optimal subsequence in the ascending order. Note that you can find and print any subsequence with the maximum length.", "sample_inputs": ["7 8\n6 2 9 2 7 2 3", "6 4\n2 2 2 3 3 3"], "sample_outputs": ["6 5\n1 2 4 6 7", "2 3\n1 2 3"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let b = Array.make (m + 1) 0 in\n let c = Array.make (m + 1) 0 in\n for i = 0 to n - 1 do\n if a.(i) <= m\n then b.(a.(i)) <- b.(a.(i)) + 1\n done;\n for i = 1 to m do\n if b.(i) > 0 then (\n\tlet j = ref i in\n\t while !j <= m do\n\t c.(!j) <- c.(!j) + b.(i);\n\t j := !j + i;\n\t done;\n )\n done;\n let mc = ref 1 in\n let mv = ref c.(1) in\n for i = 2 to m do\n\tif c.(i) > !mv then (\n\t mv := c.(i);\n\t mc := i;\n\t)\n done;\n Printf.printf \"%d %d\\n\" !mc !mv;\n for i = 0 to n - 1 do\n\tif !mc mod a.(i) = 0\n\tthen Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n in\n let b = Array.make (m + 1) 0 in\n let c = Array.make (m + 1) 0 in\n for i = 0 to n - 1 do\n if a.(i) <= m\n then b.(a.(i)) <- b.(a.(i)) + 1\n done;\n for i = 1 to m do\n if b.(i) > 0 then (\n\tlet j = ref i in\n\t while !j <= m do\n\t c.(!j) <- c.(!j) + b.(i);\n\t j := !j + i;\n\t done;\n )\n done;\n let mc = ref 1 in\n let mv = ref 0 in\n for i = 2 to m do\n\tif c.(i) > !mv then (\n\t mv := c.(i);\n\t mc := i;\n\t)\n done;\n Printf.printf \"%d %d\\n\" !mc !mv;\n for i = 0 to n - 1 do\n\tif !mc mod a.(i) = 0\n\tthen Printf.printf \"%d \" (i + 1)\n done;\n Printf.printf \"\\n\"\n"}], "src_uid": "26e1afd54da6506a349e652a40997109"} {"nl": {"description": "You are given four integers $$$a$$$, $$$b$$$, $$$x$$$ and $$$y$$$. Initially, $$$a \\ge x$$$ and $$$b \\ge y$$$. You can do the following operation no more than $$$n$$$ times: Choose either $$$a$$$ or $$$b$$$ and decrease it by one. However, as a result of this operation, value of $$$a$$$ cannot become less than $$$x$$$, and value of $$$b$$$ cannot become less than $$$y$$$. Your task is to find the minimum possible product of $$$a$$$ and $$$b$$$ ($$$a \\cdot b$$$) you can achieve by applying the given operation no more than $$$n$$$ times.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 2 \\cdot 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains five integers $$$a$$$, $$$b$$$, $$$x$$$, $$$y$$$ and $$$n$$$ ($$$1 \\le a, b, x, y, n \\le 10^9$$$). Additional constraint on the input: $$$a \\ge x$$$ and $$$b \\ge y$$$ always holds.", "output_spec": "For each test case, print one integer: the minimum possible product of $$$a$$$ and $$$b$$$ ($$$a \\cdot b$$$) you can achieve by applying the given operation no more than $$$n$$$ times.", "sample_inputs": ["7\n10 10 8 5 3\n12 8 8 7 2\n12343 43 4543 39 123212\n1000000000 1000000000 1 1 1\n1000000000 1000000000 1 1 1000000000\n10 11 2 1 5\n10 11 9 1 10"], "sample_outputs": ["70\n77\n177177\n999999999000000000\n999999999\n55\n10"], "notes": "NoteIn the first test case of the example, you need to decrease $$$b$$$ three times and obtain $$$10 \\cdot 7 = 70$$$.In the second test case of the example, you need to decrease $$$a$$$ one time, $$$b$$$ one time and obtain $$$11 \\cdot 7 = 77$$$.In the sixth test case of the example, you need to decrease $$$a$$$ five times and obtain $$$5 \\cdot 11 = 55$$$.In the seventh test case of the example, you need to decrease $$$b$$$ ten times and obtain $$$10 \\cdot 1 = 10$$$."}, "positive_code": [{"source_code": "let () =\n let t = () |> read_line |> int_of_string in\n for i = 1 to t do\n let [a; b; x; y; n] =\n ()\n |> read_line\n |> Str.split (Str.regexp \" \")\n |> List.map (fun s -> s |> String.trim |> Int64.of_string)\n in\n let check a b x y =\n let a' = min (Int64.sub a x) n in\n let b' = min (Int64.sub b y) (Int64.sub n a') in\n Int64.mul (Int64.sub a a') (Int64.sub b b')\n in\n min (check a b x y) (check b a y x)\n |> Int64.to_string\n |> print_endline\n done\n"}], "negative_code": [{"source_code": "let () =\n let t = () |> read_line |> int_of_string in\n for i = 1 to t do\n let [a; b; x; y; n] =\n ()\n |> read_line\n |> Str.split (Str.regexp \" \")\n |> List.map (fun s -> s |> String.trim |> int_of_string)\n in\n let check a b x y =\n let a' = min (a - x) n in\n let b' = min (b - y) (n - a') in\n (a - a') * (b - b')\n in\n min (check a b x y) (check b a y x)\n |> string_of_int\n |> print_endline\n done\n"}], "src_uid": "04753f73af685b4e7339d30d6d47c161"} {"nl": {"description": "A wise man told Kerem \"Different is good\" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string \"aba\" has substrings \"\" (empty substring), \"a\", \"b\", \"a\", \"ab\", \"ba\", \"aba\".If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.", "input_spec": "The first line of the input contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the length of the string s. The second line contains the string s of length n consisting of only lowercase English letters.", "output_spec": "If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.", "sample_inputs": ["2\naa", "4\nkoko", "5\nmurat"], "sample_outputs": ["1", "2", "0"], "notes": "NoteIn the first sample one of the possible solutions is to change the first character to 'b'.In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes \"abko\"."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet l2n c = (int_of_char c) - (int_of_char 'a') \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x) \n\nlet () = \n let n = read_int () in\n let s = read_string () in\n\n let hist = Array.make 26 0 in\n\n for i=0 to n-1 do\n let j = l2n s.[i] in\n hist.(j) <- hist.(j) + 1\n done;\n\n let answer = sum 0 25 (fun i -> max 0 (hist.(i) - 1)) in\n\n let answer = if n > 26 then -1 else answer in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "d9e9c53b391eb44f469cc92fdcf3ea0a"} {"nl": {"description": "Valera is a collector. Once he wanted to expand his collection with exactly one antique item.Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.", "input_spec": "The first line contains two space-separated integers n,\u2009v (1\u2009\u2264\u2009n\u2009\u2264\u200950;\u00a0104\u2009\u2264\u2009v\u2009\u2264\u2009106) \u2014 the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1\u2009\u2264\u2009ki\u2009\u2264\u200950) the number of items of the i-th seller. Then go ki space-separated integers si1,\u2009si2,\u2009...,\u2009siki (104\u2009\u2264\u2009sij\u2009\u2264\u2009106) \u2014 the current prices of the items of the i-th seller. ", "output_spec": "In the first line, print integer p \u2014 the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1,\u2009q2,\u2009...,\u2009qp (1\u2009\u2264\u2009qi\u2009\u2264\u2009n) \u2014 the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order. ", "sample_inputs": ["3 50000\n1 40000\n2 20000 60000\n3 10000 70000 190000", "3 50000\n1 50000\n3 100000 120000 110000\n3 120000 110000 120000"], "sample_outputs": ["3\n1 2 3", "0"], "notes": "NoteIn the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller.In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let v = read_int () in\n let s = Array.make n [||] in\n for i=0 to n-1 do\n let k = read_int () in\n s.(i) <- Array.init k (fun i-> read_int())\n done;\n\n let rec loop i ac = if i=n then ac else\n let m = minf 0 ((Array.length s.(i)) -1) (fun j -> s.(i).(j)) in\n if m < v then loop (i+1) (i::ac) else loop (i+1) ac\n in\n\n let ans = loop 0 [] in\n let ans = List.sort compare ans in\n\n printf \"%d\\n\" (List.length ans);\n\n List.iter (fun i -> printf \"%d \" (i+1)) ans;\n\n print_newline();\n\n"}, {"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet v=read_int();;\nlet tab=Array.make (n+1) 0;;\nlet vec=Array.make (n+1) false;;\nlet nb=ref 0;;\nfor i=1 to n do\n let x=read_int() in \n for j=1 to x do\n let a=read_int() in\n if a x);;\nlet scan_int_array_of_size n = Array.init n (fun _ -> scan_int() -1);;\nlet show_int n = Printf.printf \"%d\\n\" n;;\nlet show_int_pair (x,y) = Printf.printf \"%d %d\\n\" x y;;\n\nlet maximum tab = \n\tlet n = Array.length tab in\n\tlet m = ref 0 in\n\tfor i = 0 to n-1 do if tab.(i) <> 0 then m := i done;\n\t!m;;\n\nlet max_value tab = \n\tlet n = Array.length tab in\n\tlet m = ref 0 in\n\tfor i = 0 to n-1 do if tab.(i) > !m then m := tab.(i) done;\n\t!m;;\n\nlet test_permut tab deb fin =\n\tlet n = Array.length tab in\n\tlet vu = Array.make n false in\n\tfor i = deb to fin - 1 do vu.(tab.(i)) <- true done;\n\tlet test = ref true in\n\tfor i = 0 to (fin - deb)-1 do test := !test && vu.(i) done;\n\t!test;;\n\nlet t = scan_int ();;\nfor x = 1 to t do\n\tlet n = scan_int () in\n\tlet a = scan_int_array_of_size n in\n\tlet deja_vu = Array.make n 0 in\n\tif max_value a >= n then show_int 0 else\n\tbegin\n\t\tfor i = 0 to n-1 do deja_vu.(a.(i)) <- succ deja_vu.(a.(i)) done;\n\t\tlet m = maximum deja_vu in\n\t\tlet t1 = test_permut a 0 (m+1) && test_permut a (m+1) n and t2 = test_permut a (n-m-1) n && test_permut a 0 (n-m-1) in\n\t\tmatch t1,t2 with\n\t\t\t| true,true -> if (m+1)<>(n-m-1) then (show_int 2; show_int_pair ((m+1),(n-m-1)); show_int_pair ((n-m-1),(m+1)))\n\t\t\t\t\t\t\t\t\t\t\telse (show_int 1; show_int_pair ((m+1),(n-m-1)))\n\t\t\t| true,false -> show_int 1; show_int_pair ((m+1),(n-m-1))\n\t\t\t| false,true -> show_int 1; show_int_pair ((n-m-1),(m+1))\n\t\t\t| false,false -> show_int 0\n\tend\ndone;;"}], "negative_code": [{"source_code": "let scan_int () = Scanf.scanf \" %d\" (fun x -> x);;\nlet scan_int_array_of_size n = Array.init n (fun _ -> scan_int() -1);;\nlet show_int n = Printf.printf \"%d\\n\" n;;\nlet show_int_pair (x,y) = Printf.printf \"%d %d\\n\" x y;;\n\nlet maximum tab = \n\tlet n = Array.length tab in\n\tlet m = ref 0 in\n\tfor i = 0 to n-1 do if tab.(i) <> 0 then m := i done;\n\t!m;;\n\nlet max_value tab = \n\tlet n = Array.length tab in\n\tlet m = ref 0 in\n\tfor i = 0 to n-1 do if tab.(i) > !m then m := tab.(i) done;\n\t!m;;\n\nlet test_permut tab deb fin =\n\tlet n = Array.length tab in\n\tlet vu = Array.make n false in\n\tfor i = deb to fin - 1 do vu.(tab.(i)) <- true done;\n\tlet test = ref true in\n\tfor i = 0 to (fin - deb)-1 do test := !test && vu.(i) done;\n\t!test;;\n\nlet t = scan_int ();;\nfor x = 1 to t do\n\tlet n = scan_int () in\n\tlet a = scan_int_array_of_size n in\n\tlet deja_vu = Array.make n 0 in\n\tif max_value a >= n then show_int 0 else\n\tbegin\n\t\tfor i = 0 to n-1 do deja_vu.(a.(i)) <- succ deja_vu.(a.(i)) done;\n\t\tlet m = maximum deja_vu in\n\t\tlet t1 = test_permut a 0 (m+1) && test_permut a (m+1) n and t2 = test_permut a (n-m-1) n && test_permut a 0 (n-m-1) in\n\t\tmatch t1,t2 with\n\t\t\t| true,true -> show_int 2; show_int_pair ((m+1),(n-m-1)); show_int_pair ((n-m-1),(m+1))\n\t\t\t| true,false -> show_int 1; show_int_pair ((m+1),(n-m-1))\n\t\t\t| false,true -> show_int 1; show_int_pair ((n-m-1),(m+1))\n\t\t\t| false,false -> show_int 0\n\tend\ndone;;"}], "src_uid": "5f0f79e39aaf4abc8c7414990d1f8be1"} {"nl": {"description": "Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n\u2009=\u20091, then his feeling is \"I hate it\" or if n\u2009=\u20092 it's \"I hate that I love it\", and if n\u2009=\u20093 it's \"I hate that I love that I hate it\" and so on.Please help Dr. Banner.", "input_spec": "The only line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100)\u00a0\u2014 the number of layers of love and hate.", "output_spec": "Print Dr.Banner's feeling in one line.", "sample_inputs": ["1", "2", "3"], "sample_outputs": ["I hate it", "I hate that I love it", "I hate that I love that I hate it"], "notes": null}, "positive_code": [{"source_code": "let input () = Scanf.scanf \"%d\" (fun n -> n)\n\nlet solve input = \n let rec loop i =\n if i <= input\n then\n ((if i mod 2 <> 0\n then\n Printf.printf \"I hate \"\n else\n Printf.printf \"I love \");\n (if i <> input\n then\n Printf.printf \"that \"\n else\n Printf.printf \"it\\n\");\n loop (i + 1))\n else\n ()\n in loop 1\n\nlet () = solve (input ())"}, {"source_code": "let rec get_result n p = \n if n > 1 then\n if p = 1 then\n \"I hate that \" ^ get_result (n-1) (1-p)\n else\n \"I love that \" ^ get_result (n-1) (1-p)\n else\n if p = 1 then\n \"I hate it\\n\"\n else\n \"I love it\\n\"\n\n;;\n\nlet () =\nlet n = read_int () in \nlet () = print_string (get_result n 1) in ();;\n\n"}, {"source_code": "let main () =\n let gr () = Scanf.scanf \" %d\" (fun i -> i) in \n let n = gr () in\n let ph flag = \n match flag with \n | 0 -> \"I hate\"\n | 1 -> \"I love\"\n in \n let rec f cnt flag = \n match cnt with \n | 1 -> ph flag\n | cnt -> String.concat \" that \" [ph flag; f (cnt - 1) (1 - flag)] \n in\n Printf.printf \"%s it\\n\" (f n 0)\n ;;\nlet _ = main();;\n"}, {"source_code": "let rec f t b x =\n if t = x then \n if (b = 1) then Printf.printf \"I hate it\\n\"\n else Printf.printf \"I love it\\n\"\n else\n (if (b = 1) then Printf.printf \"I hate that \"\n else Printf.printf \"I love that \";\n f (t + 1) (1 - b) x)\n;;\nlet _ =\n let x = read_int() in\n f 1 1 x\n;;\n"}, {"source_code": "let text_gen n =\n let rec helper k acc =\n if k == n \n then acc ^ \" it\"\n else \n if k mod 2 == 0 \n then helper (k+1) (acc ^ \" that I hate\")\n else helper (k+1) (acc ^ \" that I love\")\n in helper 1 \"I hate\"\nin\n \nlet n = read_int() in\nPrintf.printf \"%s\\n\" (text_gen n)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n\n for i = 1 to n do\n if i=1 then printf \"I hate \"\n else if i land 1 = 1 then printf \"that I hate \"\n else printf \"that I love \"\n done;\n\n printf \"it\\n\"\n"}], "negative_code": [{"source_code": "let input () = Scanf.scanf \"%d\" (fun n -> n)\n\nlet solve input = \n let rec loop i =\n if i <= input\n then\n ((if i mod 2 <> 0\n then\n Printf.printf \"I hate \"\n else\n Printf.printf \"I love \");\n (if i <> input\n then\n Printf.printf \"that \"\n else\n Printf.printf \"it.\\n\");\n loop (i + 1))\n else\n ()\n in loop 1\n\nlet () = solve (input ())"}], "src_uid": "7f2441cfb32d105607e63020bed0e145"} {"nl": {"description": "People worry that computers will get too smart and take over the world, but the real problem is that they're too stupid and they've already taken over the world.\u2014 Pedro DomingosYou work for a well-known department store that uses leading technologies and employs mechanistic work\u00a0\u2014 that is, robots!The department you work in sells $$$n \\cdot k$$$ items. The first item costs $$$1$$$ dollar, the second item costs $$$2$$$ dollars, and so on: $$$i$$$-th item costs $$$i$$$ dollars. The items are situated on shelves. The items form a rectangular grid: there are $$$n$$$ shelves in total, and each shelf contains exactly $$$k$$$ items. We will denote by $$$a_{i,j}$$$ the price of $$$j$$$-th item (counting from the left) on the $$$i$$$-th shelf, $$$1 \\le i \\le n, 1 \\le j \\le k$$$.Occasionally robots get curious and ponder on the following question: what is the mean price (arithmetic average) of items $$$a_{i,l}, a_{i,l+1}, \\ldots, a_{i,r}$$$ for some shelf $$$i$$$ and indices $$$l \\le r$$$? Unfortunately, the old robots can only work with whole numbers. If the mean price turns out not to be an integer, they break down.You care about robots' welfare. You want to arrange the items in such a way that the robots cannot theoretically break. Formally, you want to choose such a two-dimensional array $$$a$$$ that: Every number from $$$1$$$ to $$$n \\cdot k$$$ (inclusively) occurs exactly once. For each $$$i, l, r$$$, the mean price of items from $$$l$$$ to $$$r$$$ on $$$i$$$-th shelf is an integer. Find out if such an arrangement is possible, and if it is, give any example of such arrangement.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$)\u00a0\u2014 the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le n, k \\le 500$$$)\u00a0\u2014 the number of shelves and length of each shelf, respectively. It is guaranteed that the sum $$$n$$$ over all test cases does not exceed $$$500$$$ and the sum $$$k$$$ over all test cases does not exceed $$$500$$$.", "output_spec": "Print the answer for each test case. If such an arrangement exists, print \"YES\" on a single line. After that, print any example on $$$n$$$ lines of $$$k$$$ numbers each, one line per shelf. Each number from $$$1$$$ to $$$n \\cdot k$$$ must occur exactly once in the output. If no good arrangement exists, print a single word \"NO\" on its own line.", "sample_inputs": ["4\n\n1 1\n\n2 2\n\n3 3\n\n3 1"], "sample_outputs": ["YES\n1 \nYES\n1 3 \n2 4 \nNO\nYES\n1 \n2 \n3"], "notes": null}, "positive_code": [{"source_code": "Scanf.scanf \"%d\" (fun t ->\n for i = 1 to t do\n Scanf.scanf \" %d %d\" (fun n k ->\n if k = 1 || n mod 2 = 0 then (\n print_endline \"YES\";\n for i = 1 to n do\n for j = 0 to k - 1 do Printf.printf \"%d \" (i + j * n) done;\n print_newline ()\n done\n ) else (\n print_endline \"NO\"\n )\n )\n done\n)\n"}], "negative_code": [{"source_code": "Scanf.scanf \"%d\" (fun t ->\n let check k n =\n let rec loop i =\n if i = 0 then true else\n if n mod i = 0 then loop (i - 1) else false\n in\n loop k\n in\n for i = 1 to t do\n Scanf.scanf \" %d %d\" (fun n k ->\n if check k n then (\n print_endline \"YES\";\n for i = 1 to n do\n for j = 0 to k - 1 do Printf.printf \"%d \" (i + j * n) done;\n print_newline ()\n done\n ) else (\n print_endline \"NO\"\n )\n )\n done\n)\n"}], "src_uid": "9fb84ddc2e04fd637812cd72110b7f36"} {"nl": {"description": "Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array $$$[0, 0, 1, 0, 2]$$$ MEX equals to $$$3$$$ because numbers $$$0, 1$$$ and $$$2$$$ are presented in the array and $$$3$$$ is the minimum non-negative integer not presented in the array; for the array $$$[1, 2, 3, 4]$$$ MEX equals to $$$0$$$ because $$$0$$$ is the minimum non-negative integer not presented in the array; for the array $$$[0, 1, 4, 3]$$$ MEX equals to $$$2$$$ because $$$2$$$ is the minimum non-negative integer not presented in the array. You are given an empty array $$$a=[]$$$ (in other words, a zero-length array). You are also given a positive integer $$$x$$$.You are also given $$$q$$$ queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ and means that you have to append one element $$$y_j$$$ to the array. The array length increases by $$$1$$$ after a query.In one move, you can choose any index $$$i$$$ and set $$$a_i := a_i + x$$$ or $$$a_i := a_i - x$$$ (i.e. increase or decrease any element of the array by $$$x$$$). The only restriction is that $$$a_i$$$ cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of $$$q$$$ queries (i.e. the $$$j$$$-th answer corresponds to the array of length $$$j$$$).Operations are discarded before each query. I.e. the array $$$a$$$ after the $$$j$$$-th query equals to $$$[y_1, y_2, \\dots, y_j]$$$.", "input_spec": "The first line of the input contains two integers $$$q, x$$$ ($$$1 \\le q, x \\le 4 \\cdot 10^5$$$) \u2014 the number of queries and the value of $$$x$$$. The next $$$q$$$ lines describe queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ ($$$0 \\le y_j \\le 10^9$$$) and means that you have to append one element $$$y_j$$$ to the array.", "output_spec": "Print the answer to the initial problem after each query \u2014 for the query $$$j$$$ print the maximum value of MEX after first $$$j$$$ queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.", "sample_inputs": ["7 3\n0\n1\n2\n2\n0\n0\n10", "4 3\n1\n2\n1\n2"], "sample_outputs": ["1\n2\n3\n3\n4\n4\n7", "0\n0\n0\n0"], "notes": "NoteIn the first example: After the first query, the array is $$$a=[0]$$$: you don't need to perform any operations, maximum possible MEX is $$$1$$$. After the second query, the array is $$$a=[0, 1]$$$: you don't need to perform any operations, maximum possible MEX is $$$2$$$. After the third query, the array is $$$a=[0, 1, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$. After the fourth query, the array is $$$a=[0, 1, 2, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$ (you can't make it greater with operations). After the fifth query, the array is $$$a=[0, 1, 2, 2, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3]$$$. Now MEX is maximum possible and equals to $$$4$$$. After the sixth query, the array is $$$a=[0, 1, 2, 2, 0, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3, 0]$$$. Now MEX is maximum possible and equals to $$$4$$$. After the seventh query, the array is $$$a=[0, 1, 2, 2, 0, 0, 10]$$$. You can perform the following operations: $$$a[3] := a[3] + 3 = 2 + 3 = 5$$$, $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$, $$$a[5] := a[5] + 3 = 0 + 3 = 3$$$, $$$a[5] := a[5] + 3 = 3 + 3 = 6$$$, $$$a[6] := a[6] - 3 = 10 - 3 = 7$$$, $$$a[6] := a[6] - 3 = 7 - 3 = 4$$$. The resulting array will be $$$a=[0, 1, 2, 5, 3, 6, 4]$$$. Now MEX is maximum possible and equals to $$$7$$$. "}, "positive_code": [{"source_code": "open! Printf;;\n\nmodule String = struct\n\tinclude String\n\tlet split c str =\n\t\tlet str = String.concat \"\" [str; String.make 1 c] in\n\t\tlet cur = ref [] in\n\t\tlet res = ref [] in\n\t\tString.iter (fun a ->\n\t\t\tmatch a = c with\n\t\t\t| false -> cur := (String.make 1 a) :: !cur\n\t\t\t| true -> \n\t\t\t\tlet char_list = List.rev (!cur) in\n\t\t\t\tres := (String.concat \"\" char_list) :: !res;\n\t\t\t\tcur := []) str ;\n\t\t\tList.rev !res \n\t;;\nend;;\n\nlet read_int_list () = \n\tread_line () |> String.split ' ' |> List.map int_of_string\n;;\n\nlet read_2_ints () =\n\tmatch read_int_list () with \n\t| [a; b] -> a, b\n\t| _ -> assert false\n;; \n\nlet n, x = read_2_ints () in\nlet arr = Array.make n 0 in\nlet res = ref 0 in\nfor _=1 to n do\n\tlet i = read_int () mod x in\n\tlet get = Array.get arr in\n\tArray.set arr i ((get i) + 1);\n\twhile ((get (!res mod x)) > 0) do\n\t\tlet ind = !res mod x in\n\t\tArray.set arr ind ((get ind) - 1);\n\t\tincr res\n\tdone;\n\tprintf \"%d\\n\" !res\ndone;;\n\t\n"}], "negative_code": [], "src_uid": "e25d4d7decfe6e0f5994f615a268b3aa"} {"nl": {"description": "Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob \u2014 to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.", "input_spec": "The first line contains integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.", "output_spec": "Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.", "sample_inputs": ["5\n2 4 7 8 10", "4\n1 2 1 1"], "sample_outputs": ["3", "2"], "notes": null}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet find_rare_parity array = \n let rec loop i odds evens =\n if i < 3\n then\n if array.(i) mod 2 > 0\n then\n loop (i + 1) (odds + 1) evens\n else\n loop (i + 1) odds (evens + 1)\n else\n if odds > evens\n then\n 0\n else\n 1\n in loop 0 0 0\n\nlet get_index parity array l =\n let rec loop i = \n if i < l\n then\n if array.(i) mod 2 = parity\n then\n i + 1\n else\n loop (i + 1)\n else\n failwith \"Corrupted input\"\n in loop 0\n\nlet solve () = \n let l = read () in\n let numbers = Array.init l (fun x -> read ()) in\n get_index (find_rare_parity numbers) numbers l\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve ())"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet find_rare_parity array = \n let rec loop i odds evens =\n if i < 3\n then\n if array.(i) mod 2 > 0\n then\n loop (i + 1) (odds + 1) evens\n else\n loop (i + 1) odds (evens + 1)\n else\n if odds > evens\n then\n `even\n else\n `odd\n in loop 0 0 0\n\nlet get_index parity array l =\n let rec loop i = \n if i < l\n then\n if parity = `odd \n then\n if array.(i) mod 2 > 0\n then\n i + 1\n else\n loop (i + 1)\n else\n if array.(i) mod 2 = 0\n then\n i + 1\n else\n loop (i + 1)\n else\n failwith \"Corrupted input\"\n in loop 0\n\nlet solve () = \n let l = read () in\n let numbers = Array.init l (fun x -> read ()) in\n get_index (find_rare_parity numbers) numbers l\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve ())"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet find_rare_parity array = \n let rec loop i odds evens =\n if i < 3\n then\n if array.(i) mod 2 > 0\n then\n loop (i + 1) (odds + 1) evens\n else\n loop (i + 1) odds (evens + 1)\n else\n if odds > evens\n then\n `even\n else\n `odd\n in loop 0 0 0\n\nlet get_odd_index array l =\n let rec loop i = \n if i < l\n then\n if array.(i) mod 2 > 0\n then\n i + 1\n else\n loop (i + 1)\n else\n failwith \"No odd numbers\"\n in loop 0\n\nlet get_even_index array l =\n let rec loop i = \n if i < l\n then\n if array.(i) mod 2 = 0\n then\n i + 1\n else\n loop (i + 1)\n else\n failwith \"No even numbers\"\n in loop 0\n\nlet solve () = \n let l = read () in\n let numbers = Array.init l (fun x -> read ()) in\n if find_rare_parity numbers = `odd\n then \n get_odd_index numbers l\n else\n get_even_index numbers l\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve ())"}, {"source_code": "let () =\n let n = Scanf.scanf \"%d \" (fun a -> a) in\n let a_lst = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf \"%d \" (fun a -> a)) in\n\n let o_l = List.mapi (fun i x -> if x mod 2 <> 0 then i+1 else -1) a_lst\n |> List.filter (fun x -> x <> -1)\n in\n let e_l = List.mapi (fun i x -> if x mod 2 = 0 then i+1 else -1) a_lst\n |> List.filter (fun x -> x <> -1)\n in\n\n if List.length o_l = 1 then\n Printf.printf \"%d\\n\" @@ List.hd o_l\n else\n Printf.printf \"%d\\n\" @@ List.hd e_l\n"}, {"source_code": "let rec split s i acc =\nbegin\n if i > String.length s \n then List.rev acc\n else \n let first = \n if String.contains_from s i ' ' \n then String.index_from s i ' ' \n else String.length s \n in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc) \nend in \nlet rec find n xs =\n match xs with\n | (1::0::0::_) | (0::1::1::_) -> n+0\n | (0::1::0::_) | (1::0::1::_) -> n+1\n | (0::0::1::_) | (1::1::0::_) -> n+2\n | bs -> find (n+1) (List.tl bs)\nin\nlet _ = int_of_string (read_line ()) in\nlet xs = split (read_line ()) 0 [] in\nprint_int (xs |> List.map (fun x -> x mod 2 ) |> find 1 )\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let rec loop cnt_ev cnt_od lst_ev lst_od = function\n | 0 -> if cnt_ev = 1 then lst_ev else lst_od\n | c -> (\n let num = read_int () in\n if num mod 2 = 0 then\n loop (cnt_ev+1) cnt_od c lst_od (c - 1)\n else\n loop cnt_ev (cnt_od+1) lst_ev c (c - 1)\n ) in\n Printf.printf \"%d\\n\" (n - (loop 0 0 0 0 n) + 1)\n"}, {"source_code": "let index_of_list elm lst =\n let rec loop lst index =\n match lst with\n | [] -> -1\n | h :: t ->\n\tif h = elm then index\n\telse loop t (index+1)\n in\n loop lst 0\n\t\nlet solve lst =\n let evens = List.filter (fun x -> x mod 2 = 0) lst in\n if List.length evens = 1 then (index_of_list (List.hd evens) lst)+1\n else\n let odds = List.filter (fun x -> x mod 2 = 1) lst in\n (index_of_list (List.hd odds) lst)+1\n\nlet rec some_int n =\n if 0 >= n then [] else (Scanf.scanf \" %d\" (fun x -> x)) :: some_int (n - 1)\n \nlet _ =\n let lst = Scanf.scanf \" %d\" some_int in\n Printf.printf \"%d\\n\" (solve (List.rev lst))\n"}, {"source_code": "let id x = x in\nlet (@.) f g = fun x -> f @@ g x in\nlet scan_int () = Scanf.scanf \" %d\" id in\nlet rec read_n_ints n = let i = scan_int () in\n if n = 1 then [i]\n else [i] @ (read_n_ints @@ n-1) in\n\nlet rec find_first_index p l = match l with\n | [] -> 0\n | hd :: tl when p hd -> 0\n | _ :: tl -> 1 + (find_first_index p tl) in\n\nlet n = scan_int () in\nlet l = read_n_ints n in\nlet is_even x = x mod 2 = 0 in\nlet n_even = l |> List.filter is_even |> List.length in\nlet index = if n_even = 1 then find_first_index is_even l\n else find_first_index (not @. is_even) l in\nPrintf.printf \"%d\\n\" @@ 1 + index"}], "negative_code": [{"source_code": "let index_of_list elm lst =\n let rec loop lst index =\n match lst with\n | [] -> -1\n | h :: t ->\n\tif h = elm then index\n\telse loop t (index+1)\n in\n loop lst 0\n\t\nlet solve lst =\n let evens = List.filter (fun x -> x mod 2 = 0) lst in\n if List.length evens = 1 then (index_of_list (List.hd evens) lst)+1\n else\n let odds = List.filter (fun x -> x mod 2 = 1) lst in\n (index_of_list (List.hd odds) lst)+1\n\nlet rec some_int n =\n if 0 >= n then [] else (Scanf.scanf \" %d\" (fun x -> x)) :: some_int (n - 1)\n \nlet _ =\n let lst = Scanf.scanf \" %d\" some_int in\n Printf.printf \"%d\\n\" (solve lst)\n"}], "src_uid": "dd84c2c3c429501208649ffaf5d91cee"} {"nl": {"description": "You are given 2 arrays $$$a$$$ and $$$b$$$, both of size $$$n$$$. You can swap two elements in $$$b$$$ at most once (or leave it as it is), and you are required to minimize the value $$$$$$\\sum_{i}|a_{i}-b_{i}|.$$$$$$Find the minimum possible value of this sum.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$ ($$$1 \\le a_i \\le {10^9}$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \\ldots, b_n$$$ ($$$1 \\le b_i \\le {10^9}$$$).", "output_spec": "Output the minimum value of $$$\\sum_{i}|a_{i}-b_{i}|$$$.", "sample_inputs": ["5\n5 4 3 2 1\n1 2 3 4 5", "2\n1 3\n4 2"], "sample_outputs": ["4", "2"], "notes": "NoteIn the first example, we can swap the first and fifth element in array $$$b$$$, so that it becomes $$$[ 5, 2, 3, 4, 1 ]$$$.Therefore, the minimum possible value of this sum would be $$$|5-5| + |4-2| + |3-3| + |2-4| + |1-1| = 4$$$.In the second example, we can swap the first and second elements. So, our answer would be $$$2$$$."}, "positive_code": [{"source_code": "let read_int64 () = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> Int64.of_int x);;\r\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\r\nlet read_pair _ = let x = read_int64 () in let y = read_int64 () in (x, y);;\r\nlet comp (a, b) (c, d) = if (Int64.compare a c) = 0 then Int64.compare b d else Int64.compare a c;; \r\n\r\nlet min x y = if Int64.compare x y < 0 then x else y\r\n\r\nlet max x y = if Int64.compare x y > 0 then x else y\r\n\r\nlet empty_read x = read_int64 ();;\r\n\r\nlet n = read_int ();;\r\nlet a = Array.init n empty_read;;\r\nlet b = Array.init n empty_read;;\r\nlet c = (Array.init n (fun i ->\r\n if Int64.compare a.(i) b.(i) <= 0\r\n then (a.(i), b.(i), 0)\r\n else (b.(i), a.(i), 1)));;\r\n\r\nlet _ = Array.stable_sort (fun (x, y, z) (u, v, w) ->\r\n if Int64.compare x u != 0\r\n then Int64.compare x u\r\n else\r\n if Int64.compare y v != 0\r\n then Int64.compare y v\r\n else compare z w) c;;\r\n\r\nlet mx = Array.make 2 Int64.zero;;\r\n\r\nlet ans = Array.fold_left Int64.add Int64.zero (\r\n Array.map (fun (a, b, c) -> Int64.sub b a) c);;\r\n\r\nlet diff = ref Int64.zero;;\r\n\r\nfor i = 0 to n - 1 do\r\n match c.(i) with (a, b, x) ->\r\n diff := max !diff (Int64.sub (min b mx.(1 - x)) a);\r\n mx.(x) <- max mx.(x) b\r\ndone;;\r\n\r\nPrintf.printf \"%s\\n\" (Int64.to_string (Int64.sub ans (Int64.mul 2L !diff)))\r\n\r\n"}, {"source_code": "let read_int64 () = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> Int64.of_int x);;\r\nlet read_int () = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x);;\r\nlet read_pair _ = let x = read_int64 () in let y = read_int64 () in (x, y);;\r\nlet comp (a, b) (c, d) = if (Int64.compare a c) = 0 then Int64.compare b d else Int64.compare a c;; \r\nlet min x y = if Int64.compare x y < 0 then x else y\r\nlet max x y = if Int64.compare x y > 0 then x else y\r\nlet empty_read x = read_int64 ();;\r\n\r\nlet n = read_int ();;\r\nlet a = Array.init n empty_read;;\r\nlet b = Array.init n empty_read;;\r\nlet c = (Array.init n (fun i ->\r\n if Int64.compare a.(i) b.(i) <= 0\r\n then (a.(i), b.(i), 0)\r\n else (b.(i), a.(i), 1)));;\r\nlet _ = Array.sort (fun (x, y, z) (u, v, w) ->\r\n if Int64.compare x u != 0\r\n then Int64.compare x u\r\n else\r\n if Int64.compare y v != 0\r\n then Int64.compare y v\r\n else compare z w) c;;\r\nlet mx = Array.make 2 Int64.zero;;\r\nlet ans = Array.fold_left Int64.add Int64.zero (\r\n Array.map (fun (a, b, c) -> Int64.sub b a) c);;\r\n \r\nlet diff = ref Int64.zero;;\r\nfor i = 0 to n - 1 do\r\n match c.(i) with (a, b, x) ->\r\n diff := max !diff (Int64.sub (min b mx.(1 - x)) a);\r\n mx.(x) <- max mx.(x) b\r\ndone;;\r\n\r\nPrintf.printf \"%s\\n\" (Int64.to_string (Int64.sub ans (Int64.mul 2L !diff)));;"}], "negative_code": [], "src_uid": "f995d575f86eee139c710cb0fe955682"} {"nl": {"description": "In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with n\u2009-\u2009k\u2009+\u20091 strings s1,\u2009s2,\u2009...,\u2009sn\u2009-\u2009k\u2009+\u20091, each either \"YES\" or \"NO\". The string s1 describes a group of soldiers 1 through k (\"YES\" if the group is effective, and \"NO\" otherwise). The string s2 describes a group of soldiers 2 through k\u2009+\u20091. And so on, till the string sn\u2009-\u2009k\u2009+\u20091 that describes a group of soldiers n\u2009-\u2009k\u2009+\u20091 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names\u00a0\u2014 it's allowed to print \"Xyzzzdj\" or \"T\" for example.Find and print any solution. It can be proved that there always exists at least one solution.", "input_spec": "The first line of the input contains two integers n and k (2\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u200950)\u00a0\u2014 the number of soldiers and the size of a group respectively. The second line contains n\u2009-\u2009k\u2009+\u20091 strings s1,\u2009s2,\u2009...,\u2009sn\u2009-\u2009k\u2009+\u20091. The string si is \"YES\" if the group of soldiers i through i\u2009+\u2009k\u2009-\u20091 is effective, and \"NO\" otherwise.", "output_spec": "Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them.", "sample_inputs": ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"], "sample_outputs": ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"], "notes": "NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is \"NO\". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is \"NO\". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is \"YES\". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is \"NO\". "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet l2n c = (int_of_char c) - (int_of_char 'a')\nlet n2l n = char_of_int ((int_of_char 'a') + n)\nlet toupper = Char.uppercase\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () = \n let n = read_int () in\n let k = read_int () in\n let eff = Array.init (n-k+1) (fun _ -> read_string() = \"YES\") in\n\n let name = ref 0 in\n\n let get_new_name () =\n let dig0 = !name mod 26 in\n let dig1 = !name / 26 in\n let s0 = String.make 1 (toupper (n2l dig0)) in\n let s1 = String.make 1 (n2l dig1) in\n name := 1 + !name;\n s0 ^ s1\n in\n\n let name_array = Array.make n \"\" in\n\n for i=0 to k-2 do\n name_array.(i) <- get_new_name ()\n done;\n\n for i=k-1 to n-1 do\n if eff.(i-(k-1)) then (\n name_array.(i) <- get_new_name ()\n ) else (\n name_array.(i) <- name_array.(i-(k-1))\n )\n done;\n\n for i=0 to n-1 do\n printf \"%s \" name_array.(i)\n done;\n print_newline()\n\n \n"}], "negative_code": [], "src_uid": "046d6f213fe2d565bfa5ce537346da4f"} {"nl": {"description": "Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.", "input_spec": "The first line contains a single number n (2\u2009\u2264\u2009n\u2009\u2264\u20091000) \u2014 the number of the tram's stops. Then n lines follow, each contains two integers ai and bi (0\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u20091000) \u2014 the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement. The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that a1\u2009=\u20090. At the last stop, all the passengers exit the tram and it becomes empty. More formally, . No passenger will enter the train at the last stop. That is, bn\u2009=\u20090. ", "output_spec": "Print a single integer denoting the minimum possible capacity of the tram (0 is allowed).", "sample_inputs": ["4\n0 3\n2 5\n4 2\n4 0"], "sample_outputs": ["6"], "notes": "NoteFor the first example, a capacity of 6 is sufficient: At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3. At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now. At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now. Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints. Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer."}, "positive_code": [{"source_code": "let _ =\n let main () =\n let n = Scanf.sscanf (read_line ()) \"%d\" (fun n -> n) in\n let rec loop i cur m =\n if i = 0 then Printf.printf \"%d\\n\" m else\n let (a, b) = Scanf.sscanf (read_line ()) \"%d %d\" (fun a b -> a, b) in\n let cur = cur - a + b in\n let m = max cur m in\n loop (i - 1) cur m\n in\n loop n 0 0\n in\n main ()\n"}, {"source_code": "let input () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet rec at_trainstop ppl_inside current_max n =\n if n > 0\n then\n let new_ppl = Scanf.scanf \"%d %d \" (fun a b -> (-a + b)) in\n at_trainstop (ppl_inside + new_ppl) (Pervasives.max current_max (ppl_inside + new_ppl)) (n - 1)\n else\n current_max\n\nlet solve input = at_trainstop 0 0 input\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input ()))"}, {"source_code": "let input () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet if_max max ppl_inside =\n if ppl_inside > max\n then\n ppl_inside\n else\n max \n\nlet rec at_trainstop ppl_inside max n =\n if n > 0\n then\n let new_ppl = Scanf.scanf \"%d %d \" (fun a b -> (-a + b)) in\n at_trainstop (ppl_inside + new_ppl) (if_max max (ppl_inside + new_ppl)) (n - 1)\n else\n max\n\nlet solve input = at_trainstop 0 0 input\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input ()))"}, {"source_code": "let rec tram n l m o i =\n\tif n = 0 then m\n\telse Scanf.scanf \"%d %d\\n\" (fun oo ii -> \n\t\ttram (n-1) (l-o+i) (max (l-o+i) m) oo ii\n\t)\n;;\n\nlet () =\n\tlet n = read_int () in\n\tprint_int (tram n 0 0 0 0)\n;;\n"}, {"source_code": "let read_int() = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x)\nlet printf = Printf.printf\n\nlet max a b = if (a > b) then a else b\n\nlet () = \n\tlet n = read_int() in \n\tlet a = Array.make (n + 1) 0 in \n\tlet b = Array.make (n + 1) 0 in \n\tlet sum = ref 0 in \n\tlet mx = ref 0 in \n\t\tfor i = 1 to n do \n\t\t\ta.(i) <- read_int();\n\t\t\tb.(i) <- read_int();\n\t\t\tsum := !sum - a.(i) + b.(i); \n\t\t\tmx := max !mx !sum;\n\t\tdone;\n\t\tprintf \"%d\\n\" (!mx) "}, {"source_code": "let read_int()=Scanf.scanf \" %d\" (fun x->x);;\nlet n=read_int() and r=ref 0 and s=ref 0;;\nfor i=1 to n do\n let x=read_int() and y=read_int() in\n r:= !r+y-x;\n s:=max !s !r\ndone;;\nPrintf.printf \"%d\" !s;;"}, {"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\nlet nn = n + 10\n\nlet a = Array.make nn (-1);;\nlet b = Array.make nn (-1);;\nlet c = Array.make nn (-1);; (*The number of people on tram after each stop*)\n\nfor i = 1 to n do\n let (ai,bi) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" ( fun x y -> (x,y) ) in\n a.(i) <- ai; b.(i) <- bi\ndone\n;;\n\nlet () = c.(0) <- 0;;\n\nfor i = 1 to n do\n c.(i) <- (c.(i-1) + b.(i-1) - a.(i-1))\ndone\n;;\n\nlet z = Array.fold_left (fun x y -> if x > y then x else y ) (-1) c\nin print_int z; print_endline \"\"\n"}, {"source_code": "let solve n stops =\n let rec loop stops passenger max_capacity = match stops with\n [] -> max_capacity\n | first :: rest ->\n loop rest (passenger+(snd first)-(fst first)) (max passenger max_capacity)\n in\n loop stops 0 0;;\n\nlet rec get_stops n stops=\n if n <= 0\n then stops\n else get_stops (n-1) (Scanf.scanf \"%d %d\\n\" (fun x y -> (x, y)) :: stops)\n\nlet get_stops n = List.rev (get_stops n [])\n\nlet _ =\n let n = Scanf.scanf \"%d\\n\" (fun x -> x) in\n let stops = get_stops n in\n Printf.printf \"%d\\n\" (solve n stops)\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet solve n =\n let rec find_max n max sum = match n with\n | 0 -> max\n | n -> let a = read_int ()\n and b = read_int () in\n let new_sum = sum - a + b in\n if max > new_sum\n then find_max (n - 1) max new_sum\n else find_max (n - 1) new_sum new_sum\n in find_max n 0 0\n\nlet () =\n let n = read_int ()\n in Printf.printf \"%d\\n\" (solve n)\n\n"}, {"source_code": "let pf = Printf.printf;;\nlet sf = Scanf.scanf;;\n\nlet (|>) x f = f x;;\nlet (@@) f x = f x;;\n\nexception Error of string\n\nlet inf = 1000000000;;\nlet eps = 1e-11;;\n\nlet _ =\n let n = sf \"%d\\n\" (fun x -> x) in\n let a = ref 0 in\n let b = ref 0 in\n let res = ref 0 in\n for i = 1 to n do\n let (x, y) = sf \"%d %d\\n\" (fun x y -> x, y) in\n a := !a + x;\n b := !b + y;\n res := max !res (!b - !a)\n done;\n pf \"%d\\n\" !res\n;;\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x)\n\nlet max a b = \n if a < b then b\n else a\n\nlet () =\n let n = ref (read_int ()) in\n let ans = ref 0 in\n let count_now = ref 0 in\n for i = 1 to !n do\n count_now := !count_now + read_int () - read_int ();\n ans := max !ans !count_now;\n done;\n Printf.printf \"%d\" !ans;\n"}, {"source_code": "let read_list () = \n let n = read_int() \n and l = ref [] in\n for i = 1 to n do\n let pair = Scanf.scanf \" %d %d\" (fun a b -> (a, b)) in\n l := pair :: !l;\n done;\n !l\n\nlet solve l =\n fst (List.fold_left\n (fun (mx, ac) (hm, hp) -> let na = (ac + hp - hm) in (max mx na, na))\n (0, 0)\n (List.rev l))\n\nlet print_res = \n print_int \n\nlet main =\n let l = read_list () in\n print_res (solve l)\n \n\n \n"}], "negative_code": [{"source_code": "let rec tram n m o i =\n\tif n = 0 then m\n\telse let oo, ii = Scanf.scanf \"%d %d\\n\" (fun o i -> (o, i)) \n\t\tin tram (n-1) (max (m-o+i) m) oo ii\n;;\n\nlet () =\n\tlet n = read_int () in\n\tprint_int (tram n 0 0 0)\n;;\n"}, {"source_code": "let read_int() = Scanf.bscanf Scanf.Scanning.stdin \" %d \" (fun x -> x)\nlet printf = Printf.printf\n\nlet max a b = if (a > b) then a else b\n\nlet () = \n\tlet n = read_int() in \n\tlet a = Array.make (n + 1) 0 in \n\tlet b = Array.make (n + 1) 0 in \n\tlet sum = ref 0 in \n\tlet mx = ref 0 in \n\t\tfor i = 1 to n do \n\t\t\ta.(i) <- read_int();\n\t\t\tb.(i) <- read_int();\n\t\t\tsum := !sum + a.(i) - b.(i); \n\t\t\tmx := max !mx !sum;\n\t\tdone;\n\t\tprintf \"%d\\n\" (!mx) "}, {"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\nlet nn = n + 10\n\nlet a = Array.make nn (-1);;\nlet b = Array.make nn (-1);;\nlet c = Array.make nn (-1);; (*The number of people on tram after each stop*)\n\nfor i = 1 to n do\n let (ai,bi) = Scanf.bscanf Scanf.Scanning.stdin \"%d %d \" ( fun x y -> (x,y) ) in\n a.(i) <- ai; b.(i) <- bi\ndone\n;;\n\nlet () = c.(0) <- 0;;\n\nfor i = 1 to n-1 do\n c.(i) <- (c.(i-1) + b.(i-1) - a.(i-1))\ndone\n;;\n\nlet z = Array.fold_left (fun x y -> if x > y then x else y ) (-1) c\nin print_int z; print_endline \"\"\n"}, {"source_code": "let read_list () = \n let n = read_int() \n and l = ref [] in\n for i = 1 to n do\n let pair = Scanf.scanf \" %d %d\" (fun a b -> (a, b)) in\n l := pair :: !l;\n done;\n !l\n\nlet solve l =\n List.fold_left \n (fun ac (hp, hm) -> max ac (ac - hp + hm))\n 0\n l\n\nlet print_res = \n print_int \n\nlet main =\n let l = read_list () in\n print_res (solve l)\n \n\n \n"}], "src_uid": "74b90fe9458b147568ac9bd09f219aab"} {"nl": {"description": "One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters \"+\" and \"1\" into this sequence. For example, the sequences \"(())()\", \"()\" and \"(()(()))\" are correct, while the bracket sequences \")(\", \"(()\" and \"(()))(\" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?", "input_spec": "The first line contains one integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$) \u2014 the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence \u2014 a non-empty string which consists only of characters \"(\" and \")\". The sum of lengths of all bracket sequences in the input is at most $$$5 \\cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.", "output_spec": "Print a single integer \u2014 the maximum number of pairs which can be made, adhering to the conditions in the statement.", "sample_inputs": ["7\n)())\n)\n((\n((\n(\n)\n)", "4\n(\n((\n(((\n(())", "2\n(())\n()"], "sample_outputs": ["2", "0", "1"], "notes": "NoteIn the first example, it's optimal to construct two pairs: \"(( \u00a0\u00a0\u00a0 )())\" and \"( \u00a0\u00a0\u00a0 )\"."}, "positive_code": [{"source_code": "Scanf.(Array.(\n let n = scanf \" %d\" @@ fun v -> v in\n let l,r,zero = make 500010 0, make 500010 0, ref 0 in\n init n (fun _ ->\n let s = scanf \" %s\" @@ fun v -> v in\n let s = init (String.length s) (fun i -> s.[i]) in\n let post,pre = fold_left (fun (sum,pre) -> function\n | '(' -> (sum+1,pre)\n | ')' -> if sum=0 then (0,pre+1) else (sum-1,pre)\n | _ -> failwith \"\"\n ) (0,0) s in\n if post>0 && pre>0 then ()\n else if post>0 then (\n r.(post) <- r.(post) + 1\n ) else if pre>0 then (\n l.(pre) <- l.(pre) + 1\n ) else (\n zero := !zero + 1\n )\n ) |> ignore;\n fold_left (fun (sum,i) v ->\n let u = r.(i) in (sum + min u v,i+1)\n ) (!zero/2,0) l\n |> fst |> print_int\n))"}, {"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)\n let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet calc s =\n let cnt,pre,post = ref 0L,ref 0L,ref 0L in\n String.iteri (fun i c ->\n if c = '(' then cnt += 1L\n else (\n cnt -= 1L;\n if !cnt < 0L then (\n pre := max (!pre) (-1L*(!cnt));\n )\n )\n ) s;\n cnt := !pre;\n String.iteri (fun i c ->\n if c = '(' then cnt += 1L\n else (\n cnt -= 1L;\n )\n ) s;\n post := !cnt;\n if !cnt>0L && !pre>0L then (\n `None\n ) else if !pre>0L then (\n `Pre !pre\n ) else if !post>0L then (\n `Post !cnt\n ) else (\n `Zero\n )\nlet () =\n let n = gi 0 in\n let pos,neg,zero = make 600010 0L,make 600010 0L,ref 0L in\n repi 1 (i32 n) (fun i ->\n let s = scanf \" %s\" @@ id in\n let v = calc s in\n match v with\n | `None -> ()\n | `Pre v ->\n neg.(i32 v) <- neg.(i32 v) + 1L\n | `Post v ->\n pos.(i32 v) <- pos.(i32 v) + 1L\n | `Zero -> zero += 1L\n );\n let r = ref 0L in\n iteri (fun i v ->\n let w = neg.(i) in\n r += min v w\n ) pos;\n r += !zero/2L;\n printf \"%Ld\\n\" !r\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)\n let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module Int64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n let pow n k =\n let rec f a n = function\n | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)\n in f 1L n k\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let iia = input_i64_array\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let gi = get_i64\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let g2 = get_2_i64\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let g3 = get_3_i64\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let g4 = get_4_i64\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let slen s = String.length s\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nlet calc s =\n let r = ref [] in\n let lv = ref 0L in\n String.iteri (fun i c ->\n if c = '(' then (\n r := i :: !r;\n lv += 1L;\n ) else (\n match !r with\n | i::tl -> (\n r := tl;\n lv -= 1L\n );\n | [] -> lv -= 1L;\n )\n ) s; !lv\nlet () =\n let n = gi 0 in\n let pos,neg,zero = make 100010 0L,make 100010 0L,ref 0L in\n repi 1 (i32 n) (fun i ->\n let s = scanf \" %s\" @@ id in\n let v = calc s in\n (* printf \"%Ld\\n\" v; *)\n if v > 0L then (\n pos.(i32 v) <- pos.(i32 v) + 1L\n ) else if v < 0L then (\n neg.(-i32 v) <- neg.(-i32 v) + 1L\n ) else zero += 1L\n );\n let r = ref 0L in\n iteri (fun i v ->\n let w = neg.(i) in\n r += min v w\n ) pos;\n r += !zero/2L;\n printf \"%Ld\\n\" !r\n\n\n\n\n\n\n\n\n"}], "src_uid": "2cfb08b2269dbf5417c1758def4c035f"} {"nl": {"description": "Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a,\u2009b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1,\u2009s3)\u2009=\u2009f(s2,\u2009s3)\u2009=\u2009t. If there is no such string, print \u2009-\u20091.", "input_spec": "The first line contains two integers n and t (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 0\u2009\u2264\u2009t\u2009\u2264\u2009n). The second line contains string s1 of length n, consisting of lowercase English letters. The third line contain string s2 of length n, consisting of lowercase English letters.", "output_spec": "Print a string of length n, differing from string s1 and from s2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.", "sample_inputs": ["3 2\nabc\nxyc", "1 0\nc\nb"], "sample_outputs": ["ayd", "-1"], "notes": null}, "positive_code": [{"source_code": "let count s1 s2 n =\n\tlet sam = ref [] and dif = ref [] in\n\tfor i = 0 to n-1 do\n\t\tif s1.[i] = s2.[i]\n\t\t\tthen sam := i :: !sam\n\t\t\telse dif := i :: !dif;\n\tdone;\n\t!sam, !dif;;\n\nlet let_chos a b = \n\tif a = 'a'\n\t\tthen if b = 'b'\n\t\t\tthen 'c'\n\t\t\telse 'b'\n\t\telse if b = 'a'\n\t\t\tthen if a = 'b'\n\t\t\t\tthen 'c'\n\t\t\t\telse 'b'\n\t\t\telse 'a';;\n\nlet t_geq_dif (sam,dif) s1 s2 n t =\n\tlet s3 = String.copy s1 in\n\t\tList.iter (fun i -> let a = let_chos (s1.[i]) (s2.[i]) in\n\t\t\t\ts3.[i] <- a) dif;\n\tlet tab = Array.of_list sam in\n\t\tfor i = 0 to t - List.length dif - 1 do\n\t\t\tlet j = tab.(i) in\n\t\t\t\ts3.[j] <- let_chos (s1.[j]) (s2.[j]);\n\t\tdone;\n\ts3;;\n\nlet t_l_dif (sam,dif) s1 s2 n t =\n\tlet s3 = String.copy s1 in\n\tlet rec aux len t' = function\n\t\t| l\twhen t' >= len\t-> l, t'\n\t\t| a::b::q\t\t-> (s3.[b] <- s2.[b]); aux (len-2) (t'-1) q\n\t\t| _\t\t\t-> [], -1\n\tin\n\tlet (a,b) = aux (List.length dif) t dif in\n\t\tif b = -1\n\t\t\tthen \"-1\"\n\t\t\telse (let tab = Array.of_list (a @ sam) in\n\t\t\t\tfor i = 0 to b-1 do\n\t\t\t\t\tlet j = tab.(i) in\n\t\t\t\t\t\ts3.[j] <- let_chos (s1.[j]) (s2.[j]);\n\t\t\t\tdone; s3);;\n\nlet main () =\n\tlet (n,t,s1,s2) = Scanf.scanf \"%d %d %s %s\" (fun i j k l -> (i,j,k,l)) in\n\tlet (sam,dif) = count s1 s2 n in\n\tPrintf.printf \"%s\" (if t >= List.length dif\n\t\t\tthen t_geq_dif (sam,dif) s1 s2 n t\n\t\t\telse t_l_dif (sam,dif) s1 s2 n t);;\n\nmain ();;\n"}], "negative_code": [], "src_uid": "8ba3a7f7cb955478481c74cd4a4eed14"} {"nl": {"description": "It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1\u2009+\u20091 to a1\u2009+\u2009a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of piles. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009103, a1\u2009+\u2009a2\u2009+\u2009...\u2009+\u2009an\u2009\u2264\u2009106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1\u2009\u2264\u2009m\u2009\u2264\u2009105), the number of juicy worms said by Marmot. The fourth line contains m integers q1,\u2009q2,\u2009...,\u2009qm (1\u2009\u2264\u2009qi\u2009\u2264\u2009a1\u2009+\u2009a2\u2009+\u2009...\u2009+\u2009an), the labels of the juicy worms.", "output_spec": "Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.", "sample_inputs": ["5\n2 7 3 4 9\n3\n1 25 11"], "sample_outputs": ["1\n5\n3"], "notes": "NoteFor the sample input: The worms with labels from [1, 2] are in the first pile. The worms with labels from [3, 9] are in the second pile. The worms with labels from [10, 12] are in the third pile. The worms with labels from [13, 16] are in the fourth pile. The worms with labels from [17, 25] are in the fifth pile. "}, "positive_code": [{"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet make_array () = \n let n = read () in\n let array = Array.make n (0, 0) in\n let rec loop i array prev = \n if i < n\n then\n let quantity = read () in\n let min = prev + 1 in\n let max = prev + quantity in\n let () = Array.set array i (min, max) in\n loop (i + 1) array max\n else\n (n, array)\n in loop 0 array 0\n\n\nlet make_list () = \n let n = read () in\n let rec loop i list =\n if i < n\n then\n let value = read () in\n loop (i + 1) (value :: list)\n else\n List.rev list\n in loop 0 []\n\nlet input () =\n let piles = make_array () in\n let worms = make_list () in\n (piles, worms)\n\nlet classify (min, max) value =\n if value >= min && value <= max\n then\n `Inside\n else\n if value < min\n then\n `To_the_left\n else\n `To_the_right\n\nlet rec binary_search array value low high = \n let mid = (low + high) / 2 in\n match classify array.(mid) value with\n | `To_the_right -> binary_search array value (mid + 1) high \n | `To_the_left -> binary_search array value low (mid - 1)\n | `Inside -> mid + 1\n\nlet wrapper (n, array) value = \n let result = binary_search array value 0 n in\n Printf.printf \"%d\\n\" result\n \nlet solve (piles, worms) = \n List.iter (wrapper piles) worms \n\nlet () =\n solve (input ())"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet long x = Int64.of_int x\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let a = Array.init n (fun _ -> read_long()) in\n let m = read_int() in\n let q = Array.init m (fun _ -> read_long()) in\n\n let ends = Array.make n 0L in\n ends.(0) <- a.(0);\n \n for i=1 to n-1 do\n ends.(i) <- ends.(i-1) ++ a.(i)\n done;\n\n let find i = \n let rec bsearch lo hi = \n (* must be in lo, lo+1....hi-1 *)\n if lo+1 = hi then lo else\n\tlet m = (lo+hi)/2 in\n\tif i > ends.(m-1) then bsearch m hi else bsearch lo m\n in\n \n bsearch 0 n\n in\n \n for i=0 to m-1 do\n printf \"%d\\n\" (1 + find q.(i))\n done;\n"}], "negative_code": [], "src_uid": "10f4fc5cc2fcec02ebfb7f34d83debac"} {"nl": {"description": "There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).", "input_spec": "The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \\le n \\le 2\\cdot10^{5}$$$, $$$0 \\le a, b \\le 2\\cdot10^{5}$$$, $$$a + b > 0$$$) \u2014 total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters \".\" and \"*\". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.", "output_spec": "Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.", "sample_inputs": ["5 1 1\n*...*", "6 2 3\n*...*.", "11 3 10\n.*....**.*.", "3 2 3\n***"], "sample_outputs": ["2", "4", "7", "0"], "notes": "NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B \u2014 student-athlete."}, "positive_code": [{"source_code": "(* Codeforces 962 B Students in Railway Carriage *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet grc () = Scanf.scanf \" %c\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\n\ntype lastType = P | A | O;; (* programmer, athlete, other *)\n\nlet rec tocharlist s i n cl =\n\tif i==n then cl\n\telse \n\t\tlet c = s.[i] in\n\t\ttocharlist s (i + 1) n (c :: cl);;\n\nlet rec maxstud np na last maxs lc = match lc with\n| [] -> maxs\n| h :: t -> \n\tif np==0 && na==0 then maxs\n\telse if h=='*' then maxstud np na O maxs t\n\telse if last==O then begin\n\t\tif np>na then maxstud (np - 1) na P (maxs + 1) t\n\t\telse maxstud np (na - 1) A (maxs + 1) t\n\t\tend\n\telse if (last==P) && (na>0) then maxstud np (na - 1) A (maxs + 1) t\n\telse if (last==A) && (np>0) then maxstud (np - 1) na P (maxs + 1) t\n\telse maxstud np na O maxs t;;\n\nlet main() =\n\tlet snab = rdln () in (* line with n a b *)\n\tlet (n,a,b) = Scanf.sscanf snab \"%d %d %d\" (fun a b c -> (a,b,c)) in\n\tlet seats = rdln () in\n\tlet lc = tocharlist seats 0 n [] in\n\tlet maxstu = maxstud a b O 0 lc in\n\tbegin\n\t\t(*Printf.printf \"%d %d %d\\n\" n a b;*)\n\t\tprint_int maxstu;\n\t\tprint_string \"\\n\"\n\tend;;\n\nmain();;"}], "negative_code": [], "src_uid": "6208dbdf9567b759b0026db4af4545a9"} {"nl": {"description": "The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.We assume that the hash table consists of h cells numbered from 0 to h\u2009-\u20091. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value \u2014 an integer between 0 and h\u2009-\u20091, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals t and cell t of the table is already occupied. Then we try to add this object to cell (t\u2009+\u2009m)\u00a0mod\u00a0h. If it is also occupied, then we try cell (t\u2009+\u20092\u00b7m)\u00a0mod\u00a0h, then cell (t\u2009+\u20093\u00b7m)\u00a0mod\u00a0h, and so on. Note that in some cases it's possible that the new object can not be added to the table. It is guaranteed that the input for this problem doesn't contain such situations.The operation a\u00a0mod\u00a0b means that we take the remainder of the division of number a by number b.This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell (t\u2009+\u2009i\u00b7m)\u00a0mod\u00a0h (i\u2009\u2265\u20090), then exactly i dummy calls have been performed.Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.", "input_spec": "The first line of input contains three integers h, m and n (1\u2009\u2264\u2009m\u2009<\u2009h), separated by spaces, where h is the size of the hash table, m is the number that is used to resolve collisions, n is the number of operations. The following n lines contains the descriptions of the operations. Their execution order corresponds to the order in which they appear in the input file. Each operation is described by a single line. The operations are described as follows: \"+ id hash\"This is the format of the operation that adds an object to the table. The first character is \"+\" (ASCII 43), followed by a single space, then the object identifier id (0\u2009\u2264\u2009id\u2009\u2264\u2009109), then another space, and the hash value of the given object hash (0\u2009\u2264\u2009hash\u2009<\u2009h). The object identifier and the hash value of this object are integers. \"- id\"This is the format of the operation that deletes an object from the table. The first character is \"-\" (ASCII 45), followed by a single space, then the object identifier id (0\u2009\u2264\u2009id\u2009\u2264\u2009109). The object identifier is an integer. It is guaranteed that for all addition operations the value of id is unique. It is also guaranteed that the initial data is correct, that is, it's always possible to add an object to the hash table and there won't be any deletions of nonexisting objects. The input limitations for getting 20 points are: 1\u2009\u2264\u2009h\u2009\u2264\u20095000 1\u2009\u2264\u2009n\u2009\u2264\u20095000 The input limitations for getting 50 points are: 1\u2009\u2264\u2009h\u2009\u2264\u20095\u00b7104 1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7104 The input limitations for getting 100 points are: 1\u2009\u2264\u2009h\u2009\u2264\u20092\u00b7105 1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105 ", "output_spec": "Print a single number \u2014 the total number of dummy calls to the hash table. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout streams and the %I64d specifier.", "sample_inputs": ["10 2 7\n+ 11 0\n+ 22 2\n+ 33 6\n+ 44 0\n+ 55 0\n- 22\n+ 66 0", "5 1 6\n+ 123 0\n+ 234 1\n+ 345 2\n- 234\n+ 456 0\n+ 567 0"], "sample_outputs": ["7", "4"], "notes": null}, "positive_code": [{"source_code": "let rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet g2d n = n land (-n)\n\nlet fenwick_new n =\n Array.make n 0\n\nlet fenwick_modify ft n x =\n let i = ref (n + 1) in\n while !i <= Array.length ft do\n ft.(!i - 1) <- ft.(!i - 1) + x;\n i := !i + g2d !i;\n done\n\nlet fenwick_count ft n =\n let i = ref (n + 1) in\n let res = ref 0 in\n while !i > 0 do\n res := !res + ft.(!i - 1);\n i := !i - g2d !i;\n done;\n !res\n\nlet fenwick_count2 ft m n =\n fenwick_count ft n - fenwick_count ft (m - 1)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let h = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make h (-1) in\n let b = Array.make (2 * h) (-1) in\n let c = Array.make h (-1) in\n let g = gcd m h in\n let () =\n let pos = ref 0 in\n for i = 0 to h - 1 do\n\tif c.(i) < 0 then (\n\t let k = ref i in\n\t for j = 0 to h / g - 1 do\n\t c.(!k) <- !pos;\n\t b.(!pos) <- !k;\n\t b.(!pos + h / g) <- !k;\n\t incr pos;\n\t k := (!k + m) mod h;\n\t done;\n\t pos := !pos + h / g;\n\t)\n done\n in\n let ft = fenwick_new (2 * h) in\n let ht = Hashtbl.create h in\n let res = ref 0L in\n for i = 0 to n - 1 do\n let op = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tmatch op with\n\t | \"+\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let l = ref (c.(hash) - 1) in\n\t let r = ref (c.(hash) + h / g) in\n\t\twhile !l < !r - 1 do\n\t\t let m = (!l + !r) / 2 in\n(*Printf.printf \"step %d %d %d %d\\n\" !l !r m (fenwick_count2 ft c.(hash) m);*)\n\t\t if fenwick_count2 ft c.(hash) m < m + 1 - c.(hash)\n\t\t then r := m\n\t\t else l := m\n\t\tdone;\n\t\tres := Int64.add !res (Int64.of_int (!r - c.(hash)));\n\t\tlet hash = b.(!r) in\n(*Printf.printf \"add %d %d %d %d\\n\" id hash !l !r;*)\n\t\t(*while a.(!j) >= 0 do\n\t\t j := (!j + m) mod h;\n\t\t incr res;\n\t\tdone;*)\n\t\t Hashtbl.replace ht id hash;\n\t\t a.(hash) <- id;\n\t\t fenwick_modify ft c.(hash) 1;\n\t\t fenwick_modify ft (c.(hash) + h / g) 1;\n\t | \"-\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Hashtbl.find ht id in\n\t\tHashtbl.remove ht id;\n\t\ta.(hash) <- -1;\n\t\tfenwick_modify ft c.(hash) (-1);\n\t\tfenwick_modify ft (c.(hash) + h / g) (-1);\n\t | _ -> assert false\n done;\n Printf.printf \"%Ld\\n\" !res;\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let h = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make h (-1) in\n let ht = Hashtbl.create h in\n let res = ref 0 in\n for i = 0 to n - 1 do\n let op = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tmatch op with\n\t | \"+\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let j = ref hash in\n\t\twhile a.(!j) >= 0 do\n\t\t j := (!j + m) mod h;\n\t\t incr res;\n\t\tdone;\n\t\tHashtbl.replace ht id !j;\n\t\ta.(!j) <- id;\n\t | \"-\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Hashtbl.find ht id in\n\t\tHashtbl.remove ht id;\n\t\ta.(hash) <- -1;\n\t | _ -> assert false\n done;\n Printf.printf \"%d\\n\" !res;\n"}, {"source_code": "let rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet g2d n = n land (-n)\n\nlet fenwick_new n =\n Array.make n 0\n\nlet fenwick_modify ft n x =\n let i = ref (n + 1) in\n while !i <= Array.length ft do\n ft.(!i - 1) <- ft.(!i - 1) + x;\n i := !i + g2d !i;\n done\n\nlet fenwick_count ft n =\n let i = ref (n + 1) in\n let res = ref 0 in\n while !i > 0 do\n res := !res + ft.(!i - 1);\n i := !i - g2d !i;\n done;\n !res\n\nlet fenwick_count2 ft m n =\n fenwick_count ft n - fenwick_count ft (m - 1)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let h = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make h (-1) in\n let b = Array.make (2 * h) (-1) in\n let c = Array.make h (-1) in\n let g = gcd m h in\n let () =\n let pos = ref 0 in\n for i = 0 to h - 1 do\n\tif c.(i) < 0 then (\n\t let k = ref i in\n\t for j = 0 to h / g - 1 do\n\t c.(!k) <- !pos;\n\t b.(!pos) <- !k;\n\t b.(!pos + h / g) <- !k;\n\t incr pos;\n\t k := (!k + m) mod h;\n\t done;\n\t pos := !pos + h / g;\n\t)\n done\n in\n let ft = fenwick_new (2 * h) in\n let ht = Hashtbl.create h in\n let res = ref 0L in\n for i = 0 to n - 1 do\n let op = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tmatch op with\n\t | \"+\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let l = ref (c.(hash) - 1) in\n\t let r = ref (c.(hash) + h / g) in\n\t\twhile !l < !r - 1 do\n\t\t let m = (!l + !r) / 2 in\n(*Printf.printf \"step %d %d %d %d\\n\" !l !r m (fenwick_count2 ft c.(hash) m);*)\n\t\t if fenwick_count2 ft c.(hash) m < m + 1 - c.(hash)\n\t\t then r := m\n\t\t else l := m\n\t\tdone;\n\t\tres := Int64.add !res (Int64.of_int (!r - c.(hash)));\n\t\tlet hash = b.(!r) in\n(*Printf.printf \"add %d %d %d %d\\n\" id hash !l !r;*)\n\t\t(*while a.(!j) >= 0 do\n\t\t j := (!j + m) mod h;\n\t\t incr res;\n\t\tdone;*)\n\t\t Hashtbl.replace ht id hash;\n\t\t a.(hash) <- id;\n\t\t fenwick_modify ft c.(hash) 1;\n\t\t fenwick_modify ft (c.(hash) + h / g) 1;\n\t | \"-\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Hashtbl.find ht id in\n\t\tHashtbl.remove ht id;\n\t\ta.(hash) <- -1;\n\t\tfenwick_modify ft c.(hash) (-1);\n\t\tfenwick_modify ft (c.(hash) + h / g) (-1);\n\t | _ -> assert false\n done;\n Printf.printf \"%Ld\\n\" !res;\n"}], "negative_code": [{"source_code": "let rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet g2d n = n land (-n)\n\nlet fenwick_new n =\n Array.make n 0\n\nlet fenwick_modify ft n x =\n let i = ref (n + 1) in\n while !i <= Array.length ft do\n ft.(!i - 1) <- ft.(!i - 1) + x;\n i := !i + g2d !i;\n done\n\nlet fenwick_count ft n =\n let i = ref (n + 1) in\n let res = ref 0 in\n while !i > 0 do\n res := !res + ft.(!i - 1);\n i := !i - g2d !i;\n done;\n !res\n\nlet fenwick_count2 ft m n =\n fenwick_count ft n - fenwick_count ft (m - 1)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let h = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make h (-1) in\n let b = Array.make (2 * h) (-1) in\n let c = Array.make h (-1) in\n let g = gcd m h in\n let () =\n let pos = ref 0 in\n for i = 0 to h - 1 do\n\tif c.(i) < 0 then (\n\t for j = 0 to h / g - 1 do\n\t c.((i + j * m) mod h) <- !pos;\n\t b.(!pos) <- (i + j * m) mod h;\n\t b.(!pos + h / g) <- (i + j * m) mod h;\n\t incr pos\n\t done;\n\t pos := !pos + h / g;\n\t)\n done\n in\n let ft = fenwick_new (2 * h) in\n let ht = Hashtbl.create h in\n let res = ref 0 in\n for i = 0 to n - 1 do\n let op = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tmatch op with\n\t | \"+\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let l = ref (c.(hash) - 1) in\n\t let r = ref (c.(hash) + h / g) in\n\t\twhile !l < !r - 1 do\n\t\t let m = (!l + !r) / 2 in\n(*Printf.printf \"step %d %d %d %d\\n\" !l !r m (fenwick_count2 ft c.(hash) m);*)\n\t\t if fenwick_count2 ft c.(hash) m < m + 1 - c.(hash)\n\t\t then r := m\n\t\t else l := m\n\t\tdone;\n\t\tres := !res + !r - c.(hash);\n\t\tlet hash = b.(!r) in\n(*Printf.printf \"add %d %d %d %d\\n\" id hash !l !r;*)\n\t\t(*while a.(!j) >= 0 do\n\t\t j := (!j + m) mod h;\n\t\t incr res;\n\t\tdone;*)\n\t\t Hashtbl.replace ht id hash;\n\t\t a.(hash) <- id;\n\t\t fenwick_modify ft c.(hash) 1;\n\t\t fenwick_modify ft (c.(hash) + h / g) 1;\n\t | \"-\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Hashtbl.find ht id in\n\t\tHashtbl.remove ht id;\n\t\ta.(hash) <- -1;\n\t\tfenwick_modify ft c.(hash) (-1);\n\t\tfenwick_modify ft (c.(hash) + h / g) (-1);\n\t | _ -> assert false\n done;\n Printf.printf \"%d\\n\" !res;\n"}, {"source_code": "let rec gcd a b =\n if b = 0\n then a\n else gcd b (a mod b)\n\nlet g2d n = n land (-n)\n\nlet fenwick_new n =\n Array.make n 0\n\nlet fenwick_modify ft n x =\n let i = ref (n + 1) in\n while !i <= Array.length ft do\n ft.(!i - 1) <- ft.(!i - 1) + x;\n i := !i + g2d !i;\n done\n\nlet fenwick_count ft n =\n let i = ref (n + 1) in\n let res = ref 0 in\n while !i > 0 do\n res := !res + ft.(!i - 1);\n i := !i - g2d !i;\n done;\n !res\n\nlet fenwick_count2 ft m n =\n fenwick_count ft n - fenwick_count ft (m - 1)\n\nlet _ =\n let sb = Scanf.Scanning.stdib in\n let h = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make h (-1) in\n let b = Array.make (2 * h) (-1) in\n let c = Array.make h (-1) in\n let g = gcd m h in\n let () =\n let pos = ref 0 in\n for i = 0 to h - 1 do\n\tif c.(i) < 0 then (\n\t for j = 0 to h / g - 1 do\n\t c.((i + j * m) mod h) <- !pos;\n\t b.(!pos) <- (i + j * m) mod h;\n\t b.(!pos + h / g) <- (i + j * m) mod h;\n\t incr pos\n\t done;\n\t pos := !pos + h / g;\n\t)\n done\n in\n let ft = fenwick_new (2 * h) in\n let ht = Hashtbl.create h in\n let res = ref 0 in\n for i = 0 to n - 1 do\n let op = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\tmatch op with\n\t | \"+\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let l = ref (c.(hash) - 1) in\n\t let r = ref (c.(hash) + h / g) in\n\t\twhile !l < !r - 1 do\n\t\t let m = (!l + !r) / 2 in\n(*Printf.printf \"step %d %d %d %d\\n\" !l !r m (fenwick_count2 ft c.(hash) m);*)\n\t\t if fenwick_count2 ft c.(hash) m < m + 1 - c.(hash)\n\t\t then r := m\n\t\t else l := m\n\t\tdone;\n\t\tres := !res + !r - c.(hash);\n\t\tlet hash = b.(!r) in\n(*Printf.printf \"add %d %d %d %d\\n\" id hash !l !r;*)\n\t\t(*while a.(!j) >= 0 do\n\t\t j := (!j + m) mod h;\n\t\t incr res;\n\t\tdone;*)\n\t\t Hashtbl.replace ht id hash;\n\t\t a.(hash) <- id;\n\t\t fenwick_modify ft !r 1;\n\t\t fenwick_modify ft (!r + h / g) 1;\n\t | \"-\" ->\n\t let id = Scanf.bscanf sb \"%d \" (fun s -> s) in\n\t let hash = Hashtbl.find ht id in\n\t\tHashtbl.remove ht id;\n\t\ta.(hash) <- -1;\n\t\tfenwick_modify ft c.(hash) (-1);\n\t\tfenwick_modify ft (c.(hash) + h / g) (-1);\n\t | _ -> assert false\n done;\n Printf.printf \"%d\\n\" !res;\n"}], "src_uid": "7bf9c0e67312a7768ae89c42edb4a2de"} {"nl": {"description": "There's a chip in the point $$$(0, 0)$$$ of the coordinate plane. In one operation, you can move the chip from some point $$$(x_1, y_1)$$$ to some point $$$(x_2, y_2)$$$ if the Euclidean distance between these two points is an integer (i.e. $$$\\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$$$ is integer).Your task is to determine the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 3000$$$)\u00a0\u2014 number of test cases. The single line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \\le x, y \\le 50$$$)\u00a0\u2014 the coordinates of the destination point.", "output_spec": "For each test case, print one integer\u00a0\u2014 the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.", "sample_inputs": ["3\n8 6\n0 0\n9 15"], "sample_outputs": ["1\n0\n2"], "notes": "NoteIn the first example, one operation $$$(0, 0) \\rightarrow (8, 6)$$$ is enough. $$$\\sqrt{(0-8)^2+(0-6)^2}=\\sqrt{64+36}=\\sqrt{100}=10$$$ is an integer.In the second example, the chip is already at the destination point.In the third example, the chip can be moved as follows: $$$(0, 0) \\rightarrow (5, 12) \\rightarrow (9, 15)$$$. $$$\\sqrt{(0-5)^2+(0-12)^2}=\\sqrt{25+144}=\\sqrt{169}=13$$$ and $$$\\sqrt{(5-9)^2+(12-15)^2}=\\sqrt{16+9}=\\sqrt{25}=5$$$ are integers."}, "positive_code": [{"source_code": "let distance a b = let x1,y1 = a in\r\n let x2,y2 = b in (sqrt ((float_of_int (x2-x1))**2. +. (float_of_int (y2-y1))**2.))\r\n;;\r\n\r\nlet fisi x = match float_of_int(int_of_float x) with\r\n |r when r = x -> true\r\n |_ -> false\r\n;;\r\n\r\nlet n = int_of_string (input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let x , y = Scanf.sscanf (input_line stdin) \"%d %d\" (fun x y -> (x,y)) in\r\n let rep = match distance (0,0) (x,y) with \r\n |0. -> 0\r\n |r when fisi r -> 1\r\n |_ -> 2 \r\n in print_endline (string_of_int rep)\r\ndone ;\r\n;;\r\n \r\n"}], "negative_code": [], "src_uid": "fce6d690c2790951f7e04c622c3c2d44"} {"nl": {"description": "Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi,\u20091,\u2009xi,\u20092,\u2009...,\u2009xi,\u2009ki. He remembers n such strings ti.You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 the number of strings Ivan remembers. The next n lines contain information about the strings. The i-th of these lines contains non-empty string ti, then positive integer ki, which equal to the number of times the string ti occurs in string s, and then ki distinct positive integers xi,\u20091,\u2009xi,\u20092,\u2009...,\u2009xi,\u2009ki in increasing order \u2014 positions, in which occurrences of the string ti in the string s start. It is guaranteed that the sum of lengths of strings ti doesn't exceed 106, 1\u2009\u2264\u2009xi,\u2009j\u2009\u2264\u2009106, 1\u2009\u2264\u2009ki\u2009\u2264\u2009106, and the sum of all ki doesn't exceed 106. The strings ti can coincide. It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists.", "output_spec": "Print lexicographically minimal string that fits all the information Ivan remembers. ", "sample_inputs": ["3\na 4 1 3 5 7\nab 2 1 5\nca 1 4", "1\na 1 3", "3\nab 1 1\naba 1 3\nab 2 3 5"], "sample_outputs": ["abacaba", "aaa", "ababab"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nmodule Pset = Set.Make (struct type t = int*int let compare = compare end)\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n\n let t = Array.make n \"\" in\n let tlen = Array.make n 0 in\n let x = Array.make n [||] in\n\n let last_index = ref 0 in\n \n for i=0 to n-1 do\n t.(i) <- read_string();\n tlen.(i) <- String.length t.(i);\n let k = read_int() in\n x.(i) <- Array.init k read_int;\n last_index := max !last_index (x.(i).(k-1) + tlen.(i) - 1)\n done;\n\n let m = !last_index + 2 in\n\n let st_list = Array.make m [] in\n\n for i=0 to n-1 do\n let k = Array.length x.(i) in\n for j=0 to k-1 do\n let st = x.(i).(j) in\n st_list.(st) <- (i,st)::(st_list.(st));\n done\n done;\n\n let rec loop pos set = if pos > !last_index then () else\n (* process the events at position pos (boundary) then\n\t figure out what is in that box *)\n let set = List.rev_append st_list.(pos) set in\n let rec pop_loop set =\n\tmatch set with [] -> []\n\t | (ind,st)::tail -> if tlen.(ind) + st > pos then set else pop_loop tail\n in\n let set = pop_loop set in\n let ch = if set = [] then 'a'\n\telse let (i,ind) = List.hd set in t.(i).[pos-ind]\n in\n printf \"%c\" ch;\n loop (pos+1) set\n in\n\n loop 1 [];\n\n print_newline()\n"}], "negative_code": [], "src_uid": "d66e55ac7fa8a7b57ccd57d9242fd2a2"} {"nl": {"description": "There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team\u2019s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person\u2019s teammate?", "input_spec": "There are 2n lines in the input. The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009400) \u2014 the number of teams to be formed. The i-th line (i\u2009>\u20091) contains i\u2009-\u20091 numbers ai1, ai2, ... , ai(i\u2009-\u20091). Here aij (1\u2009\u2264\u2009aij\u2009\u2264\u2009106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)", "output_spec": "Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.", "sample_inputs": ["2\n6\n1 2\n3 4 5", "3\n487060\n3831 161856\n845957 794650 976977\n83847 50566 691206 498447\n698377 156232 59015 382455 626960"], "sample_outputs": ["2 1 4 3", "6 5 4 3 2 1"], "notes": "NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively."}, "positive_code": [{"source_code": "type heap =\n\t | E\n\t | N of (int * (int * int)) * heap * heap;;\n\nlet rec add x = function\n\t| E\t\t-> N(x,E,E)\n\t| N(a,l,r)\t-> if x > a\n\t\t\t\tthen N(x,r, add a l)\n\t\t\t\telse N(a,r, add x l);;\n\nlet is_empty = function\n\t| E\t-> true\n\t| _\t-> false;;\n\nlet root (N(a,_,_)) = a;;\n\nlet rec supp = function\n\t| E\t\t-> E\n\t| N(_,E,E)\t-> E\n\t| N(_,E,r)\t-> let x = root r in\n\t\t\t\tN(x,E,supp r)\n\t| N(_,l,E)\t-> let x = root l in\n\t\t\t\tN(x,supp l,E)\n\t| N(_,l,r)\t-> let [a;b] = List.map root [l;r] in\n\t\t\t\tif a > b\n\t\t\t\t\tthen N(a,r, supp l)\n\t\t\t\t\telse N(b,supp r,l);;\n\nlet main () =\t\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) in\n\tlet tas = ref E and tab = Array.make (2*n + 1) (-1) in\n\t\tfor i=2 to 2*n do\n\t\t\tfor j=1 to i-1 do\n\t\t\t\tScanf.scanf \" %d\" (fun k -> tas := add (k,(i,j)) !tas);\n\t\t\tdone;\n\t\tdone;\n\twhile not (is_empty !tas) do\n\t\tlet (_,(b,c)) = root !tas in\n\t\t\ttas := supp !tas;\n\t\t\tif tab.(b) = -1 && tab.(c) = -1\n\t\t\t\tthen begin\n\t\t\t\t\ttab.(b) <- c;\n\t\t\t\t\ttab.(c) <- b;\n\t\t\t\t end;\n\tdone;\n\tfor i=1 to 2*n do\n\t\tPrintf.printf \"%d \" (tab.(i));\n\tdone;;\n\nmain ();;\n\t\n"}], "negative_code": [], "src_uid": "8051385dab9d7286f54fd332c64e836e"} {"nl": {"description": "Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?", "input_spec": "The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 100$$$)\u00a0\u2014 the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \\le r \\le 100$$$)\u00a0\u2014 the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive,\u00a0\u2014 the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.", "output_spec": "Print all tram lines that Arkady could be in, in arbitrary order.", "sample_inputs": ["3\n3 1 4 6\n2 1 4\n5 10 5 6 4 1", "5\n1 1\n10 10 9 8 7 100 5 4 3 99 1\n5 1 2 3 4 5\n5 4 1 3 2 5\n4 10 1 5 3"], "sample_outputs": ["1 4", "1"], "notes": "NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule Lib = struct\n let i32,i64,ist = Int64.(to_int,of_int,to_string)\n let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)\n let labs = Int64.abs\n let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)\n let (+=) r v = r := !r + v\n let (-=) r v = r := !r - v\n let ( *= ) r v = r := !r * v\n let (/=) r v = r := !r / v\n let (%=) r v = r := !r % v\n let max_i64,min_i64 = Int64.(max_int,min_int)\n (* math *)\n let ceildiv p q = (p+q-1L) / q\n let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)\n let lcm m n = m / gcd m n * n\n module I64_infix = struct\n let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =\n let open Int64 in\n (logand),(logor),(logxor),lognot,\n (fun u v -> shift_left u (i32 v)),\n (fun u v -> shift_right u (i32 v)),\n (fun u v -> shift_right_logical u (i32 v))\n end\n (* input *)\n let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v))\n let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v)\n let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v)\n let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w)\n let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x)\n let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y)\n let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y)\n (* utils *)\n external id : 'a -> 'a = \"%identity\"\n let ( *< ) f g x = f (g x)\n let ( *> ) f g x = g (f x)\n let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)\n let alen a = i64 @@ Array.length a\n let llen l = i64 @@ List.length l\n let string_of_list ?(separator=\" \") f ls = ls |> List.map f |> String.concat separator\n let string_of_array ?(separator=\" \") f a = a |> Array.to_list |> string_of_list ~separator f\n let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []\n let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n let fail _ = failwith \"fail\"\n let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]\n let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev\n let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten\n let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a\n let binary_search ng ok f = let d = if ng < ok then 1L else -1L in\n let rec f0 ng ok =\n if labs (ok - ng) <= 1L then ok\n else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok\n in f0 (ng-1L*d) (ok+1L*d)\n let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)\n let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) > v)\n let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)\n let rec fix f x = f (fix f) x\n let fix_memo ?(size=10000) f x =\n let tb = Hashtbl.create ~random:true size in\n let rec f0 x =\n try Hashtbl.find tb x with\n | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)\n in f0 x\n (* imperative *)\n let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done\n let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done\n let repm f t ?(stride=1L) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m\n let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done\n let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do\n match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done\n let repim f t ?(stride=1) m0 fbod =\n let i,c,m = ref f,ref true,ref m0 in\n while !i<=t && !c do match fbod !m !i with\n | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m\n let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v\n let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v\n let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v\n let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v\n let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v\n (* output *)\n let print_list_mle f ls = string_of_list f ls |> print_endline\n let print_array_mle f a = string_of_array f a |> print_endline\n let print_list f ls = ls |> List.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n let print_array f a = a |> Array.iter (fun v -> printf \"%s \" @@ f v); print_newline ()\n (* debug *)\n let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)\n let dump_i64_list ls = print_list ist ls\n let dump_i64_array a = print_array ist a\nend open Lib open Array\n\nmodule IMap = Map.Make(Int64)\nlet () =\n let n = get_i64 0 in\n let mp = ref @@ IMap.empty in\n rep 1L n (fun _ ->\n let k = get_i64 0 in\n let a = input_i64_array k in\n iter (fun v ->\n mp := IMap.add v (1L + try IMap.find v !mp with _ -> 0L) !mp\n ) a\n );\n IMap.iter (fun v c ->\n (* printf \"%2Ld: %2Ld\\n\" v c *)\n if c>=n then printf \"%Ld \" v\n ) !mp\n\n\n\n\n\n\n\n\n"}], "negative_code": [], "src_uid": "16c54cf7d8b484b5e22a7d391fdc5cd3"} {"nl": {"description": "There are $$$n$$$ people who want to participate in a boat competition. The weight of the $$$i$$$-th participant is $$$w_i$$$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are $$$k$$$ teams $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, $$$\\dots$$$, $$$(a_k, b_k)$$$, where $$$a_i$$$ is the weight of the first participant of the $$$i$$$-th team and $$$b_i$$$ is the weight of the second participant of the $$$i$$$-th team, then the condition $$$a_1 + b_1 = a_2 + b_2 = \\dots = a_k + b_k = s$$$, where $$$s$$$ is the total weight of each team, should be satisfied.Your task is to choose such $$$s$$$ that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 50$$$) \u2014 the number of participants. The second line of the test case contains $$$n$$$ integers $$$w_1, w_2, \\dots, w_n$$$ ($$$1 \\le w_i \\le n$$$), where $$$w_i$$$ is the weight of the $$$i$$$-th participant.", "output_spec": "For each test case, print one integer $$$k$$$: the maximum number of teams people can compose with the total weight $$$s$$$, if you choose $$$s$$$ optimally.", "sample_inputs": ["5\n5\n1 2 3 4 5\n8\n6 6 6 6 6 6 8 8\n8\n1 2 2 1 2 1 1 2\n3\n1 3 3\n6\n1 1 3 4 2 2"], "sample_outputs": ["2\n3\n4\n1\n2"], "notes": "NoteIn the first test case of the example, we can reach the optimal answer for $$$s=6$$$. Then the first boat is used by participants $$$1$$$ and $$$5$$$ and the second boat is used by participants $$$2$$$ and $$$4$$$ (indices are the same as weights).In the second test case of the example, we can reach the optimal answer for $$$s=12$$$. Then first $$$6$$$ participants can form $$$3$$$ pairs.In the third test case of the example, we can reach the optimal answer for $$$s=3$$$. The answer is $$$4$$$ because we have $$$4$$$ participants with weight $$$1$$$ and $$$4$$$ participants with weight $$$2$$$.In the fourth test case of the example, we can reach the optimal answer for $$$s=4$$$ or $$$s=6$$$.In the fifth test case of the example, we can reach the optimal answer for $$$s=3$$$. Note that participant with weight $$$3$$$ can't use the boat because there is no suitable pair for him in the list."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\n\nlet get_answer x people = \n let n = Array.length people in\n let pair = Hashtbl.create n in\n let answer = Array.make 1 0 in\n \n let up id =\n let now = Array.make 1 0 in\n if Hashtbl.mem pair id then (\n let value = Hashtbl.find pair id in\n now.(0) <- value;\n );\n Hashtbl.add pair id (now.(0) + 1);\n in\n \n for i = 0 to n - 1 do\n let person = people.(i) in\n if Hashtbl.mem pair (x - person) then (\n let cnt = Hashtbl.find pair (x - person) in\n if cnt > 0 then (\n answer.(0) <- (answer.(0) + 1);\n Hashtbl.add pair (x - person) (cnt - 1);\n ) else (\n up person;\n )\n ) else (\n up person;\n )\n done;\n answer.(0)\n\nlet solve() =\n let n = read_int() in\n let arr = Array.init n read_int in\n let answer = Array.make 1 0 in\n for i = 2 to 100 do\n answer.(0) <- (max answer.(0) (get_answer i arr))\n done;\n printf \"%d\\n\" answer.(0)\n\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done\n\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \"%d \" (fun x -> x)\n\nlet get_answer x people = \n let n = Array.length people in\n let pair = Hashtbl.create n in\n let answer = Array.make 1 0 in\n \n let up id =\n let now = Array.make 1 0 in\n if Hashtbl.mem pair id then (\n let value = Hashtbl.find pair id in\n now.(0) <- value;\n );\n Hashtbl.add pair id (now.(0) + 1);\n in\n \n for i = 0 to n - 1 do\n let person = people.(i) in\n if Hashtbl.mem pair (x - person) then (\n let cnt = Hashtbl.find pair (x - person) in\n if cnt > 0 then (\n answer.(0) <- (answer.(0) + 1);\n Hashtbl.add pair (x - person) (cnt - 1);\n ) else (\n up person;\n )\n ) else (\n up person;\n )\n done;\n answer.(0)\n\nlet solve() =\n let n = read_int() in\n let arr = Array.init n read_int in\n let answer = Array.make 1 0 in\n for i = 2 to 15 do\n answer.(0) <- (max answer.(0) (get_answer i arr))\n done;\n printf \"%d\\n\" answer.(0)\n\n\nlet () = \n let cases = read_int() in\n for case = 1 to cases do\n solve()\n done\n\n"}], "src_uid": "0048623eeb27c6f7c6900d8b6e620f19"} {"nl": {"description": "As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest.The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.).Gennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the i-th problem will take ai minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the i-th problem always equals ai minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.).Help Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of the problems. The next line contains n space-separated integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009720) \u2014 each number shows how much time in minutes Gennady will spend writing a solution to the problem.", "output_spec": "Print two integers \u2014 the number of problems Gennady will solve and the total penalty time considering that he chooses the optimal strategy.", "sample_inputs": ["3\n30 330 720"], "sample_outputs": ["2 10"], "notes": "NoteIn the sample, one of Gennady's possible optimal strategies is as follows. At 18:10 (6:10 PM) he begins to write the first problem and solves it in 30 minutes (18:40 or 6.40 P.M.). At 18:40 (6.40 P.M.) he begins to write the second problem. There are 320 minutes left before the New Year, so Gennady does not have the time to finish writing the second problem before the New Year. At 0:00 (12.00 A.M.) he distracts from the second problem, submits the first one, and returns immediately to writing the second problem. At 0:10 (0.10 A.M.), he completes the solution for the second problem, submits it and gets 10 minute penalty time. Note that as the total duration of the contest is 720 minutes and Gennady has already spent 10 minutes on reading the problems, he will not have time to solve the third problem during the contest. Yes, such problems happen to exist.Competitions by the given rules are held annually on the site http://b23.ru/3wvc"}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a\n in\n let res = ref 0 in\n let penalty = ref 0 in\n let t = ref 0 in\n let t1 = 350\n and t2 = 710 in\n for i = 0 to n - 1 do\n t := !t + a.(i);\n if !t <= t1\n then incr res\n else if !t <= t2 then (\n\tincr res;\n\tpenalty := !penalty + !t - t1;\n )\n done;\n Printf.printf \"%d %d\\n\" !res !penalty\n"}], "negative_code": [], "src_uid": "76f94436b4388682b25c7213248b76a2"} {"nl": {"description": "One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.", "input_spec": "The first line contains two space-separated integers n and k (1\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n space-separated integers: a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105) \u2014 the sequence that the shooshuns found.", "output_spec": "Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.", "sample_inputs": ["3 2\n3 1 1", "3 1\n3 1 1"], "sample_outputs": ["1", "-1"], "notes": "NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1."}, "positive_code": [{"source_code": "open Scanf\nopen Str\n\nlet (|>) x f = f x \n\nlet regexp_spc = regexp \" \"\n\n\nlet _ =\n let n :: k_ :: _ = () |> read_line |> (split regexp_spc) |> List.map int_of_string in\n let k = k_ - 1 in\n let a = () |> read_line |> (split regexp_spc) |> List.map int_of_string |> Array.of_list in\n let isok = ref true in \n let md = ref (-1) in\n for i = 0 to n-1 do\n if a.(i) <> a.(k) then md := i else ();\n if i > k & a.(i) <> a.(k) then isok := false else ();\n done;\n\n let ans = if !isok then !md + 1 else -1 in\n ans |> string_of_int |> print_endline\n\n"}], "negative_code": [{"source_code": "open Scanf\nopen Str\n\nlet (|>) x f = f x \n\nlet regexp_spc = regexp \" \"\n\n\nlet _ =\n let n :: k_ :: _ = () |> read_line |> (split regexp_spc) |> List.map int_of_string in\n let k = k_ - 1 in\n let a = () |> read_line |> (split regexp_spc) |> List.map int_of_string |> Array.of_list in\n let isok = ref true in \n let md = ref 0 in\n for i = 0 to n-1 do\n if a.(i) <> a.(k) then md := i else ();\n if i > k & a.(i) <> a.(k) then isok := false else ();\n done;\n\n let ans = if !isok then !md + 1 else -1 in\n ans |> string_of_int |> print_endline\n\n"}], "src_uid": "bcee233ddb1509a14f2bd9fd5ec58798"} {"nl": {"description": "Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster.There are $$$n$$$ books in the family library. The $$$i$$$-th book is described by three integers: $$$t_i$$$ \u2014 the amount of time Alice and Bob need to spend to read it, $$$a_i$$$ (equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ if not), and $$$b_i$$$ (equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ if not).So they need to choose some books from the given $$$n$$$ books in such a way that: Alice likes at least $$$k$$$ books from the chosen set and Bob likes at least $$$k$$$ books from the chosen set; the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $$$t_i$$$ over all books that are in the chosen set.Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.", "input_spec": "The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \\le k \\le n \\le 2 \\cdot 10^5$$$). The next $$$n$$$ lines contain descriptions of books, one description per line: the $$$i$$$-th line contains three integers $$$t_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \\le t_i \\le 10^4$$$, $$$0 \\le a_i, b_i \\le 1$$$), where: $$$t_i$$$ \u2014 the amount of time required for reading the $$$i$$$-th book; $$$a_i$$$ equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ otherwise; $$$b_i$$$ equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ otherwise. ", "output_spec": "If there is no solution, print only one integer -1. Otherwise print one integer $$$T$$$ \u2014 the minimum total reading time of the suitable set of books.", "sample_inputs": ["8 4\n7 1 1\n2 1 1\n4 0 1\n8 1 1\n1 0 1\n1 1 1\n1 0 1\n3 0 0", "5 2\n6 0 0\n9 0 0\n1 0 1\n2 1 1\n5 1 0", "5 3\n3 0 0\n2 1 0\n3 1 0\n5 0 1\n3 0 1"], "sample_outputs": ["18", "8", "-1"], "notes": null}, "positive_code": [{"source_code": "module A = Array\nmodule C = Char\nmodule I = Int64\nmodule L = List\nmodule Q = Queue\nmodule S = String\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet ssf = Scanf.sscanf\n\nlet l_init n f =\n let rec loop acc i =\n if i >= n then acc else loop ((f i) :: acc) (i+1)\n in List.rev (loop [] 0)\n\nlet read_int () = sf \"%d \" (fun x -> x)\nlet read_int64 () = sf \"%Ld \" (fun x -> x)\nlet read_float () = sf \"%f \" (fun x -> x)\nlet read_list read n = l_init n (fun _ -> read ())\nlet read_array read n = A.init n (fun _ -> read ())\nlet err s = raise (Failure s)\n\nlet l_take_opt n l =\n let rec loop acc i = function\n | _ when i = n -> Some (L.rev acc)\n | hd::tl -> loop (hd::acc) (succ i) tl\n | [] -> None\n in loop [] 0 l\n\nlet inf = int_of_float 1e18\nlet eps = 1e-11\n\nlet map2_min f l1 l2 =\n let rec loop acc = function\n | (_, []) | ([], _) -> acc\n | (a1::l1, a2::l2) -> loop ((f a1 a2)::acc) (l1, l2)\n in loop [] (l1, l2)\n\nlet read_book () =\n let t = read_int64() in\n let a = read_int() in\n let b = read_int() in\n (t, a, b)\n\nlet partition books =\n let rec loop common_ts alice_ts bob_ts = function\n | [] -> common_ts, alice_ts, bob_ts\n | (t, a, b)::tl when a = 1 && b = 1 -> loop (t::common_ts) alice_ts bob_ts tl\n | (t, a, b)::tl when a = 1 -> loop common_ts (t::alice_ts) bob_ts tl\n | (t, a, b)::tl when b = 1 -> loop common_ts alice_ts (t::bob_ts) tl\n | _ -> assert false\n in loop [] [] [] books\n\nlet ranked_times (ts, a_ts, b_ts) =\n map2_min I.add (L.sort I.compare a_ts) (L.sort I.compare b_ts)\n |> L.append ts\n |> L.sort I.compare\n\nlet solve k ts =\n match l_take_opt k ts with\n | None -> -1L\n | Some selection -> L.fold_left I.add 0L selection\n\nlet () =\n let rec loop () =\n try let n = read_int() in\n let k = read_int() in\n (read_list read_book n)\n |> L.filter (fun (_, a, b) -> (a != 0) || (b != 0))\n |> partition\n |> ranked_times\n |> solve k\n |> pf \"%Ld\\n\";\n loop ()\n with End_of_file -> ()\n in loop ()\n"}], "negative_code": [{"source_code": "module A = Array\nmodule C = Char\nmodule I = Int64\nmodule L = List\nmodule Q = Queue\nmodule S = String\n\nlet pf = Printf.printf\nlet sf = Scanf.scanf\nlet ssf = Scanf.sscanf\n\nlet l_init n f =\n let rec loop acc i =\n if i >= n then acc else loop ((f i) :: acc) (i+1)\n in List.rev (loop [] 0)\n\nlet read_int () = sf \"%d \" (fun x -> x)\nlet read_int64 () = sf \"%ld \" (fun x -> x)\nlet read_float () = sf \"%f \" (fun x -> x)\nlet read_list read n = l_init n (fun _ -> read ())\nlet read_array read n = A.init n (fun _ -> read ())\nlet err s = raise (Failure s)\n\nlet l_take_opt n l =\n let rec loop acc i = function\n | _ when i = n -> Some (L.rev acc)\n | hd::tl -> loop (hd::acc) (succ i) tl\n | [] -> None\n in loop [] 0 l\n\nlet inf = int_of_float 1e18\nlet eps = 1e-11\n\nlet map2_min f l1 l2 =\n let rec loop acc = function\n | (_, []) | ([], _) -> acc\n | (a1::l1, a2::l2) -> loop ((f a1 a2)::acc) (l1, l2)\n in loop [] (l1, l2)\n\nlet read_book () =\n let t = read_int() in\n let a = read_int() in\n let b = read_int() in\n (t, a, b)\n\nlet partition books =\n let rec loop common_ts alice_ts bob_ts = function\n | [] -> common_ts, alice_ts, bob_ts\n | (t, a, b)::tl when a = 1 && b = 1 -> loop (t::common_ts) alice_ts bob_ts tl\n | (t, a, b)::tl when a = 1 -> loop common_ts (t::alice_ts) bob_ts tl\n | (t, a, b)::tl when b = 1 -> loop common_ts alice_ts (t::bob_ts) tl\n | _ -> assert false\n in loop [] [] [] books\n\nlet ranked_times (ts, a_ts, b_ts) =\n map2_min (fun i j -> i + j) (L.sort compare a_ts) (L.sort compare b_ts)\n |> L.append ts\n |> L.sort compare\n\nlet solve k ts =\n match l_take_opt k ts with\n | None -> -1\n | Some selection -> L.fold_left (fun i j -> i + j) 0 selection\n\nlet () =\n let rec loop () =\n try let n = read_int() in\n let k = read_int() in\n (read_list read_book n)\n |> L.filter (fun (_, a, b) -> (a != 0) || (b != 0))\n |> partition\n |> ranked_times\n |> solve k\n |> pf \"%d\\n\";\n loop ()\n with End_of_file -> ()\n in loop ()\n"}], "src_uid": "6a80b2af22cf8e5bb01ff47d257db196"} {"nl": {"description": "A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with \"#\". As this operation is pretty expensive, you should find the minimum number of characters to replace with \"#\", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.", "input_spec": "The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100\u2009000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.", "output_spec": "Print the minimum number of characters that must be replaced with \"#\" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.", "sample_inputs": ["intellect\ntell", "google\napple", "sirisiri\nsir"], "sample_outputs": ["1", "0", "2"], "notes": "NoteIn the first sample AI's name may be replaced with \"int#llect\".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be \"s#ris#ri\"."}, "positive_code": [{"source_code": "(* started at 8:08 *)\n\nopen Printf\nopen Scanf\n\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let text = read_string () in\n let pat = read_string () in\n\n let n = String.length text in\n let m = String.length pat in\n\n let answer = \n if m > n then 0 else\n let rec loop c i = if i+m-1 > n-1 then c else\n\t let e = String.sub text i m in\n\t if pat = e then loop (c+1) (i+m) else loop c (i+1)\n in\n loop 0 0\n in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "62a672fcaee8be282700176803c623a7"} {"nl": {"description": "Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1,\u2009l2,\u2009...,\u2009lm (1\u2009\u2264\u2009li\u2009\u2264\u2009n). For each number li he wants to know how many distinct numbers are staying on the positions li, li\u2009+\u20091, ..., n. Formally, he want to find the number of distinct numbers among ali,\u2009ali\u2009+\u20091,\u2009...,\u2009an.?Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each li.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105). The second line contains n integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009105) \u2014 the array elements. Next m lines contain integers l1,\u2009l2,\u2009...,\u2009lm. The i-th line contains integer li (1\u2009\u2264\u2009li\u2009\u2264\u2009n).", "output_spec": "Print m lines \u2014 on the i-th line print the answer to the number li.", "sample_inputs": ["10 10\n1 2 3 4 1 2 3 4 100000 99999\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10"], "sample_outputs": ["6\n6\n6\n6\n6\n5\n4\n3\n2\n1"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n\tlet n = read_int ()\n\tand m = read_int () in\n\tlet a = Array.init n read_int in\n\n\tlet vis = Array.make 100001 false\n\tand suf = Array.make (n + 1) 0 in\n\n\tfor i = n - 1 downto 0 do\n\t\tlet x = a.(i) in\n\t\tsuf.(i) <- suf.(i + 1);\n\t\tif not vis.(x) then suf.(i) <- suf.(i) + 1;\n\t\tvis.(x) <- true\n\tdone;\n\tfor i = 1 to m do\n\t\tlet l = read_int () in\n\t\tprintf \"%d\\n\" suf.(l - 1)\n\tdone"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x) in\n\nlet n = read_int() and m = read_int() in\nlet a = Array.init n (fun _ -> read_int()) in\nlet e = Array.init 100001 (fun _ -> false) in\nlet b = Array.make n 0 in\n\nb.(n-1) <- 1;\ne.(a.(n-1)) <- true;\n\nfor i = n-2 downto 0 do\n b.(i) <- b.(i+1);\n if not e.(a.(i)) then\n begin\n e.(a.(i)) <- true;\n b.(i) <- b.(i) + 1;\n end\ndone;\n\nfor i = 1 to m do\n let l = read_int() in\n Printf.printf \"%d\\n\" b.(l-1);\ndone;"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\\n\" x;;\n\nlet () =\n let n = read_int() in\n let m = read_int() in\n let a = Array.init n read_int in\n let dp = Array.make n 0 in\n let check = Array.make 100000 0 in\n check.(a.(n-1) - 1) <- 1;\n dp.(n-1) <- 1; \n let rec loop = function \n | k -> (if check.(a.(k)-1) = 0 \n then\n (check.(a.(k)-1) <- 1;\n dp.(k) <- dp.(k+1) + 1)\n else \n dp.(k) <- dp.(k+1));\n if k > 0 then loop (k-1);\n in\n let rec loop2 = function\n | k when k = m -> ()\n | k -> let t = read_int 0 in \n print_int dp.(t-1); loop2 (k+1) in \n if n > 1 then loop (n-2);\n loop2 0;;\n"}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n\tlet n = read_int ()\n\tand m = read_int () in\n\n\tlet tab = Array.make n 0\n\tand uzyte = Array.make 100007 false \n\tand dp = Array.make (n + 1) 0 in\n\n\tfor i = 0 to n - 1 do\n\t\ttab.(i) <- read_int ()\n\tdone;\n\n\tfor i = n - 1 downto 0 do \n\t\tif uzyte.(tab.(i)) = false then\n\t\t\tdp.(i) <- dp.(i + 1) + 1\n\t\telse\n\t\t\tdp.(i) <- dp.(i + 1);\n\n\t\tuzyte.(tab.(i)) <- true;\n\tdone;\n\n\tfor i = 1 to m do\n\t\tlet a = read_int () in\n\t\tprintf \"%d\\n\" dp.(a - 1);\n\tdone;"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet list_init n f =\n let rec loop i list = \n if i < n\n then\n let element = f(i) in\n loop (i + 1) (element :: list)\n else\n List.rev list\n in loop 0 []\n\nlet input () = \n let n = read () in\n let m = read () in\n let arr = Array.init n (fun n -> read ()) in\n let list = list_init m (fun n -> read ()) in\n (n, arr, list)\n\nlet count_duplicates n arr = \n let seen = Array.make 100001 0 in\n let dup_count = Array.make n 0 in \n let rec loop i count = \n if i >= 0\n then\n let a = arr.(i) in\n if seen.(a) = 0\n then\n (seen.(a) <- 1;\n dup_count.(i) <- count;\n loop (i - 1) count)\n else\n (dup_count.(i) <- count + 1;\n loop (i - 1) (count + 1))\n else\n dup_count\n in loop (n - 1) 0\n\nlet count_uniques arr i n list = \n let a = n - i - arr.(i) in\n (a :: list)\n\nlet solve (n, arr, list) = \n let dups = count_duplicates n arr in\n let rec loop rest uniqs = \n match rest with\n | (i :: tl) -> loop tl (count_uniques dups (i - 1) n uniqs)\n | [] -> List.rev uniqs\n in loop list []\n\nlet print list = List.iter (Printf.printf \"%d\\n\") list\n\nlet () = print (solve (input ()))\n"}, {"source_code": "let read () = Scanf.scanf \"%d \" (fun n -> n)\n\nlet list_init n f =\n let rec loop i list = \n if i < n\n then\n let element = f(i) in\n loop (i + 1) (element :: list)\n else\n List.rev list\n in loop 0 []\n\nlet input () = \n let n = read () in\n let m = read () in\n let arr = Array.init n (fun n -> read ()) in\n let list = list_init m (fun n -> read ()) in\n (n, arr, list)\n\nlet count_uniqs n arr = \n let seen = Array.make 100001 0 in\n let uniq_count = Array.make n 0 in \n let rec loop i count = \n if i >= 0\n then\n let a = arr.(i) in\n if seen.(a) = 0\n then\n (seen.(a) <- 1;\n uniq_count.(i) <- count + 1;\n loop (i - 1) (count + 1))\n else\n (uniq_count.(i) <- count;\n loop (i - 1) count)\n else\n uniq_count\n in loop (n - 1) 0\n\nlet solve (n, arr, list) = \n let uniqs = count_uniqs n arr in\n List.map (fun i -> uniqs.(i - 1)) list\n\nlet print list = List.iter (Printf.printf \"%d\\n\") list\n\nlet () = print (solve (input ()))\n"}], "negative_code": [], "src_uid": "1e156dfc65ef88f19ca1833f75192259"} {"nl": {"description": "A picture can be represented as an $$$n\\times m$$$ grid ($$$n$$$ rows and $$$m$$$ columns) so that each of the $$$n \\cdot m$$$ cells is colored with one color. You have $$$k$$$ pigments of different colors. You have a limited amount of each pigment, more precisely you can color at most $$$a_i$$$ cells with the $$$i$$$-th pigment.A picture is considered beautiful if each cell has at least $$$3$$$ toroidal neighbors with the same color as itself.Two cells are considered toroidal neighbors if they toroidally share an edge. In other words, for some integers $$$1 \\leq x_1,x_2 \\leq n$$$ and $$$1 \\leq y_1,y_2 \\leq m$$$, the cell in the $$$x_1$$$-th row and $$$y_1$$$-th column is a toroidal neighbor of the cell in the $$$x_2$$$-th row and $$$y_2$$$-th column if one of following two conditions holds: $$$x_1-x_2 \\equiv \\pm1 \\pmod{n}$$$ and $$$y_1=y_2$$$, or $$$y_1-y_2 \\equiv \\pm1 \\pmod{m}$$$ and $$$x_1=x_2$$$. Notice that each cell has exactly $$$4$$$ toroidal neighbors. For example, if $$$n=3$$$ and $$$m=4$$$, the toroidal neighbors of the cell $$$(1, 2)$$$ (the cell on the first row and second column) are: $$$(3, 2)$$$, $$$(2, 2)$$$, $$$(1, 3)$$$, $$$(1, 1)$$$. They are shown in gray on the image below: The gray cells show toroidal neighbors of $$$(1, 2)$$$. Is it possible to color all cells with the pigments provided and create a beautiful picture?", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$). The description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$3 \\leq n,m \\leq 10^9$$$, $$$1 \\leq k \\leq 10^5$$$) \u2014 the number of rows and columns of the picture and the number of pigments. The next line contains $$$k$$$ integers $$$a_1,a_2,\\dots, a_k$$$ ($$$1 \\leq a_i \\leq 10^9$$$) \u2014 $$$a_i$$$ is the maximum number of cells that can be colored with the $$$i$$$-th pigment. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print \"Yes\" (without quotes) if it is possible to color a beautiful picture. Otherwise, print \"No\" (without quotes).", "sample_inputs": ["6\n\n4 6 3\n\n12 9 8\n\n3 3 2\n\n8 8\n\n3 3 2\n\n9 5\n\n4 5 2\n\n10 11\n\n5 4 2\n\n9 11\n\n10 10 3\n\n11 45 14"], "sample_outputs": ["Yes\nNo\nYes\nYes\nNo\nNo"], "notes": "NoteIn the first test case, one possible solution is as follows: In the third test case, we can color all cells with pigment $$$1$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\nlet sum i j f = fold i j (fun i a -> (long (f i)) ++ a) 0L\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let k = read_int() in\n let a = Array.init k read_int in\n\n let possible n m =\n let col c = a.(c)/n in (* number of columns filable by this color *)\n let is_a_big_color = exists 0 (k-1) (fun c -> col c >= 3) in\n let usable_size = sum 0 (k-1) (fun c ->\n\tlet x = col c in if x >= 2 then x else 0\n ) in\n usable_size >= long m && (not (m mod 2 = 1 && (not is_a_big_color)))\n in\n\n let answer = (possible n m) || (possible m n) in\n if answer then printf \"Yes\\n\" else printf \"No\\n\"\n done\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\n \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let k = read_int() in\n let a = Array.init k read_int in\n\n let possible n m =\n let col c = a.(c)/n in (* number of columns filable by this color *)\n let is_a_big_color = exists 0 (k-1) (fun c -> col c >= 3) in\n let usable_size = sum 0 (k-1) (fun c ->\n\tlet x = col c in if x >= 2 then x else 0\n ) in\n usable_size >= m && (not (m mod 2 = 1 && (not is_a_big_color)))\n in\n\n let answer = (possible n m) || (possible m n) in\n if answer then printf \"Yes\\n\" else printf \"No\\n\"\n done\n"}], "src_uid": "002129eec704af8976a2bf02cc532d59"} {"nl": {"description": "Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to m are placed in such a way that each number appears exactly in one leaf.Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.", "input_spec": "The first line contains a single integer n\u00a0\u2014 the number of nodes in the tree (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105). Each of the next n\u2009-\u20091 lines contains two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n)\u00a0\u2014 the ends of the edge of the tree; the edge leads from node ui to node vi. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.", "output_spec": "Print two space-separated integers \u2014 the maximum possible and the minimum possible result of the game.", "sample_inputs": ["5\n1 2\n1 3\n2 4\n2 5", "6\n1 2\n1 3\n3 4\n1 5\n5 6"], "sample_outputs": ["3 2", "3 3"], "notes": "NoteConsider the first sample. The tree contains three leaves: 3, 4 and 5. If we put the maximum number 3 at node 3, then the first player moves there and the result will be 3. On the other hand, it is easy to see that for any rearrangement the first player can guarantee the result of at least 2.In the second sample no matter what the arragment is the first player can go along the path that ends with a leaf with number 3."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet inf = max_int/2\n\nlet () = \n let n = read_int () in\n\n let tree = Array.make n [] in\n\n if n=1 then printf \"1 1\\n\" else (\n\n for i=0 to n-2 do\n let a = read_int()-1 in\n let b = read_int()-1 in\n tree.(a) <- b::tree.(a);\n tree.(b) <- a::tree.(b);\n done;\n \n let rec count_leaves u p =\n if tree.(u) = [p] then 1\n else List.fold_left (fun t v -> \n\tif v = p then t else t + (count_leaves v u)\n ) 0 tree.(u)\n in\n \n let m = count_leaves 0 (-1) in\n \n let rec dfs0 u p =\n if tree.(u) = [p] then 0 \n else List.fold_left (fun t v -> \n\tif v = p then t else min t (dfs1 v u)\n ) inf tree.(u)\n and dfs1 u p =\n if tree.(u) = [p] then 0\n else List.fold_left (fun t v -> \n\tif v = p then t else 1 + t + (dfs0 v u)\n ) (-1) tree.(u)\n in\n \n let r0 = dfs0 0 (-1) in\n let r1 = dfs1 0 (-1) in\n \n printf \"%d %d\\n\" (m-r0) (r1+1)\n )\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet inf = max_int/2\n\nlet () = \n let n = read_int () in\n\n let tree = Array.make n [] in\n\n for i=0 to n-2 do\n let a = read_int()-1 in\n let b = read_int()-1 in\n tree.(a) <- b::tree.(a);\n tree.(b) <- a::tree.(b);\n done;\n\n let rec count_leaves u p =\n if tree.(u) = [p] then 1\n else List.fold_left (fun t v -> \n if v = p then t else t + (count_leaves v u)\n ) 0 tree.(u)\n in\n\n let m = count_leaves 0 (-1) in\n\n let rec dfs0 u p =\n if tree.(u) = [p] then 0 \n else List.fold_left (fun t v -> \n if v = p then t else min t (dfs1 v u)\n ) inf tree.(u)\n and dfs1 u p =\n if tree.(u) = [p] then 0\n else List.fold_left (fun t v -> \n if v = p then t else 1 + t + (dfs0 v u)\n ) (-1) tree.(u)\n in\n\n let r0 = dfs0 0 (-1) in\n let r1 = dfs1 0 (-1) in\n\n printf \"%d %d\\n\" (m-r0) (r1+1)\n"}], "src_uid": "4a55e76aa512b8ce0f3f84bc6da3f86f"} {"nl": {"description": "The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.The Two-dimensional kingdom has a regular army of n people. Each soldier registered himself and indicated the desired size of the bulletproof vest: the i-th soldier indicated size ai. The soldiers are known to be unpretentious, so the command staff assumes that the soldiers are comfortable in any vests with sizes from ai\u2009-\u2009x to ai\u2009+\u2009y, inclusive (numbers x,\u2009y\u2009\u2265\u20090 are specified). The Two-dimensional kingdom has m vests at its disposal, the j-th vest's size equals bj. Help mobilize the Two-dimensional kingdom's army: equip with vests as many soldiers as possible. Each vest can be used only once. The i-th soldier can put on the j-th vest, if ai\u2009-\u2009x\u2009\u2264\u2009bj\u2009\u2264\u2009ai\u2009+\u2009y.", "input_spec": "The first input line contains four integers n, m, x and y (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105, 0\u2009\u2264\u2009x,\u2009y\u2009\u2264\u2009109) \u2014 the number of soldiers, the number of vests and two numbers that specify the soldiers' unpretentiousness, correspondingly. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) in non-decreasing order, separated by single spaces \u2014 the desired sizes of vests. The third line contains m integers b1,\u2009b2,\u2009...,\u2009bm (1\u2009\u2264\u2009bj\u2009\u2264\u2009109) in non-decreasing order, separated by single spaces \u2014 the sizes of the available vests.", "output_spec": "In the first line print a single integer k \u2014 the maximum number of soldiers equipped with bulletproof vests. In the next k lines print k pairs, one pair per line, as \"ui vi\" (without the quotes). Pair (ui, vi) means that soldier number ui must wear vest number vi. Soldiers and vests are numbered starting from one in the order in which they are specified in the input. All numbers of soldiers in the pairs should be pairwise different, all numbers of vests in the pairs also should be pairwise different. You can print the pairs in any order. If there are multiple optimal answers, you are allowed to print any of them.", "sample_inputs": ["5 3 0 0\n1 2 3 3 4\n1 3 5", "3 3 2 2\n1 5 9\n3 5 7"], "sample_outputs": ["2\n1 1\n3 2", "3\n1 1\n2 2\n3 3"], "notes": "NoteIn the first sample you need the vests' sizes to match perfectly: the first soldier gets the first vest (size 1), the third soldier gets the second vest (size 3). This sample allows another answer, which gives the second vest to the fourth soldier instead of the third one.In the second sample the vest size can differ from the desired size by at most 2 sizes, so all soldiers can be equipped."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n let a = Array.make n 0l in\n let b = Array.make m 0l in\n for i = 0 to n - 1 do\n let k = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n\ta.(i) <- k\n done;\n for i = 0 to m - 1 do\n let k = Scanf.bscanf sb \"%ld \" (fun s -> s) in\n\tb.(i) <- k\n done;\n let ai = ref 0 in\n let bi = ref 0 in\n let res = ref [] in\n while !ai < n && !bi < m do\n\tif Int32.sub a.(!ai) x <= b.(!bi) && b.(!bi) <= Int32.add a.(!ai) y\n\tthen (\n\t res := (!ai, !bi) :: !res;\n\t incr ai;\n\t incr bi;\n\t) else if Int32.sub a.(!ai) x > b.(!bi)\n\tthen incr bi\n\telse incr ai\n done;\n let k = List.length !res in\n\tPrintf.printf \"%d\\n\" k;\n\tList.iter (fun (a, b) -> Printf.printf \"%d %d\\n\" (a + 1) (b + 1)) !res\n"}], "negative_code": [], "src_uid": "c6bbb16b1a3946ce38e67dc4824ecf89"} {"nl": {"description": "Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter \u2014 its complexity. The complexity of the i-th chore equals hi.As Petya is older, he wants to take the chores with complexity larger than some value x (hi\u2009>\u2009x) to leave to Vasya the chores with complexity less than or equal to x (hi\u2009\u2264\u2009x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a\u2009+\u2009b\u2009=\u2009n).In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?", "input_spec": "The first input line contains three integers n,\u2009a and b (2\u2009\u2264\u2009n\u2009\u2264\u20092000; a,\u2009b\u2009\u2265\u20091; a\u2009+\u2009b\u2009=\u2009n) \u2014 the total number of chores, the number of Petya's chores and the number of Vasya's chores. The next line contains a sequence of integers h1,\u2009h2,\u2009...,\u2009hn (1\u2009\u2264\u2009hi\u2009\u2264\u2009109), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different. All numbers on the lines are separated by single spaces.", "output_spec": "Print the required number of ways to choose an integer value of x. If there are no such ways, print 0.", "sample_inputs": ["5 2 3\n6 2 3 100 1", "7 3 4\n1 1 9 1 1 1 1"], "sample_outputs": ["3", "0"], "notes": "NoteIn the first sample the possible values of x are 3, 4 or 5.In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4."}, "positive_code": [{"source_code": "open Array;;\n \nlet (|>) x f = f x\nlet identity = fun x -> x\n \nlet flip f y x = f x y\n \nlet readInStr _ = Scanf.scanf \"%d \" identity\nlet readIntLn _ = Scanf.scanf \"%d\\n\" identity\nlet main () =\n let n = readInStr () in\n let a = readInStr () in\n let b = readIntLn () in\n let h = init n (fun i -> readInStr()) in\n fast_sort(-)h;\n if b <= n-1\n then h.(b) - h.(b-1) |> print_int\n else print_int 1\n ;;\nmain()"}, {"source_code": "open Array;;\n \nlet (|>) x f = f x\nlet identity = fun x -> x\n \nlet flip f y x = f x y\n\nlet readInStr _ = Scanf.scanf \"%d \" identity\nlet readIntLn _ = Scanf.scanf \"%d\\n\" identity\nlet main () =\n let n = readInStr () in\n let a = readInStr () in\n let b = readIntLn () in\n let h = init n (fun i -> readInStr()) in\n fast_sort(-)h;\n h.(b) - h.(b-1) |> print_int\n ;;\nmain()"}], "negative_code": [], "src_uid": "d3c8c1e32dcf4286bef19e9f2b79c8bd"} {"nl": {"description": "Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of rectangles. Each of the following n lines contains four integers x1,\u2009y1,\u2009x2,\u2009y2 (1\u2009\u2264\u2009x1\u2009\u2264\u2009x2\u2009\u2264\u2009100, 1\u2009\u2264\u2009y1\u2009\u2264\u2009y2\u2009\u2264\u2009100), where x1 and y1 are the number of the column and row of the lower left cell and x2 and y2 are the number of the column and row of the upper right cell of a rectangle.", "output_spec": "In a single line print the sum of all values in the cells of the table.", "sample_inputs": ["2\n1 1 2 3\n2 2 3 3", "2\n1 1 3 3\n1 1 3 3"], "sample_outputs": ["10", "18"], "notes": "NoteNote to the first sample test:Values of the table in the first three rows and columns will be as follows:121121110So, the sum of values will be equal to 10.Note to the second sample test:Values of the table in the first three rows and columns will be as follows:222222222So, the sum of values will be equal to 18."}, "positive_code": [{"source_code": "let () =\n\tlet n = Scanf.scanf \"%d\" (fun i -> i) and res = ref 0 in\n\t\tfor i=1 to n do\n\t\t\tScanf.scanf \" %d %d %d %d\" (fun i j k l -> res := !res + (k-i+1)*(l-j+1));\n\t\tdone;\n\tPrintf.printf \"%d\" !res\n"}, {"source_code": "let xint _ = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () = \n let n = xint () in\n let sum = ref 0 in\n for i = 1 to n do\n let x1 = xint () in\n let y1 = xint () in\n let x2 = xint () in\n let y2 = xint () in\n sum := !sum + (x2 - x1 + 1) * (y2 - y1 + 1);\n done;\n print_int !sum\n"}], "negative_code": [], "src_uid": "ca5c44093b1ab7c01970d83b5f49d0c6"} {"nl": {"description": "There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that: Alice will get $$$a$$$ ($$$a > 0$$$) candies; Betty will get $$$b$$$ ($$$b > 0$$$) candies; each sister will get some integer number of candies; Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$); all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The only line of a test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^9$$$) \u2014 the number of candies you have.", "output_spec": "For each test case, print the answer \u2014 the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.", "sample_inputs": ["6\n7\n1\n2\n3\n2000000000\n763243547"], "sample_outputs": ["3\n0\n0\n1\n999999999\n381621773"], "notes": "NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are: $$$a=6$$$, $$$b=1$$$; $$$a=5$$$, $$$b=2$$$; $$$a=4$$$, $$$b=3$$$. "}, "positive_code": [{"source_code": "(* Codeforces 1335 A Candies and Two Sisters train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet numa n = \n let amax = Int64.sub n Int64.one in \n let n2 = Int64.div n (Int64.of_int 2) in\n let amin = Int64.add n2 Int64.one in \n let d = Int64.sub amax amin in\n Int64.add d Int64.one;; \n \nlet do_one () = \n\tlet n = grl () in\n let na = numa n in\n Printf.printf \"%Ld\\n\" na;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [], "src_uid": "b69170c8377623beb66db4706a02ffc6"} {"nl": {"description": "Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). Each of the next n\u2009-\u20091 lines contains two integers ui and vi (1\u2009\u2264\u2009ui,\u2009vi\u2009\u2264\u2009n; ui\u2009\u2260\u2009vi) meaning there is an edge between nodes ui and vi. The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).", "output_spec": "In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.", "sample_inputs": ["10\n2 1\n3 1\n4 2\n5 1\n6 2\n7 5\n8 6\n9 8\n10 5\n1 0 1 1 0 1 0 1 0 1\n1 0 1 0 0 1 1 1 0 1"], "sample_outputs": ["2\n4\n7"], "notes": null}, "positive_code": [{"source_code": "(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)\n\nopen Printf\nopen Scanf\nopen Array\n\nmodule S = String\nmodule Q = Queue\nmodule T = Stack\nmodule H = Hashtbl\nmodule L = List\n\n(* misc *)\nlet neg_compare x y = - compare x y\nlet min3 a b c = min a (min b c)\nlet mid3 a b c = if a < b then max a (min b c) else max b (min a c) \nlet max3 a b c = max a (max b c)\nlet min4 a b c d = min (min a b) (min c d)\nlet max4 a b c d = max (max a b) (max c d)\nlet itb a = a <> 0\nlet bti b = if b then 1 else 0\nlet rec bsearch_min a b test =\n if b - a = 1 then b else \n let mid = (a-b)/2 + b in \n if test mid then bsearch_min a mid test else \n bsearch_min mid b test\nlet rec bsearch_max a b test = \n if b - a = 1 then a else \n let mid = (a-b)/2 + b in \n if test mid then bsearch_max mid b test else \n bsearch_max a mid test\n(* int *)\nlet sqrt_floor n = bsearch_max 0 (1 lsl 31) (fun i -> i*i <= n)\nlet sqrt_ceil n = bsearch_min (-1) (1 lsl 31) (fun i -> n <= i*i) \n(* float *)\nlet round f = truncate (f +. 0.5)\nlet inv_float f = 1. /. f\n(* functional *)\nlet id x = x\nlet const x _ = x\nlet (|>) x f = f x\nlet (^>) x f = f x\nlet (@@) a b = a b \nlet on g f a b = g (f a) (f b)\nlet rec fix f = f (fun x -> fix f x)\nlet ift cond a = if cond then a\nlet ifte cond a b = if cond then a else b\nlet rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f\n(* predicate *)\nlet is_odd x = x land 1 = 1\nlet is_even x = x land 1 = 0\n(* option *)\nlet is_none = function | Some _ -> false | None -> true\nlet is_some = function | Some _ -> true | None -> false\nlet default x = function Some y -> y | None -> x\n(* ref *)\nlet (+=) a b = a := !a + b\nlet (-=) a b = a := !a - b \nlet ( *= ) a b = a := !a * b\nlet assign_min x y = x := min !x y \nlet assign_max x y = x := max !x y\n(* array *) \nlet set_min x i v = x.(i) <- min x.(i) v \nlet set_max x i v = x.(i) <- max x.(i) v \nlet swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t \n(* int, int *)\nlet (+:) (a,b) (c,d) = (a+c,b+d)\nlet (-:) (a,b) (c,d) = (a-c,b-d)\n(* number theory *)\nlet sieve_under len = (* len > 0 *)\n let sieve = Array.make len true in \n Array.fill sieve 0 (min len 2) false;\n let rec erase i k = if i >= len then () else (sieve.(i) <- false; erase (i+k) k) in \n for i = 2 to sqrt_floor len do if sieve.(i) then erase (2*i) i done;\n sieve\n(* Arithmetic *)\nlet negate x = -x\nlet rec factorial n = if n = 0 then 1 else n * factorial (n-1)\nlet rec gcd a b = if b = 0 then a else gcd b (a mod b)\nlet rec extgcd a b = \n if b = 0 then 1,0,a else\n let x,y,g = extgcd b (a mod b) in \n y,x-(a/b)*y,g\nlet rec pow x n = if n = 0 then 1 else\n let n' = n/2 in\n let p = pow x n' in\n if is_odd n then x*p*p else p*p\nlet rec modpow m x n = \n if n = 0 then 1 else \n let n' = n/2 in\n let p = modpow m x n' in \n if is_even n then (p*p mod m) else\n (x*(p*p mod m) mod m) \nlet modinv m i = let _,x,_ = extgcd m i in x\n(* IO *)\nlet is_digit c =\n let i = int_of_char c in\n 48 <= i && i < 58\nlet is_space c = c = ' ' || c = '\\n' || c = '\\t' || c = '\\r' \nlet read_char () = try input_char stdin with End_of_file -> '\\000'\nlet rec read_letter () = \n let c = read_char() in \n if is_space c then read_letter() else c \nlet read_int () = \n let digit c = int_of_char c - 48 in\n let rec read n = \n let c = read_char() in \n if is_digit c then read (10*n + (digit c)) else \n n \n in\n let rec run c = \n if is_digit c then read (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -read (digit c) else run c \n end else \n if c = '\\000' then 0 else \n run (read_char())\n in \n run (read_char())\nlet read_float () = \n let digit c = float (int_of_char c - 48) in\n let rec read_decimial m f = \n let c = read_char () in \n if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f\n in \n let rec read_integral n = \n let c = read_char () in \n if is_digit c then read_integral (10. *. n +. digit c) else \n if c = '.' then n +. read_decimial 0.1 0.0 else \n n \n in \n let rec run c = begin \n if is_digit c then read_integral (digit c) else \n if c = '-' then begin \n let c = read_char() in \n if is_digit c then -. read_integral (digit c) else \n run c \n end else \n if c = '.' then read_decimial 0.1 0.0 else \n if c = '\\000' then 0.0 else \n run (read_char())\n end in \n run (read_char())\nlet read_word () = \n let open Buffer in \n let buf = create 128 in \n let rec read c = \n if is_space c || c = '\\000' then contents buf else begin \n add_char buf c; \n read (read_char())\n end \n in\n let rec run c = \n if is_space c then run (read_char()) else \n if c = '\\000' then \"\" else \n read c \n in \n run (read_char())\nlet read_line () = \n let open Buffer in \n let buf = create (4*1024) in \n let rec run c = \n if c = '\\n' || c = '\\000' then contents buf else begin \n add_char buf c;\n run (read_char())\n end \n in\n run (read_char()) \nlet newline () = print_newline()\nlet print_tuple s (x,y) = printf s x y \nlet print_array s arr = Array.iter (printf s) arr; print_newline()\nlet print_matrix s mat = Array.iter (print_array s) mat\nlet print_list s lis = List.iter (printf s) lis; print_newline()\n;;\n\nlet _ = \n let len = read_int() in \n let graph = make len [] in \n for i = 0 to len-2 do \n let a = read_int() - 1 in\n let b = read_int() - 1 in \n graph.(a) <- b :: graph.(a);\n graph.(b) <- a :: graph.(b)\n done;\n let ini = init len (fun i -> read_int() ) in \n let goal = init len (fun i -> read_int() ) in \n\n let cnt = ref [] in \n let rec dfs lv odd even p i = \n let curr = if is_odd lv then (ini.(i) lxor odd) else (ini.(i) lxor even) in \n if curr <> goal.(i) then begin \n cnt := i :: !cnt;\n let odd = if is_odd lv then odd lxor 1 else odd in \n let even = if is_even lv then even lxor 1 else even in \n L.iter (fun j -> if j <> p then dfs (lv+1) odd even i j) graph.(i) \n end else \n L.iter (fun j -> if j <> p then dfs (lv+1) odd even i j) graph.(i) \n in \n dfs 0 0 0 (-1) 0;\n printf \"%d\\n\" (L.length !cnt);\n L.iter (fun i -> printf \"%d\\n\" (i+1)) !cnt\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\nlet () = \n let n = read_int () in\n let tree = Array.make n [] in\n \n for i=0 to n-2 do \n let u = (read_int()) -1 in\n let v = (read_int()) -1 in\n tree.(u) <- v::tree.(u);\n tree.(v) <- u::tree.(v);\n done;\n\n let init = Array.init n (fun _ -> read_int()) in\n \n for i=0 to n-1 do\n let b = read_int () in\n init.(i) <- init.(i) lxor b\n done;\n\n let parent = Array.make n (-1) in\n\n let rec dfs u p = \n List.iter (fun v -> \n if v <> p then (\n\tparent.(v) <- u;\n\tdfs v u\n )\n ) tree.(u)\n in\n\n dfs 0 (-1);\n\n let rec loop i ac = if i=n then ac else\n let condadd bit = if bit=0 then ac else i::ac in\n if parent.(i) < 0 || parent.(parent.(i)) < 0 then loop (i+1) (condadd init.(i))\n else loop (i+1) (condadd (init.(i) lxor init.(parent.(parent.(i)))))\n in\n\n let li = loop 0 [] in\n printf \"%d\\n\" (List.length li);\n List.iter (fun i -> printf \"%d\\n\" (i+1)) (loop 0 [])\n"}], "negative_code": [], "src_uid": "f3a27e4dc3085712608ecf844e663dfd"} {"nl": {"description": "In the snake exhibition, there are $$$n$$$ rooms (numbered $$$0$$$ to $$$n - 1$$$) arranged in a circle, with a snake in each room. The rooms are connected by $$$n$$$ conveyor belts, and the $$$i$$$-th conveyor belt connects the rooms $$$i$$$ and $$$(i+1) \\bmod n$$$. In the other words, rooms $$$0$$$ and $$$1$$$, $$$1$$$ and $$$2$$$, $$$\\ldots$$$, $$$n-2$$$ and $$$n-1$$$, $$$n-1$$$ and $$$0$$$ are connected with conveyor belts.The $$$i$$$-th conveyor belt is in one of three states: If it is clockwise, snakes can only go from room $$$i$$$ to $$$(i+1) \\bmod n$$$. If it is anticlockwise, snakes can only go from room $$$(i+1) \\bmod n$$$ to $$$i$$$. If it is off, snakes can travel in either direction. Above is an example with $$$4$$$ rooms, where belts $$$0$$$ and $$$3$$$ are off, $$$1$$$ is clockwise, and $$$2$$$ is anticlockwise.Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 1000$$$): the number of test cases. The description of the test cases follows. The first line of each test case description contains a single integer $$$n$$$ ($$$2 \\le n \\le 300\\,000$$$): the number of rooms. The next line of each test case description contains a string $$$s$$$ of length $$$n$$$, consisting of only '<', '>' and '-'. If $$$s_{i} = $$$ '>', the $$$i$$$-th conveyor belt goes clockwise. If $$$s_{i} = $$$ '<', the $$$i$$$-th conveyor belt goes anticlockwise. If $$$s_{i} = $$$ '-', the $$$i$$$-th conveyor belt is off. It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$300\\,000$$$.", "output_spec": "For each test case, output the number of returnable rooms.", "sample_inputs": ["4\n4\n-><-\n5\n>>>>>\n3\n<--\n2\n<>"], "sample_outputs": ["3\n5\n3\n0"], "notes": "NoteIn the first test case, all rooms are returnable except room $$$2$$$. The snake in the room $$$2$$$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement. In the second test case, all rooms are returnable by traveling on the series of clockwise belts."}, "positive_code": [{"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x) ;;\nlet read_string () = Scanf.scanf \" %s\" (fun x -> x) ;;\n\nlet rec count_freq str i (c1, c2, c3) =\n if i >= String.length str then\n (c1, c2, c3)\n else\n let newcnt = \n if str.[i] = '<' then (c1 + 1, c2, c3)\n else if str.[i] = '>' then (c1, c2 + 1, c3)\n else (c1, c2, c3 + 1)\n in \n count_freq str (i + 1) newcnt\n\nlet rec check_minus i str1 str2 =\n if i >= String.length str1 then\n 0\n else\n let newcnt = \n if str1.[i] = '-' then 1\n else if str2.[i] = '-' then 1\n else 0\n in \n (check_minus (i + 1) str1 str2) + newcnt\n \nlet solve_test() =\n let n = read_int() and \n str = read_string() in\n let (cnt1, cnt2, cnt3) = count_freq str 0 (0, 0, 0)\n in \n let ans = \n if ( (cnt1 + cnt3) = n ) then n\n else if ( (cnt2 + cnt3) = n ) then n\n else check_minus 0 str ( (String.make 1 str.[n - 1]) ^ (String.sub str 0 (n - 1)) )\n in \n Printf.printf \"%d\\n\" ans\n \n \nlet t = read_int();;\nlet () =\n for i = 1 to t do\n solve_test ()\n done"}], "negative_code": [], "src_uid": "f82685f41f4ba1146fea8e1eb0c260dc"} {"nl": {"description": "One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides, any two neighboring parts were painted different colors, that is, the red and the blue color were alternating, i. e. followed one after the other. The outer area of the wall (the area that lied outside all circles) was painted blue. Help Sherlock Holmes determine the total area of red parts of the wall.Let us remind you that two circles are called concentric if their centers coincide. Several circles are called concentric if any two of them are concentric.", "input_spec": "The first line contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). The second line contains n space-separated integers ri (1\u2009\u2264\u2009ri\u2009\u2264\u20091000) \u2014 the circles' radii. It is guaranteed that all circles are different.", "output_spec": "Print the single real number \u2014 total area of the part of the wall that is painted red. The answer is accepted if absolute or relative error doesn't exceed 10\u2009-\u20094.", "sample_inputs": ["1\n1", "3\n1 4 2"], "sample_outputs": ["3.1415926536", "40.8407044967"], "notes": "NoteIn the first sample the picture is just one circle of radius 1. Inner part of the circle is painted red. The area of the red part equals \u03c0\u2009\u00d7\u200912\u2009=\u2009\u03c0.In the second sample there are three circles of radii 1, 4 and 2. Outside part of the second circle is painted blue. Part between the second and the third circles is painted red. Part between the first and the third is painted blue. And, finally, the inner part of the first circle is painted red. Overall there are two red parts: the ring between the second and the third circles and the inner part of the first circle. Total area of the red parts is equal (\u03c0\u2009\u00d7\u200942\u2009-\u2009\u03c0\u2009\u00d7\u200922)\u2009+\u2009\u03c0\u2009\u00d7\u200912\u2009=\u2009\u03c0\u2009\u00d7\u200912\u2009+\u2009\u03c0\u2009=\u200913\u03c0"}, "positive_code": [{"source_code": "let pi = acos(-1.0)\n\nlet area lst =\n match \n List.fold_left \n (fun (area, sign) r -> area +.sign *. pi *. r *. r, -.sign)\n (0.0, 1.0)\n (List.fast_sort (fun a b -> - compare a b) lst)\n with (area, _) -> area\n\nlet main =\n let rec fix f x y = f (fix f) x y in\n let my_read_float =\n let buffer = String.create 5 in\n (fix (fun self_applied n () ->\n buffer.[n] <- input_char stdin;\n match buffer.[n] with\n | ' ' | '\\n' -> float_of_string (String.sub buffer 0 n)\n | _ -> self_applied (n + 1) ())) 0\n in\n let read_list = \n (fix (fun self_applied lst -> function\n | 0 -> lst \n | n -> self_applied ((my_read_float ()) :: lst) (n - 1))) []\n in\n let n = read_int () in\n print_float (area (read_list n));\n print_newline ()\n \n \n \n\n"}], "negative_code": [{"source_code": "let pi = acos(-1.0)\n\nlet area lst =\n match \n List.fold_left \n (fun (area, sign) r -> area +.sign *. pi *. r *. r, -.sign)\n (0.0, 1.0)\n (List.fast_sort compare lst)\n with (area, _) -> area\n\nlet main =\n let rec fix f x y = f (fix f) x y in\n let my_read_float =\n let buffer = String.create 3 in\n (fix (fun self_applied n () ->\n buffer.[n] <- input_char stdin;\n match buffer.[n] with\n | ' ' | '\\n' -> float_of_string (String.sub buffer 0 n)\n | _ -> self_applied (n + 1) ())) 0\n in\n let read_list = \n (fix (fun self_applied lst -> function\n | 0 -> lst \n | n -> self_applied ((my_read_float ()) :: lst) (n - 1))) []\n in\n let n = read_int () in\n print_float (area (read_list n));\n print_newline ()\n \n \n \n\n"}], "src_uid": "48b9c68380d3bd64bbc69d921a098641"} {"nl": {"description": "You are given a list of $$$n$$$ integers. You can perform the following operation: you choose an element $$$x$$$ from the list, erase $$$x$$$ from the list, and subtract the value of $$$x$$$ from all the remaining elements. Thus, in one operation, the length of the list is decreased by exactly $$$1$$$.Given an integer $$$k$$$ ($$$k>0$$$), find if there is some sequence of $$$n-1$$$ operations such that, after applying the operations, the only remaining element of the list is equal to $$$k$$$.", "input_spec": "The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \\leq n \\leq 2\\cdot 10^5$$$, $$$1 \\leq k \\leq 10^9$$$), the number of integers in the list, and the target value, respectively. The second line of each test case contains the $$$n$$$ integers of the list $$$a_1, a_2, \\ldots, a_n$$$ ($$$-10^9 \\leq a_i \\leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases is not greater that $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print YES if you can achieve $$$k$$$ with a sequence of $$$n-1$$$ operations. Otherwise, print NO. You may print each letter in any case (for example, \"YES\", \"Yes\", \"yes\", \"yEs\" will all be recognized as a positive answer).", "sample_inputs": ["4\n\n4 5\n\n4 2 2 7\n\n5 4\n\n1 9 1 3 4\n\n2 17\n\n17 0\n\n2 17\n\n18 18"], "sample_outputs": ["YES\nNO\nYES\nNO"], "notes": "NoteIn the first example we have the list $$$\\{4, 2, 2, 7\\}$$$, and we have the target $$$k = 5$$$. One way to achieve it is the following: first we choose the third element, obtaining the list $$$\\{2, 0, 5\\}$$$. Next we choose the first element, obtaining the list $$$\\{-2, 3\\}$$$. Finally, we choose the first element, obtaining the list $$$\\{5\\}$$$. "}, "positive_code": [{"source_code": "let parse s len = let rep = Array.make len (0) in\r\n let temp = ref \"\" in\r\n let count = ref 0 in\r\n for j = 0 to String.length s -1 do\r\n if s.[j] = ' ' then (rep.(!count)<- (int_of_string !temp) ; incr count ;temp := \"\")\r\n else (temp := !temp ^ (String.make 1 s.[j]))\r\n done; rep.(!count)<- (int_of_string !temp) ; rep ;;\r\n\r\nlet isIn x tab = let toto = ref false in for i = 0 to Array.length tab -1 do\r\n if tab.(i) = x then toto := true ; done ; !toto \r\n;;\r\n\r\nexception Tototo;;\r\n\r\nlet comp x y = x - y;;\r\n \r\n \r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len,test = Scanf.sscanf (input_line stdin) \"%d %d\" (fun len test -> (len,test)) in\r\n let str = (input_line stdin) in\r\n let tab = parse str len in \r\n try \r\n let f x =if test>0 then (Int64.add (Int64.of_int x) (Int64.of_int (-test))) else Int64.add (Int64.of_int (-x)) (Int64.of_int test) in\r\n let tab2 = (Array.map f tab) in \r\n let toto = Hashtbl.create len in\r\n for j = 0 to Array.length tab -1 do\r\n Hashtbl.add toto (Int64.of_int tab.(j)) 0 ; \r\n done;\r\n for j = 0 to Array.length tab2 -1 do\r\n if Hashtbl.mem toto (tab2.(j)) then raise Tototo\r\n done;\r\n print_endline \"NO\" \r\n with Tototo -> print_endline \"YES\" \r\n\r\n (*\r\n if isIn (tot - test) tab then print_endline \"YES\" else print_endline \"NO\"*)\r\ndone ;;"}], "negative_code": [{"source_code": "let parse s len = let max = ref (-1) in let rep = Array.make len 0 in\r\n let temp = ref \"\" in\r\n let count = ref 0 in\r\n for j = 0 to String.length s -1 do\r\n if s.[j] = ' ' then (rep.(!count)<-(int_of_string !temp) ; incr count ;if !max < int_of_string !temp then max := int_of_string !temp ;temp := \"\")\r\n else (temp := !temp ^ (String.make 1 s.[j]))\r\n done; rep.(!count)<-(int_of_string !temp) ; if !max < int_of_string !temp then max := int_of_string !temp ; rep ;;\r\n\r\nlet isIn x tab = let toto = ref false in for i = 0 to Array.length tab -1 do\r\n if tab.(i) = x then toto := true ; done ; !toto \r\n;;\r\n\r\nexception Tototo;;\r\n\r\nlet comp x y = x - y;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len,test = Scanf.sscanf (input_line stdin) \"%d %d\" (fun len test -> (len,test)) in\r\n let str = (input_line stdin) in\r\n let tab = parse str len in \r\n try \r\n let f x = if test>0 then x - test else test-x in\r\n let tab2 = (Array.map f tab) in \r\n let toto = Hashtbl.create len in\r\n for j = 0 to Array.length tab -1 do\r\n Hashtbl.add toto (tab.(j)) 0 ; \r\n done;\r\n for j = 0 to Array.length tab2 -1 do\r\n if Hashtbl.mem toto (tab2.(j)) then raise Tototo\r\n done;\r\n print_endline \"NO\" \r\n with Tototo -> print_endline \"YES\" \r\n\r\n (*\r\n if isIn (tot - test) tab then print_endline \"YES\" else print_endline \"NO\"*)\r\ndone ;;"}, {"source_code": "let parse s len = let max = ref (-1) in let rep = Array.make len 0 in\r\n let temp = ref \"\" in\r\n let count = ref 0 in\r\n for j = 0 to String.length s -1 do\r\n if s.[j] = ' ' then (rep.(!count)<-(int_of_string !temp) ; incr count ;if !max < int_of_string !temp then max := int_of_string !temp ;temp := \"\")\r\n else (temp := !temp ^ (String.make 1 s.[j]))\r\n done; rep.(!count)<-(int_of_string !temp) ; if !max < int_of_string !temp then max := int_of_string !temp ; (rep,!max) ;;\r\n\r\nlet isIn x tab = let toto = ref false in for i = 0 to Array.length tab -1 do\r\n if tab.(i) = x then toto := true ; done ; !toto \r\n;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in\r\nfor i = 0 to n-1 do\r\n let len,test = Scanf.sscanf (input_line stdin) \"%d %d\" (fun len test -> (len,test)) in\r\n let str = (input_line stdin) in\r\n let tab,tot = parse str len in\r\nif isIn (tot - test) tab then print_endline \"YES\" else print_endline \"NO\"\r\ndone ;;"}], "src_uid": "aae82b2687786818996e4e94c5505d8e"} {"nl": {"description": "One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of \"x y\" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences.The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s\u2009=\u2009s1s2... s|s|.A substring of s is a non-empty string x\u2009=\u2009s[a... b]\u2009=\u2009sasa\u2009+\u20091... sb (1\u2009\u2264\u2009a\u2009\u2264\u2009b\u2009\u2264\u2009|s|). For example, \"code\" and \"force\" are substrings or \"codeforces\", while \"coders\" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a\u2009\u2260\u2009c or b\u2009\u2260\u2009d. For example, if s=\"codeforces\", s[2...2] and s[6...6] are different, though their content is the same.A subsequence of s is a non-empty string y\u2009=\u2009s[p1p2... p|y|]\u2009=\u2009sp1sp2... sp|y| (1\u2009\u2264\u2009p1\u2009<\u2009p2\u2009<\u2009...\u2009<\u2009p|y|\u2009\u2264\u2009|s|). For example, \"coders\" is a subsequence of \"codeforces\". Two subsequences u\u2009=\u2009s[p1p2... p|u|] and v\u2009=\u2009s[q1q2... q|v|] are considered different if the sequences p and q are different.", "input_spec": "The input consists of two lines. The first of them contains s (1\u2009\u2264\u2009|s|\u2009\u2264\u20095000), and the second one contains t (1\u2009\u2264\u2009|t|\u2009\u2264\u20095000). Both strings consist of lowercase Latin letters.", "output_spec": "Print a single number \u2014 the number of different pairs \"x y\" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109\u2009+\u20097).", "sample_inputs": ["aa\naa", "codeforces\nforceofcode"], "sample_outputs": ["5", "60"], "notes": "NoteLet's write down all pairs \"x y\" that form the answer in the first sample: \"s[1...1] t[1]\", \"s[2...2] t[1]\", \"s[1...1] t[2]\",\"s[2...2] t[2]\", \"s[1...2] t[1\u00a02]\"."}, "positive_code": [{"source_code": "let _ =\n let m = 1000000007l in\n let sb = Scanf.Scanning.stdib in\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let t = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let ns = String.length s in\n let nt = String.length t in\n let a = Array.make_matrix (nt + 1) (ns + 1) 0 in\n let res = ref 0l in\n for i = 0 to nt do\n for j = 0 to ns do\n\ta.(i).(j) <- 0\n done\n done;\n for i = 1 to nt do\n for j = 1 to ns do\n\tif t.[i - 1] = s.[j - 1]\n\tthen a.(i).(j) <-\n\t Int32.(to_int\n\t\t (rem (add\n\t\t\t (add\n\t\t\t (of_int a.(i - 1).(j - 1))\n\t\t\t 1l)\n\t\t\t (of_int a.(i - 1).(j)))\n\t\t m))\n\telse a.(i).(j) <- a.(i - 1).(j)\n done\n done;\n (*for i = 0 to nt do\n for j = 0 to ns do\n\tPrintf.printf \"%d \" a.(i).(j)\n done;\n Printf.printf \"\\n\"\n done;*)\n for j = 0 to ns do\n res := Int32.rem (Int32.add !res (Int32.of_int a.(nt).(j))) m\n done;\n Printf.printf \"%ld\\n\" !res\n"}], "negative_code": [], "src_uid": "4022f8f796d4f2b7e43a8360bf34e35f"} {"nl": {"description": "Many schoolchildren look for a job for the summer, and one day, when Gerald was still a schoolboy, he also decided to work in the summer. But as Gerald was quite an unusual schoolboy, he found quite unusual work. A certain Company agreed to pay him a certain sum of money if he draws them three identical circles on a plane. The circles must not interfere with each other (but they may touch each other). He can choose the centers of the circles only from the n options granted by the Company. He is free to choose the radius of the circles himself (all three radiuses must be equal), but please note that the larger the radius is, the more he gets paid. Help Gerald earn as much as possible.", "input_spec": "The first line contains a single integer n \u2014 the number of centers (3\u2009\u2264\u2009n\u2009\u2264\u20093000). The following n lines each contain two integers xi,\u2009yi (\u2009-\u2009104\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009104) \u2014 the coordinates of potential circle centers, provided by the Company. All given points are distinct.", "output_spec": "Print a single real number \u2014 maximum possible radius of circles. The answer will be accepted if its relative or absolute error doesn't exceed 10\u2009-\u20096.", "sample_inputs": ["3\n0 1\n1 0\n1 1", "7\n2 -3\n-2 -3\n3 0\n-3 -1\n1 -2\n2 -2\n-1 0"], "sample_outputs": ["0.50000000000000000000", "1.58113883008418980000"], "notes": null}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = read_int() in (u,read_int())\n\nlet pi = 4.0 *. atan 1.0\n\nlet () = \n let n = read_int () in\n let input = Array.init n (fun _ -> read_pair()) in\n\n let sq x = x*x in\n\n let cross (x1,y1) (x2,y2) = x1*y2 - x2*y1 in\n\n let sub i j = \n let ((xi,yi),(xj,yj)) = (input.(i), input.(j)) in\n (xi-xj , yi-yj)\n in\n\n let len2 (x,y) = sq x + sq y in\n\n let dist2 i j = len2 (sub i j) in \n\n let angle i j k = \n let v = sub k i in\n let w = sub j i in\n let a = float (len2 (sub k j)) in\n let b = float (len2 v) in\n let c = float (len2 w) in\n let alpha = acos ((a -. b-. c) /. (-.2.0 *. (sqrt (b *. c)))) in\n if cross v w < 0 then -.alpha else alpha\n in\n\n let best_triangle i = \n let a = Array.init n (fun j -> ((dist2 i j), j)) in\n let () = Array.sort (fun (a,b) (c,d) -> compare c a) a in\n let k = snd a.(0) in\n let rec loop jj maxa mina = if jj=n then None else\n let j = snd a.(jj) in\n let alpha = angle i j k in\n let maxa = max maxa alpha in\n let mina = min mina alpha in\n\tif maxa -. mina >= pi /. 3.0 then Some j else loop (jj+1) maxa mina\n in\n match loop 1 0.0 0.0 with \n\t| None -> 0\n\t| Some j -> dist2 i j\n in\n\n let rec loop i m = if i=n then m else\n loop (i+1) (max (best_triangle i) m)\n in\n\n printf \"%.9f\\n\" ((sqrt(float(loop 0 0))) /. 2.0)\n"}], "negative_code": [], "src_uid": "8a92946f7c927c236c29ac10568f5079"} {"nl": {"description": "One day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B is an archenemy to student A.The students want to split so as no two archenemies were in one team. If splitting in the required manner is impossible, some students will have to sit on the bench.Determine the minimum number of students you will have to send to the bench in order to form the two teams in the described manner and begin the game at last.", "input_spec": "The first line contains two integers n and m (2\u2009\u2264\u2009n\u2009\u2264\u2009100, 1\u2009\u2264\u2009m\u2009\u2264\u2009100) \u2014 the number of students and the number of pairs of archenemies correspondingly. Next m lines describe enmity between students. Each enmity is described as two numbers ai and bi (1\u2009\u2264\u2009ai,\u2009bi\u2009\u2264\u2009n, ai\u2009\u2260\u2009bi) \u2014 the indexes of the students who are enemies to each other. Each enmity occurs in the list exactly once. It is guaranteed that each student has no more than two archenemies. You can consider the students indexed in some manner with distinct integers from 1 to n.", "output_spec": "Print a single integer \u2014 the minimum number of students you will have to send to the bench in order to start the game.", "sample_inputs": ["5 4\n1 2\n2 4\n5 3\n1 4", "6 2\n1 4\n3 4", "6 6\n1 2\n2 3\n3 1\n4 5\n5 6\n6 4"], "sample_outputs": ["1", "0", "2"], "notes": null}, "positive_code": [{"source_code": "\nopen Scanf\nopen Printf\n\n\nlet (|>) f x = x f\n\n\nmodule DisJoint: sig\n\n type 'a t\n val create : 'a -> 'a t\n val get : 'a t -> 'a\n val set : 'a t -> 'a -> unit\n val same : 'a t -> 'a t -> bool\n val union : 'a t -> 'a t -> unit\n\nend = struct\n\n type 'a root = {\n mutable value: 'a;\n mutable rank: int;\n }\n\n type 'a t = { mutable parent : 'a parent; }\n and 'a parent =\n | Parent of 'a t\n | Root of 'a root\n\n let create v =\n { parent = Root { value = v; rank = 0; }; }\n\n let compress t =\n let rec loop t ac =\n match t.parent with\n | Root _ ->\n let p = Parent t in\n List.iter (fun t -> t.parent <- p) ac;\n | Parent t' -> loop t' (t :: ac)\n in loop t []\n\n let find t =\n compress t;\n match t.parent with\n | Root r -> (t, r)\n | Parent t ->\n match t.parent with\n | Root r -> (t, r)\n | Parent _ -> assert false\n\n let root t =\n snd (find t)\n\n let get t =\n (root t).value\n\n let set t v =\n (root t).value <- v\n\n let same t1 t2 =\n (root t1) == (root t2)\n\n let union t1 t2 =\n let (t1, r1) = find t1 in\n let (t2, r2) = find t2 in\n if r1 == r2 then ()\n else\n if r1.rank < r2.rank then\n t1.parent <- Parent t2\n else\n (t2.parent <- Parent t1;\n if r1.rank = r2.rank then\n r1.rank <- r1.rank + 1)\n\nend\n\n\nlet (n, input) =\n bscanf Scanning.stdib \"%d %d \" (fun n m ->\n (n, Array.init m (fun _ ->\n bscanf Scanning.stdib \"%d %d \" (fun a b -> (a, b)))))\n\nlet _ =\n let ct = ref 0 in\n let u = Array.init (n + 1) (fun i -> DisJoint.create i) in\n input |> Array.iter (fun (a, b) ->\n if not (DisJoint.same u.(a) u.(b)) then\n DisJoint.union u.(a) u.(b)\n else\n u |> Array.map (fun b -> if DisJoint.same u.(a) b then 1 else 0)\n |> Array.fold_left (+) 0\n |> (fun c -> if c mod 2 = 1 then incr ct));\n\n printf \"%d\"\n (if (n - !ct) mod 2 = 0 then !ct else !ct + 1)\n"}, {"source_code": "\nopen Scanf\nopen Printf\n\n\nlet (|>) f x = x f\n\n\nlet (n, arr) =\n bscanf Scanning.stdib \"%d %d \" (fun n m ->\n (n, Array.init m (fun _ ->\n bscanf Scanning.stdib \"%d %d \" (fun a b -> (a, b)))))\n\nlet ct = ref 0\n\nlet rec merge (a, b, len) = function\n | [] -> []\n | (a2, b2, len2) :: xs ->\n if (a2 = a && b2 = b) || (a2 = b && b2 = a) then\n if (len + len2) mod 2 = 1 then\n (incr ct; xs)\n else\n xs\n else\n if a2 = a then (b, b2, len + len2) :: xs else\n if a2 = b then (a, b2, len + len2) :: xs else\n if b2 = a then (a2, b, len + len2) :: xs else\n if b2 = b then (a, a2, len + len2) :: xs else\n (a2, b2, len2) :: merge (a, b, len) xs\n\nlet rec process = function\n | [] -> printf \"%d\" (match (n mod 2, !ct mod 2) with\n | (0, 0) -> !ct\n | (0, 1) -> !ct + 1\n | (1, 0) -> !ct + 1\n | (1, 1) -> !ct)\n | x :: xs -> process (merge x xs)\n\nlet _ = process\n (arr |> Array.to_list\n |> List.map (fun (a, b) -> (a, b, 1)))\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "\nopen Scanf\nopen Printf\n\n\nlet (|>) f x = x f\n\n\nmodule DisJoint: sig\n\n type 'a t\n val create : 'a -> 'a t\n val get : 'a t -> 'a\n val set : 'a t -> 'a -> unit\n val same : 'a t -> 'a t -> bool\n val union : 'a t -> 'a t -> unit\n\nend = struct\n\n type 'a root = {\n mutable value: 'a;\n mutable rank: int;\n }\n\n type 'a t = { mutable parent : 'a parent; }\n and 'a parent =\n | Parent of 'a t\n | Root of 'a root\n\n let create v =\n { parent = Root { value = v; rank = 0; }; }\n\n let compress t =\n let rec loop t ac =\n match t.parent with\n | Root _ ->\n let p = Parent t in\n List.iter (fun t -> t.parent <- p) ac;\n | Parent t' -> loop t' (t :: ac)\n in loop t []\n\n let find t =\n compress t;\n match t.parent with\n | Root r -> (t, r)\n | Parent t ->\n match t.parent with\n | Root r -> (t, r)\n | Parent _ -> assert false\n\n let root t =\n snd (find t)\n\n let get t =\n (root t).value\n\n let set t v =\n (root t).value <- v\n\n let same t1 t2 =\n (root t1) == (root t2)\n\n let union t1 t2 =\n let (t1, r1) = find t1 in\n let (t2, r2) = find t2 in\n if r1 == r2 then ()\n else\n if r1.rank < r2.rank then\n t1.parent <- Parent t2\n else\n (t2.parent <- Parent t1;\n if r1.rank = r2.rank then\n r1.rank <- r1.rank + 1)\n\nend\n\n\nlet (n, input) =\n bscanf Scanning.stdib \"%d %d \" (fun n m ->\n (n, Array.init m (fun _ ->\n bscanf Scanning.stdib \"%d %d \" (fun a b -> (a, b)))))\n\nlet _ =\n let ct = ref 0 in\n let u = Array.init (n + 1) (fun i -> DisJoint.create i) in\n input |> Array.iter (fun (a, b) ->\n if DisJoint.same u.(a) u.(b) then\n (let c = u |> Array.map (fun b -> if DisJoint.same u.(a) b then 1 else 0)\n |> Array.fold_left (+) 0 in\n if c mod 2 = 1 then incr ct)\n else\n DisJoint.union u.(a) u.(b));\n\n printf \"%d\"\n (if (n - !ct) mod 2 = 0 then !ct else !ct + 1)\n"}, {"source_code": "\nopen Scanf\nopen Printf\n\n\nlet (|>) f x = x f\n\n\nlet (n, arr) =\n bscanf Scanning.stdib \"%d %d \" (fun n m ->\n (n, Array.init m (fun _ ->\n bscanf Scanning.stdib \"%d %d \" (fun a b -> (a, b)))))\n\nlet ct = ref 0\n\nlet rec merge (a, b, len) = function\n | [] -> []\n | (a2, b2, len2) :: xs ->\n if (a2 = a && b2 = b) || (a2 = b && b2 = a) then\n if (len + len2) mod 2 = 1 then\n (incr ct; xs)\n else\n xs\n else\n if a2 = a then (b, b2, len + len2) :: xs else\n if a2 = b then (a, b2, len + len2) :: xs else\n if b2 = a then (a2, b, len + len2) :: xs else\n if b2 = b then (a, a2, len + len2) :: xs else\n (a2, b2, len2) :: merge (a, b, len) xs\n\nlet rec process = function\n | [] -> printf \"%d\" (if (n + !ct) mod 2 = 0 then !ct else !ct + 1)\n | x :: xs -> process (merge x xs)\n\nlet _ = process\n (arr |> Array.to_list\n |> List.map (fun (a, b) -> (a, b, 1)))\n\n\n\n\n\n\n\n\n\n"}], "negative_code": [{"source_code": "\nopen Scanf\nopen Printf\n\n\nlet (|>) f x = x f\n\n\nlet (n, arr) =\n bscanf Scanning.stdib \"%d %d \" (fun n m ->\n (n, Array.init m (fun _ ->\n bscanf Scanning.stdib \"%d %d \" (fun a b -> (a, b)))))\n\nlet ct = ref 0\n\nlet rec merge (a, b, len) = function\n | [] -> []\n | (a2, b2, len2) :: xs ->\n if (a2 = a && b2 = b) || (a2 = b && b2 = a) then\n if (len + len2) mod 2 = 1 then\n (incr ct; xs)\n else\n xs\n else\n if a2 = a then (b, b2, len + len2) :: xs else\n if a2 = b then (a, b2, len + len2) :: xs else\n if b2 = a then (a2, b, len + len2) :: xs else\n if b2 = b then (a, a2, len + len2) :: xs else\n (a2, b2, len2) :: merge (a, b, len) xs\n\nlet rec process = function\n | [] -> printf \"%d\" (if n mod 2 = 1 && !ct mod 2 = 0 then !ct + 1 else !ct)\n | x :: xs -> process (merge x xs)\n\nlet _ = process\n (arr |> Array.to_list\n |> List.map (fun (a, b) -> (a, b, 1)))\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "\nopen Scanf\nopen Printf\n\n\nlet (|>) f x = x f\n\n\nmodule DisJoint: sig\n\n type 'a t\n val create : 'a -> 'a t\n val get : 'a t -> 'a\n val set : 'a t -> 'a -> unit\n val same : 'a t -> 'a t -> bool\n val union : 'a t -> 'a t -> unit\n\nend = struct\n\n type 'a root = {\n mutable value: 'a;\n mutable rank: int;\n }\n\n type 'a t = { mutable parent : 'a parent; }\n and 'a parent =\n | Parent of 'a t\n | Root of 'a root\n\n let create v =\n { parent = Root { value = v; rank = 0; }; }\n\n let compress t =\n let rec loop t ac =\n match t.parent with\n | Root _ ->\n let p = Parent t in\n List.iter (fun t -> t.parent <- p) ac;\n | Parent t' -> loop t' (t :: ac)\n in loop t []\n\n let find t =\n compress t;\n match t.parent with\n | Root r -> (t, r)\n | Parent t ->\n match t.parent with\n | Root r -> (t, r)\n | Parent _ -> assert false\n\n let root t =\n snd (find t)\n\n let get t =\n (root t).value\n\n let set t v =\n (root t).value <- v\n\n let same t1 t2 =\n (root t1) == (root t2)\n\n let union t1 t2 =\n let (t1, r1) = find t1 in\n let (t2, r2) = find t2 in\n if r1 == r2 then ()\n else\n if r1.rank < r2.rank then\n t1.parent <- Parent t2\n else\n (t2.parent <- Parent t1;\n if r1.rank = r2.rank then\n r1.rank <- r1.rank + 1)\n\nend\n\n\nlet (n, input) =\n bscanf Scanning.stdib \"%d %d \" (fun n m ->\n (n, Array.init m (fun _ ->\n bscanf Scanning.stdib \"%d %d \" (fun a b -> (a, b)))))\n\nlet _ =\n let ct = ref 0 in\n let u = Array.init (n + 1) (fun i -> DisJoint.create i) in\n input |> Array.iter (fun (a, b) ->\n if DisJoint.same u.(a) u.(b) then incr ct else\n DisJoint.union u.(a) u.(b));\n\n printf \"%d\"\n (if (n - !ct) mod 2 = 0 then !ct else !ct + 1)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "\nopen Scanf\nopen Printf\n\n\nlet (n, arr) =\n bscanf Scanning.stdib \"%d %d \" (fun n m ->\n (n, Array.init m (fun _ ->\n bscanf Scanning.stdib \"%d %d \" (fun a b -> (a, b)))))\n\nlet ct = ref 0\n\nlet rec merge (a, b) = function\n | [] -> []\n | (a2, b2) :: xs ->\n if (a2 = a && b2 = b) || (a2 = b && b2 = a) then\n (incr ct; xs)\n else\n if a2 = a then (b, b2) :: xs else\n if a2 = b then (a, b2) :: xs else\n if b2 = a then (a2, b) :: xs else\n if b2 = b then (a, a2) :: xs else\n (a2, b2) :: merge (a, b) xs\n\nlet rec process = function\n | [] -> printf \"%d\" (if n mod 2 = 1 && !ct mod 2 = 0 then !ct + 1 else !ct)\n | x :: xs -> process (merge x xs)\n\nlet _ = process (Array.to_list arr)\n"}, {"source_code": "\nopen Scanf\nopen Printf\n\n\nlet (|>) f x = x f\n\n\nlet (n, arr) =\n bscanf Scanning.stdib \"%d %d \" (fun n m ->\n (n, Array.init m (fun _ ->\n bscanf Scanning.stdib \"%d %d \" (fun a b -> (a, b)))))\n\nlet ct = ref 0\n\nlet rec merge (a, b, len) = function\n | [] -> []\n | (a2, b2, len2) :: xs ->\n if (a2 = a && b2 = b) || (a2 = b && b2 = a) then\n if (len + len2) mod 2 = 1 then\n (incr ct; xs)\n else\n xs\n else\n if a2 = a then (b, b2, len + len2) :: xs else\n if a2 = b then (a, b2, len + len2) :: xs else\n if b2 = a then (a2, b, len + len2) :: xs else\n if b2 = b then (a, a2, len + len2) :: xs else\n (a2, b2, len2) :: merge (a, b, len) xs\n\nlet rec process = function\n | [] -> printf \"%d\" (if n mod 2 = 1 && !ct mod 2 = 0 then !ct + 1 else !ct)\n | x :: xs -> process (merge x xs)\n\nlet _ = process\n (arr |> Array.to_list\n |> List.map (fun (a, b) -> (a, b, 0)))\n\n\n\n\n\n\n\n\n\n\n\n\n"}, {"source_code": "\nopen Scanf\nopen Printf\n\n\nlet ct = ref 0\n\nlet rec merge (a, b) = function\n | [] -> []\n | (a2, b2) :: xs ->\n if (a2 = a && b2 = b) || (a2 = b && b2 = a) then\n (incr ct; xs)\n else\n if a2 = a then (b, b2) :: xs else\n if a2 = b then (a, b2) :: xs else\n if b2 = a then (a2, b) :: xs else\n if b2 = b then (a, a2) :: xs else\n (a2, b2) :: merge (a, b) xs\n\nlet rec process = function\n | [] -> printf \"%d\" !ct\n | x :: xs -> process (merge x xs)\n\nlet _ = process\n (Array.to_list\n (bscanf Scanning.stdib \"%d %d \" (fun n m ->\n Array.init m (fun _ ->\n bscanf Scanning.stdib \"%d %d \" (fun a b -> (a, b))))))\n"}], "src_uid": "a0e55bfbdeb3dc550e1f86b9fa7cb06d"} {"nl": {"description": "Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:Given two binary numbers $$$a$$$ and $$$b$$$ of length $$$n$$$. How many different ways of swapping two digits in $$$a$$$ (only in $$$a$$$, not $$$b$$$) so that bitwise OR of these two numbers will be changed? In other words, let $$$c$$$ be the bitwise OR of $$$a$$$ and $$$b$$$, you need to find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will not be equal to $$$c$$$.Note that binary numbers can contain leading zeros so that length of each number is exactly $$$n$$$.Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $$$01010_2$$$ OR $$$10011_2$$$ = $$$11011_2$$$.Well, to your surprise, you are not Rudolf, and you don't need to help him$$$\\ldots$$$ You are the security staff! Please find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will be changed.", "input_spec": "The first line contains one integer $$$n$$$ ($$$2\\leq n\\leq 10^5$$$)\u00a0\u2014 the number of bits in each number. The second line contains a binary number $$$a$$$ of length $$$n$$$. The third line contains a binary number $$$b$$$ of length $$$n$$$.", "output_spec": "Print the number of ways to swap two bits in $$$a$$$ so that bitwise OR will be changed.", "sample_inputs": ["5\n01011\n11001", "6\n011000\n010011"], "sample_outputs": ["4", "6"], "notes": "NoteIn the first sample, you can swap bits that have indexes $$$(1, 4)$$$, $$$(2, 3)$$$, $$$(3, 4)$$$, and $$$(3, 5)$$$.In the second example, you can swap bits that have indexes $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 4)$$$, $$$(3, 4)$$$, $$$(3, 5)$$$, and $$$(3, 6)$$$."}, "positive_code": [{"source_code": "exception NotSameLength;;\nopen Num;;\n\nlet zero = num_of_int 0;;\nlet one = num_of_int 1;;\n\nlet solver bits1 bits2 =\n let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with\n | [], [] -> n0, n1, m0, m1\n | b1::q1, b2::q2 when b1 = one-> aux q1 q2 (if (b2 = zero) then (n0, (add_num n1 one), m0, (add_num m1 one)) else (n0, (add_num n1 one), m0, m1))\n | b1::q1, b2::q2 when b1 = zero -> aux q1 q2 (if (b2 = zero) then ((add_num n0 one), n1, (add_num m0 one), m1) else ((add_num n0 one), n1, m0, m1))\n | _ -> raise NotSameLength\n in\n let n0, n1, m0, m1 = aux bits1 bits2 (zero, zero, zero, zero)\n in\n add_num (mult_num m1 n0) (mult_num (sub_num n1 m1) m0);;\n\nlet line1 = read_line();;\nlet line_bits1 = read_line();;\nlet line_bits2 = read_line();;\n\nlet parse_bits line = List.map (fun b -> num_of_string b) (Str.split (Str.regexp \"\") line);;\nlet bits1 = parse_bits line_bits1;;\nlet bits2 = parse_bits line_bits2;;\nprint_string @@ string_of_num @@ solver bits1 bits2;;\n"}], "negative_code": [{"source_code": "exception NotSameLength;;\n\nlet solver bits1 bits2 =\n let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with\n | [], [] -> n0, n1, m0, m1\n | 1::q1, b2::q2 -> aux q1 q2 (if (b2 == 0) then (n0, (n1 + 1), m0, (m1 + 1)) else (n0, (n1 + 1), m0, m1))\n | 0::q1, b2::q2 -> aux q1 q2 (if (b2 == 0) then ((n0 + 1), n1, (m0 + 1), m1) else ((n0 + 1), n1, m0, m1))\n | _ -> raise NotSameLength\n in\n let n0, n1, m0, m1 = aux bits1 bits2 (0, 0, 0, 0)\n in\n m1 * n0 + (n1 - m1) * m0;;\n\nlet bits1_1 = 0::1::0::1::1::[];;\nlet bits2_1 = 1::1::0::0::1::[];;\nlet bits1_2 = 0::1::1::0::0::0::[];;\nlet bits2_2 = 0::1::0::0::1::1::[];;\n\nlet line1 = read_line();;\nlet line_bits1 = read_line();;\nlet line_bits2 = read_line();;\n\nlet parse_bits line = List.map (fun b -> int_of_string b) (Str.split (Str.regexp \"\") line);;\nlet bits1 = parse_bits line_bits1;;\nlet bits2 = parse_bits line_bits2;;\nprint_int @@ solver bits1 bits2;;\n"}, {"source_code": "exception NotSameLength;;\n\nlet solver bits1 bits2 =\n let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with\n | [], [] -> n0, n1, m0, m1\n | b1::q1, b2::q2 when b1 == 1 -> aux q1 q2 (if (b2 == 0) then (n0, n1 + 1, m0, m1 + 1) else (n0, n1+ 1, m0, m1))\n | b1::q1, b2::q2 when b1 == 0 -> aux q1 q2 (if (b2 == 0) then (n0 + 1, n1, m0 + 1, m1) else (n0 + 1, n1, m0, m1))\n | _ -> raise NotSameLength\n in\n let n0, n1, m0, m1 = aux bits1 bits2 (0, 0, 0, 0)\n in\n (assert (m1 <= n1));\n m1 * n0 + (n1 - m1) * m0;;\n\n(*\nlet line1 = read_line();;\nlet line_bits1 = read_line();;\nlet line_bits2 = read_line();;\n\nlet parse_bits line = List.map (fun b -> int_of_string b) (Str.split (Str.regexp \"\") line);;\nlet bits1 = parse_bits line_bits1;;\nlet bits2 = parse_bits line_bits2;;\nprint_string @@ string_of_int @@ solver bits1 bits2;;\n *)\nlet rec f n =\n if n > 0 then begin print_int n; print_newline ();f(n * 10) end;;\n\nf 1;;\nprint_int max_int;;\n"}, {"source_code": "exception NotSameLength;;\n\nlet solver bits1 bits2 =\n let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with\n | [], [] -> n0, n1, m0, m1\n | b1::q1, b2::q2 when b1 == 1 -> aux q1 q2 (if (b2 == 0) then (n0, n1 + 1, m0, m1 + 1) else (n0, n1+ 1, m0, m1))\n | b1::q1, b2::q2 when b1 == 0 -> aux q1 q2 (if (b2 == 0) then (n0 + 1, n1, m0 + 1, m1) else (n0 + 1, n1, m0, m1))\n | _ -> raise NotSameLength\n in\n let n0, n1, m0, m1 = aux bits1 bits2 (0, 0, 0, 0)\n in\n (assert (m1 <= n1));\n m1 * n0 + (n1 - m1) * m0;;\n\n(*\nlet line1 = read_line();;\nlet line_bits1 = read_line();;\nlet line_bits2 = read_line();;\n\nlet parse_bits line = List.map (fun b -> int_of_string b) (Str.split (Str.regexp \"\") line);;\nlet bits1 = parse_bits line_bits1;;\nlet bits2 = parse_bits line_bits2;;\nprint_string @@ string_of_int @@ solver bits1 bits2;;\n *)\nlet rec f n =\n if n > 0 then begin print_int n; print_newline ();f(n * 10) end;;\n\nf 1;;\n"}, {"source_code": "exception NotSameLength;;\n\nlet solver bits1 bits2 =\n let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with\n | [], [] -> n0, n1, m0, m1\n | b1::q1, b2::q2 when b1 == 1 -> aux q1 q2 (if (b2 == 0) then (n0, n1 + 1, m0, m1 + 1) else (n0, n1+ 1, m0, m1))\n | b1::q1, b2::q2 when b1 == 0 -> aux q1 q2 (if (b2 == 0) then (n0 + 1, n1, m0 + 1, m1) else (n0 + 1, n1, m0, m1))\n | _ -> raise NotSameLength\n in\n let n0, n1, m0, m1 = aux bits1 bits2 (0, 0, 0, 0)\n in\n m1 * n0 + (n1 - m1) * m0;;\n\nlet line1 = read_line();;\nlet line_bits1 = read_line();;\nlet line_bits2 = read_line();;\n\nlet parse_bits line = List.map (fun b -> int_of_string b) (Str.split (Str.regexp \"\") line);;\nlet bits1 = parse_bits line_bits1;;\nlet bits2 = parse_bits line_bits2;;\nprint_string @@ string_of_int @@ solver bits1 bits2;;\n"}, {"source_code": "exception NotSameLength;;\nopen Num;;\n\nlet zero = num_of_int 0;;\nlet one = num_of_int 1;;\n\nlet solver bits1 bits2 =\n let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with\n | [], [] -> n0, n1, m0, m1\n | b1::q1, b2::q2 when b1 = one-> aux q1 q2 (if (b2 = zero) then (n0, (add_num n1 one), m0, (add_num m1 one)) else (n0, (add_num n1 one), m0, m1))\n | b1::q1, b2::q2 when b1 = zero -> aux q1 q2 (if (b2 = zero) then ((add_num n0 one), n1, (add_num m1 one), m1) else ((add_num n0 one), n1, m0, m1))\n | _ -> raise NotSameLength\n in\n let n0, n1, m0, m1 = aux bits1 bits2 (zero, zero, zero, zero)\n in\n add_num (mult_num m1 n0) (mult_num (sub_num n1 m1) m0);;\n\nlet line1 = read_line();;\nlet line_bits1 = read_line();;\nlet line_bits2 = read_line();;\n\nlet parse_bits line = List.map (fun b -> num_of_string b) (Str.split (Str.regexp \"\") line);;\nlet bits1 = parse_bits line_bits1;;\nlet bits2 = parse_bits line_bits2;;\nprint_string @@ string_of_num @@ solver bits1 bits2;;\n"}, {"source_code": "exception NotSameLength;;\n\nlet solver bits1 bits2 =\n let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with\n | [], [] -> n0, n1, m0, m1\n | b1::q1, b2::q2 when b1 == 1 -> aux q1 q2 (if (b2 == 0) then (n0, n1 + 1, m0, m1 + 1) else (n0, n1+ 1, m0, m1))\n | b1::q1, b2::q2 when b1 == 0 -> aux q1 q2 (if (b2 == 0) then (n0 + 1, n1, m0 + 1, m1) else (n0 + 1, n1, m0, m1))\n | _ -> raise NotSameLength\n in\n let n0, n1, m0, m1 = aux bits1 bits2 (0, 0, 0, 0)\n in\n (assert (m1 <= n1));\n m1 * n0 + (n1 - m1) * m0;;\n\nlet line1 = read_line();;\nlet line_bits1 = read_line();;\nlet line_bits2 = read_line();;\n\nlet parse_bits line = List.map (fun b -> int_of_string b) (Str.split (Str.regexp \"\") line);;\nlet bits1 = parse_bits line_bits1;;\nlet bits2 = parse_bits line_bits2;;\nprint_string @@ string_of_int @@ solver bits1 bits2;;\n"}], "src_uid": "621c82478be3dadcf60c383ba078a49e"} {"nl": {"description": "Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.", "input_spec": "The first line of the input data contains an integer number n (3\u2009\u2264\u2009n\u2009\u2264\u2009106), n \u2014 the amount of hills around the capital. The second line contains n numbers \u2014 heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.", "output_spec": "Print the required amount of pairs.", "sample_inputs": ["5\n1 2 4 5 3"], "sample_outputs": ["7"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet rec rev a l h =\n if l < h-1 then (\n let t = a.(l) in\n a.(l) <- a.(h-1);\n a.(h-1) <- t;\n rev a (l+1) (h-1)\n )\n\nlet rotate a x =\n let n = Array.length a in\n rev a 0 x;\n rev a x n;\n rev a 0 n\n\nlet () =\n let open Int64 in\n let addi x y = add x (of_int y) in\n\n let n = read_int 0 in\n let a = Array.init n read_int in\n let _,ma = Array.fold_left (fun (i,x) y -> (i+1,if x = -1 || y > a.(x) then i else x)) (0,-1) a in\n rotate a ma;\n\n let l = Array.make n 0\n and c = Array.make n 0 in\n for i = 1 to n-1 do\n let t = ref (i-1) in\n while !t > 0 && a.(i) > a.(!t) do\n t := l.(!t);\n done;\n if a.(i) = a.(!t) then (\n c.(i) <- c.(!t)+1;\n l.(i) <- l.(!t)\n ) else\n l.(i) <- !t\n done;\n\n let ans = ref 0L\n and r = Array.make n 0 in\n for i = n-1 downto 0 do\n ans := addi !ans c.(i);\n let t = ref (i+1) in\n while !t < n && a.(i) >= a.(!t) do\n t := r.(!t)\n done;\n r.(i) <- !t;\n if a.(i) < a.(0) then\n if l.(i) = 0 && r.(i) = n then\n ans := addi !ans 1\n else\n ans := addi !ans 2\n done;\n Printf.printf \"%Ld\\n\" !ans"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\n\nlet rec rev a l h =\n if l < h-1 then (\n let t = a.(l) in\n a.(l) <- a.(h-1);\n a.(h-1) <- t;\n rev a (l+1) (h-1)\n )\n\nlet rotate a x =\n let n = Array.length a in\n rev a 0 x;\n rev a x n;\n rev a 0 n\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let _,ma = Array.fold_left (fun (i,x) y -> (i+1,if x = -1 || y > a.(x) then i else x)) (0,-1) a in\n rotate a ma;\n\n let l = Array.make n 0\n and c = Array.make n 0 in\n for i = 1 to n-1 do\n let t = ref (i-1) in\n while !t > 0 && a.(i) > a.(!t) do\n t := l.(!t);\n done;\n if a.(i) = a.(!t) then (\n c.(i) <- c.(!t)+1;\n l.(i) <- l.(!t)\n ) else\n l.(i) <- !t\n done;\n\n let ans = ref 0\n and r = Array.make n 0 in\n for i = n-1 downto 0 do\n ans := !ans+c.(i);\n let t = ref (i+1) in\n while !t < n && a.(i) >= a.(!t) do\n t := r.(!t)\n done;\n r.(i) <- !t;\n if a.(i) < a.(0) then\n if l.(i) = 0 && r.(i) = n then\n ans := !ans+1\n else\n ans := !ans+2\n done;\n Printf.printf \"%d\\n\" !ans\n"}], "src_uid": "e32328aaeeea789e993d09335764c021"} {"nl": {"description": "Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1\u2009\u2264\u2009i\u2009\u2264\u2009n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integers a1,\u2009\u2009a2,\u2009\u2009...,\u2009\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109).", "output_spec": "Print a single integer \u2014 the length of the maximum non-decreasing subsegment of sequence a.", "sample_inputs": ["6\n2 2 1 3 4 1", "3\n2 2 9"], "sample_outputs": ["3", "3"], "notes": "NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one."}, "positive_code": [{"source_code": "open Printf\nopen List\nopen Pervasives\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if (String.unsafe_get s i) = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n\n(* 2 2 1 3 4 1 *)\nlet rec longest_non_decr_seq seq last count longest = \n match seq with \n | [] -> longest\n | hd::tl -> \n if last > hd then longest_non_decr_seq tl hd 1 (if count > longest then\n count else longest)\n else longest_non_decr_seq tl hd (count + 1) (if (count + 1) > longest then\n (count + 1 ) else longest)\n\nlet get_list_size () = \n int_of_string (read_line ())\n\nlet get_input_list () = \n let in_line = read_line() in\n List.map int_of_string (split_on_char ' ' in_line)\n\nlet () = \n let expected_len = get_list_size () in \n let list = get_input_list () in\n assert (expected_len = List.length list);\n match list with\n | [] -> printf \"0\\n\"\n | hd::_ -> printf \"%d\\n\" (longest_non_decr_seq list hd 0 0)\n \n"}, {"source_code": "let list_init n f =\n let rec read n list = \n if n > 0\n then\n let var = f() in\n read (n - 1) (var :: list)\n else\n List.rev list\n in read n []\n\nlet income n = list_init n (fun i -> Scanf.scanf \"%d \" (fun k -> k))\n\nlet input () = \n let days = Scanf.scanf \"%d \" (fun n -> n) in\n income days\n\nlet max a b =\n if a > b\n then\n a\n else\n b\n\nlet find_max list = \n let rec loop list prev count max_seen =\n match list with\n |(head :: tail) -> \n if prev <= head \n then\n let new_count = count + 1 in\n loop tail head new_count (max new_count max_seen)\n else\n loop tail head 1 max_seen\n |[] -> max_seen\n\n in loop list 0 0 0\n\nlet solve list = find_max list\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (solve (input ()))"}, {"source_code": "let list_init n f =\n let rec read n list = \n if n > 0\n then\n let var = f() in\n read (n - 1) (var :: list)\n else\n List.rev list\n in read n []\n\nlet income n = list_init n (fun i -> Scanf.scanf \"%d \" (fun k -> k))\n\nlet input () = \n let days = Scanf.scanf \"%d \" (fun n -> n) in\n income days\n\nlet find_max list = \n let rec loop list prev count max_seen =\n match list with\n |(head :: tail) -> \n if prev <= head \n then\n let new_count = count + 1 in\n loop tail head new_count (Pervasives.max new_count max_seen)\n else\n loop tail head 1 max_seen\n |[] -> max_seen\n\n in loop list 0 0 0\n\nlet print result = Printf.printf \"%d\\n\" result\n\nlet () = print (find_max (input ()))"}, {"source_code": "let read_int () = Scanf.scanf \" %d\" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let ans = ref 0 in\n let rec loop acc prev = function\n | 0 -> ()\n | num -> (\n let curr = read_int () in\n if curr >= prev then\n (ans := max !ans (acc + 1);\n loop (acc + 1) curr (num - 1))\n else\n loop 1 curr (num - 1)\n ) in\n loop 0 0 n;\n Printf.printf \"%d\\n\" !ans\n"}, {"source_code": "open Big_int;;\n\nlet rec biggest aux = function\n\t|[a]\t-> aux\n\t| a::b::q -> if compare_big_int a b > -1\n\t\t\tthen biggest (aux + 1) (b::q)\n\t\t\telse max aux (biggest 1 (b::q));;\n\nlet main () =\n\tlet l = ref [] and n = Scanf.scanf \"%d\" (fun i -> i) in\n\t\tfor i=1 to n do\n\t\t\tl := (Scanf.scanf \" %s\" big_int_of_string)::!l;\n\t\tdone;\n\tPrintf.printf \"%d\" (biggest 1 !l);;\n\nmain ();; \n"}, {"source_code": "open Printf\nopen String\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) ;;\n\nlet a = Array.make n (-1);;\n\nfor i = 0 to n-1 do\n let jj = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x) in\n a.(i) <- jj\ndone\n\nlet c = Array.make n 1;; (* This is the array counting the number of increasing sequence *)\n\nlet d = ref 1;;\n\n for i = 1 to n-1 do\n begin\n if( a.(i) >= a.(i-1) ) then\n c.(i) <- c.(i-1) + 1;\n if( !d < c.(i) ) then d := c.(i)\n end\n done;;\n\nlet () = print_int !d; print_endline \"\";;\n"}, {"source_code": "let read_int () = Scanf.scanf \" %d \" (fun x -> x);;\nlet () =\n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n let rec go i prev cnt best =\n if i = n then max cnt best else\n if a.(i) >= prev then go (i+1) a.(i) (cnt+1) best else\n go (i+1) a.(i) 1 (max cnt best)\n in\n Printf.printf \"%d\\n\" (go 0 0 0 0);;\n\n"}, {"source_code": "let n = int_of_string (input_line stdin);;\nlet first = Scanf.scanf \"%d \" (fun v -> v);;\n\nlet rec solve num_remaining last acc best =\n if num_remaining == 0 then (max acc best) else\n let v = Scanf.scanf \"%d \" (fun v -> v) in\n if v >= last then solve (num_remaining - 1) v (acc + 1) best\n else solve (num_remaining - 1) v 1 (max acc best);;\n\nlet ans = solve (n - 1) first 1 0 in\nPrintf.printf \"%d\\n\" ans;"}], "negative_code": [{"source_code": "open Printf\nopen Pervasives"}, {"source_code": "open Pervasives\nopen Printf\n\nlet () = printf \"%d\\n\" 3"}, {"source_code": "open Printf\nopen List\nopen Pervasives\n\nlet split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if (String.unsafe_get s i) = sep then begin\n r := String.sub s (i + 1) (!j - i - 1) :: !r;\n j := i\n end\n done;\n String.sub s 0 !j :: !r\n\n\nlet rec longest_non_decr_seq seq last count longest = \n match seq with \n | [] -> longest\n | hd::tl -> \n if last > hd then longest_non_decr_seq tl hd 0 (if count > longest then\n count else longest)\n else longest_non_decr_seq tl hd (count + 1) (if (count + 1) > longest then\n (count + 1 ) else longest)\n\nlet get_list_size () = \n int_of_string (read_line ())\n\nlet get_input_list () = \n let in_line = read_line() in\n List.map int_of_string (split_on_char ' ' in_line)\n\nlet () = \n let expected_len = get_list_size () in \n let list = get_input_list () in\n assert (expected_len = List.length list);\n printf \"%d\\n\" ((longest_non_decr_seq list 2 0 0) + 1)\n"}, {"source_code": "open Printf\nopen String\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x) ;;\n\nlet a = Array.make n (-1);;\n\nfor i = 0 to n-1 do\n let jj = Scanf.bscanf Scanf.Scanning.stdin \"%d \" (fun x -> x) in\n a.(i) <- jj\ndone\n\nlet c = Array.make n 1;; (* This is the array counting the number of increasing sequence *)\n\nlet d = ref 0;;\n\n for i = 1 to n-1 do\n begin\n if( a.(i) >= a.(i-1) ) then\n c.(i) <- c.(i-1) + 1;\n if( !d < c.(i) ) then d := c.(i)\n end\n done;;\n\nlet () = print_int !d; print_endline \"\";;\n"}], "src_uid": "1312b680d43febdc7898ffb0753a9950"} {"nl": {"description": "Omkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an $$$n$$$ by $$$m$$$ grid ($$$1 \\leq n, m \\leq 2000$$$) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions: For any two adjacent (sharing a side) cells, the absolute value of the difference of numbers in them is at most $$$1$$$. If the number in some cell is strictly larger than $$$0$$$, it should be strictly greater than the number in at least one of the cells adjacent to it. Unfortunately, Ajit is not fully worthy of Omkar's powers yet. He sees each cell as a \"0\" or a \"#\". If a cell is labeled as \"0\", then the number in it must equal $$$0$$$. Otherwise, the number in it can be any nonnegative integer.Determine how many different assignments of elements exist such that these special conditions are satisfied. Two assignments are considered different if there exists at least one cell such that the numbers written in it in these assignments are different. Since the answer may be enormous, find the answer modulo $$$10^9+7$$$.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 2000, nm \\geq 2$$$) \u2013 the dimensions of the forest. $$$n$$$ lines follow, each consisting of one string of $$$m$$$ characters. Each of these characters is either a \"0\" or a \"#\". It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ and the sum of $$$m$$$ over all test cases does not exceed $$$2000$$$.", "output_spec": "For each test case, print one integer: the number of valid configurations modulo $$$10^9+7$$$.", "sample_inputs": ["4\n3 4\n0000\n00#0\n0000\n2 1\n#\n#\n1 2\n##\n6 29\n#############################\n#000##0###0##0#0####0####000#\n#0#0##00#00##00####0#0###0#0#\n#0#0##0#0#0##00###00000##00##\n#000##0###0##0#0##0###0##0#0#\n#############################"], "sample_outputs": ["2\n3\n3\n319908071"], "notes": "NoteFor the first test case, the two valid assignments are$$$0000\\\\ 0000\\\\ 0000$$$and$$$0000\\\\ 0010\\\\ 0000$$$"}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet p = 1_000_000_007L\n\nlet ( ** ) a b = Int64.rem (Int64.mul a b) p\nlet ( -- ) a b = let y = Int64.sub a b in if y<0L then Int64.add y p else y\n\nlet rec powermod a b = (* a^b mod p. b is a short a is a long *)\n if b=0 then 1L else\n let r = powermod a (b lsr 1) in\n let r2 = r**r in\n if b land 1 = 0 then r2 else r2**a\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x)\n \nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int () in\n let m = read_int () in\n let board = Array.init n read_string in\n let count ch =\n sum 0 (n-1) (fun r ->\n\tsum 0 (m-1) (fun c -> if board.(r).[c] = ch then 1 else 0))\n in\n let zeros = count '0' in\n let sharps = count '#' in\n let answer = (powermod 2L sharps) -- (if zeros = 0 then 1L else 0L) in\n printf \"%Ld\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "4e9dfc5e988cebb9a92f0c0b7ec06981"} {"nl": {"description": "The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times. When he came to the fruit stall of Ashot, he saw that the seller hadn't distributed price tags to the goods, but put all price tags on the counter. Later Ashot will attach every price tag to some kind of fruits, and Valera will be able to count the total price of all fruits from his list. But Valera wants to know now what can be the smallest total price (in case of the most \u00ablucky\u00bb for him distribution of price tags) and the largest total price (in case of the most \u00abunlucky\u00bb for him distribution of price tags).", "input_spec": "The first line of the input contains two integer number n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100) \u2014 the number of price tags (which is equal to the number of different kinds of fruits that Ashot sells) and the number of items in Valera's list. The second line contains n space-separated positive integer numbers. Each of them doesn't exceed 100 and stands for the price of one fruit of some kind. The following m lines contain names of the fruits from the list. Each name is a non-empty string of small Latin letters which length doesn't exceed 32. It is guaranteed that the number of distinct fruits from the list is less of equal to n. Also it is known that the seller has in stock all fruits that Valera wants to buy.", "output_spec": "Print two numbers a and b (a\u2009\u2264\u2009b) \u2014 the minimum and the maximum possible sum which Valera may need to buy all fruits from his list.", "sample_inputs": ["5 3\n4 2 1 10 5\napple\norange\nmango", "6 5\n3 5 1 6 8 1\npeach\ngrapefruit\nbanana\norange\norange"], "sample_outputs": ["7 19", "11 30"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\n\nlet cnt b m =\n let c = Array.make m 0 in\n let rec go i j k =\n if i >= m then\n k\n else if j < m && b.(i) = b.(j) then\n go i (j+1) k\n else (\n c.(k) <- j-i;\n go j j (k+1)\n )\n in\n let mm = go 0 0 0 in\n let cc = Array.make mm 0 in\n Array.blit c 0 cc 0 mm;\n Array.sort compare cc;\n mm, cc\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let a = Array.init n read_int in\n let b = Array.init m read_str in\n Array.sort compare a;\n Array.sort compare b;\n let mm, c = cnt b m in\n let ans1 = ref 0 and ans2 = ref 0 in\n for i = 0 to min n mm - 1 do\n ans1 := !ans1 + a.(i) * c.(mm-1-i);\n ans2 := !ans2 + a.(n-1-i) * c.(mm-1-i);\n done;\n Printf.printf \"%d %d\\n\" !ans1 !ans2\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet read_str _ = Scanf.bscanf Scanf.Scanning.stdib \" %s\" (fun x -> x)\nlet (|>) x f = f x\n\nlet cnt b m =\n let c = Array.make m 0 in\n let rec go i j k =\n if i >= m then\n k\n else if j < m && b.(i) = b.(j) then\n go i (j+1) k\n else (\n c.(k) <- j-i;\n go j j (k+1)\n )\n in\n let mm = go 0 0 0 in\n mm, c\n\nlet () =\n let n = read_int 0 in\n let m = read_int 0 in\n let a = Array.init n read_int in\n let b = Array.init m read_str in\n Array.sort compare a;\n Array.sort compare b;\n let mm, c = cnt b m in\n let ans1 = ref 0 and ans2 = ref 0 in\n for i = 0 to min n mm - 1 do\n ans1 := !ans1 + a.(i) * c.(m-1-i);\n ans2 := !ans2 + a.(n-1-i) * c.(i);\n done;\n Printf.printf \"%d %d\\n\" !ans1 !ans2\n"}], "src_uid": "31c43b62784a514cfdb9ebb835e94cad"} {"nl": {"description": "Let's consider all integers in the range from $$$1$$$ to $$$n$$$ (inclusive).Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $$$\\mathrm{gcd}(a, b)$$$, where $$$1 \\leq a < b \\leq n$$$.The greatest common divisor, $$$\\mathrm{gcd}(a, b)$$$, of two positive integers $$$a$$$ and $$$b$$$ is the biggest integer that is a divisor of both $$$a$$$ and $$$b$$$.", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\leq t \\leq 100$$$) \u00a0\u2014 the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$2 \\leq n \\leq 10^6$$$).", "output_spec": "For each test case, output the maximum value of $$$\\mathrm{gcd}(a, b)$$$ among all $$$1 \\leq a < b \\leq n$$$.", "sample_inputs": ["2\n3\n5"], "sample_outputs": ["1\n2"], "notes": "NoteIn the first test case, $$$\\mathrm{gcd}(1, 2) = \\mathrm{gcd}(2, 3) = \\mathrm{gcd}(1, 3) = 1$$$.In the second test case, $$$2$$$ is the maximum possible value, corresponding to $$$\\mathrm{gcd}(2, 4)$$$."}, "positive_code": [{"source_code": "let rec main (t : int) =\n if t = 0 then\n ()\n else\n let n = read_int() in\n print_endline (string_of_int (n / 2));\n main (t - 1)\nin\nlet t = read_int () in\nmain t\n"}], "negative_code": [], "src_uid": "b46244f39e30c0cfab592a97105c60f4"} {"nl": {"description": "Billy investigates the question of applying greedy algorithm to different spheres of life. At the moment he is studying the application of greedy algorithm to the problem about change. There is an amount of n coins of different face values, and the coins of each value are not limited in number. The task is to collect the sum x with the minimum amount of coins. Greedy algorithm with each its step takes the coin of the highest face value, not exceeding x. Obviously, if among the coins' face values exists the face value 1, any sum x can be collected with the help of greedy algorithm. However, greedy algorithm does not always give the optimal representation of the sum, i.e. the representation with the minimum amount of coins. For example, if there are face values {1,\u20093,\u20094} and it is asked to collect the sum 6, greedy algorithm will represent the sum as 4\u2009+\u20091\u2009+\u20091, while the optimal representation is 3\u2009+\u20093, containing one coin less. By the given set of face values find out if there exist such a sum x that greedy algorithm will collect in a non-optimal way. If such a sum exists, find out the smallest of these sums.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009400) \u2014 the amount of the coins' face values. The second line contains n integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), describing the face values. It is guaranteed that a1\u2009>\u2009a2\u2009>\u2009...\u2009>\u2009an and an\u2009=\u20091.", "output_spec": "If greedy algorithm collects any sum in an optimal way, output -1. Otherwise output the smallest sum that greedy algorithm collects in a non-optimal way.", "sample_inputs": ["5\n25 10 5 2 1", "3\n4 3 1"], "sample_outputs": ["-1", "6"], "notes": null}, "positive_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let ans = ref (-1) in\n for i = 1 to n-1 do\n for j = i to n-1 do\n (* representation of a_{i-1}-1 *)\n let p = a.(i-1)-1 |> ref\n and c = ref 1\n and w = ref a.(j) in\n for k = i to j do\n let t = !p / a.(k) in\n c := !c + t;\n w := !w + a.(k) * t;\n p := !p mod a.(k)\n done;\n\n p := !w;\n for k = 0 to n-1 do\n c := !c - !p / a.(k);\n p := !p mod a.(k)\n done;\n if !c < 0 && (!ans < 0 || !w < !ans) then\n ans := !w;\n done\n done;\n Printf.printf \"%d\\n\" !ans\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let ans = ref (-1) in\n for i = 1 to n-1 do\n for j = i to n-1 do\n (* representation of a_{i-1}-1 *)\n let p = a.(i-1)-1 |> ref\n and c = ref 1\n and w = ref a.(j) in\n for k = i to j do\n let t = !p / a.(k) in\n c := !c + t;\n w := !w + a.(k) * t;\n p := !p mod a.(k)\n done;\n\n p := !w;\n for k = 0 to n-1 do\n c := !c - !p / a.(k);\n p := !p mod a.(k)\n done;\n if !c < 0 && (!ans < 0 || !w < !ans) then\n ans := !w;\n done\n done;\n Printf.printf \"%d\\n\" !ans\n"}], "negative_code": [{"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let ans = ref (-1) in\n for i = 1 to n-1 do\n for j = i to n-1 do\n let p = a.(i-1)-1 |> ref\n and c = ref 1\n and w = ref a.(j) in\n for k = i to j do\n let t = !p / a.(k) in\n c := !c + t;\n w := !w + a.(k) * t;\n p := !p mod a.(k)\n done;\n if !p = 0 then (\n p := !w;\n for k = 0 to n-1 do\n c := !c - !p / a.(k);\n p := !p mod a.(k)\n done\n );\n if !c < 0 && (!ans < 0 || !w < !ans) then\n ans := !w;\n done\n done;\n Printf.printf \"%d\\n\" !ans\n"}, {"source_code": "let read_int _ = Scanf.bscanf Scanf.Scanning.stdib \" %d\" (fun x -> x)\nlet (|>) x f = f x\n\nlet () =\n let n = read_int 0 in\n let a = Array.init n read_int in\n let ans = ref (-1) in\n for i = 1 to n-1 do\n for j = i to n-1 do\n let p = a.(i-1)-1 |> ref\n and c = ref 0\n and w = ref a.(j) in\n for k = i to j do\n let t = !p / a.(k) in\n c := !c + t;\n w := !w + a.(k) * t;\n p := !p mod a.(k)\n done;\n if !p = 0 then (\n p := !w;\n for k = 0 to n-1 do\n c := !c - !p / a.(k);\n p := !p mod a.(k)\n done\n );\n if !c < 0 && (!ans < 0 || !w < !ans) then\n ans := !w;\n done\n done;\n Printf.printf \"%d\\n\" !ans\n"}], "src_uid": "c592778fe180234ab007f113f2440393"} {"nl": {"description": "You are given an array of n integer numbers a0,\u2009a1,\u2009...,\u2009an\u2009-\u20091. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.", "input_spec": "The first line contains positive integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009105) \u2014 size of the given array. The second line contains n integers a0,\u2009a1,\u2009...,\u2009an\u2009-\u20091 (1\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 elements of the array. It is guaranteed that in the array a minimum occurs at least two times.", "output_spec": "Print the only number \u2014 distance between two nearest minimums in the array.", "sample_inputs": ["2\n3 3", "3\n5 6 5", "9\n2 1 3 5 4 1 2 3 1"], "sample_outputs": ["1", "2", "3"], "notes": null}, "positive_code": [{"source_code": "let split = Str.split (Str.regexp \" \")\n\nlet () =\n let _ = read_line () in (* skip the 1st line *)\n let ns = read_line ()\n |> split\n |> (List.map int_of_string) in\n let minimum = List.fold_left min max_int ns in\n let rec nearest d p i ns =\n match ns with\n [] -> d\n | head :: tail -> if head = minimum\n then nearest (min d (i-p)) i (i+1) tail\n else nearest d p (i+1) tail in\n print_int (nearest 100000 (-100000) 0 ns);\n print_newline ()\n"}], "negative_code": [], "src_uid": "67af292ff23880ad9fd4349729e36158"} {"nl": {"description": "Of course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied: Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bj\u2009\u2264\u2009bi. Rings should not fall one into the the other. That means one can place ring j on the ring i only if bj\u2009>\u2009ai. The total height of all rings used should be maximum possible. ", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of rings in factory's stock. The i-th of the next n lines contains three integers ai, bi and hi (1\u2009\u2264\u2009ai,\u2009bi,\u2009hi\u2009\u2264\u2009109, bi\u2009>\u2009ai)\u00a0\u2014 inner radius, outer radius and the height of the i-th ring respectively.", "output_spec": "Print one integer\u00a0\u2014 the maximum height of the tower that can be obtained.", "sample_inputs": ["3\n1 5 1\n2 6 2\n3 7 3", "4\n1 2 1\n1 3 3\n4 6 2\n5 7 1"], "sample_outputs": ["6", "4"], "notes": "NoteIn the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4."}, "positive_code": [{"source_code": "(*********************************************************************************)\n\ntype disk = {\n\ta : int; (* inner radius *)\n\tb : int; (* outer radius *)\n\th : int64; (* dist height *)\n};;\n\n(*********************************************************************************)\n\t\nlet read_disks n =\n\tlet arr = Array.make n {a=0; b=0; h=Int64.zero} in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %d %d %Ld \" (fun a b h -> arr.(k) <- {a=a; b=b; h=h};);\n\t\tdone;\n\t\tarr;\n\tend\n;;\n\n(*********************************************************************************)\n\nlet find_highest_tower arr =\n\t(* precondition: arr is sorted by increasing disk.b *)\n\tlet n = Array.length arr in\n\tlet s = Array.make n arr.(0) in\n\tlet m = ref 1 in\n\tlet t = ref arr.(0).h in (* highest possible tower containing disk k-1 *)\n\tlet tt = ref !t in (* highest possible tower built from disks from 0 to (k-1) *)\n\tbegin\n\tfor k = 1 to n - 1 do\n\t\tlet d = arr.(k) in\n\t\tbegin\n\t\twhile (!m > 0) && (d.b <= s.(!m - 1).a) do\n\t\t\tbegin\n\t\t\tm := !m - 1;\n\t\t\tt := Int64.sub !t s.(!m).h;\n\t\t\tend\n\t\tdone;\n\t\ts.(!m) <- d;\n\t\tm := !m + 1;\n\t\tt := Int64.add !t d.h;\n\t\ttt := max !tt !t;\n\t\tend\n\tdone;\n\t!tt;\n\tend\n;;\n\n(*********************************************************************************)\n\nlet cmp_disks_desc d1 d2 =\n\tif ( d1.b == d2.b ) then compare d2.a d1.a\n\telse compare d2.b d1.b\n;;\n\n(*********************************************************************************)\n\nlet read_and_process n =\n\tlet a = read_disks n in\n\tbegin\n\t\tArray.sort cmp_disks_desc a;\n\t\tPrintf.printf \"%Ld\\n\" (find_highest_tower a);\n\tend\n;;\n\n(*********************************************************************************)\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" read_and_process\n;;\n\n(*********************************************************************************)\n\nread_input ()\n"}, {"source_code": "(*********************************************************************************)\n\ntype disk = {\n\ta : int; (* inner radius *)\n\tb : int; (* outer radius *)\n\th : int64; (* dist height *)\n};;\n\n(*********************************************************************************)\n\t\nlet read_disks n =\n\tlet arr = Array.make n {a=0; b=0; h=Int64.zero} in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %d %d %Ld \" (fun a b h -> arr.(k) <- {a=a; b=b; h=h};);\n\t\tdone;\n\t\tarr;\n\tend\n;;\n\n(*********************************************************************************)\n\nlet lower_bound arr n x less =\n\tlet l = ref 0 in\n\tlet r = ref n in\n\tbegin\n\t\twhile !l < !r do\n\t\t\tlet mid = !l + (!r - !l) / 2 in\n\t\t\tif (less arr.(mid) x) then\n\t\t\t\tbegin\n\t\t\t\t\tl := mid + 1;\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tbegin\n\t\t\t\t\tr := mid;\n\t\t\t\tend\n\t\tdone;\n\t\t!r\n\tend\n;;\n\n(*********************************************************************************)\nlet upper_bound arr n x less =\n\tlet l = ref 0 in\n\tlet r = ref n in\n\tbegin\n\t\twhile !l < !r do\n\t\t\tlet mid = !l + (!r - !l) / 2 in\n\t\t\tif (less x arr.(mid)) then\n\t\t\t\tbegin\n\t\t\t\t\tr := mid;\n\t\t\t\tend\n\t\t\telse (* a[mid] <= x *)\n\t\t\t\tbegin\n\t\t\t\t\tl := mid + 1;\n\t\t\t\tend\n\t\tdone;\n\t\t!r\n\tend\n;;\n\n(*********************************************************************************)\n\nlet find_highest_tower arr =\n\t(* precondition: arr is sorted by increasing disk.b *)\n\tlet n = Array.length arr in\n\tlet tw = Array.make n 0 in\n\t(* \n\t\tTowers are arranged according to increase of width and decrease of height.\n\t\tIn essence tower with a smaller width can precede a tower with a greater width only if it is higher.\n\t*)\n\tlet th = Array.make n Int64.zero in \n\tlet m = ref 0 in (* amount of towers to lookup *)\n\tbegin\n\tfor k = 0 to n - 1 do\n\t\tlet d = arr.(k) in\n\t\tlet j = upper_bound tw !m d.a (<) in (* find the tower with width > outer radius of the disk, or return the end of tower list *)\n\t\tlet t = if j < !m then (Int64.add th.(j) d.h) else d.h in\n\t\tlet mm = lower_bound th j t (>) in (* find first tower which is not taller than the new one *)\n\t\tbegin\n\t\t\tm := mm + 1; (* no point to search beyond the widest tower *)\n\t\t\ttw.(mm) <- d.b;\n\t\t\tth.(mm) <- t;\n\t\t\t(*Printf.printf \"j=%d, m=%d, w=%d, h=%Ld\\n\" j !m d.b t;*)\n\t\tend\n\tdone;\n\tth.( 0 )\n\tend\n;;\n\n(*********************************************************************************)\n\nlet cmp_disks d1 d2 =\n\tif d1.b < d2.b then -1\n\telse if d2.b < d1.b then 1\n\telse compare d1.a d2.a\n;;\n\n(*********************************************************************************)\n\nlet read_and_process n =\n\tlet a = read_disks n in\n\tbegin\n\t\tArray.sort cmp_disks a;\n\t\tPrintf.printf \"%Ld\\n\" (find_highest_tower a);\n\tend\n;;\n\n(*********************************************************************************)\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" read_and_process\n;;\n\n(*********************************************************************************)\n\nread_input ()\n"}], "negative_code": [{"source_code": "(*********************************************************************************)\n\ntype disk = {\n\ta : int; (* inner radius *)\n\tb : int; (* outer radius *)\n\th : int; (* dist height *)\n\tmutable t : int; (* height of tallest tower containing this disk *)\n};;\n\n(*********************************************************************************)\n\nlet print_disks a =\n\tlet n = Array.length a in\n\tfor k = 0 to n - 1 do\n\t\tlet d = a.(k) in\n\t\tPrintf.printf \"a=%d; b=%d; h=%d; t=%d;\\n\" d.a d.b d.h d.t;\n\tdone;\n\t(*print_newline ();*)\n;;\n\n(*********************************************************************************)\n\nlet create_disk va vb vh = { a=va; b=vb; h=vh; t=vh };;\n\n(*********************************************************************************)\n\t\nlet read_disks n =\n\tlet arr = Array.make n (create_disk 0 0 0) in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %d %d %d \" (fun a b h -> arr.(k) <- (create_disk a b h););\n\t\tdone;\n\t\tarr;\n\tend\n;;\n\n(*********************************************************************************)\n\nlet find_highest_tower arr =\n\t(* precondition: arr is sorted by increasing disk.b *)\n\tlet n = Array.length arr in\n\tlet tt = ref 0 in (* height of the tallest tower *)\n\tbegin\n\t\tfor k = 0 to n - 1 do (* Invariant k: tt contains height of the tallest tower from arr[0] to arr[k-1] *)\n\t\t\tlet d = arr.(k) in\n\t\t\tlet t = ref 0 in (* height of the tallest tower involving disk d.(k) *)\n\t\t\tbegin\n\t\t\t\t(*\t\n\t\t\t\t*\tWe need to check only the towers ending with the disk of outer radius <= d.b \n\t\t\t\t*\tbecause the towers ending with wider disks cannot be placed on top of disk d.\n\t\t\t\t*\tAll these good towers are to the left of k-th disk because by precondition our array is sorted by disk.b\n\t\t\t\t*\n\t\t\t\t*\tInvariant j: \n\t\t\t\t*\t------------\n\t\t\t\t*\tt is the height of the tallest tower such that it contains some (possibly all or none) \n\t\t\t\t*\tproperly arranged disks in the range (j..k)\n\t\t\t\t*)\n\t\t\t\tfor j=(k-1) downto 0 do \n\t\t\t\t\tlet dd = arr.(j) in\n\t\t\t\t\t(*\n\t\t\t\t\t*\tOnly disks with outer radius greater than arr[k].b can be put on top of k-th disk\n\t\t\t\t\t*)\n\t\t\t\t\tt := if dd.b > d.a then max !t dd.t else !t;\n\t\t\t\tdone;\n\t\t\t\td.t <- (!t + d.h);\n\t\t\t\t(*\n\t\t\t\t\tThe tallest tower from 0-th to k-th is either:\n\t\t\t\t\t1. The tallest one among those containing the k-th disk\n\t\t\t\t\t2. The tallest one among those which do not contain k-th disk\n\t\t\t\t*)\n\t\t\t\ttt := max !tt d.t;\n\t\t\tend\n\t\tdone;\n\n\t\t!tt\n\tend\n;;\n\n(*********************************************************************************)\n\nlet read_and_process n =\n\tlet a = read_disks n in\n\tbegin\n\t\tArray.sort (fun d1 d2 -> compare d1.b d2.b) a;\n\t\tPrintf.printf \"%d\\n\" (find_highest_tower a);\n\tend\n;;\n\n(*********************************************************************************)\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" read_and_process\n;;\n\n(*********************************************************************************)\n\nread_input ()\n"}, {"source_code": "(*********************************************************************************)\n\ntype disk = {\n\ta : int; (* inner radius *)\n\tb : int; (* outer radius *)\n\th : int; (* dist height *)\n\tmutable t : int; (* height of tallest tower containing this disk *)\n};;\n\n(*********************************************************************************)\n\nlet print_disks a =\n\tlet n = Array.length a in\n\tfor k = 0 to n - 1 do\n\t\tlet d = a.(k) in\n\t\tPrintf.printf \"a=%d; b=%d; h=%d; t=%d;\\n\" d.a d.b d.h d.t;\n\tdone;\n\t(*print_newline ();*)\n;;\n\n(*********************************************************************************)\n\nlet create_disk va vb vh = { a=va; b=vb; h=vh; t=vh };;\n\n(*********************************************************************************)\n\t\nlet read_disks n =\n\tlet arr = Array.make n (create_disk 0 0 0) in\n\tbegin\n\t\tfor k=0 to (n - 1) do\n\t\t\tScanf.bscanf Scanf.Scanning.stdin \" %d %d %d \" (fun a b h -> arr.(k) <- (create_disk a b h););\n\t\tdone;\n\t\tarr;\n\tend\n;;\n\n(*********************************************************************************)\n\nlet find_highest_tower arr =\n\t(* precondition: arr is sorted by increasing disk.b *)\n\tlet n = Array.length arr in\n\tlet tt = ref 0 in (* height of the tallest tower *)\n\tbegin\n\t\tfor k = 0 to n - 1 do (* Invariant k: tt contains height of the tallest tower from arr[0] to arr[k-1] *)\n\t\t\tlet d = arr.(k) in\n\t\t\tlet t = ref 0 in (* height of the tallest tower involving disk d.(k) *)\n\t\t\tbegin\n\t\t\t\t(*\t\n\t\t\t\t*\tWe need to check only the towers ending with the disk of outer radius <= d.b \n\t\t\t\t*\tbecause the towers ending with wider disks cannot be placed on top of disk d.\n\t\t\t\t*\tAll these good towers are to the left of k-th disk because by precondition our array is sorted by disk.b\n\t\t\t\t*\n\t\t\t\t*\tInvariant j: \n\t\t\t\t*\t------------\n\t\t\t\t*\tt is the height of the tallest tower such that it contains some (possibly all or none) \n\t\t\t\t*\tproperly arranged disks in the range (j..k)\n\t\t\t\t*)\n\t\t\t\tfor j=(k-1) downto 0 do \n\t\t\t\t\tlet dd = arr.(j) in\n\t\t\t\t\t(*\n\t\t\t\t\t*\tOnly disks with outer radius greater than arr[k].b can be put on top of k-th disk\n\t\t\t\t\t*)\n\t\t\t\t\tt := if dd.b > d.a then max !t dd.t else !t;\n\t\t\t\tdone;\n\t\t\t\td.t <- (!t + d.h);\n\t\t\t\t(*\n\t\t\t\t\tThe tallest tower from 0-th to k-th is either:\n\t\t\t\t\t1. The tallest one among those containing the k-th disk\n\t\t\t\t\t2. The tallest one among those which do not contain k-th disk\n\t\t\t\t*)\n\t\t\t\ttt := max !tt d.t;\n\t\t\tend\n\t\tdone;\n\n\t\t!tt\n\tend\n;;\n\n(*********************************************************************************)\n\nlet cmp_disks d1 d2 =\n\tif d1.b < d2.b then -1\n\telse if d2.b < d1.b then 1\n\telse compare d1.a d2.a\n;;\n\n(*********************************************************************************)\n\nlet read_and_process n =\n\tlet a = read_disks n in\n\tbegin\n\t\tArray.sort cmp_disks a;\n\t\tPrintf.printf \"%d\\n\" (find_highest_tower a);\n\tend\n;;\n\n(*********************************************************************************)\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %d \" read_and_process\n;;\n\n(*********************************************************************************)\n\nread_input ()\n"}], "src_uid": "8d0f569359f655f3685c68fb364114a9"} {"nl": {"description": "In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length li.Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed.Sticks with lengths a1, a2, a3 and a4 can make a rectangle if the following properties are observed: a1\u2009\u2264\u2009a2\u2009\u2264\u2009a3\u2009\u2264\u2009a4 a1\u2009=\u2009a2 a3\u2009=\u2009a4 A rectangle can be made of sticks with lengths of, for example, 3\u00a03\u00a03\u00a03 or 2\u00a02\u00a04\u00a04. A rectangle cannot be made of, for example, sticks 5\u00a05\u00a05\u00a07.Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length 5 can either stay at this length or be transformed into a stick of length 4.You have to answer the question \u2014 what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?", "input_spec": "The first line of the input contains a positive integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014\u00a0the number of the available sticks. The second line of the input contains n positive integers li (2\u2009\u2264\u2009li\u2009\u2264\u2009106)\u00a0\u2014\u00a0the lengths of the sticks.", "output_spec": "The first line of the output must contain a single non-negative integer\u00a0\u2014\u00a0the maximum total area of the rectangles that Ilya can make from the available sticks.", "sample_inputs": ["4\n2 4 4 2", "4\n2 2 3 5", "4\n100003 100004 100005 100006"], "sample_outputs": ["8", "0", "10000800015"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a;\n in\n let xs = ref [] in\n let pos = ref (n - 1) in\n let _ =\n while !pos > 0 do\n if a.(!pos) = a.(!pos - 1) ||\n\ta.(!pos) = a.(!pos - 1) + 1\n then (\n\txs := a.(!pos - 1) :: !xs;\n\tpos := !pos - 2\n ) else decr pos\n done;\n in\n let xs = Array.of_list (List.rev !xs) in\n let res = ref 0L in\n for i = 0 to Array.length xs / 2 - 1 do\n res := Int64.add !res\n\t(Int64.mul (Int64.of_int xs.(2 * i)) (Int64.of_int xs.(2 * i + 1)));\n done;\n Printf.printf \"%Ld\\n\" !res;\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s)\n done;\n Array.sort compare a;\n in\n let xs = ref [] in\n let pos = ref (n - 1) in\n let _ =\n while !pos > 0 do\n if a.(!pos) = a.(!pos - 1) ||\n\ta.(!pos) = a.(!pos - 1) + 1\n then (\n\txs := a.(!pos - 1) :: !xs;\n\tpos := !pos - 2\n ) else decr pos\n done;\n in\n let xs = Array.of_list !xs in\n let res = ref 0L in\n for i = 0 to Array.length xs / 2 - 1 do\n res := Int64.add !res\n\t(Int64.mul (Int64.of_int xs.(2 * i)) (Int64.of_int xs.(2 * i + 1)));\n done;\n Printf.printf \"%Ld\\n\" !res;\n"}], "src_uid": "0e162ea665732714283317e7c052e234"} {"nl": {"description": "Sometimes some words like \"localization\" or \"internationalization\" are so long that writing them many times in one text is quite tiresome.Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.Thus, \"localization\" will be spelt as \"l10n\", and \"internationalization\u00bb will be spelt as \"i18n\".You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.", "output_spec": "Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.", "sample_inputs": ["4\nword\nlocalization\ninternationalization\npneumonoultramicroscopicsilicovolcanoconiosis"], "sample_outputs": ["word\nl10n\ni18n\np43s"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let main () =\n let n = read_int () in\n for i = 1 to n do\n let s = read_line () in\n let l = String.length s in\n if l > 10 then (\n Printf.printf \"%c%d%c\\n\" s.[0] (l - 2) s.[l - 1]\n ) else print_endline s\n done\n in\n main ()\n"}, {"source_code": "let number_of_words = Scanf.scanf \"%d \" (fun n -> n)\n\nlet abbreviate w = \n let l = String.length w in\n let first_char = String.make 1 (String.get w 0) in\n let last_char = String.make 1 (String.get w (l - 1)) in\n if l > 10\n then first_char ^ Pervasives.string_of_int (l - 2) ^ last_char\n else w\n\nlet rec reading_words n = \n if n > 0\n then \n let word = Scanf.scanf \"%s \" (fun word -> word) in\n Printf.printf \"%s\\n\" (abbreviate word);\n reading_words (n - 1)\n else \n ()\n\nlet () = reading_words number_of_words\n\n"}, {"source_code": "let number_of_words = Scanf.scanf \"%d \" (fun n -> n)\n\nlet abbreviate w = \n let l = String.length w in\n let first_char = String.make 1 (String.get w 0) in\n let last_char = String.make 1 (String.get w (l - 1)) in\n if l > 10\n then first_char ^ string_of_int (l - 2) ^ last_char\n else w\n\nlet rec reading_words n = \n if n > 0\n then \n let word = Scanf.scanf \"%s \" (fun word -> word) in\n Printf.printf \"%s\\n\" (abbreviate word);\n reading_words (n - 1)\n else \n ()\n\nlet () = reading_words number_of_words\n\n"}, {"source_code": "let input () =\n Scanf.bscanf Scanf.Scanning.stdin \" %s\" (fun x -> x)\n\nlet eat () =\n let s = input ()\n in let len = String.length s\n in if len > 10 then\n Printf.printf \"%c%d%c\\n\" (String.get s 0) (len - 2) (String.get s (len - 1))\n else\n Printf.printf \"%s\\n\" s\n\nlet main () =\n let n = Scanf.bscanf Scanf.Scanning.stdin \" %d\" (fun x -> x)\n in let rec int x =\n if x = 0 then ()\n else (eat (); int (x - 1))\n in int n\n\n;;\nmain ();;\n"}, {"source_code": "(* Code Forces : Way Too Long Words *)\n\nopen Scanf\nopen Printf\n\nlet i = scanf \" %d\" (fun i -> i)\n\nlet l_w =\n let rec loop i out =\n if i = 0 then\n out\n else\n loop (i-1) ((scanf \" %s\" (fun w -> w))::out)\n in loop i []\n\nlet () =\n let l_w' =\n List.rev_map\n (fun w ->\n let len = String.length w in\n if len > 10 then\n let b = String.sub w 0 1 in\n let e = String.sub w (len - 1) 1 in\n let slen = string_of_int (len-2) in\n b ^ slen ^ e\n else\n w)\n l_w\n in\n List.iter (fun w -> printf \"%s\\n\" w) l_w'\n"}, {"source_code": "let () =\n let n=read_int () in\n for i=1 to n do\n let s=read_line () in\n let len=String.length s in\n if len > 10 then\n print_endline ((String.sub s 0 1) ^ (string_of_int(len - 2)) ^ (String.sub s (len - 1) 1))\n else\n print_endline s\n done\n"}, {"source_code": "for i=1to read_int()do let s,c=read_line(),print_char in let l=String.length s in if l>10then(c s.[0];print_int(l-2);c s.[l-1])else print_string s; c '\\n' done\n"}, {"source_code": "let short s =\n\tlet len = String.length s in\n\tif len > 10 then\n\t\t(String.sub s 0 1) ^ (string_of_int (len-2)) ^ (String.sub s (len-1) 1)\n\telse\n\t\ts\n;;\n\nlet () =\n\tlet n = read_int() in\n\tfor i = 1 to n do print_string (short (read_line()) ^ \"\\n\") done\n;;\n"}, {"source_code": "let readList n f =\n let rec loop n =\n if n == 0 then\n []\n else\n f() :: loop (n-1)\n in\n List.rev(loop n);;\n\nlet solve() =\n let str = read_line() in\n let len = String.length str in\n if (len) <= 10 then\n Printf.printf \"%s\\n\" str\n else\n Printf.printf \"%c%d%c\\n\" (str.[0]) (len-2) (str.[len-1]);;\n\nlet n = read_int() in\nreadList n solve\n"}, {"source_code": "let process s len = \n String.sub s 0 1 ^ string_of_int (len-2) ^ String.sub s (len-1) 1\n\nlet rec solve n = \n match n with \n | 0 -> ()\n | n -> \n let s = read_line () in\n let f s = \n let len = String.length s in\n match s with \n | s when len <= 10 -> print_string (s ^ \"\\n\")\n | s -> print_string ((process s len) ^ \"\\n\")\n in let top n = \n f s; \n solve (n-1) in top n\n \nlet n = read_int() in\n solve n\n"}, {"source_code": "let n=read_int();;\nfor i=1 to n do\n let s=read_line() in\n if String.length(s)<=10 then print_endline(s)\n else print_endline((String.sub s 0 1)^string_of_int(String.length(s)-2)^(String.sub s (String.length(s)-1) 1))\ndone;;"}, {"source_code": "\nlet () =\n let n = read_int () in\n for i = 1 to n do\n let str = read_line () in\n let len = String.length str in\n if len>10 then\n Printf.printf \"%c%d%c\\n\" (String.get str 0) (len-2) (String.get str (len-1))\n else\n Printf.printf \"%s\\n\" str\n done;;\n"}, {"source_code": "let next_int ()= \n\tScanf.scanf \" %d\" (function i -> i);;\n\t\nlet next_string ()= \n\tScanf.scanf \" %s\" (function i -> i);;\n\nlet string_of_char c = \n\tString.make 1 c\n;;\n\t\nlet n = next_int();;\n\nlet rec read n =\n\tif n = 0 then [] \n\telse next_string() :: (read (n - 1))\n;;\n\nlet data = read n;;\n\nlet change s = \n\tlet len = String.length s in\n\tif len <= 10 then s\n\telse string_of_char (String.get s 0) ^ (string_of_int (len - 2)) ^ string_of_char (String.get s (len - 1))\n;;\n\nlet ans = List.map change data;;\n\nList.map (function x -> print_endline x) (List.rev ans);;"}, {"source_code": "let n=read_int();;\nfor i=1 to n do\n let str=read_line() in \n let va=String.length(str) in\n if va<=10 then print_endline(str) else print_endline((String.make 1 str.[0])^(string_of_int (va-2))^(String.make 1 str.[va-1]));\ndone;;\n"}, {"source_code": "\nlet abbr s =\n let len = String.length s in\n let head = String.sub s 0 1 in\n let last = String.sub s (len - 1) 1\n in\n if 10 < len then\n head ^ (string_of_int (len - 2)) ^ last\n else\n s\n;;\n\nlet make_list n =\n Array.to_list (Array.init n (fun _ -> read_line ()))\n;;\n\n(* solve :: bytes list -> bytes *)\nlet solve xs =\n String.concat \"\\n\" (List.map abbr xs)\n;;\n\nlet () =\n Printf.printf \"%s\\n\"\n (solve (make_list (read_int ())))\n;;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> (read_line ()) :: read_lines (n - 1)\n\nlet () =\n let num = read_int() in\n read_lines num\n |> List.rev\n |> List.iter (fun str ->\n let len = String.length str in\n if len <= 10\n then\n Printf.printf \"%s\\n\" str\n else\n Printf.printf \"%c%d%c\\n\" str.[0] (len - 2) str.[len - 1]\n )\n;;\n"}, {"source_code": "open Scanf\nopen Num\nopen Printf\nopen String\n\nlet n = Scanf.bscanf Scanf.Scanning.stdin \"%d \" ( fun x -> x)\n\nfor i = 1 to n do\n let s = Scanf.bscanf Scanf.Scanning.stdin \"%s \" ( fun x -> x) in\n let l = length s in \n if ( l <= 10) then\n print_endline s\n else\n let s1 = String.make 1 (String.get s 0) in\n let se = String.make 1 (String.get s ( l - 1)) in\n let num = string_of_int ( l - 2 ) in \n print_endline (s1 ^ num ^ se)\ndone\n"}, {"source_code": "let abbrev word =\n let len = (String.length word) in\n if len < 11 then word\n else (String.make 1 (String.get word 0))\n ^ (string_of_int (len-2)) \n ^ (String.make 1 (String.get word (len-1)))\n\nlet main () =\n let gr () = Scanf.scanf \" %d\\n\" (fun i -> i) in\n let n = gr () in\n for i = 1 to n do\n let grr () = Scanf.scanf \"%s\\n\" (fun i -> i) in\n let word = grr () in\n Printf.printf \"%s\\n\" (abbrev word)\n done\n;;\n\nlet _ = main();;\n"}, {"source_code": "let len word = String.length word;;\nlet first word = String.make 1 (String.get word 0);;\nlet last word = String.make 1 (String.get word ((len word) - 1));;\nlet abbr word = (first word) ^ (string_of_int ((len word) - 2)) ^ (last word);;\nlet solve word = if len word > 10 then abbr word else word;;\n\nlet rec read_and_solve n = if n > 0 then (\n Scanf.scanf \"%s\\n\" (fun s -> print_string ((solve s) ^ \"\\n\"));\n read_and_solve (n - 1);\n) else ();;\n\nlet () = Scanf.scanf \"%d\\n\" read_and_solve;;"}, {"source_code": "open Printf\nopen Scanf\n\nlet id x = x\n\nlet abbreviate s =\n let n = String.length s in\n if n > 10 then sprintf \"%c%d%c\" s.[0] (n - 2) s.[n-1] else s\n\nlet () =\n let n = scanf \" %d\" id in\n for i = 1 to n do begin\n let s = scanf \" %s\" id in\n let t = abbreviate s in\n printf \"%s\\n\" t\n end done\n"}, {"source_code": "let trans = function\n | s when (String.length s) <= 10 -> s\n | s -> let head = String.get s 0\n and len = String.length s in\n let tail = String.get s (len - 1)\n in\n Printf.sprintf \"%c%d%c\" head (len - 2) tail;;\n\nlet case_num = read_int ();;\nfor i = 1 to case_num do\n let s = read_line ()\n in Printf.printf \"%s\\n\" (trans s)\ndone ;;\n"}, {"source_code": "open Printf\n\nlet compress word = \n let l = String.length word in\n if l > 10 then\n sprintf \"%c%d%c\" (word.[0]) (l - 2) (word.[l - 1])\n else\n word\n\nlet main =\n let n = read_int() in\n for i = 1 to n do\n let word = read_line() in\n printf \"%s\\n\" (compress word)\n done"}, {"source_code": "let read_string() = Scanf.bscanf Scanf.Scanning.stdib \" %s \" (fun x -> x)\n\nlet () =\n let n = read_int() in\n for i=1 to n do\n let s = read_string() in\n let l = String.length s in\n if l > 10 then Printf.printf \"%c%d%c\\n\" s.[0] (l - 2) s.[l - 1]\n else print_endline s\n done"}], "negative_code": [{"source_code": "let _ =\n let main () =\n let n = read_int () in\n for i = 1 to n do\n let s = read_line () in\n let l = String.length s in\n if l >= 10 then (\n Printf.printf \"%c%d%c\\n\" s.[0] (l - 2) s.[l - 1]\n ) else print_endline s\n done\n in\n main ()\n"}, {"source_code": "let input () =\n Scanf.bscanf Scanf.Scanning.stdin \"%s\" (fun x -> x)\n\nlet main () =\n let s = input ()\n in let len = String.length s\n in if len > 10 then\n Printf.printf \"%c%d%c\" (String.get s 0) (len - 2) (String.get s (len - 1))\n else\n Printf.printf \"%s\" s\n;;\n\nmain ();;\n"}, {"source_code": "let n=read_int();;\nfor i=1 to n do\n let s=read_line() in\n if String.length(s)<10 then print_endline(s)\n else print_endline((String.sub s 0 1)^string_of_int(String.length(s)-2)^(String.sub s (String.length(s)-1) 1))\ndone;;"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> (read_line ()) :: read_lines (n - 1)\n\nlet () =\n let num = read_int() in\n read_lines num\n |> List.rev\n |> List.iter (fun str ->\n let len = String.length str in\n if len <= num\n then\n Printf.printf \"%s\\n\" str\n else\n Printf.printf \"%c%d%c\\n\" str.[0] (len - 2) str.[len - 1]\n )\n;;\n"}, {"source_code": "let rec read_lines n =\n match n with\n | 0 -> []\n | _ -> (read_line ()) :: read_lines (n - 1)\n\nlet () =\n let num = read_int() in\n read_lines num\n |> List.iter (fun str ->\n let len = String.length str in\n if len <= num\n then\n Printf.printf \"%s\\n\" str\n else\n Printf.printf \"%c%d%c\\n\" str.[0] (len - 2) str.[len - 1]\n )\n;;\n"}, {"source_code": "let abbrev word =\n let len = (String.length word) in\n if len < 10 then word\n else (String.make 1 (String.get word 0))\n ^ (string_of_int (len-2)) \n ^ (String.make 1 (String.get word (len-1)))\n\nlet main () =\n let gr () = Scanf.scanf \" %d\\n\" (fun i -> i) in\n let n = gr () in\n for i = 1 to n do\n let grr () = Scanf.scanf \"%s\\n\" (fun i -> i) in\n let word = grr () in\n Printf.printf \"%s\\n\" (abbrev word)\n done\n;;\n\nlet _ = main();;\n"}], "src_uid": "6639d6c53951f8c1a8324fb24ef68f7a"} {"nl": {"description": "Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1,\u2009i2,\u2009i3, that 1\u2009\u2264\u2009i1\u2009<\u2009i2\u2009<\u2009i3\u2009\u2264\u2009n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b\u00b7k0,\u2009b\u00b7k1,\u2009...,\u2009b\u00b7kr\u2009-\u20091.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.", "input_spec": "The first line of the input contains two integers, n and k (1\u2009\u2264\u2009n,\u2009k\u2009\u2264\u20092\u00b7105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109) \u2014 elements of the sequence.", "output_spec": "Output a single number \u2014 the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.", "sample_inputs": ["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"], "sample_outputs": ["4", "1", "6"], "notes": "NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet divides a b = (* does b divide a? *)\n let c = a//b in\n let d = c ** b in\n d = a\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\n\nlet read_long () = bscanf Scanning.stdib \" %Ld \" (fun x -> x)\nlet () = \n let n = short (read_long ()) in\n let k = read_long () in\n let a = Array.init n (fun _ -> read_long()) in\n \n let get h key = \n try Hashtbl.find h key with Not_found -> 0L\n in\n \n let add h key d =\n Hashtbl.replace h key ((get h key) ++ d)\n in\n\n let h1 = Hashtbl.create 10 in\n let h2 = Hashtbl.create 10 in\n let h3 = Hashtbl.create 10 in\n\n for i=0 to n-1 do\n let x = a.(i) in\n if divides x k then (\n (* update h3 first *)\n let y = x//k in\n let c = get h2 y in\n add h3 x c;\n\n (* now update h2 *) \n let c = get h1 y in\n add h2 x c;\n );\n\n (* now update h1 *)\n add h1 x 1L\n done;\n\n let total = Hashtbl.fold (\n fun _ v tot -> tot ++ v\n ) h3 0L\n in\n\n printf \"%Ld\\n\" total;\n\n \n \n"}], "negative_code": [], "src_uid": "bd4b3bfa7511410c8e54658cc1dddb46"} {"nl": {"description": "The Little Elephant very much loves sums on intervals.This time he has a pair of integers l and r (l\u2009\u2264\u2009r). The Little Elephant has to find the number of such integers x (l\u2009\u2264\u2009x\u2009\u2264\u2009r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not.Help him and count the number of described numbers x for a given pair l and r.", "input_spec": "The single line contains a pair of integers l and r (1\u2009\u2264\u2009l\u2009\u2264\u2009r\u2009\u2264\u20091018) \u2014 the boundaries of the interval. Please, do not use the %lld specifier to read or write 64-bit integers in \u0421++. It is preferred to use cin, cout streams or the %I64d specifier.", "output_spec": "On a single line print a single integer \u2014 the answer to the problem.", "sample_inputs": ["2 47", "47 1024"], "sample_outputs": ["12", "98"], "notes": "NoteIn the first sample the answer includes integers 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44. "}, "positive_code": [{"source_code": "#load \"str.cma\";;\n\nlet array_of_int n =\n let rec iter ls cur =\n\tif Int64.compare cur 0L = 0 then ls\n\telse\n\t let r = Int64.to_int (Int64.rem cur 10L) and\n\t\t l = Int64.div cur 10L in\n\t iter (r :: ls) l in\n Array.of_list (iter [] n);;\n\nlet int_of_array arr l r =\n let rec iter i res =\n\tif i > r then res\n\telse iter (i + 1) (Int64.add (Int64.mul res 10L) (Int64.of_int arr.(i))) in\n iter l 0L;;\n\nlet pow_int n e =\n let rec iter i cur =\n\tif i >= e then cur\n\telse iter (i + 1) (Int64.mul cur (Int64.of_int n))\n in iter 0 1L;;\n\t\nlet rec num_x n =\n if Int64.compare n 10L < 0 then n\n else if Int64.compare n 100L < 0 then\n\tlet l = Int64.div n 10L and\n\t\tr = Int64.rem n 10L in\n\tInt64.add (if Int64.compare r l >= 0 then l else Int64.pred l) 9L\n else\n\tlet na = array_of_int n in\n\tlet\tl = na.(Array.length na - 1) and\n\t\tr = na.(0) and\n\t\tmid = int_of_array na 1 (Array.length na - 2) in\n\tlet m = num_x (Int64.sub (pow_int 10 (Array.length na - 1)) 1L) and\n\t\tmm = Int64.mul (pow_int 10 (Array.length na - 2)) (Int64.of_int (r - 1)) and\n\t\tmmm = Int64.add mid (if r > l then 0L else 1L) in\n\tInt64.add (Int64.add m mm) mmm;;\n\nlet get_input () =\n let ls = List.map (fun x -> (Int64.of_string x))\n\t(Str.split (Str.regexp \"[ \\t]+\") (read_line ())) in \n(List.hd ls, List.hd (List.tl ls));;\n\nlet (x, y) = get_input () in\nbegin\n Printf.printf \"%Ld\\n\" (Int64.sub (num_x y) ( (num_x (Int64.sub x 1L)) ));\nend\n"}], "negative_code": [{"source_code": "#load \"str.cma\";;\n\nlet array_of_int n =\n let rec iter ls cur =\n\tif Int64.compare cur 0L = 0 then ls\n\telse\n\t let r = Int64.to_int (Int64.rem cur 10L) and\n\t\t l = Int64.div cur 10L in\n\t iter (r :: ls) l in\n Array.of_list (iter [] n);;\n\nlet int_of_array arr l r =\n let rec iter i res =\n\tif i > r then res\n\telse iter (i + 1) (Int64.add (Int64.mul res 10L) (Int64.of_int arr.(i))) in\n iter l 0L;;\n\nlet pow_int n e =\n let rec iter i cur =\n\tif i >= e then cur\n\telse iter (i + 1) (Int64.mul cur (Int64.of_int n))\n in iter 0 1L;;\n\t\nlet rec num_x n =\n if Int64.compare n 10L < 0 then n\n else if Int64.compare n 100L < 0 then\n\tlet l = Int64.div n 10L and\n\t\tr = Int64.rem n 10L in\n\tInt64.add (if Int64.compare r l >= 0 then l else Int64.pred l) 9L\n else\n\tlet na = array_of_int n in\n\tlet\tl = na.(Array.length na - 1) and\n\t\tr = na.(0) and\n\t\tmid = int_of_array na 1 (Array.length na - 2) in\n\tlet m = num_x (Int64.sub (pow_int 10 (Array.length na - 1)) 1L) and\n\t\tmm = Int64.mul (pow_int 10 (Array.length na - 2)) (Int64.of_int (r - 1)) and\n\t\tmmm = Int64.add mid (if r >= l then 0L else 1L) in\n\tInt64.add (Int64.add m mm) mmm;;\n\nlet get_input () =\n let ls = List.map (fun x -> (Int64.of_string x))\n\t(Str.split (Str.regexp \"[ \\t]+\") (read_line ())) in \n(List.hd ls, List.hd (List.tl ls));;\n\nlet (x, y) = get_input () in\nPrintf.printf \"%Ld\\n\" (Int64.sub (num_x y) (Int64.sub (num_x x) 1L));;\n"}], "src_uid": "9642368dc4ffe2fc6fe6438c7406c1bd"} {"nl": {"description": "The ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP.In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed.The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings \"ab\" and \"ba\" is called \"abba\", and the dynasty, which had only the king \"abca\", is called \"abca\".Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland.Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B.", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20095\u00b7105) \u2014 the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters.", "output_spec": "Print a single number \u2014 length of the sought dynasty's name in letters. If Vasya's list is wrong and no dynasty can be found there, print a single number 0.", "sample_inputs": ["3\nabc\nca\ncba", "4\nvvp\nvvp\ndam\nvvp", "3\nab\nc\ndef"], "sample_outputs": ["6", "0", "1"], "notes": "NoteIn the first sample two dynasties can exist: the one called \"abcca\" (with the first and second kings) and the one called \"abccba\" (with the first and third kings). In the second sample there aren't acceptable dynasties.The only dynasty in the third sample consists of one king, his name is \"c\"."}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make n 0 in\n let b = Array.make n 0 in\n let c = Array.make n 0 in\n let () =\n for i = 0 to n - 1 do\n let s = Scanf.bscanf sb \"%s \" (fun s -> s) in\n\ta.(i) <- Char.code s.[0] - Char.code 'a';\n\tb.(i) <- Char.code s.[String.length s - 1] - Char.code 'a';\n\tc.(i) <- String.length s;\n done;\n in\n let d = Array.make_matrix 26 26 0 in\n let max (x : int) y = if x > y then x else y in\n for i = 0 to n - 1 do\n let aa = a.(i)\n and bb = b.(i) in\n\tfor j = 0 to 25 do\n\t if d.(j).(aa) > 0\n\t then d.(j).(bb) <- max d.(j).(bb) (d.(j).(aa) + c.(i));\n\tdone;\n\td.(aa).(bb) <- max d.(aa).(bb) c.(i);\n done;\n let res = ref 0 in\n for i = 0 to 25 do\n\tres := max !res d.(i).(i)\n done;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [], "src_uid": "f5a17a59659b3902d87f1fd7e89e8f32"} {"nl": {"description": "Programmer Sasha is a student at MIPT (Moscow Institute of Physics and Technology) and he needs to make a laboratory work to pass his finals.A laboratory unit is a plane with standard coordinate axes marked on it. Physicists from Moscow Institute of Physics and Technology charged the axes by large electric charges: axis X is positive and axis Y is negative.Experienced laboratory worker marked n points with integer coordinates (xi,\u2009yi) on the plane and stopped the time. Sasha should use \"atomic tweezers\" to place elementary particles in these points. He has an unlimited number of electrons (negatively charged elementary particles) and protons (positively charged elementary particles). He can put either an electron or a proton at each marked point. As soon as all marked points are filled with particles, laboratory worker will turn on the time again and the particles will come in motion and after some time they will stabilize in equilibrium. The objective of the laboratory work is to arrange the particles in such a way, that the diameter of the resulting state (the maximum distance between the pairs of points of the set) is as small as possible.Since Sasha is a programmer, he naively thinks that all the particles will simply \"fall\" into their projections on the corresponding axes: electrons will fall on axis X, while protons will fall on axis Y. As we are programmers too, we will consider the same model as Sasha. That is, a particle gets from point (x,\u2009y) to point (x,\u20090) if it is an electron and to point (0,\u2009y) if it is a proton.As the laboratory has high background radiation and Sasha takes care of his laptop, he did not take it with him, and now he can't write a program that computes the minimum possible diameter of the resulting set. Therefore, you will have to do it for him.Print a square of the minimum possible diameter of the set.", "input_spec": "The first line of the input contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100\u2009000)\u00a0\u2014 the number of points marked on the plane. Each of the next n lines contains two integers xi and yi (\u2009-\u2009108\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009108)\u00a0\u2014 the coordinates of the i-th point. It is guaranteed that no two points coincide.", "output_spec": "Print a single integer\u00a0\u2014 the square of the minimum possible diameter of the set.", "sample_inputs": ["3\n1 10\n1 20\n1 30", "2\n1 10\n10 1"], "sample_outputs": ["0", "2"], "notes": "NoteIn the first sample Sasha puts electrons at all points, all particles eventually fall at a single point (1,\u20090).In the second sample Sasha puts an electron at point (1,\u200910), and a proton at point (10,\u20091). The result is a set of two points (1,\u20090) and (0,\u20091), which has a diameter of ."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\nlet abs = Int64.abs \nlet sq x = x**x\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet minmax (a,b) x = (min a x, max b x)\nlet minmax1 (a,b) (c,d) = (min a c, max b d) \n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let pointx = Array.make (n+1) 0 in\n let pointy = Array.make (n+1) 0 in\n\n for i=0 to n-1 do\n let (x,y) = read_pair() in\n pointy.(i) <- x;\n pointx.(i) <- y;\n done;\n\n let maxx = long (maxf 0 (n-1) (fun i -> pointx.(i))) in\n let minx = long (minf 0 (n-1) (fun i -> pointx.(i))) in\n let maxy = long (maxf 0 (n-1) (fun i -> pointy.(i))) in\n let miny = long (minf 0 (n-1) (fun i -> pointy.(i))) in\n\n let opt1 = sq (maxx -- minx) in\n let opt2 = sq (maxy -- miny) in\n\n let n = n+1 in (* add the zero point in for convenience *)\n \n let perm = Array.init n (fun i -> i) in\n Array.fast_sort (fun i j -> compare pointx.(i) pointx.(j)) perm;\n\n let search pointx pointy =\n \n let prefix = Array.make n (0L,0L) in\n let suffix = Array.make n (0L,0L) in\n \n prefix.(0) <- (pointy.(0), pointy.(0));\n for i=1 to n-1 do\n prefix.(i) <- minmax prefix.(i-1) pointy.(i)\n done;\n \n suffix.(n-1) <- (pointy.(n-1), pointy.(n-1));\n for i=n-2 downto 0 do\n suffix.(i) <- minmax suffix.(i+1) pointy.(i)\n done;\n \n let get ar j = if j<0 || j>=n then (0L,0L) else ar.(j) in\n \n (* now prefix.(i) = (ylo, yhi), where ylo is the min \n value among pointy.(0)...pointy.(i), yhi is analogous.\n also suffix.(i) = same thing but for range i...n-1\n *)\n\n let rec findzero i =\n if (pointx.(i), pointy.(i)) = (0L,0L) then i else findzero (i+1)\n in\n let zero_index = findzero 0 in\n\n let rec values i j =\n (* for this (i,j) returns (horiz_score, max(diag_score, vert_score))\n\t We assume pointx.(i) <= 0 and pointx.(j) >= 0 and \n abs pointx.(i) >= abs pointx.(j)\n *)\n let (miny, maxy) = minmax1 (get prefix (i-1)) (get suffix (j+1)) in\n let vert_score = sq (maxy -- miny) in\n let diag_score = max (sq miny) (sq maxy) ++ (sq pointx.(i)) in\n let horiz_score = sq (pointx.(j) -- pointx.(i)) in\n (horiz_score, max vert_score diag_score)\n in\n\n let test i j = let (h,v) = values i j in h >= v in\n\n let starthi = ref (n-1) in\n \n minf 0 zero_index (fun i ->\n let rec fixst () =\n\tif abs pointx.(!starthi) > abs pointx.(i) then (\n\t starthi := !starthi - 1;\n\t fixst ()\n\t)\n in\n fixst();\n \n let rec bsearch lo hi =\n\tif lo+1 = hi then lo else\n\t let m = (lo + hi) / 2 in\n\t if test i m then bsearch lo m else bsearch m hi\n in\n\n if !starthi = zero_index || test i zero_index then\n\tlet (h,v) = values i zero_index in max h v\n else\n\tlet index = bsearch zero_index !starthi in\n\tlet v1 = let (h,v) = values i index in max h v in\n\tlet v2 = let (h,v) = values i (index+1) in max h v in\n\tmin v1 v2\n )\n in\n\n let pointx = Array.init n (fun i -> long pointx.(perm.(i))) in\n let pointy = Array.init n (fun i -> long pointy.(perm.(i))) in\n let opt3 = search pointx pointy in\n\n let rev ar n =\n for i=0 to n/2 - 1 do\n let (p,q) = (ar.(i), ar.(n-1-i)) in\n ar.(i) <- q;\n ar.(n-1-i) <- p\n done\n in\n rev pointx n;\n rev pointy n;\n\n let opt4 = search pointx pointy in\n \n printf \"%Ld\\n\" (min (min opt1 opt2) (min opt3 opt4))\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\n \nlet sq x = x**x\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet minmax (a,b) x = (min a x, max b x)\nlet minmax1 (a,b) (c,d) = (min a c, max b d) \n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let pointx = Array.make n 0 in\n let pointy = Array.make n 0 in\n\n for i=0 to n-1 do\n let (x,y) = read_pair() in\n pointx.(i) <- x;\n pointy.(i) <- y;\n done;\n\n let perm = Array.init n (fun i -> i) in\n Array.fast_sort (fun i j -> compare pointx.(i) pointx.(j)) perm;\n\n let pointx = Array.init n (fun i -> long pointx.(perm.(i))) in\n let pointy = Array.init n (fun i -> long pointy.(perm.(i))) in \n\n let prefix = Array.make n (0L,0L) in\n let suffix = Array.make n (0L,0L) in\n\n prefix.(0) <- (pointy.(0), pointy.(0));\n for i=1 to n-1 do\n prefix.(i) <- minmax prefix.(i-1) pointy.(i)\n done;\n\n suffix.(n-1) <- (pointy.(n-1), pointy.(n-1));\n for i=n-2 downto 0 do\n suffix.(i) <- minmax suffix.(i+1) pointy.(i)\n done;\n\n let dist_works d =\n let rec scan i j =\n if i=0 && j=n-1 then true else\n (* (i,j) is a new range. Check it *)\n\tlet (min3, max3) =\n\t match (i=0, j=n-1) with\n\t | (true,true) -> failwith \"no way\"\n\t | (true,false) -> suffix.(j+1)\n\t | (false,true) -> prefix.(i-1)\n\t | (false,false) -> minmax1 suffix.(j+1) prefix.(i-1)\n\tin\n\tlet dist2_from_axis a b = max (sq a) (sq b) in\n\tlet dx = dist2_from_axis pointx.(i) pointx.(j) in\n\tlet dy = dist2_from_axis min3 max3 in\n\tif sq (max3 -- min3) <= d && dx ++ dy <= d then true\n\telse if j = n-1 && i = n-1 then false else\n\t let j' = if j=n-1 || sq (pointx.(j+1)--pointx.(i)) > d then j else j+1 in\n\t let i' = if j=j' then i+1 else i in\n\t scan i' j'\n in\n let rec findj j = if j=n-1 then j else if pointx.(j+1) >= 0L then j else findj (j+1) in\n let j = findj 0 in\n let rec findi i = if sq (pointx.(j)--pointx.(i)) <= d then i else findi (i+1) in\n let i = findi 0 in\n scan i j\n in\n \n let rec bsearch lo hi = (* lo fails, hi works *)\n if lo++1L >= hi then hi else\n let mid = (lo ++ hi) // 2L in\n if dist_works mid then bsearch lo mid else bsearch mid hi\n in\n\n (* let rec findlo lo = if not (dist_works lo) then lo else findlo (lo//4L) in\n let lo = findlo 40000000000000000L in *)\n\n let maxd = sq (pointx.(0) -- pointx.(n-1)) in\n let maxy = maxf 0 (n-1) (fun i -> pointy.(i)) in\n let miny = minf 0 (n-1) (fun i -> pointy.(i)) in\n let opt1 = min maxd (sq (maxy -- miny)) in\n let opt2 = if dist_works 0L then 0L else bsearch 0L opt1 in\n \n printf \"%Ld\\n\" opt2\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %Ld %Ld \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n\n let point = Array.init n (fun _ -> read_pair()) in\n\n Array.sort (fun (x1,y1) (x2,y2) -> compare (Int64.abs y2) (Int64.abs y1) ) point;\n (* sorted in decreasing order by absolute value *)\n\n let score a b = a**a ++ b**b in\n\n let maxx = maxf 0 (n-1) (fun i -> fst point.(i)) in\n let minx = minf 0 (n-1) (fun i -> fst point.(i)) in\n let maxy = maxf 0 (n-1) (fun i -> snd point.(i)) in\n let miny = minf 0 (n-1) (fun i -> snd point.(i)) in\n \n let rec loop i width ac = if i=n then ac else\n (* delete point i-1 from y *)\n let width = max width (Int64.abs (fst point.(i-1))) in\n let height = Int64.abs (snd point.(i)) in\n loop (i+1) width (min (score width height) ac)\n in\n\n let opt1 = score (maxx -- minx) 0L in\n let opt2 = score (maxy -- miny) 0L in\n \n let answer = loop 1 0L (min opt1 opt2) in\n (* this loop only considers projecting to two axes *)\n \n printf \"%Ld\\n\" answer\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\n\nlet long x = Int64.of_int x\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet minf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %Ld %Ld \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n\n (*\n let xx = Array.make n (0L,0) in\n let yy = Array.make n (0L,0) in \n *)\n \n let point = Array.init n (fun i -> (read_pair(), i)) in\n\n let pointy = Array.copy point in\n\n Array.sort (fun ((x1,y1),i) ((x2,y2),j) -> compare (Int64.abs y2) (Int64.abs y1) ) pointy;\n (* sorted in decreasing order by absolute value *)\n\n let rec loop i width ac = if i=n then ac else\n (* delete point i from y *)\n let ((x,y),_) = pointy.(i) in\n let width = max width (Int64.abs x) in\n let height = Int64.abs y in\n let score = width ** width ++ height ** height in\n loop (i+1) width (min score ac)\n in\n\n let answer = loop 0 0L 0L in\n\n printf \"%Ld\\n\" answer\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\n \nlet sq x = x**x\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet minmax (a,b) x = (min a x, max b x)\nlet minmax1 (a,b) (c,d) = (min a c, max b d) \n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let pointx = Array.make n 0 in\n let pointy = Array.make n 0 in\n\n for i=0 to n-1 do\n let (x,y) = read_pair() in\n pointx.(i) <- x;\n pointy.(i) <- y;\n done;\n\n let perm = Array.init n (fun i -> i) in\n Array.fast_sort (fun i j -> compare pointx.(i) pointx.(j)) perm;\n\n let pointx = Array.init n (fun i -> long pointx.(perm.(i))) in\n let pointy = Array.init n (fun i -> long pointy.(perm.(i))) in \n\n let prefix = Array.make n (0L,0L) in\n let suffix = Array.make n (0L,0L) in\n\n prefix.(0) <- (pointy.(0), pointy.(0));\n for i=1 to n-1 do\n prefix.(i) <- minmax prefix.(i-1) pointy.(i)\n done;\n\n suffix.(n-1) <- (pointy.(n-1), pointy.(n-1));\n for i=n-2 downto 0 do\n suffix.(i) <- minmax suffix.(i+1) pointy.(i)\n done;\n\n let dist_works d =\n let rec scan i j =\n if i=0 && j=n-1 then true else\n (* (i,j) is a new range. Check it *)\n\tlet (min3, max3) =\n\t match (i=0, j=n-1) with\n\t | (true,true) -> failwith \"no way\"\n\t | (true,false) -> suffix.(j+1)\n\t | (false,true) -> prefix.(i-1)\n\t | (false,false) -> minmax1 suffix.(j+1) prefix.(i-1)\n\tin\n\tlet dist2_from_axis a b = max (sq a) (sq b) in\n\tlet dx = dist2_from_axis pointx.(i) pointx.(j) in\n\tlet dy = dist2_from_axis min3 max3 in\n\tif sq (max3 -- min3) <= d && dx ++ dy <= d then true\n\telse if j = n-1 && i = n-1 then false else\n\t let j' = if j=n-1 || sq (pointx.(j+1)--pointx.(i)) > d then j else j+1 in\n\t let i' = if j=j' then i+1 else i in\n\t scan i' j'\n in\n let rec findj j = if j=n-1 then j else if pointx.(j) >= 0L then j else findj (j+1) in\n let j = findj 0 in\n let rec findi i = if sq (pointx.(j)--pointx.(i)) <= d then i else findi (i+1) in\n let i = findi 0 in\n scan i j\n in\n \n let rec bsearch lo hi = (* lo fails, hi works *)\n if lo++1L >= hi then hi else\n let mid = (lo ++ hi) // 2L in\n if dist_works mid then bsearch lo mid else bsearch mid hi\n in\n\n (* let rec findlo lo = if not (dist_works lo) then lo else findlo (lo//4L) in\n let lo = findlo 40000000000000000L in *)\n\n let maxd = sq (pointx.(0) -- pointx.(n-1)) in\n let maxy = maxf 0 (n-1) (fun i -> pointy.(i)) in\n let miny = minf 0 (n-1) (fun i -> pointy.(i)) in\n let opt1 = min maxd (sq (maxy -- miny)) in\n let opt2 = if dist_works 0L then 0L else bsearch 0L opt1 in\n \n printf \"%Ld\\n\" opt2\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\n\nlet sq x = x**x\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet minmax (a,b) x = (min a x, max b x)\nlet minmax1 (a,b) (c,d) = (min a c, max b d) \n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %Ld %Ld \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n\n let point = Array.init n (fun _ -> read_pair()) in\n\n Array.sort compare point;\n (* sorted by increasing x value *)\n\n let pointx = Array.init n (fun i -> fst point.(i)) in\n let pointy = Array.init n (fun i -> snd point.(i)) in \n\n let prefix = Array.make n (0L,0L) in\n let suffix = Array.make n (0L,0L) in\n\n prefix.(0) <- (snd point.(0), pointy.(0));\n for i=1 to n-1 do\n prefix.(i) <- minmax prefix.(i-1) pointy.(i)\n done;\n\n suffix.(n-1) <- (pointy.(n-1), pointy.(n-1));\n for i=n-2 downto 0 do\n suffix.(i) <- minmax suffix.(i+1) pointy.(i)\n done;\n\n let dist_works d =\n let rec scan (i,j) =\n if i=0 && j=n-1 then true else\n (* (i,j) is a new range. Check it *)\n\tlet (min3, max3) =\n\t match (i=0, j=n-1) with\n\t | (true,true) -> failwith \"no way\"\n\t | (true,false) -> suffix.(j+1)\n\t | (false,true) -> prefix.(i-1)\n\t | (false,false) -> minmax1 suffix.(j+1) prefix.(i-1)\n\tin\n\tlet dist2_from_axis a b = max (sq a) (sq b) in\n\tlet dx = dist2_from_axis min3 max3 in\n\tlet dy = dist2_from_axis pointx.(i) pointx.(j) in\n\tif sq (max3 -- min3) <= d && dx ++ dy <= d then true\n\telse if j = n-1 then false else\n\t let j = j+1 in\n\t let rec advancei i = if sq (pointx.(j) -- pointx.(i)) <= d then i\n\t else advancei (i+1)\n\t in\n\t scan (advancei i, j)\n in\n scan (0,0)\n in\n \n let rec bsearch lo hi = (* lo fails, hi works *)\n if lo++1L = hi then hi else\n let mid = (lo ++ hi) // 2L in\n if dist_works mid then bsearch lo mid else bsearch mid hi\n in\n let maxd = sq (pointx.(0) -- pointx.(n-1)) in\n let opt1 = if dist_works 0L then 0L else bsearch 0L maxd in\n \n let maxy = maxf 0 (n-1) (fun i -> pointy.(i)) in\n let miny = minf 0 (n-1) (fun i -> pointy.(i)) in\n let opt2 = sq (maxy -- miny) in\n \n printf \"%Ld\\n\" (min opt1 opt2)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\n \nlet sq x = x**x\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet minmax (a,b) x = (min a x, max b x)\nlet minmax1 (a,b) (c,d) = (min a c, max b d) \n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let pointx = Array.make n 0 in\n let pointy = Array.make n 0 in\n\n for i=0 to n-1 do\n let (x,y) = read_pair() in\n pointx.(i) <- x;\n pointy.(i) <- y;\n done;\n\n let perm = Array.init n (fun i -> i) in\n Array.fast_sort (fun i j -> compare pointx.(j) pointx.(i)) perm;\n\n let pointx = Array.init n (fun i -> long pointx.(perm.(i))) in\n let pointy = Array.init n (fun i -> long pointy.(perm.(i))) in \n\n let prefix = Array.make n (0L,0L) in\n let suffix = Array.make n (0L,0L) in\n\n prefix.(0) <- (pointy.(0), pointy.(0));\n for i=1 to n-1 do\n prefix.(i) <- minmax prefix.(i-1) pointy.(i)\n done;\n\n suffix.(n-1) <- (pointy.(n-1), pointy.(n-1));\n for i=n-2 downto 0 do\n suffix.(i) <- minmax suffix.(i+1) pointy.(i)\n done;\n\n let dist_works d =\n let rec scan i j =\n if i=0 && j=n-1 then true else\n (* (i,j) is a new range. Check it *)\n\tlet (min3, max3) =\n\t match (i=0, j=n-1) with\n\t | (true,true) -> failwith \"no way\"\n\t | (true,false) -> suffix.(j+1)\n\t | (false,true) -> prefix.(i-1)\n\t | (false,false) -> minmax1 suffix.(j+1) prefix.(i-1)\n\tin\n\tlet dist2_from_axis a b = max (sq a) (sq b) in\n\tlet dx = dist2_from_axis pointx.(i) pointx.(j) in\n\tlet dy = dist2_from_axis min3 max3 in\n\tif sq (max3 -- min3) <= d && dx ++ dy <= d then true\n\telse if j = n-1 && i = n-1 then false else\n\t let j' = if j=n-1 || sq (pointx.(j+1)--pointx.(i)) > d then j else j+1 in\n\t let i' = if j=j' then i+1 else i in\n\t scan i' j'\n in\n let rec findj j = if j=n-1 then j else if pointx.(j+1) <= 0L then j else findj (j+1) in\n let j = findj 0 in\n let rec findi i = if sq (pointx.(j)--pointx.(i)) <= d then i else findi (i+1) in\n let i = findi 0 in\n scan i j\n in\n \n let rec bsearch lo hi = (* lo fails, hi works *)\n if lo++1L >= hi then hi else\n let mid = (lo ++ hi) // 2L in\n if dist_works mid then bsearch lo mid else bsearch mid hi\n in\n\n (* let rec findlo lo = if not (dist_works lo) then lo else findlo (lo//4L) in\n let lo = findlo 40000000000000000L in *)\n\n let maxd = sq (pointx.(0) -- pointx.(n-1)) in\n let maxy = maxf 0 (n-1) (fun i -> pointy.(i)) in\n let miny = minf 0 (n-1) (fun i -> pointy.(i)) in\n let opt1 = min maxd (sq (maxy -- miny)) in\n let opt2 = if dist_works 0L then 0L else bsearch 0L opt1 in\n \n printf \"%Ld\\n\" opt2\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\n \nlet sq x = x**x\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet minmax (a,b) x = (min a x, max b x)\nlet minmax1 (a,b) (c,d) = (min a c, max b d) \n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let pointx = Array.make n 0 in\n let pointy = Array.make n 0 in\n\n for i=0 to n-1 do\n let (x,y) = read_pair() in\n pointy.(i) <- x;\n pointx.(i) <- y;\n done;\n\n let perm = Array.init n (fun i -> i) in\n Array.fast_sort (fun i j -> compare pointx.(i) pointx.(j)) perm;\n\n let pointx = Array.init n (fun i -> long pointx.(perm.(i))) in\n let pointy = Array.init n (fun i -> long pointy.(perm.(i))) in \n\n let prefix = Array.make n (0L,0L) in\n let suffix = Array.make n (0L,0L) in\n\n prefix.(0) <- (pointy.(0), pointy.(0));\n for i=1 to n-1 do\n prefix.(i) <- minmax prefix.(i-1) pointy.(i)\n done;\n\n suffix.(n-1) <- (pointy.(n-1), pointy.(n-1));\n for i=n-2 downto 0 do\n suffix.(i) <- minmax suffix.(i+1) pointy.(i)\n done;\n\n let dist_works d =\n let rec scan i j =\n if i=0 && j=n-1 then true else\n (* (i,j) is a new range. Check it *)\n\tlet (min3, max3) =\n\t match (i=0, j=n-1) with\n\t | (true,true) -> failwith \"no way\"\n\t | (true,false) -> suffix.(j+1)\n\t | (false,true) -> prefix.(i-1)\n\t | (false,false) -> minmax1 suffix.(j+1) prefix.(i-1)\n\tin\n\tlet dist2_from_axis a b = max (sq a) (sq b) in\n\tlet dx = dist2_from_axis pointx.(i) pointx.(j) in\n\tlet dy = dist2_from_axis min3 max3 in\n\tif sq (max3 -- min3) <= d && dx ++ dy <= d then true\n\telse if j = n-1 && i = n-1 then false else\n\t let j' = if j=n-1 || sq (pointx.(j+1)--pointx.(i)) > d then j else j+1 in\n\t let i' = if j=j' then i+1 else i in\n\t scan i' j'\n in\n let rec findj j = if j=n-1 then j else if pointx.(j+1) >= 0L then j else findj (j+1) in\n let j = findj 0 in\n let rec findi i = if sq (pointx.(j)--pointx.(i)) <= d then i else findi (i+1) in\n let i = findi 0 in\n scan i j\n in\n \n let rec bsearch lo hi = (* lo fails, hi works *)\n if lo++1L >= hi then hi else\n let mid = (lo ++ hi) // 2L in\n if dist_works mid then bsearch lo mid else bsearch mid hi\n in\n\n (* let rec findlo lo = if not (dist_works lo) then lo else findlo (lo//4L) in\n let lo = findlo 40000000000000000L in *)\n\n let maxd = sq (pointx.(0) -- pointx.(n-1)) in\n let maxy = maxf 0 (n-1) (fun i -> pointy.(i)) in\n let miny = minf 0 (n-1) (fun i -> pointy.(i)) in\n let opt1 = min maxd (sq (maxy -- miny)) in\n let opt2 = if dist_works 0L then 0L else bsearch 0L opt1 in\n \n printf \"%Ld\\n\" opt2\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet long x = Int64.of_int x\n \nlet sq x = x**x\n \nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet minmax (a,b) x = (min a x, max b x)\nlet minmax1 (a,b) (c,d) = (min a c, max b d) \n \nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let n = read_int () in\n let pointx = Array.make n 0 in\n let pointy = Array.make n 0 in\n\n for i=0 to n-1 do\n let (x,y) = read_pair() in\n pointx.(i) <- x;\n pointy.(i) <- y;\n done;\n\n let perm = Array.init n (fun i -> i) in\n Array.fast_sort (fun i j -> compare pointx.(j) pointx.(i)) perm;\n\n let pointx = Array.init n (fun i -> long pointx.(perm.(i))) in\n let pointy = Array.init n (fun i -> long pointy.(perm.(i))) in \n\n let prefix = Array.make n (0L,0L) in\n let suffix = Array.make n (0L,0L) in\n\n prefix.(0) <- (pointy.(0), pointy.(0));\n for i=1 to n-1 do\n prefix.(i) <- minmax prefix.(i-1) pointy.(i)\n done;\n\n suffix.(n-1) <- (pointy.(n-1), pointy.(n-1));\n for i=n-2 downto 0 do\n suffix.(i) <- minmax suffix.(i+1) pointy.(i)\n done;\n\n let dist_works d =\n let rec scan i j =\n if i=0 && j=n-1 then true else\n (* (i,j) is a new range. Check it *)\n\tlet (min3, max3) =\n\t match (i=0, j=n-1) with\n\t | (true,true) -> failwith \"no way\"\n\t | (true,false) -> suffix.(j+1)\n\t | (false,true) -> prefix.(i-1)\n\t | (false,false) -> minmax1 suffix.(j+1) prefix.(i-1)\n\tin\n\tlet dist2_from_axis a b = max (sq a) (sq b) in\n\tlet dx = dist2_from_axis pointx.(i) pointx.(j) in\n\tlet dy = dist2_from_axis min3 max3 in\n\tif sq (max3 -- min3) <= d && dx ++ dy <= d then true\n\telse if j = n-1 && i = n-1 then false else\n\t let j' = if j=n-1 || sq (pointx.(j+1)--pointx.(i)) > d then j else j+1 in\n\t let i' = if j=j' then i+1 else i in\n\t scan i' j'\n in\n let rec findj j = if j=n-1 then j else if pointx.(j+1) >= 0L then j else findj (j+1) in\n let j = findj 0 in\n let rec findi i = if sq (pointx.(j)--pointx.(i)) <= d then i else findi (i+1) in\n let i = findi 0 in\n scan i j\n in\n \n let rec bsearch lo hi = (* lo fails, hi works *)\n if lo++1L >= hi then hi else\n let mid = (lo ++ hi) // 2L in\n if dist_works mid then bsearch lo mid else bsearch mid hi\n in\n\n (* let rec findlo lo = if not (dist_works lo) then lo else findlo (lo//4L) in\n let lo = findlo 40000000000000000L in *)\n\n let maxd = sq (pointx.(0) -- pointx.(n-1)) in\n let maxy = maxf 0 (n-1) (fun i -> pointy.(i)) in\n let miny = minf 0 (n-1) (fun i -> pointy.(i)) in\n let opt1 = min maxd (sq (maxy -- miny)) in\n let opt2 = if dist_works 0L then 0L else bsearch 0L opt1 in\n \n printf \"%Ld\\n\" opt2\n"}], "src_uid": "9ad15477fb41bcda1454eb81e1a2bd78"} {"nl": {"description": "You have matrix a of size n\u2009\u00d7\u2009n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column. Matrix a meets the following two conditions: for any numbers i,\u2009j (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n) the following inequality holds: aij\u2009\u2265\u20090; . Matrix b is strictly positive, if for any numbers i,\u2009j (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n) the inequality bij\u2009>\u20090 holds. You task is to determine if there is such integer k\u2009\u2265\u20091, that matrix ak is strictly positive.", "input_spec": "The first line contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of rows and columns in matrix a. The next n lines contain the description of the rows of matrix a. The i-th line contains n non-negative integers ai1,\u2009ai2,\u2009...,\u2009ain (0\u2009\u2264\u2009aij\u2009\u2264\u200950). It is guaranteed that .", "output_spec": "If there is a positive integer k\u2009\u2265\u20091, such that matrix ak is strictly positive, print \"YES\" (without the quotes). Otherwise, print \"NO\" (without the quotes). ", "sample_inputs": ["2\n1 0\n0 1", "5\n4 5 6 1 2\n1 2 3 4 5\n6 4 1 2 4\n1 1 1 1 1\n4 4 4 4 4"], "sample_outputs": ["NO", "YES"], "notes": null}, "positive_code": [{"source_code": "(* \n In graph theoretic terms, b_ij > 0 in the matrix A^k means that there is a\n path of k steps from i to j. Now, because there is at least one non-zero\n on the diagonal, it means that node represents a cycle of length 1. So if\n the graph has one strong component then eventually with a high enough power\n you will e able to get from anywhere to anywhere in that number of steps.\n Also, if the graph is not strongly connected, then there will be some b_ij\n which always remain 0.\n\n So the property holds if and only if the graph has one big strong component.\n\n If they had not made the condition that there is a non-zero on the diagonal,\n then we would also have to somehow determine if the GCD of the cycle lengths\n in the graph. I'm not sure how to do that efficiently.\n\n Danny Sleator, March 2014\n*)\n\n\nopen Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet strong edge degree = \n let n = Array.length degree in\n let num = Array.make n 0 in\n let low = Array.make n 0 in\n let answer = Array.make n 0 in\n let onstack = Array.make n false in\n \n let stacktop = ref [] in\n let stackpush x = \n stacktop := x :: !stacktop;\n onstack.(x) <- true\n in\n\n let stackpop () =\n match !stacktop with [] -> failwith \"popping an empty stack\"\n | x::t -> \n\tstacktop := t;\n\tonstack.(x) <- false;\n\tx\n in\n\n let count = ref 0 in\n let comp = ref 0 in\n\n let rec dfs u =\n if num.(u) <> 0 then () else (\n count := !count + 1;\n num.(u) <- !count;\n low.(u) <- !count;\n stackpush u;\n\n for i=0 to degree.(u)-1 do dfs edge.(u).(i) done;\n for i=0 to degree.(u)-1 do \n\tlet v = edge.(u).(i) in\n\tif onstack.(v) then low.(u) <- min low.(u) low.(v);\n done;\n\n if num.(u) = low.(u) then (\n\tlet rec loop () = \n\t let x = stackpop() in\n\t answer.(x) <- !comp;\n\t if x <> u then loop();\n\tin\n\tloop ();\n\tcomp := !comp + 1\n )\n )\n in\n\n for x=0 to n-1 do dfs x done;\n (!comp, answer)\n\nlet () = \n let n = read_int () in\n let edge = Array.make_matrix n n 0 in\n let degree = Array.make n 0 in\n for i=0 to n-1 do\n for j=0 to n-1 do\n if read_int() > 0 then (\n\tlet d = degree.(i) in\n\tedge.(i).(d) <- j;\n\tdegree.(i) <- d + 1;\n )\n done\n done;\n let (comp,_) = strong edge degree in\n if comp=1 then printf \"YES\\n\" else printf \"NO\\n\";\n"}], "negative_code": [], "src_uid": "9cf8b711a3fcf5dd5059f323f107a0bd"} {"nl": {"description": "There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \\le j \\le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j < t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.", "input_spec": "The first line of the input contains an integer $$$t$$$ ($$$1 \\le t \\le 100$$$) \u2014 the number of test cases. Then test cases follow. The first line of a test case contains one integer $$$n$$$ ($$$1 \\le n \\le 1000$$$) \u2014 the number of packages. The next $$$n$$$ lines contain descriptions of packages. The $$$i$$$-th package is given as two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \\le x_i, y_i \\le 1000$$$) \u2014 the $$$x$$$-coordinate of the package and the $$$y$$$-coordinate of the package. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package. The sum of all values $$$n$$$ over test cases in the test doesn't exceed $$$1000$$$.", "output_spec": "Print the answer for each test case. If it is impossible to collect all $$$n$$$ packages in some order starting from ($$$0,0$$$), print \"NO\" on the first line. Otherwise, print \"YES\" in the first line. Then print the shortest path \u2014 a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path. Note that in this problem \"YES\" and \"NO\" can be only uppercase words, i.e. \"Yes\", \"no\" and \"YeS\" are not acceptable.", "sample_inputs": ["3\n5\n1 3\n1 2\n3 3\n5 5\n4 3\n2\n1 0\n0 1\n1\n4 3"], "sample_outputs": ["YES\nRUUURRRRUU\nNO\nYES\nRRRRUUU"], "notes": "NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below: "}, "positive_code": [{"source_code": "open! Printf;;\n\nmodule String = struct\n\tinclude String\n\tlet split c str =\n\t\tlet str = String.concat \"\" [str; String.make 1 c] in\n\t\tlet cur = ref [] in\n\t\tlet res = ref [] in\n\t\tString.iter (fun a ->\n\t\t\tmatch a = c with\n\t\t\t| false -> cur := (String.make 1 a) :: !cur\n\t\t\t| true -> \n\t\t\t\tlet char_list = List.rev (!cur) in\n\t\t\t\tres := (String.concat \"\" char_list) :: !res;\n\t\t\t\tcur := []) str ;\n\t\t\tList.rev !res \n\t;;\nend;;\n\nlet read_int_list () = \n\tread_line () |> String.split ' ' |> List.map int_of_string\n;;\n\nlet read_2_ints () =\n\tmatch read_int_list () with \n\t| [a; b] -> a, b\n\t| _ -> assert false\n;; \n\nlet compare (a, b) (c, d) =\n\tif a == c then compare b d\n\telse compare a c\n;;\n\nlet tests = read_int () in\nfor _ = 1 to tests do\n\tlet n = read_int () in\n\tlet list = ref [] in\n\tfor _ = 1 to n do\n\t\tlist := (read_2_ints ()) :: !list;\n\t\t()\n\tdone;\n\tlet list = List.rev (!list) |> List.sort compare in\n\tlet check (a, b, bo) (c, d) =\n\t\tc, d, (match bo with\n\t\t| false -> false\n\t\t| true -> (a<=c) && (b<=d))\n\tin \n\tlet check = List.fold_left check (0, 0, true) list in\n\t(match check with\n\t| _, _, false -> print_string \"NO\"\n\t| _, _, true -> \n\t\tprint_string \"YES\\n\";\n\t\tlet move (a, b) (c, d) =\n\t\t\tprint_string (String.make (c-a) 'R');\n\t\t\tprint_string (String.make (d-b) 'U');\n\t\t\t(c, d)\n\t\tin\t\n\t\tlet _ = List.fold_left move (0, 0) list in\n\t\t());\n\tprint_newline ()\ndone;\n\t\n"}], "negative_code": [], "src_uid": "b01c627abc00f97767c237e304f8c17f"} {"nl": {"description": "You are given two strings of equal length $$$s$$$ and $$$t$$$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.For example, if $$$s$$$ is \"acbc\" you can get the following strings in one operation: \"aabc\" (if you perform $$$s_2 = s_1$$$); \"ccbc\" (if you perform $$$s_1 = s_2$$$); \"accc\" (if you perform $$$s_3 = s_2$$$ or $$$s_3 = s_4$$$); \"abbc\" (if you perform $$$s_2 = s_3$$$); \"acbb\" (if you perform $$$s_4 = s_3$$$); Note that you can also apply this operation to the string $$$t$$$.Please determine whether it is possible to transform $$$s$$$ into $$$t$$$, applying the operation above any number of times.Note that you have to answer $$$q$$$ independent queries.", "input_spec": "The first line contains one integer $$$q$$$ ($$$1 \\le q \\le 100$$$)\u00a0\u2014 the number of queries. Each query is represented by two consecutive lines. The first line of each query contains the string $$$s$$$ ($$$1 \\le |s| \\le 100$$$) consisting of lowercase Latin letters. The second line of each query contains the string $$$t$$$ ($$$1 \\le |t| \\leq 100$$$, $$$|t| = |s|$$$) consisting of lowercase Latin letters.", "output_spec": "For each query, print \"YES\" if it is possible to make $$$s$$$ equal to $$$t$$$, and \"NO\" otherwise. You may print every letter in any case you want (so, for example, the strings \"yEs\", \"yes\", \"Yes\", and \"YES\" will all be recognized as positive answer).", "sample_inputs": ["3\nxabb\naabx\ntechnocup\ntechnocup\na\nz"], "sample_outputs": ["YES\nYES\nNO"], "notes": "NoteIn the first query, you can perform two operations $$$s_1 = s_2$$$ (after it $$$s$$$ turns into \"aabb\") and $$$t_4 = t_3$$$ (after it $$$t$$$ turns into \"aabb\"). In the second query, the strings are equal initially, so the answer is \"YES\".In the third query, you can not make strings $$$s$$$ and $$$t$$$ equal. Therefore, the answer is \"NO\"."}, "positive_code": [{"source_code": "module SS = Set.Make(struct type t = char let compare = compare end)\n\nlet to_set string =\n let s = ref SS.empty in\n String.iter (fun c -> s := SS.add c !s) string;\n !s\n\nlet _ =\n let n = int_of_string (input_line stdin) in\n for i = 1 to n do\n let l = input_line stdin in\n let r = input_line stdin in\n let l = to_set l in\n let r = to_set r in\n if SS.is_empty (SS.inter l r) then\n Format.printf \"NO@.\"\n else\n Format.printf \"YES@.\"\n\n\n\n done\n"}], "negative_code": [], "src_uid": "9b9b01e5d2329291eee80356525eaf04"} {"nl": {"description": "You might have remembered Theatre square from the problem 1A. Now it's finally getting repaved.The square still has a rectangular shape of $$$n \\times m$$$ meters. However, the picture is about to get more complicated now. Let $$$a_{i,j}$$$ be the $$$j$$$-th square in the $$$i$$$-th row of the pavement.You are given the picture of the squares: if $$$a_{i,j} = $$$ \"*\", then the $$$j$$$-th square in the $$$i$$$-th row should be black; if $$$a_{i,j} = $$$ \".\", then the $$$j$$$-th square in the $$$i$$$-th row should be white. The black squares are paved already. You have to pave the white squares. There are two options for pavement tiles: $$$1 \\times 1$$$ tiles\u00a0\u2014 each tile costs $$$x$$$ burles and covers exactly $$$1$$$ square; $$$1 \\times 2$$$ tiles\u00a0\u2014 each tile costs $$$y$$$ burles and covers exactly $$$2$$$ adjacent squares of the same row. Note that you are not allowed to rotate these tiles or cut them into $$$1 \\times 1$$$ tiles. You should cover all the white squares, no two tiles should overlap and no black squares should be covered by tiles.What is the smallest total price of the tiles needed to cover all the white squares?", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$)\u00a0\u2014 the number of testcases. Then the description of $$$t$$$ testcases follow. The first line of each testcase contains four integers $$$n$$$, $$$m$$$, $$$x$$$ and $$$y$$$ ($$$1 \\le n \\le 100$$$; $$$1 \\le m \\le 1000$$$; $$$1 \\le x, y \\le 1000$$$)\u00a0\u2014 the size of the Theatre square, the price of the $$$1 \\times 1$$$ tile and the price of the $$$1 \\times 2$$$ tile. Each of the next $$$n$$$ lines contains $$$m$$$ characters. The $$$j$$$-th character in the $$$i$$$-th line is $$$a_{i,j}$$$. If $$$a_{i,j} = $$$ \"*\", then the $$$j$$$-th square in the $$$i$$$-th row should be black, and if $$$a_{i,j} = $$$ \".\", then the $$$j$$$-th square in the $$$i$$$-th row should be white. It's guaranteed that the sum of $$$n \\times m$$$ over all testcases doesn't exceed $$$10^5$$$.", "output_spec": "For each testcase print a single integer\u00a0\u2014 the smallest total price of the tiles needed to cover all the white squares in burles.", "sample_inputs": ["4\n1 1 10 1\n.\n1 2 10 1\n..\n2 1 10 1\n.\n.\n3 3 3 7\n..*\n*..\n.*."], "sample_outputs": ["10\n1\n20\n18"], "notes": "NoteIn the first testcase you are required to use a single $$$1 \\times 1$$$ tile, even though $$$1 \\times 2$$$ tile is cheaper. So the total price is $$$10$$$ burles.In the second testcase you can either use two $$$1 \\times 1$$$ tiles and spend $$$20$$$ burles or use a single $$$1 \\times 2$$$ tile and spend $$$1$$$ burle. The second option is cheaper, thus the answer is $$$1$$$.The third testcase shows that you can't rotate $$$1 \\times 2$$$ tiles. You still have to use two $$$1 \\times 1$$$ tiles for the total price of $$$20$$$.In the fourth testcase the cheapest way is to use $$$1 \\times 1$$$ tiles everywhere. The total cost is $$$6 \\cdot 3 = 18$$$."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_string _ = bscanf Scanning.stdin \" %s \" (fun x -> x) \nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let (n,m) = read_pair() in\n let (x,y) = read_pair() in\n let board = Array.init n read_string in\n\n if y >= 2*x then (\n let n_white = sum 0 (n-1) (fun i -> sum 0 (m-1) (fun j ->\n\tif board.(i).[j] = '.' then 1 else 0))\n in\n printf \"%d\\n\" (n_white * x)\n ) else (\n let rec loop i j ac1 ac2 =\n\t(* filled all cells before i. ac1 = # singles, ac2 = # dominoes *)\n\tif j=m then (ac1, ac2) else \n\t match board.(i).[j] with\n\t | '.' ->\n\t if j+1 < m && board.(i).[j+1] = '.'\n\t then loop i (j+2) ac1 (ac2+1)\n\t else loop i (j+1) (ac1+1) ac2\n\t | '*' -> loop i (j+1) ac1 ac2\n\t | _ -> failwith \"bad board\"\n in\n let singles = sum 0 (n-1) (fun i -> fst (loop i 0 0 0)) in \n let doubles = sum 0 (n-1) (fun i -> snd (loop i 0 0 0)) in\n printf \"%d\\n\" (singles * x + doubles * y)\n )\n \n done\n"}], "negative_code": [], "src_uid": "69ef9492fcdcc979cb31fa95c3e76db9"} {"nl": {"description": "Ayush and Ashish play a game on an unrooted tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$. Players make the following move in turns: Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to $$$1$$$. A tree is a connected undirected graph without cycles.There is a special node numbered $$$x$$$. The player who removes this node wins the game. Ayush moves first. Determine the winner of the game if each player plays optimally.", "input_spec": "The first line of the input contains a single integer $$$t$$$ $$$(1 \\leq t \\leq 10)$$$\u00a0\u2014 the number of testcases. The description of the test cases follows. The first line of each testcase contains two integers $$$n$$$ and $$$x$$$ $$$(1\\leq n \\leq 1000, 1 \\leq x \\leq n)$$$\u00a0\u2014 the number of nodes in the tree and the special node respectively. Each of the next $$$n-1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \\leq u, v \\leq n, \\text{ } u \\ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.", "output_spec": "For every test case, if Ayush wins the game, print \"Ayush\", otherwise print \"Ashish\" (without quotes).", "sample_inputs": ["1\n3 1\n2 1\n3 1", "1\n3 2\n1 2\n1 3"], "sample_outputs": ["Ashish", "Ayush"], "notes": "NoteFor the $$$1$$$st test case, Ayush can only remove node $$$2$$$ or $$$3$$$, after which node $$$1$$$ becomes a leaf node and Ashish can remove it in his turn.For the $$$2$$$nd test case, Ayush can remove node $$$2$$$ in the first move itself."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\nlet rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdin \" %d %d \" (fun x y -> (x,y))\nlet () = \n let cases = read_int () in\n\n for case = 1 to cases do\n let (n,x) = read_pair() in\n let degx = ref 0 in\n for i=1 to n-1 do\n let (u,v) = read_pair() in\n if u=x || v=x then degx := 1 + !degx\n done;\n\n let answer = if !degx = 1 || !degx = 0 then \"Ayush\"\n else if n mod 2 = 0 then \"Ayush\" else \"Ashish\"\n in\n\n printf \"%s\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "1a93a35395436f9e15760400f991f1ce"} {"nl": {"description": "Petya has n integers: 1,\u20092,\u20093,\u2009...,\u2009n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group.", "input_spec": "The first line contains a single integer n (2\u2009\u2264\u2009n\u2009\u2264\u200960\u2009000) \u2014 the number of integers Petya has.", "output_spec": "Print the smallest possible absolute difference in the first line. In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them.", "sample_inputs": ["4", "2"], "sample_outputs": ["0\n2 1 4", "1\n1 1"], "notes": "NoteIn the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0.In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n\n let printmod4 st n =\n for i = 1 to n/4 do\n printf \"%d %d \" (st+i-1) (st+n-i) \n done;\n print_newline()\n in\n \n match n mod 4 with\n | 0 ->\n printf \"0\\n\";\n printf \"%d \" (n/2);\n printmod4 1 n\n | 1 ->\n printf \"1\\n\";\n printf \"%d \" ((n-1)/2);\n printmod4 2 (n-1);\n | 2 ->\n printf \"1\\n\";\n printf \"%d \" (1 + (n-2)/2);\n printf \"%d \" 1;\n printmod4 3 (n-2);\n | 3 ->\n printf \"0\\n\";\n printf \"%d \" (1 + (n-3)/2);\n printf \"%d \" 3;\n printmod4 4 (n-3);\n | _ -> failwith \"can't happen\"\n"}], "negative_code": [], "src_uid": "4c387ab2a0d028141634ade32ae97d03"} {"nl": {"description": "Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a1,\u2009a2,\u2009...,\u2009an, and Banban's have brightness b1,\u2009b2,\u2009...,\u2009bm respectively.Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.You are asked to find the brightness of the chosen pair if both of them choose optimally.", "input_spec": "The first line contains two space-separated integers n and m (2\u2009\u2264\u2009n,\u2009m\u2009\u2264\u200950). The second line contains n space-separated integers a1,\u2009a2,\u2009...,\u2009an. The third line contains m space-separated integers b1,\u2009b2,\u2009...,\u2009bm. All the integers range from \u2009-\u2009109 to 109.", "output_spec": "Print a single integer\u00a0\u2014 the brightness of the chosen pair.", "sample_inputs": ["2 2\n20 18\n2 14", "5 3\n-1 0 1 2 3\n-1 0 1"], "sample_outputs": ["252", "2"], "notes": "NoteIn the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself."}, "positive_code": [{"source_code": "\nopen Scanf\nopen Printf\n\nmodule Int64M = struct\n include Int64\n let (+) = Int64.add\n let (-) = Int64.sub\n let ( * ) = Int64.mul\n let compare = Int64.compare\n let rem = Int64.rem\n let of_int = Int64.of_int\n let of_string = Int64.of_string\nend\n\nlet input_list n =\n let input_int _ = scanf \" %d\" (fun x -> x) in\n Array.init n input_int\n\nlet array_count f a =\n let g i v = if f v then i + 1 else i in\n Array.fold_left g 0 a\n\nlet count_polarity a =\n let negzero = array_count (fun v -> v <= 0) a in\n (negzero, Array.length a - negzero)\n\nlet array_max a = Array.fold_left max a.(0) a\nlet array_min a = Array.fold_left min a.(0) a\n\nlet filter_once n a =\n let filtered = ref false in\n let f i =\n if !filtered = true\n then a.(i + 1)\n else\n if a.(i) = n\n then (filtered := true; a.(i + 1))\n else a.(i)\n in\n Array.init (Array.length a - 1) f\n\nlet do_compute tommy banban =\n let ret = ref (Int64.min_int, min_int, min_int) in\n let open Int64M in\n Array.iter (fun t ->\n Array.iter (fun b ->\n let (curmax, _, _) = !ret in\n if t * b > curmax then ret := (t * b, to_int t, to_int b)\n ) banban\n ) tommy;\n !ret\n\nlet rec compute tommy banban =\n let (max1, t1, b1) = do_compute tommy banban in\n (* Printf.printf \"%d %d %d\\n\" (Int64.to_int max1) t1 b1; *)\n let tommy_filtered = filter_once (Int64.of_int t1) tommy in\n let (max2, t2, b2) = do_compute tommy_filtered banban in\n (* Printf.printf \"%d %d %d\\n\" (Int64.to_int max2) t2 b2; *)\n max2\n\nlet () =\n let n, m = scanf \" %u %u \" (fun x y -> x, y) in\n let tommy = input_list n in\n let banban = input_list m in\n let tommy = Array.map Int64.of_int tommy in\n let banban = Array.map Int64.of_int banban in\n let ret = compute tommy banban in\n ret |> Int64.to_string |> print_endline\n\n (* let tn, tp = count_polarity tommy in\n let bn, bp = count_polarity banban in *)\n (* the decision tree is too fucking tricky and\n I'm going to bruteforce as the tag suggested ... *)\n (* let ret: int = \n if bp > 0\n then if tn = 0 then\n (* T no negative, B has positive -> max2 T * max B *)\n 0\n else if ... *)\n (* in *)\n\n"}], "negative_code": [], "src_uid": "c408b1d198c7c88fc635936d960c962a"} {"nl": {"description": "In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di \u2014 buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.", "input_spec": "The input starts with two positive integers n and s (1\u2009\u2264\u2009n\u2009\u2264\u20091000,\u20091\u2009\u2264\u2009s\u2009\u2264\u200950), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0\u2009\u2264\u2009pi\u2009\u2264\u2009105) and an integer qi (1\u2009\u2264\u2009qi\u2009\u2264\u2009104) \u2014 direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.", "output_spec": "Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.", "sample_inputs": ["6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10"], "sample_outputs": ["S 50 8\nS 40 1\nB 25 10\nB 20 4"], "notes": "NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders."}, "positive_code": [{"source_code": "module IntMap = Map.Make(struct type t = int let compare = compare end)\n\nlet rec takeTo n l =\n match l with\n | [] -> []\n | h :: t -> if n = 0 then [] else h :: takeTo (n - 1) t\n\nlet addOrder s p q =\n let prev = if IntMap.mem p s\n then IntMap.find p s\n else 0\n in\n\n IntMap.add p (q + prev) s\n\nlet () = Scanf.scanf \"%d %d\\n\" (fun n s ->\n let buy = ref IntMap.empty\n and sell = ref IntMap.empty in\n\n for i = 1 to n do\n (* direction, price and quantity *)\n Scanf.scanf \"%c %d %d\\n\" (fun d p q ->\n match d with\n | 'B' -> buy := addOrder !buy ~-p q\n | 'S' -> sell := addOrder !sell p q\n )\n done;\n\n List.iter (fun (p, q) -> Printf.printf \"S %d %d\\n\" p q)\n (List.rev (takeTo s (IntMap.bindings !sell)));\n List.iter (fun (p, q) -> Printf.printf \"B %d %d\\n\" ~-p q)\n (takeTo s (IntMap.bindings !buy))\n)\n"}], "negative_code": [{"source_code": "module IntMap = Map.Make(struct type t = int let compare = compare end)\n\nlet rec takeTo n l =\n match l with\n | [] -> []\n | h :: t -> if n = 0 then [] else h :: takeTo (n - 1) t\n\nlet addOrder s p q =\n let prev = if IntMap.mem p s\n then IntMap.find p s\n else 0\n in\n\n IntMap.add p (q + prev) s\n\nlet () = Scanf.scanf \"%d %d\\n\" (fun n s ->\n let buy = ref IntMap.empty\n and sell = ref IntMap.empty in\n\n for i = 1 to n do\n (* direction, price and quantity *)\n Scanf.scanf \"%c %d %d\\n\" (fun d p q ->\n match d with\n | 'B' -> buy := addOrder !buy ~-p q\n | 'S' -> sell := addOrder !sell p q\n )\n done;\n\n List.iter (fun (p, q) -> Printf.printf \"S %d %d\\n\" p q)\n (takeTo s (IntMap.bindings !sell));\n List.iter (fun (p, q) -> Printf.printf \"B %d %d\\n\" ~-p q)\n (takeTo s (IntMap.bindings !buy))\n)\n"}], "src_uid": "267c04c77f97bbdf7697dc88c7bfa4af"} {"nl": {"description": "An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.", "input_spec": "The single line of the input contains integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009100) \u2014 the required degree of the vertices of the regular graph.", "output_spec": "Print \"NO\" (without quotes), if such graph doesn't exist. Otherwise, print \"YES\" in the first line and the description of any suitable graph in the next lines. The description of the made graph must start with numbers n and m \u2014 the number of vertices and edges respectively. Each of the next m lines must contain two integers, a and b (1\u2009\u2264\u2009a,\u2009b\u2009\u2264\u2009n, a\u2009\u2260\u2009b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order. The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges). ", "sample_inputs": ["1"], "sample_outputs": ["YES\n2 1\n1 2"], "notes": "NoteIn the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge."}, "positive_code": [{"source_code": "let f k =\n\tfor i=1 to k-1 do\n\t\tfor j=k to 2*k-2 do\n\t\t\tPrintf.printf \"%d %d\\n\" i j;\n\t\tdone;\n\t\tif i mod 2 = 1\n\t\t\tthen Printf.printf \"%d %d\\n\" i (i+1);\n\tdone;\n\tfor j=k to 2*k-2 do\n\t\tPrintf.printf \"%d %d\\n\" j (2*k-1);\n\tdone;\n\tfor i=1 to k-1 do\n\t\tfor j=k to 2*k-2 do\n\t\t\tPrintf.printf \"%d %d\\n\" (2*k - 1 + i) (2*k - 1 + j);\n\t\tdone;\n\t\tif i mod 2 = 1\n\t\t\tthen Printf.printf \"%d %d\\n\" (2*k - 1 + i) (2*k + i);\n\tdone;\n\tfor j=k to 2*k-2 do\n\t\tPrintf.printf \"%d %d\\n\" (2*k - 1 + j) (4*k-2);\n\tdone;\n\tPrintf.printf \"%d %d\\n\" (4*k -2) (2*k - 1)\n\nlet () =\n\tlet k = Scanf.scanf \"%d\" (fun i -> i) in\n\t\tif k mod 2 = 0\n\t\t\tthen Printf.printf \"NO\"\n\t\t\telse begin\n\t\t\t Printf.printf \"YES\\n\";\n\t\t\t Printf.printf \"%d %d\\n\" (4*(k-1) +2) (k*(2*(k-1) + 1));\n\t\t\t f k\n\t\t\t end\n"}], "negative_code": [{"source_code": "let f k =\n\tfor i=1 to k-1 do\n\t\tfor j=k to 2*k-2 do\n\t\t\tPrintf.printf \"%d %d\\n\" i j;\n\t\t\tPrintf.printf \"%d %d\\n\" j i;\n\t\tdone;\n\t\tif i mod 2 = 1\n\t\t\tthen (Printf.printf \"%d %d\\n\" i (i+1);\n\t\t\t Printf.printf \"%d %d\\n\" (i+1) i);\n\tdone;\n\tfor j=k to 2*k-2 do\n\t\tPrintf.printf \"%d %d\\n\" j (2*k-1);\n\t\tPrintf.printf \"%d %d\\n\" (2*k-1) j;\n\tdone;\n\tfor i=1 to k-1 do\n\t\tfor j=k to 2*k-2 do\n\t\t\tPrintf.printf \"%d %d\\n\" (2*k - 1 + i) (2*k - 1 + j);\n\t\t\tPrintf.printf \"%d %d\\n\" (2*k - 1 + j) (2*k - 1 + i);\n\t\tdone;\n\t\tif i mod 2 = 1\n\t\t\tthen (Printf.printf \"%d %d\\n\" (2*k - 1 + i) (2*k + i);\nPrintf.printf \"%d %d\\n\" (2*k + i) (2*k - 1 + i));\n\tdone;\n\tfor j=k to 2*k-2 do\n\t\tPrintf.printf \"%d %d\\n\" (2*k - 1 + j) (4*k-2);\n\t\tPrintf.printf \"%d %d\\n\" (4*k-2) (2*k - 1 + j);\n\tdone;\n\tPrintf.printf \"%d %d\\n\" (4*k -2) (2*k - 1);\n\tPrintf.printf \"%d %d\\n\" (2*k -1) (4*k - 2)\n\nlet () =\n\tlet k = Scanf.scanf \"%d\" (fun i -> i) in\n\t\tif k mod 2 = 0\n\t\t\tthen Printf.printf \"NO\"\n\t\t\telse begin\n\t\t\t Printf.printf \"YES\\n\";\n\t\t\t f k\n\t\t\t end\n"}], "src_uid": "1e061d8c4bff217047ddc58e88be0c3f"} {"nl": {"description": "You have got a shelf and want to put some books on it.You are given $$$q$$$ queries of three types: L $$$id$$$ \u2014 put a book having index $$$id$$$ on the shelf to the left from the leftmost existing book; R $$$id$$$ \u2014 put a book having index $$$id$$$ on the shelf to the right from the rightmost existing book; ? $$$id$$$ \u2014 calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index $$$id$$$ will be leftmost or rightmost. You can assume that the first book you will put can have any position (it does not matter) and queries of type $$$3$$$ are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so $$$id$$$s don't repeat in queries of first two types.Your problem is to answer all the queries of type $$$3$$$ in order they appear in the input.Note that after answering the query of type $$$3$$$ all the books remain on the shelf and the relative order of books does not change.If you are Python programmer, consider using PyPy instead of Python when you submit your code.", "input_spec": "The first line of the input contains one integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^5$$$) \u2014 the number of queries. Then $$$q$$$ lines follow. The $$$i$$$-th line contains the $$$i$$$-th query in format as in the problem statement. It is guaranteed that queries are always valid (for query type $$$3$$$, it is guaranteed that the book in each such query is already placed, and for other types, it is guaranteed that the book was not placed before). It is guaranteed that there is at least one query of type $$$3$$$ in the input. In each query the constraint $$$1 \\le id \\le 2 \\cdot 10^5$$$ is met.", "output_spec": "Print answers to queries of the type $$$3$$$ in order they appear in the input.", "sample_inputs": ["8\nL 1\nR 2\nR 3\n? 2\nL 4\n? 1\nL 5\n? 1", "10\nL 100\nR 100000\nR 123\nL 101\n? 123\nL 10\nR 115\n? 100\nR 110\n? 115"], "sample_outputs": ["1\n1\n2", "0\n2\n1"], "notes": "NoteLet's take a look at the first example and let's consider queries: The shelf will look like $$$[1]$$$; The shelf will look like $$$[1, 2]$$$; The shelf will look like $$$[1, 2, 3]$$$; The shelf looks like $$$[1, \\textbf{2}, 3]$$$ so the answer is $$$1$$$; The shelf will look like $$$[4, 1, 2, 3]$$$; The shelf looks like $$$[4, \\textbf{1}, 2, 3]$$$ so the answer is $$$1$$$; The shelf will look like $$$[5, 4, 1, 2, 3]$$$; The shelf looks like $$$[5, 4, \\textbf{1}, 2, 3]$$$ so the answer is $$$2$$$. Let's take a look at the second example and let's consider queries: The shelf will look like $$$[100]$$$; The shelf will look like $$$[100, 100000]$$$; The shelf will look like $$$[100, 100000, 123]$$$; The shelf will look like $$$[101, 100, 100000, 123]$$$; The shelf looks like $$$[101, 100, 100000, \\textbf{123}]$$$ so the answer is $$$0$$$; The shelf will look like $$$[10, 101, 100, 100000, 123]$$$; The shelf will look like $$$[10, 101, 100, 100000, 123, 115]$$$; The shelf looks like $$$[10, 101, \\textbf{100}, 100000, 123, 115]$$$ so the answer is $$$2$$$; The shelf will look like $$$[10, 101, 100, 100000, 123, 115, 110]$$$; The shelf looks like $$$[10, 101, 100, 100000, 123, \\textbf{115}, 110]$$$ so the answer is $$$1$$$. "}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet dl l = l|>Array.of_list|>dump_array\n\nlet () =\n\tlet q = get_i64 0 in\n\tlet a = Array.make 200018 `Null in\n\tlet lf,rg = ref 0,ref 0 in \n\t(* let llf,rrg = ref [], ref [] in *)\n\trep 1L q (fun _ ->\n\t\tlet c,i = scanf \" %c %Ld\" (fun u v -> u,v) in (\n\t\t\tmatch c with\n\t\t\t| 'L' ->\n\t\t\t\tlf := !lf +$ 1;\n\t\t\t\t(* llf := i :: !llf; printf \"left :\"; dl !llf; *)\n\t\t\t\ta.(i32 i) <- `Left (!lf);\n\t\t\t| 'R' -> \n\t\t\t\trg := !rg +$ 1;\n\t\t\t\t(* rrg := i :: !rrg; printf \"right:\"; dl !rrg; *)\n\t\t\t\ta.(i32 i) <- `Right (!rg);\n\t\t\t| '?' ->\n\t\t\t\tlet pos = a.(i32 i) in (\n\t\t\t\t\tmatch pos with\n\t\t\t\t\t| `Left q -> printf \"%d\\n\" @@ min (!lf -$ q) (!rg+$q-$1)\n\t\t\t\t\t| `Right q -> printf \"%d\\n\" @@ min (!rg -$ q) (!lf+$q-$1)\n\t\t\t\t\t| _ -> exit 1\n\t\t\t\t)\n\t\t\t| c -> printf \"err: %c\\n\" c; exit 1;\n\t\t);\n\t\t`Ok\n\t)\n\n\n"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\n\nlet () =\n\tlet q = get_i64 0 in\n\tlet a = Array.make 200018 `Null in\n\tlet lf,rg = ref 0,ref 0 in \n\trep 1L q (fun _ ->\n\t\tlet c,i = scanf \" %c %Ld\" (fun u v -> u,v) in (\n\t\t\tmatch c with\n\t\t\t| 'L' ->\n\t\t\t\tlf := !lf +$ 1;\n\t\t\t\ta.(i32 i) <- `Left (!lf);\n\t\t\t| 'R' -> \n\t\t\t\trg := !rg +$ 1;\n\t\t\t\ta.(i32 i) <- `Right (!rg);\n\t\t\t| '?' ->\n\t\t\t\tlet pos = a.(i32 i) in (\n\t\t\t\t\tmatch pos with\n\t\t\t\t\t| `Left q -> printf \"%d\\n\" (!lf -$ q)\n\t\t\t\t\t| `Right q -> printf \"%d\\n\" (!rg -$ q)\n\t\t\t\t\t| _ -> exit 0\n\t\t\t\t)\n\t\t\t| c -> printf \"err: %c\\n\" c; exit 0;\n\t\t);\n\t\t`Ok\n\t)\n\n\n"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet dl l = l|>Array.of_list|>dump_array\n\nlet () =\n\tlet q = get_i64 0 in\n\tlet a = Array.make 200018 `Null in\n\tlet lf,rg = ref 0,ref 0 in \n\t(* let llf,rrg = ref [], ref [] in *)\n\trep 1L q (fun _ ->\n\t\tlet c,i = scanf \" %c %Ld\" (fun u v -> u,v) in (\n\t\t\tmatch c with\n\t\t\t| 'L' ->\n\t\t\t\tlf := !lf +$ 1;\n\t\t\t\t(* llf := i :: !llf; printf \"left :\"; dl !llf; *)\n\t\t\t\ta.(i32 i) <- `Left (!lf);\n\t\t\t| 'R' -> \n\t\t\t\trg := !rg +$ 1;\n\t\t\t\t(* rrg := i :: !rrg; printf \"right:\"; dl !rrg; *)\n\t\t\t\ta.(i32 i) <- `Right (!rg);\n\t\t\t| '?' ->\n\t\t\t\tlet pos = a.(i32 i) in (\n\t\t\t\t\tmatch pos with\n\t\t\t\t\t| `Left q -> printf \"%d\\n\" @@ min (!lf -$ q) (!rg+$q+$1)\n\t\t\t\t\t| `Right q -> printf \"%d\\n\" @@ min (!rg -$ q) (!rg+$q+$1)\n\t\t\t\t\t| _ -> exit 1\n\t\t\t\t)\n\t\t\t| c -> printf \"err: %c\\n\" c; exit 1;\n\t\t);\n\t\t`Ok\n\t)"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet dl l = l|>Array.of_list|>dump_array\n\nlet () =\n\tlet q = get_i64 0 in\n\tlet a = Array.make 200018 `Null in\n\tlet lf,rg = ref 0,ref 0 in \n\t(* let llf,rrg = ref [], ref [] in *)\n\trep 1L q (fun _ ->\n\t\tlet c,i = scanf \" %c %Ld\" (fun u v -> u,v) in (\n\t\t\tmatch c with\n\t\t\t| 'L' ->\n\t\t\t\tlf := !lf +$ 1;\n\t\t\t\t(* llf := i :: !llf; printf \"left :\"; dl !llf; *)\n\t\t\t\ta.(i32 i) <- `Left (!lf);\n\t\t\t| 'R' -> \n\t\t\t\trg := !rg +$ 1;\n\t\t\t\t(* rrg := i :: !rrg; printf \"right:\"; dl !rrg; *)\n\t\t\t\ta.(i32 i) <- `Right (!rg);\n\t\t\t| '?' ->\n\t\t\t\tlet pos = a.(i32 i) in (\n\t\t\t\t\tmatch pos with\n\t\t\t\t\t| `Left q -> printf \"%d\\n\" @@ min (!lf -$ q) (!rg+$q-$1)\n\t\t\t\t\t| `Right q -> printf \"%d\\n\" @@ min (!rg -$ q) (!rg+$q-$1)\n\t\t\t\t\t| _ -> exit 1\n\t\t\t\t)\n\t\t\t| c -> printf \"err: %c\\n\" c; exit 1;\n\t\t);\n\t\t`Ok\n\t)\n\n\n"}], "src_uid": "e61509d5f0bcd405b1a0c9ba74449df2"} {"nl": {"description": "You are given a permutation $$$p_1, p_2, \\ldots, p_n$$$ of length $$$n$$$. You have to choose two integers $$$l,r$$$ ($$$1 \\le l \\le r \\le n$$$) and reverse the subsegment $$$[l,r]$$$ of the permutation. The permutation will become $$$p_1,p_2, \\dots, p_{l-1},p_r,p_{r-1}, \\dots, p_l,p_{r+1},p_{r+2}, \\dots ,p_n$$$.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length $$$a$$$ and $$$b$$$, $$$a$$$ is lexicographically smaller than $$$b$$$ if at the first position they differ, $$$a$$$ has the smaller element.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 500$$$)\u00a0\u2014 the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \\le n \\le 500$$$)\u00a0\u2014 the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \\dots, p_n$$$ ($$$1 \\le p_i \\le n$$$)\u00a0\u2014 the elements of the permutation.", "output_spec": "For each test case print the lexicographically smallest permutation you can obtain.", "sample_inputs": ["4\n\n1\n\n1\n\n3\n\n2 1 3\n\n4\n\n1 4 2 3\n\n5\n\n1 2 3 4 5"], "sample_outputs": ["1 \n1 2 3 \n1 2 4 3 \n1 2 3 4 5"], "notes": "NoteIn the first test case, the permutation has length $$$1$$$, so the only possible segment is $$$[1,1]$$$. The resulting permutation is $$$[1]$$$.In the second test case, we can obtain the identity permutation by reversing the segment $$$[1,2]$$$. The resulting permutation is $$$[1,2,3]$$$.In the third test case, the best possible segment is $$$[2,3]$$$. The resulting permutation is $$$[1,2,4,3]$$$.In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment $$$[1,1]$$$. The resulting permutation is $$$[1,2,3,4,5]$$$."}, "positive_code": [{"source_code": "let find x t = let rep = ref 0 in\r\n for i = 0 to Array.length t -1 do\r\n if t.(i) = x then rep:=i ;\r\n done ;\r\n !rep ;;\r\n\r\nlet inverse s n1 n2 = let rep = ref \"\" in\r\n let pile = Stack.create () in\r\n for i = 0 to Array.length s -1 do \r\n let popo = if i = Array.length s -1 then \"\" else \" \" in\r\n if in2 then (rep := (!rep)^(string_of_int s.(i)^popo))\r\n else (\r\n if i = n2 then (Stack.push s.(i) pile ; for j = n1 to n2 -1 do rep := (!rep)^(string_of_int (Stack.pop pile))^\" \";done; rep:=(!rep)^(string_of_int (Stack.pop pile))^popo) \r\n else (Stack.push s.(i) pile ) )\r\n done ; !rep ;;\r\n\r\nlet to_t s len = let t = Array.make len 0 in\r\n let temp = ref \"\" in\r\n let inc = ref 0 in\r\n for i = 0 to String.length s -1 do\r\n if s.[i] = ' ' then (t.(!inc)<- int_of_string (!temp); incr inc ; temp:= \"\" )else \r\n temp := !temp^(String.make 1 (s.[i])) done ; t.(!inc)<- int_of_string (!temp); t;;\r\n\r\nlet n = int_of_string(input_line stdin) in\r\n\r\nfor i = 0 to n-1 do \r\n let len = int_of_string(input_line stdin) in\r\n let str = (input_line stdin) in \r\n let t = to_t str len in\r\n let finito = ref false in\r\n let interest = ref (-1,-1) in\r\n for j = 0 to Array.length t -1 do\r\n if not(!finito) && (t.(j))<>j+1 then\r\n (interest := (j,find (j+1) t) ; \r\n finito := true)\r\n done ; \r\n let rety = if !interest <> (-1,-1) then \r\n (let a,b = !interest in inverse t a b ) \r\n else str in\r\n print_endline rety\r\ndone;\r\n;;"}, {"source_code": "(* Codeforces 1638 A Reverse train *)\r\n \r\n(* you can use either gr or rdln but not both *)\r\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\r\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\r\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\r\nlet rdln() = input_line stdin;;\r\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\r\nlet debug = false;;\r\n \r\n(* reading list *)\r\nlet rec readlist n acc = match n with\r\n\t| 0 -> List.rev acc\r\n\t| _ -> readlist (n -1) (gr() :: acc);;\r\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\r\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\r\nlet list_to_s li = String.concat \" \" (List.map string_of_int li);;\r\n\r\n\r\nlet rec extract_smallest_start i first l = match l with\r\n | [] -> (i, [])\r\n | h :: t ->\r\n if h == i then extract_smallest_start (i+1) (h :: first) t\r\n else \r\n (i, l);;\r\n\r\nlet rec get_until_a a part l = match l with\r\n | [] -> (part, l)\r\n | h :: t -> \r\n if h == a then (a :: part, t)\r\n else get_until_a a (h :: part) t;;\r\n\r\nlet rec generater n = if n==0 then [] else n :: generater (n-1);;\r\nlet generate n = List.rev (generater n);;\r\n\r\nlet do_one () = \r\n let n = gr () in\r\n let p = readlist n [] in\r\n let nfirst, pl = extract_smallest_start 1 [] p in\r\n (*let _ = Printf.printf \"nfirst = %d\\n\" nfirst in\r\n let _ = Printf.printf \"pl: %s\\n\" (list_to_s pl) in*)\r\n let pend = if List.length pl == 0 then [] \r\n else \r\n ( let revpart, pla = get_until_a nfirst [] pl in\r\n (List.append revpart pla)) in\r\n let lret = List.append (generate (nfirst-1)) pend in\r\n (printlisti lret; print_string \"\\n\");;\r\n \r\nlet do_all () = \r\n let t = gr () in\r\n for i = 1 to t do\r\n do_one ()\r\n done;;\r\n \r\nlet main() =\r\n\tdo_all ();;\r\n \r\nmain();;"}], "negative_code": [{"source_code": "let find x s = let rep = ref 0 in\r\n for i = 0 to String.length s -1 do\r\n if s.[i] = (string_of_int(x)).[0] then rep:=i ;\r\n done ;\r\n !rep ;;\r\n\r\nlet inverse s n1 n2 = let rep = ref \"\" in\r\n let pile = Stack.create () in\r\n for i = 0 to String.length s -1 do \r\n if in2 then (rep := (!rep)^(String.make 1 (s.[i])))\r\n else (\r\n if i = n2 then (Stack.push (String.make 1 (s.[i])) pile ; for j = n1 to n2 do rep := (!rep)^(Stack.pop pile);done;) \r\n else (\r\n (String.make 1 (s.[i])) ; Stack.push (String.make 1 (s.[i])) pile ))\r\n done ; !rep ;;\r\n\r\n\r\nlet n = int_of_string(input_line stdin) in\r\n\r\nfor i = 0 to n-1 do \r\n let len = int_of_string(input_line stdin) in\r\n let str = (input_line stdin) in \r\n let finito = ref false in\r\n let interest = ref (-1,-1) in\r\n for j = 0 to String.length str -1 do\r\n if str.[j] <> ' ' && not(!finito) && str.[j]<>(string_of_int (j/2 +1)).[0] then\r\n (prerr_endline (string_of_int j);\r\n interest := (j,find (j/2 +1) str) ; \r\n finito := true)\r\n done ; \r\n let rety = if !interest <> (-1,-1) then \r\n (let a,b = !interest in inverse str a b ) \r\n else str in\r\n print_endline rety\r\ndone;\r\n;;"}], "src_uid": "a57823a7ca0f67a07f94175ab59d33de"} {"nl": {"description": "There is a light source on the plane. This source is so small that it can be represented as point. The light source is moving from point $$$(a, s_y)$$$ to the $$$(b, s_y)$$$ $$$(s_y < 0)$$$ with speed equal to $$$1$$$ unit per second. The trajectory of this light source is a straight segment connecting these two points. There is also a fence on $$$OX$$$ axis represented as $$$n$$$ segments $$$(l_i, r_i)$$$ (so the actual coordinates of endpoints of each segment are $$$(l_i, 0)$$$ and $$$(r_i, 0)$$$). The point $$$(x, y)$$$ is in the shade if segment connecting $$$(x,y)$$$ and the current position of the light source intersects or touches with any segment of the fence. You are given $$$q$$$ points. For each point calculate total time of this point being in the shade, while the light source is moving from $$$(a, s_y)$$$ to the $$$(b, s_y)$$$.", "input_spec": "First line contains three space separated integers $$$s_y$$$, $$$a$$$ and $$$b$$$ ($$$-10^9 \\le s_y < 0$$$, $$$1 \\le a < b \\le 10^9$$$) \u2014 corresponding coordinates of the light source. Second line contains single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 number of segments in the fence. Next $$$n$$$ lines contain two integers per line: $$$l_i$$$ and $$$r_i$$$ ($$$1 \\le l_i < r_i \\le 10^9$$$, $$$r_{i - 1} < l_i$$$) \u2014 segments in the fence in increasing order. Segments don't intersect or touch each other. Next line contains single integer $$$q$$$ ($$$1 \\le q \\le 2 \\cdot 10^5$$$) \u2014 number of points to check. Next $$$q$$$ lines contain two integers per line: $$$x_i$$$ and $$$y_i$$$ ($$$1 \\le x_i, y_i \\le 10^9$$$) \u2014 points to process.", "output_spec": "Print $$$q$$$ lines. The $$$i$$$-th line should contain one real number \u2014 total time of the $$$i$$$-th point being in the shade, while the light source is moving from $$$(a, s_y)$$$ to the $$$(b, s_y)$$$. The answer is considered as correct if its absolute of relative error doesn't exceed $$$10^{-6}$$$.", "sample_inputs": ["-3 1 6\n2\n2 4\n6 7\n5\n3 1\n1 3\n6 1\n6 4\n7 6"], "sample_outputs": ["5.000000000000000\n3.000000000000000\n0.000000000000000\n1.500000000000000\n2.000000000000000"], "notes": "Note The 1-st point is always in the shade; the 2-nd point is in the shade while light source is moving from $$$(3, -3)$$$ to $$$(6, -3)$$$; the 3-rd point is in the shade while light source is at point $$$(6, -3)$$$. the 4-th point is in the shade while light source is moving from $$$(1, -3)$$$ to $$$(2.5, -3)$$$ and at point $$$(6, -3)$$$; the 5-th point is in the shade while light source is moving from $$$(1, -3)$$$ to $$$(2.5, -3)$$$ and from $$$(5.5, -3)$$$ to $$$(6, -3)$$$; "}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let sy = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let a = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let f = Array.make n (0.0, 0.0) in\n let _ =\n for i = 0 to n - 1 do\n let l = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let r = Scanf.bscanf sb \"%f \" (fun s -> s) in\n\tf.(i) <- (l, r)\n done;\n in\n let s = Array.make (n + 1) 0.0 in\n let _ =\n for i = 0 to n - 1 do\n s.(i + 1) <- s.(i) +. snd f.(i) -. fst f.(i)\n done;\n in\n let q = Scanf.bscanf sb \"%d \" (fun s -> s) in\n for i = 1 to q do\n let x = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let y = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let x1 = (sy *. x -. a *. y) /. (sy -. y) in\n let x2 = (sy *. x -. b *. y) /. (sy -. y) in\n let idx1 =\n\tlet l = ref (-1) in\n\tlet r = ref n in\n\t while !l < !r - 1 do\n\t let m = (!l + !r) / 2 in\n\t if fst f.(m) <= x1\n\t then l := m\n\t else r := m\n\t done;\n\t !l\n in\n let idx2 =\n\tlet l = ref (-1) in\n\tlet r = ref n in\n\t while !l < !r - 1 do\n\t let m = (!l + !r) / 2 in\n\t if fst f.(m) <= x2\n\t then l := m\n\t else r := m\n\t done;\n\t !l\n in\n let g = s.(idx2 + 1) -. s.(idx1 + 1) in\n let g =\n\tif idx1 >= 0 && x1 <= snd f.(idx1)\n\tthen g +. snd f.(idx1) -. x1\n\telse g\n in\n let g =\n\tif idx2 >= 0 && x2 <= snd f.(idx2)\n\tthen g -. (snd f.(idx2) -. x2)\n\telse g\n in\n\t(*Printf.printf \"asd %f %f %d %d %f\\n\" x1 x2 idx1 idx2 g;*)\n\tPrintf.printf \"%.15f\\n\" (g /. (x2 -. x1) *. (b -. a))\n done\n"}], "negative_code": [], "src_uid": "2863d7304de4a07a8f6cd95bffaf590c"} {"nl": {"description": "One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t.", "input_spec": "The first input line contains a single integer n \u2014 the number of cupboards in the kitchen (2\u2009\u2264\u2009n\u2009\u2264\u2009104). Then follow n lines, each containing two integers li and ri (0\u2009\u2264\u2009li,\u2009ri\u2009\u2264\u20091). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.", "output_spec": "In the only output line print a single integer t \u2014 the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.", "sample_inputs": ["5\n0 1\n1 0\n0 1\n1 1\n0 1"], "sample_outputs": ["3"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n let n = read_int() in\n let c = Array.make 2 0 in\n for i=0 to n-1 do\n let l = read_int() in\n let r = read_int() in\n\tif l=0 then c.(0) <- c.(0) + 1;\n\tif r=0 then c.(1) <- c.(1) + 1;\n done;\n let left = min c.(0) (n-c.(0)) in\n let right = min c.(1) (n-c.(1)) in\n Printf.printf \"%d\\n\" (left+right)\n"}], "negative_code": [], "src_uid": "2052b0b4abdcf7d613b56842b1267f60"} {"nl": {"description": "IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids \u2014 one triangular, one quadrangular and one pentagonal.The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length. ", "input_spec": "The only line of the input contains three integers l3,\u2009l4,\u2009l5 (1\u2009\u2264\u2009l3,\u2009l4,\u2009l5\u2009\u2264\u20091000) \u2014 the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.", "output_spec": "Output one number \u2014 the total volume of the pyramids. Absolute or relative error should not be greater than 10\u2009-\u20099.", "sample_inputs": ["2 5 3"], "sample_outputs": ["38.546168065709"], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let l3 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let l4 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let l5 = Scanf.bscanf sb \"%f \" (fun s -> s) in\n let pi = 4.0 *. atan 1.0 in\n let sqr x = x *. x in\n let solve l n =\n let n = float_of_int n in\n let alpha = pi /. n in\n let d = l /. 2.0 /. tan alpha in\n let e = l *. sqrt 3.0 /. 2.0 in\n let h = sqrt (sqr e -. sqr d) in\n let s = n *. d *. l /. 2.0 in\n let v = h *. s /. 3.0 in\n v\n in\n let res = solve l3 3 +. solve l4 4 +. solve l5 5 in\n Printf.printf \"%.9f\\n\" res\n"}], "negative_code": [], "src_uid": "560bc97986a355d461bd462c4e1ea9db"} {"nl": {"description": "Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character \"#\" stands for the space occupied by the turboplow and character \".\" stands for the free space): ### ..# .#. #...#. ### .#. ###.#. ..# ### #.. Simon faced a quite natural challenge: placing in the given n\u2009\u00d7\u2009m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot \"overlap\", that is, they cannot share the same cell in the warehouse.Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?", "input_spec": "The only line contains two space-separated integers n and m \u2014 the sizes of the warehouse (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20099).", "output_spec": "In the first line print the maximum number of turboplows that can be positioned in the warehouse. In each of the next n lines print m characters. Use \".\" (dot) to mark empty space and use successive capital Latin letters (\"A\" for the first turboplow, \"B\" for the second one and so on until you reach the number of turboplows in your scheme) to mark place for the corresponding turboplows considering that they are positioned in the optimal manner in the warehouse. The order in which you number places for the turboplows does not matter. If there are several optimal solutions for a warehouse of the given size, print any of them.", "sample_inputs": ["3 3", "5 6", "2 2"], "sample_outputs": ["1\nAAA\n.A.\n.A.", "4\nA..C..\nAAAC..\nABCCCD\n.B.DDD\nBBB..D", "0\n..\n.."], "notes": null}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let a = Array.make_matrix n m (-1) in\n let b = Array.make_matrix n m (-1) in\n let res = ref 0 in\n let pred = ref 10 in\n let rec bf x y k =\n (*Printf.printf \"asd %d %d %d\\n\" x y k;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tPrintf.printf \"%d \" a.(i).(j)\n done;\n Printf.printf \"\\n\"\n done;*)\n let x = ref x in\n let y = ref y in\n while !x < n && a.(!x).(!y) >= 0 do\n\tincr x\n done;\n (*Printf.printf \"qwe %d %d %d\\n\" !x !y k;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tPrintf.printf \"%d \" a.(i).(j)\n done;\n Printf.printf \"\\n\"\n done;*)\n if !x = n then (\n\tif !y < m - 1 then (\n\t x := 0;\n\t incr y;\n\t bf !x !y k;\n\t) else (\n\t if !res < k then (\n\t res := k;\n\t for i = 0 to n - 1 do\n\t for j = 0 to m - 1 do\n\t\tb.(i).(j) <- a.(i).(j)\n\t done\n\t done;\n\t if !res >= !pred then raise Not_found\n\t )\n\t)\n ) else (\n\tlet x = !x\n\tand y = !y in\n\t if x <= n - 3 && y <= m - 3 &&\n\t a.(x).(y + 1) < 0 &&\n\t a.(x).(y + 2) < 0 &&\n\t a.(x + 1).(y + 1) < 0 &&\n\t a.(x + 2).(y + 1) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x).(y + 1) <- k;\n\t a.(x).(y + 2) <- k;\n\t a.(x + 1).(y + 1) <- k;\n\t a.(x + 2).(y + 1) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x).(y + 1) <- -1;\n\t a.(x).(y + 2) <- -1;\n\t a.(x + 1).(y + 1) <- -1;\n\t a.(x + 2).(y + 1) <- -1;\n\t );\n\t if 1 <= x && x <= n - 2 && y <= m - 3 &&\n\t a.(x).(y + 1) < 0 &&\n\t a.(x).(y + 2) < 0 &&\n\t a.(x + 1).(y + 2) < 0 &&\n\t a.(x - 1).(y + 2) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x).(y + 1) <- k;\n\t a.(x).(y + 2) <- k;\n\t a.(x + 1).(y + 2) <- k;\n\t a.(x - 1).(y + 2) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x).(y + 1) <- -1;\n\t a.(x).(y + 2) <- -1;\n\t a.(x + 1).(y + 2) <- -1;\n\t a.(x - 1).(y + 2) <- -1;\n\t );\n\t if 2 <= x && x <= n - 1 && y <= m - 3 &&\n\t a.(x).(y + 1) < 0 &&\n\t a.(x).(y + 2) < 0 &&\n\t a.(x - 1).(y + 1) < 0 &&\n\t a.(x - 2).(y + 1) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x).(y + 1) <- k;\n\t a.(x).(y + 2) <- k;\n\t a.(x - 1).(y + 1) <- k;\n\t a.(x - 2).(y + 1) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x).(y + 1) <- -1;\n\t a.(x).(y + 2) <- -1;\n\t a.(x - 1).(y + 1) <- -1;\n\t a.(x - 2).(y + 1) <- -1;\n\t );\n\t if x <= n - 3 && y <= m - 3 &&\n\t a.(x + 1).(y) < 0 &&\n\t a.(x + 2).(y) < 0 &&\n\t a.(x + 1).(y + 1) < 0 &&\n\t a.(x + 1).(y + 2) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x + 1).(y) <- k;\n\t a.(x + 2).(y) <- k;\n\t a.(x + 1).(y + 1) <- k;\n\t a.(x + 1).(y + 2) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x + 1).(y) <- -1;\n\t a.(x + 2).(y) <- -1;\n\t a.(x + 1).(y + 1) <- -1;\n\t a.(x + 1).(y + 2) <- -1;\n\t );\n\t bf (x + 1) y k;\n )\n in\n (match n, m with\n | 9, 9 -> pred := 13\n | 8, 9 -> pred := 12\n | 9, 8 -> pred := 12\n | 8, 8 -> pred := 10\n | 7, 9 -> pred := 10\n | 9, 7 -> pred := 10\n | 7, 8 -> pred := 9\n | 8, 7 -> pred := 9\n | _ -> ()\n );\n (try bf 0 0 0 with Not_found -> ());\n Printf.printf \"%d\\n\" !res;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tlet v = b.(i).(j) in\n\tlet c =\n\t if v < 0\n\t then '.'\n\t else Char.chr (Char.code 'A' + v)\n\tin\n\t Printf.printf \"%c\" c\n done;\n Printf.printf \"\\n\"\n done\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x) \n\nlet n = read_int()\nlet m = read_int()\n\nlet (h,w) = (n+1,m+1)\n\nlet wall = -2\nlet hole = -1\nlet empty = 0\n\nlet a = Array.make (h*w) wall\nlet () = \n for i=0 to n-1 do for j=0 to m-1 do\n a.(w*i+j) <- empty\n done done\n\nlet p = Array.make 4 [||]\nlet () = \n p.(0) <- [|w;w+1;w+2;2*w|];\n p.(1) <- [|1;2;w+1;2*w+1|];\n p.(2) <- [|w-2;w-1;w;2*w|];\n p.(3) <- [|w;2*w-1;2*w;2*w+1|]\n\nlet rec backtrack i blanks = (* i is the first empty space, blanks is the # of blanks left *)\n if i=h*w then true else if a.(i) != empty then backtrack (i+1) blanks else \n let rec trypiece q = if q=4 then (\n if blanks=0 then false else (\n\ta.(i) <- hole;\n\tif backtrack (i+1) (blanks-1) then true else (\n\t a.(i) <- empty;\n\t false\n\t)\n )\n ) else (\n let rec fit j = if j=4 then true else a.(i+p.(q).(j)) = 0 && (fit (j+1)) in\n let rec fill j x = if j=4 then a.(i) <- x else (\n\ta.(i+p.(q).(j)) <- x;\n\tfill (j+1) x\n )\n in\n\tif not (fit 0) then trypiece (q+1) else (\n\t fill 0 (i+1);\n\t if backtrack (i+1) blanks then true else (\n\t fill 0 empty;\n\t trypiece (q+1)\n\t )\n\t)\n )\n in\n trypiece 0\n\nlet rec tryblanks b = if backtrack 0 b then b else tryblanks (b+5)\n\nlet () = \n let blanks = tryblanks (n*m mod 5) in\n let lab = Array.make (h*w) (-1) in\n let rec labels i c = if i=h*w then () else (\n if a.(i)=hole || a.(i)=wall || lab.(a.(i)) >= 0 then labels (i+1) c else (\n lab.(a.(i)) <- c;\n labels (i+1) (c+1)\n )\n )\n in\n Printf.printf \"%d\\n\" (((n*m)-blanks)/5);\n labels 0 0;\n for i=0 to n-1 do \n for j=0 to m-1 do\n\tlet c = if a.(w*i+j) = hole then '.' else char_of_int ((int_of_char 'A') + lab.(a.(w*i+j))) in\n\t print_char c\n done;\n print_newline ()\n done\n"}], "negative_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = min n m\n and m = max n m in\n let a = Array.make_matrix n m (-1) in\n let b = Array.make_matrix n m (-1) in\n let res = ref 0 in\n let pred = ref 10 in\n let rec bf x y k =\n (*Printf.printf \"asd %d %d %d\\n\" x y k;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tPrintf.printf \"%d \" a.(i).(j)\n done;\n Printf.printf \"\\n\"\n done;*)\n let x = ref x in\n let y = ref y in\n while !x < n && a.(!x).(!y) >= 0 do\n\tincr x\n done;\n (*Printf.printf \"qwe %d %d %d\\n\" !x !y k;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tPrintf.printf \"%d \" a.(i).(j)\n done;\n Printf.printf \"\\n\"\n done;*)\n if !x = n then (\n\tif !y < m - 1 then (\n\t x := 0;\n\t incr y;\n\t bf !x !y k;\n\t) else (\n\t if !res < k then (\n\t res := k;\n\t for i = 0 to n - 1 do\n\t for j = 0 to m - 1 do\n\t\tb.(i).(j) <- a.(i).(j)\n\t done\n\t done;\n\t if !res >= !pred then raise Not_found\n\t )\n\t)\n ) else (\n\tlet x = !x\n\tand y = !y in\n\t if x <= n - 3 && y <= m - 3 &&\n\t a.(x).(y + 1) < 0 &&\n\t a.(x).(y + 2) < 0 &&\n\t a.(x + 1).(y + 1) < 0 &&\n\t a.(x + 2).(y + 1) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x).(y + 1) <- k;\n\t a.(x).(y + 2) <- k;\n\t a.(x + 1).(y + 1) <- k;\n\t a.(x + 2).(y + 1) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x).(y + 1) <- -1;\n\t a.(x).(y + 2) <- -1;\n\t a.(x + 1).(y + 1) <- -1;\n\t a.(x + 2).(y + 1) <- -1;\n\t );\n\t if 1 <= x && x <= n - 2 && y <= m - 3 &&\n\t a.(x).(y + 1) < 0 &&\n\t a.(x).(y + 2) < 0 &&\n\t a.(x + 1).(y + 2) < 0 &&\n\t a.(x - 1).(y + 2) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x).(y + 1) <- k;\n\t a.(x).(y + 2) <- k;\n\t a.(x + 1).(y + 2) <- k;\n\t a.(x - 1).(y + 2) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x).(y + 1) <- -1;\n\t a.(x).(y + 2) <- -1;\n\t a.(x + 1).(y + 2) <- -1;\n\t a.(x - 1).(y + 2) <- -1;\n\t );\n\t if 2 <= x && x <= n - 1 && y <= m - 3 &&\n\t a.(x).(y + 1) < 0 &&\n\t a.(x).(y + 2) < 0 &&\n\t a.(x - 1).(y + 1) < 0 &&\n\t a.(x - 2).(y + 1) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x).(y + 1) <- k;\n\t a.(x).(y + 2) <- k;\n\t a.(x - 1).(y + 1) <- k;\n\t a.(x - 2).(y + 1) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x).(y + 1) <- -1;\n\t a.(x).(y + 2) <- -1;\n\t a.(x - 1).(y + 1) <- -1;\n\t a.(x - 2).(y + 1) <- -1;\n\t );\n\t if x <= n - 3 && y <= m - 3 &&\n\t a.(x + 1).(y) < 0 &&\n\t a.(x + 2).(y) < 0 &&\n\t a.(x + 1).(y + 1) < 0 &&\n\t a.(x + 1).(y + 2) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x + 1).(y) <- k;\n\t a.(x + 2).(y) <- k;\n\t a.(x + 1).(y + 1) <- k;\n\t a.(x + 1).(y + 2) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x + 1).(y) <- -1;\n\t a.(x + 2).(y) <- -1;\n\t a.(x + 1).(y + 1) <- -1;\n\t a.(x + 1).(y + 2) <- -1;\n\t );\n\t bf (x + 1) y k;\n )\n in\n (match n, m with\n | 9, 9 -> pred := 13\n | 8, 9 -> pred := 12\n | 8, 8 -> pred := 10\n | 7, 9 -> pred := 10\n | 7, 8 -> pred := 9\n | _ -> ()\n );\n (try bf 0 0 0 with Not_found -> ());\n Printf.printf \"%d\\n\" !res;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tlet v = b.(i).(j) in\n\tlet c =\n\t if v < 0\n\t then '.'\n\t else Char.chr (Char.code 'A' + v)\n\tin\n\t Printf.printf \"%c\" c\n done;\n Printf.printf \"\\n\"\n done\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let n = min n m\n and m = max n m in\n let a = Array.make_matrix n m (-1) in\n let b = Array.make_matrix n m (-1) in\n let res = ref 0 in\n let pred = ref 10 in\n let rec bf x y k =\n (*Printf.printf \"asd %d %d %d\\n\" x y k;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tPrintf.printf \"%d \" a.(i).(j)\n done;\n Printf.printf \"\\n\"\n done;*)\n let x = ref x in\n let y = ref y in\n while !x < n && a.(!x).(!y) >= 0 do\n\tincr x\n done;\n (*Printf.printf \"qwe %d %d %d\\n\" !x !y k;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tPrintf.printf \"%d \" a.(i).(j)\n done;\n Printf.printf \"\\n\"\n done;*)\n if !x = n then (\n\tif !y < m - 1 then (\n\t x := 0;\n\t incr y;\n\t bf !x !y k;\n\t) else (\n\t if !res < k then (\n\t res := k;\n\t for i = 0 to n - 1 do\n\t for j = 0 to m - 1 do\n\t\tb.(i).(j) <- a.(i).(j)\n\t done\n\t done;\n\t if !res >= !pred then raise Not_found\n\t )\n\t)\n ) else (\n\tlet x = !x\n\tand y = !y in\n\t if x <= n - 3 && y <= m - 3 &&\n\t a.(x).(y + 1) < 0 &&\n\t a.(x).(y + 2) < 0 &&\n\t a.(x + 1).(y + 1) < 0 &&\n\t a.(x + 2).(y + 1) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x).(y + 1) <- k;\n\t a.(x).(y + 2) <- k;\n\t a.(x + 1).(y + 1) <- k;\n\t a.(x + 2).(y + 1) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x).(y + 1) <- -1;\n\t a.(x).(y + 2) <- -1;\n\t a.(x + 1).(y + 1) <- -1;\n\t a.(x + 2).(y + 1) <- -1;\n\t );\n\t if 1 <= x && x <= n - 2 && y <= m - 3 &&\n\t a.(x).(y + 1) < 0 &&\n\t a.(x).(y + 2) < 0 &&\n\t a.(x + 1).(y + 2) < 0 &&\n\t a.(x - 1).(y + 2) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x).(y + 1) <- k;\n\t a.(x).(y + 2) <- k;\n\t a.(x + 1).(y + 2) <- k;\n\t a.(x - 1).(y + 2) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x).(y + 1) <- -1;\n\t a.(x).(y + 2) <- -1;\n\t a.(x + 1).(y + 2) <- -1;\n\t a.(x - 1).(y + 2) <- -1;\n\t );\n\t if 2 <= x && x <= n - 1 && y <= m - 3 &&\n\t a.(x).(y + 1) < 0 &&\n\t a.(x).(y + 2) < 0 &&\n\t a.(x - 1).(y + 1) < 0 &&\n\t a.(x - 2).(y + 1) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x).(y + 1) <- k;\n\t a.(x).(y + 2) <- k;\n\t a.(x - 1).(y + 1) <- k;\n\t a.(x - 2).(y + 1) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x).(y + 1) <- -1;\n\t a.(x).(y + 2) <- -1;\n\t a.(x - 1).(y + 1) <- -1;\n\t a.(x - 2).(y + 1) <- -1;\n\t );\n\t if x <= n - 3 && y <= m - 3 &&\n\t a.(x + 1).(y) < 0 &&\n\t a.(x + 2).(y) < 0 &&\n\t a.(x + 1).(y + 1) < 0 &&\n\t a.(x + 1).(y + 2) < 0\n\t then (\n\t a.(x).(y) <- k;\n\t a.(x + 1).(y) <- k;\n\t a.(x + 2).(y) <- k;\n\t a.(x + 1).(y + 1) <- k;\n\t a.(x + 1).(y + 2) <- k;\n\t bf x y (k + 1);\n\t a.(x).(y) <- -1;\n\t a.(x + 1).(y) <- -1;\n\t a.(x + 2).(y) <- -1;\n\t a.(x + 1).(y + 1) <- -1;\n\t a.(x + 1).(y + 2) <- -1;\n\t );\n\t bf (x + 1) y k;\n )\n in\n (match n, m with\n | 9, 9 -> pred := 13\n | 8, 9 -> pred := 12\n | 7, 9 -> pred := 10\n | 7, 8 -> pred := 9\n | _ -> ()\n );\n (try bf 0 0 0 with Not_found -> ());\n Printf.printf \"%d\\n\" !res;\n for i = 0 to n - 1 do\n for j = 0 to m - 1 do\n\tlet v = b.(i).(j) in\n\tlet c =\n\t if v < 0\n\t then '.'\n\t else Char.chr (Char.code 'A' + v)\n\tin\n\t Printf.printf \"%c\" c\n done;\n Printf.printf \"\\n\"\n done\n"}], "src_uid": "f29eba31c20246686b8427b7aeadd184"} {"nl": {"description": "The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i,\u20090). There are m flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move.In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line.Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.", "input_spec": "The first line contains two space-separated integers n and m (1\u2009\u2264\u2009n\u2009\u2264\u2009106,\u20091\u2009\u2264\u2009m\u2009\u2264\u2009250), denoting the number of binoculars and the number of flamingos, respectively. Then m lines follow, the i-th line will contain two space-separated integers xi and yi (1\u2009\u2264\u2009xi,\u2009yi\u2009\u2264\u2009109), which means that the i-th flamingo is located at point (xi,\u2009yi). All flamingos will be located at distinct points.", "output_spec": "Print a single integer denoting the maximum total number of flamingos that can be seen by all the binoculars.", "sample_inputs": ["5 5\n2 1\n4 1\n3 2\n4 3\n4 4"], "sample_outputs": ["11"], "notes": "NoteThis picture shows the answer to the example test case. "}, "positive_code": [{"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let n = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let m = Scanf.bscanf sb \"%d \" (fun s -> s) in\n let x = Array.make m 0 in\n let y = Array.make m 0 in\n let () =\n for i = 0 to m - 1 do\n x.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n y.(i) <- Scanf.bscanf sb \"%d \" (fun s -> s);\n done;\n in\n let area x y x1 y1 x2 y2 =\n Int64.sub\n (Int64.mul (Int64.of_int (x1 - x))\n\t (Int64.of_int (y2 - y)))\n (Int64.mul (Int64.of_int (x2 - x))\n\t (Int64.of_int (y1 - y)))\n in\n let check x1 y1 x2 y2 =\n let x1 = Int64.of_int x1 in\n let y1 = Int64.of_int y1 in\n let x2 = Int64.of_int x2 in\n let y2 = Int64.of_int y2 in\n let a = Int64.sub (Int64.mul x2 y1) (Int64.mul x1 y2) in\n let b = Int64.sub y1 y2 in\n if Int64.rem a b = 0L\n then Some (Int64.div a b)\n else None\n in\n let a = Array.make (n + 1) 1 in\n for i = 0 to m - 1 do\n for j = i + 1 to m - 1 do\n\tif y.(i) <> y.(j) then (\n\t match check x.(i) y.(i) x.(j) y.(j) with\n\t | Some x' ->\n\t\tif x' > 0L && x' <= Int64.of_int n then (\n\t\t let x' = Int64.to_int x' in\n\t\t let c = ref 2 in\n\t\t for k = 0 to m - 1 do\n\t\t if k <> i && k <> j &&\n\t\t\tarea x.(i) y.(i) x.(j) y.(j) x.(k) y.(k) = 0L\n\t\t then incr c\n\t\t done;\n\t\t a.(x') <- max a.(x') !c\n\t\t)\n\t | None -> ()\n\t)\n done\n done;\n let res = ref 0 in\n for i = 1 to n do\n\tres := !res + a.(i)\n done;\n Printf.printf \"%d\\n\" !res\n"}], "negative_code": [], "src_uid": "a06dbb1fb1d7116a457f031b85531e49"} {"nl": {"description": "You are given a positive integer $$$n$$$.The weight of a permutation $$$p_1, p_2, \\ldots, p_n$$$ is the number of indices $$$1\\le i\\le n$$$ such that $$$i$$$ divides $$$p_i$$$. Find a permutation $$$p_1,p_2,\\dots, p_n$$$ with the minimum possible weight (among all permutations of length $$$n$$$).A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$). The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$1 \\leq n \\leq 10^5$$$) \u2014 the length of permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.", "output_spec": "For each test case, print a line containing $$$n$$$ integers $$$p_1, p_2,\\dots, p_n$$$ so that the permutation $$$p$$$ has the minimum possible weight. If there are several possible answers, you can print any of them.", "sample_inputs": ["2\n\n1\n\n4"], "sample_outputs": ["1\n2 1 4 3"], "notes": "NoteIn the first test case, the only valid permutation is $$$p=[1]$$$. Its weight is $$$1$$$.In the second test case, one possible answer is the permutation $$$p=[2,1,4,3]$$$. One can check that $$$1$$$ divides $$$p_1$$$ and $$$i$$$ does not divide $$$p_i$$$ for $$$i=2,3,4$$$, so the weight of this permutation is $$$1$$$. It is impossible to find a permutation of length $$$4$$$ with a strictly smaller weight."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet () = \n let cases = read_int () in\n for case = 1 to cases do\n let n = read_int() in\n for i=0 to n-1 do\n printf \"%d \" (if i = 0 then n else i)\n done;\n print_newline()\n done\n"}], "negative_code": [], "src_uid": "955bc1e2769ea407ef02506bf1e4259b"} {"nl": {"description": "Burenka and Tonya are playing an old Buryat game with a chip on a board of $$$n \\times m$$$ cells.At the beginning of the game, the chip is located in the lower left corner of the board. In one move, the player can move the chip to the right or up by any odd number of cells (but you cannot move the chip both to the right and up in one move). The one who cannot make a move loses.Burenka makes the first move, the players take turns. Burenka really wants to win the game, but she is too lazy to come up with a strategy, so you are invited to solve the difficult task of finding it. Name the winner of the game (it is believed that Burenka and Tonya are masters of playing with chips, so they always move in the optimal way). Chip's starting cell is green, the only cell from which chip can't move is red. if the chip is in the yellow cell, then blue cells are all options to move the chip in one move. ", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\leq t \\leq 10^4$$$) \u2014 the number of test cases. The following is a description of the input data sets. The only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\leq n, m \\leq 10^9$$$) \u2014 the dimensions of the game board.", "output_spec": "For each test case print a single line \u2014 the name of the winner of the game (\"Burenka\" or \"Tonya\").", "sample_inputs": ["6\n\n1 1\n\n1 4\n\n5 6\n\n2 2\n\n6 3\n\n999999999 1000000000"], "sample_outputs": ["Tonya\nBurenka\nBurenka\nTonya\nBurenka\nBurenka"], "notes": "NoteIn the first case, Burenka has no move, so Tonya wins.In the second case, Burenka can move $$$3$$$ cells to the right, after which Tony will not be able to make a move, which means that Burenka wins.In the third case, Burenka can move $$$5$$$ squares to the right. Then we can say that we have a game on a board of $$$1 \\times 5$$$ cells, and Tonya is the first player. In such game the second player wins, so in the original one Burenka will win."}, "positive_code": [{"source_code": "\nlet sf = Scanf.scanf\nlet read_int () = sf \" %d\" (fun x -> x)\n\nlet () =\n let t = read_int () in\n for _ = 1 to t do\n let n = read_int () in\n let m = read_int () in\n if (n + m) mod 2 = 0 then\n Printf.printf \"Tonya\\n\"\n else\n Printf.printf \"Burenka\\n\"\n done;"}, {"source_code": "(* 2n+1, 1 then second player wins \r\nsince 1st moves 2a-1, 2nd moves 2(n-a)+1, leaving 1,1 for first.\r\n\r\n2n,1 then first player wins since first moves 2n-1\r\nwhich leaves second with 1,1\r\n\r\n2n,2m then 2x+1,2m so second player wins.\r\n2n+1,2m then first moves 2m-1 leaving 2n+1,1 and that means\r\nfirst player wins as second player must go first in this grid type.\r\n\r\n2n+1,2m+1 then first player moves 2a-1 in either direction so\r\nsecond should move in that direction s.t 1,2m+1 or 2n+1,1 which means they win as the player that \r\nneeds to go seconds in the config wins.\r\n*)\r\n\r\nlet read_long () = Scanf.scanf \" %Ld\" (fun l-> l);;\r\nlet read_int () = Scanf.scanf \" %d\" (fun x-> x);;\r\nlet run_case = function\r\n| () ->\r\n let n = read_long () in\r\n let m = read_long () in\r\n let nrem = Int64.sub n (Int64.mul (Int64.div n 2L) 2L) in\r\n let mrem = Int64.sub m (Int64.mul (Int64.div m 2L) 2L) in\r\n if ((nrem=0L)&&(mrem=0L)) then print_string \"Tonya\"\r\n else if ((nrem=0L)||(mrem=0L)) then print_string \"Burenka\"\r\n else print_string \"Tonya\"\r\n;;\r\n\r\nlet rec iter_cases = function\r\n| 0->()\r\n| t -> run_case (); print_newline (); iter_cases (t-1)\r\n;;\r\n\r\nlet t=read_int () in iter_cases t;;\r\n"}], "negative_code": [], "src_uid": "13611e428c24b94023811063bbbfa077"} {"nl": {"description": "There are $$$n$$$ children numbered from $$$1$$$ to $$$n$$$ in a kindergarten. Kindergarten teacher gave $$$a_i$$$ ($$$1 \\leq a_i \\leq n$$$) candies to the $$$i$$$-th child. Children were seated in a row in order from $$$1$$$ to $$$n$$$ from left to right and started eating candies. While the $$$i$$$-th child was eating candies, he calculated two numbers $$$l_i$$$ and $$$r_i$$$\u00a0\u2014 the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.Formally, $$$l_i$$$ is the number of indices $$$j$$$ ($$$1 \\leq j < i$$$), such that $$$a_i < a_j$$$ and $$$r_i$$$ is the number of indices $$$j$$$ ($$$i < j \\leq n$$$), such that $$$a_i < a_j$$$.Each child told to the kindergarten teacher the numbers $$$l_i$$$ and $$$r_i$$$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $$$l$$$ and $$$r$$$ determine whether she could have given the candies to the children such that all children correctly calculated their values $$$l_i$$$ and $$$r_i$$$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.", "input_spec": "On the first line there is a single integer $$$n$$$ ($$$1 \\leq n \\leq 1000$$$)\u00a0\u2014 the number of children in the kindergarten. On the next line there are $$$n$$$ integers $$$l_1, l_2, \\ldots, l_n$$$ ($$$0 \\leq l_i \\leq n$$$), separated by spaces. On the next line, there are $$$n$$$ integer numbers $$$r_1, r_2, \\ldots, r_n$$$ ($$$0 \\leq r_i \\leq n$$$), separated by spaces.", "output_spec": "If there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print \u00abNO\u00bb (without quotes). Otherwise, print \u00abYES\u00bb (without quotes) on the first line. On the next line, print $$$n$$$ integers $$$a_1, a_2, \\ldots, a_n$$$, separated by spaces\u00a0\u2014 the numbers of candies the children $$$1, 2, \\ldots, n$$$ received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition $$$1 \\leq a_i \\leq n$$$. The number of children seating to the left of the $$$i$$$-th child that got more candies than he should be equal to $$$l_i$$$ and the number of children seating to the right of the $$$i$$$-th child that got more candies than he should be equal to $$$r_i$$$. If there is more than one solution, find any of them.", "sample_inputs": ["5\n0 0 1 1 2\n2 0 1 0 0", "4\n0 0 2 0\n1 1 1 1", "3\n0 0 0\n0 0 0"], "sample_outputs": ["YES\n1 3 1 2 1", "NO", "YES\n1 1 1"], "notes": "NoteIn the first example, if the teacher distributed $$$1$$$, $$$3$$$, $$$1$$$, $$$2$$$, $$$1$$$ candies to $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$4$$$-th, $$$5$$$-th child, respectively, then all the values calculated by the children are correct. For example, the $$$5$$$-th child was given $$$1$$$ candy, to the left of him $$$2$$$ children were given $$$1$$$ candy, $$$1$$$ child was given $$$2$$$ candies and $$$1$$$ child\u00a0\u2014 $$$3$$$ candies, so there are $$$2$$$ children to the left of him that were given more candies than him.In the second example it is impossible to distribute the candies, because the $$$4$$$-th child made a mistake in calculating the value of $$$r_4$$$, because there are no children to the right of him, so $$$r_4$$$ should be equal to $$$0$$$.In the last example all children may have got the same number of candies, that's why all the numbers are $$$0$$$. Note that each child should receive at least one candy."}, "positive_code": [{"source_code": "let split_on_char sep s =\n let r = ref [] in\n let j = ref (String.length s) in\n for i = String.length s - 1 downto 0 do\n if String.unsafe_get s i = sep then (\n r := String.sub s (i + 1) (!j - i - 1) :: !r ;\n j := i )\n done ;\n String.sub s 0 !j :: !r\n\nlet insert s i a n x =\n let min = ref 0 and max = ref (n+1) in\n while !max - !min > 0 do\n if x < a.((!max + !min) / 2) then max := (!max + !min) / 2\n else min := ((!max + !min) / 2) + 1;\n done ;\n for i = n downto !min do\n a.(i + 1) <- a.(i)\n done ;\n a.(!min) <- x ;\n s.(i) <- n + 1 - !min\n\n;;\nlet n = Scanf.sscanf (read_line ()) \"%i\" (fun n -> n) in\nlet l = Array.make n 0 in\nsplit_on_char ' ' (read_line ())\n|> List.iteri (fun i x -> l.(i) <- int_of_string x) ;\nlet r = Array.make n 0 in\nsplit_on_char ' ' (read_line ())\n|> List.iteri (fun i x -> r.(i) <- int_of_string x) ;\nlet total = Array.init n (fun i -> (l.(i) + r.(i), i + 1)) in\nArray.fast_sort compare total ;\nlet current = ref n in\nlet bonbon = ref 0 in\nlet sol = Array.make n 0 in\nfor i = n - 1 downto 0 do\n if !current > fst total.(i) then (\n current := fst total.(i) ;\n incr bonbon ) ;\n sol.(snd total.(i) - 1) <- !bonbon\ndone ;\nlet sl = Array.make n 0 in\nlet al = Array.make n sol.(0) in\nlet sr = Array.make n 0 in\nlet ar = Array.make n sol.(n - 1) in\nfor i = 1 to n - 1 do\n insert sl i al (i - 1) sol.(i) ;\n insert sr (n - 1 - i) ar (i - 1) sol.(n - 1 - i);\ndone ;\nif sl = l && sr = r then (\n print_endline \"YES\" ;\n Array.iter (Printf.printf \"%i \") sol )\nelse print_string \"NO\" ;\nprint_newline ()\n"}], "negative_code": [], "src_uid": "fa531c38833907d619f1102505ddbb6a"} {"nl": {"description": "The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. ", "input_spec": "The first line contains single integer n (2\u2009\u2264\u2009n\u2009\u2264\u200960\u2009000)\u00a0\u2014 the number of friends. The second line contains n integers x1,\u2009x2,\u2009...,\u2009xn (1\u2009\u2264\u2009xi\u2009\u2264\u2009109)\u00a0\u2014 the current coordinates of the friends, in meters. The third line contains n integers v1,\u2009v2,\u2009...,\u2009vn (1\u2009\u2264\u2009vi\u2009\u2264\u2009109)\u00a0\u2014 the maximum speeds of the friends, in meters per second.", "output_spec": "Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10\u2009-\u20096. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if holds.", "sample_inputs": ["3\n7 1 3\n1 2 1", "4\n5 10 3 2\n2 3 2 4"], "sample_outputs": ["2.000000000000", "1.400000000000"], "notes": "NoteIn the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds."}, "positive_code": [{"source_code": "let read_array n = let a = Array.make n 0 in\n for i = 0 to (n - 1) do\n Scanf.scanf \" %d\" (fun x -> a.(i) <- x)\n done;\n a\n\nlet best_time pos spd =\n let n = Array.length pos in\n let max_x = float_of_int (Array.fold_left max min_int pos) in\n let min_v = float_of_int (Array.fold_left min max_int spd) in\n let merge (a, b) (c, d) = (max a c, min b d) in\n let feasible_time t =\n let range = ref (neg_infinity, infinity) in\n for i = 0 to (n-1) do\n let (x, dx) = (float_of_int pos.(i), float_of_int spd.(i) *. t) in\n range := merge !range (x -. dx, x +. dx)\n done;\n let (a, b) = !range in a <= b\n in\n let rec find lo hi it =\n if (hi -. lo) < epsilon_float || it >= 64\n then lo\n else\n let m = lo +. (hi -. lo) /. 2. in\n if feasible_time m\n then find lo m (it + 1)\n else find (m +. epsilon_float) hi (it + 1)\n in\n find 0.0 (max_x /. min_v) 0\n\nlet () =\n let n = Scanf.scanf \"%d\" (fun x -> x) in\n let pos = read_array n in\n let spd = read_array n in\n Printf.printf \"%10.12f\\n\" (best_time pos spd)\n"}, {"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_float _ = bscanf Scanning.stdib \" %f \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let x = Array.init n read_float in\n let v = Array.init n read_float in\n\n let intersect (lo1,hi1) (lo2,hi2) = (max lo1 lo2, min hi1 hi2) in\n let no_overlap (lo,hi) = lo > hi in\n\n let overlap_interval t =\n (* given time t, if they overlap return Some (lo,hi) else None *)\n let rec loop oldinterval i =\n if i=n then Some oldinterval else\n\tlet my_hi = x.(i) +. t *. v.(i) in\n\tlet my_lo = x.(i) -. t *. v.(i) in\n\tlet newinterval = if i=0 then (my_lo,my_hi) else intersect (my_lo,my_hi) oldinterval in\n\tif no_overlap newinterval then None else loop newinterval (i+1)\n in\n loop (0.0, 0.0) 0\n in\n\n let rec bsearch lo_t hi_t count = (* hi has overlap, lo has no overlap *)\n if count = 50 then hi_t else\n let m = (lo_t +. hi_t) /. 2.0 in\n match overlap_interval m with\n\t| None -> bsearch m hi_t (count+1)\n\t| Some _ -> bsearch lo_t m (count+1)\n in\n\n let rec find_hi t = match overlap_interval t with None -> find_hi (2.0 *. t) | Some _ -> t in\n\n let answer = match overlap_interval 0.0 with Some _ -> 0.0\n | None -> bsearch 0.0 (find_hi 1.0) 0\n in\n\n printf \"%.10f\\n\" answer\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_float _ = bscanf Scanning.stdib \" %f \" (fun x -> x)\n \nlet () = \n let n = read_int () in\n let x = Array.init n read_float in\n let v = Array.init n read_float in\n\n let intersect (lo1,hi1) (lo2,hi2) = (max lo1 lo2, min hi1 hi2) in\n let no_overlap (lo,hi) = lo > hi in\n\n let overlap_interval t =\n (* given time t, if they overlap return Some (lo,hi) else None *)\n let rec loop oldinterval i =\n if i=n then Some oldinterval else\n\tlet my_hi = x.(i) +. t *. v.(i) in\n\tlet my_lo = x.(i) -. t *. v.(i) in\n\tlet newinterval = if i=0 then (my_lo,my_hi) else intersect (my_lo,my_hi) oldinterval in\n\tif no_overlap newinterval then None else loop newinterval (i+1)\n in\n loop (0.0, 0.0) 0\n in\n\n let rec bsearch lo_t hi_t count = (* hi has overlap, lo has no overlap *)\n if count = 50 then hi_t else\n let m = (lo_t +. hi_t) /. 2.0 in\n match overlap_interval m with\n\t| None -> bsearch m hi_t (count+1)\n\t| Some _ -> bsearch lo_t m (count+1)\n in\n\n let rec find_hi t = match overlap_interval t with None -> find_hi (2.0 *. t) | Some _ -> t in\n\n let answer = match overlap_interval 0.0 with Some (lo,hi) -> lo | None ->\n bsearch 0.0 (find_hi 1.0) 0\n in\n\n printf \"%.10f\\n\" answer\n"}], "src_uid": "f13f27a131b9315ebbb8688e2f43ddde"} {"nl": {"description": "Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi essays. He can raise the exam grade multiple times.What is the minimum number of essays that Vanya needs to write to get scholarship?", "input_spec": "The first line contains three integers n, r, avg (1\u2009\u2264\u2009n\u2009\u2264\u2009105, 1\u2009\u2264\u2009r\u2009\u2264\u2009109, 1\u2009\u2264\u2009avg\u2009\u2264\u2009min(r,\u2009106))\u00a0\u2014 the number of exams, the maximum grade and the required grade point average, respectively. Each of the following n lines contains space-separated integers ai and bi (1\u2009\u2264\u2009ai\u2009\u2264\u2009r, 1\u2009\u2264\u2009bi\u2009\u2264\u2009106).", "output_spec": "In the first line print the minimum number of essays.", "sample_inputs": ["5 5 4\n5 2\n4 7\n3 1\n3 2\n2 5", "2 5 4\n5 2\n5 2"], "sample_outputs": ["4", "0"], "notes": "NoteIn the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.In the second sample, Vanya doesn't need to write any essays as his general point average already is above average."}, "positive_code": [{"source_code": "exception Invalid_input\n\nlet (|>) x f = f x\n\nlet rec make_list = fun len f ->\n if len = 0 then\n []\n else\n (f ()) :: (make_list (len - 1) f)\n\nlet rec count_essay = fun maximum_grade target l ->\n let open Int64 in\n if (compare target zero) <= 0 then\n zero\n else\n let (grade, essay) = List.hd l in\n let grade_up = sub maximum_grade (of_int grade) in\n if (compare grade_up target) <= 0 then\n (add (mul grade_up (of_int essay)) (count_essay maximum_grade (sub target grade_up) (List.tl l)))\n else\n (mul target (of_int essay))\n\nlet () =\n let (n, r, avg) = read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map int_of_string\n |> fun li ->\n match li with\n | a :: b :: [c] ->\n (a, b, c)\n | _ ->\n raise Invalid_input\n in\n let exams = make_list n (fun () ->\n read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map int_of_string\n |> fun li ->\n match li with\n | a :: [b] ->\n (a, b)\n | _ ->\n raise Invalid_input\n )\n |> List.fast_sort (fun (_, a) (_, b) -> a - b)\n in\n let current_score = exams\n |> List.fold_left (fun sum (a, _) -> Int64.(add sum (of_int a))) Int64.zero\n in\n exams\n |> count_essay (Int64.of_int r) Int64.(sub (mul (of_int n) (of_int avg)) current_score)\n |> Int64.to_string\n |> print_string\n |> print_newline\n"}], "negative_code": [{"source_code": "open Str\n\nexception Invalid_input\n\nlet (|>) x f = f x\n\nlet rec make_list = fun len f ->\n if len = 0 then\n []\n else\n (f ()) :: (make_list (len - 1) f)\n\nlet rec count_essay = fun maximum_grade target l ->\n if target <= 0.0 then\n 0.0\n else\n let (grade, essay) = List.hd l in\n let grade_up = maximum_grade -. grade in\n if grade_up <= target then\n grade_up *. essay +. (count_essay maximum_grade (target -. grade_up) (List.tl l))\n else\n target *. essay\n\nlet () =\n let (n, r, avg) = read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map float_of_string\n |> fun li ->\n match li with\n | a :: b :: [c] ->\n (a, b, c)\n | _ ->\n raise Invalid_input\n in\n let exams = make_list (int_of_float n) (fun () ->\n read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map float_of_string\n |> fun li ->\n match li with\n | a :: [b] ->\n (a, b)\n | _ ->\n raise Invalid_input\n )\n |> List.fast_sort (fun (_, a) (_, b) ->\n if a < b then -1 else 1\n )\n in\n let current_score = exams\n |> List.fold_left (fun sum (a, _) -> sum +. a) 0.0\n in\n exams\n |> count_essay r (n *. avg -. current_score)\n |> int_of_float\n |> Printf.printf \"%d\\n\"\n"}, {"source_code": "open Str\n\nexception Invalid_input\n\nlet (|>) x f = f x\n\nlet rec make_list = fun len f ->\n if len = 0 then\n []\n else\n (f ()) :: (make_list (len - 1) f)\n\nlet rec count_essay = fun maximum_grade target l ->\n if target <= 0 then\n 0\n else\n let (grade, essay) = List.hd l in\n let grade_up = maximum_grade - grade in\n if grade_up <= target then\n grade_up * essay + (count_essay maximum_grade (target - grade_up) (List.tl l))\n else\n target * essay\n\nlet () =\n let (n, r, avg) = read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map int_of_string\n |> fun li ->\n match li with\n | a :: b :: [c] ->\n (a, b, c)\n | _ ->\n raise Invalid_input\n in\n let exams = make_list n (fun () ->\n read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map int_of_string\n |> fun li ->\n match li with\n | a :: [b] ->\n (a, b)\n | _ ->\n raise Invalid_input\n )\n |> List.fast_sort (fun (_, a) (_, b) ->\n a - b\n )\n in\n let current_score = exams\n |> List.fold_left (fun sum (a, _) -> sum + a) 0\n in\n exams\n |> count_essay r (n * avg - current_score)\n |> Printf.printf \"%d\\n\"\n"}, {"source_code": "open Str\n\nexception Invalid_input\n\nlet (|>) x f = f x\n\nlet rec make_list = fun len f ->\n if len = 0 then\n []\n else\n (f ()) :: (make_list (len - 1) f)\n\nlet rec count_essay = fun maximum_grade target l ->\n if target <= 0.0 then\n 0.0\n else\n let (grade, essay) = List.hd l in\n let grade_up = maximum_grade -. grade in\n if grade_up <= target then\n grade_up *. essay +. (count_essay maximum_grade (target -. grade_up) (List.tl l))\n else\n target *. essay\n\nlet () =\n let (n, r, avg) = read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map float_of_string\n |> fun li ->\n match li with\n | a :: b :: [c] ->\n (a, b, c)\n | _ ->\n raise Invalid_input\n in\n let exams = make_list (int_of_float n) (fun () ->\n read_line ()\n |> Str.split (Str.regexp \" +\")\n |> List.map float_of_string\n |> fun li ->\n match li with\n | a :: [b] ->\n (a, b)\n | _ ->\n raise Invalid_input\n )\n |> List.fast_sort (fun (_, a) (_, b) ->\n if a < b then -1 else 1\n )\n in\n let current_score = exams\n |> List.fold_left (fun sum (a, _) -> sum +. a) 0.0\n in\n exams\n |> count_essay r (n *. avg -. current_score)\n |> Printf.printf \"%.f\\n\"\n"}], "src_uid": "55270ee4e6aae7fc0c9bb070fcbf5560"} {"nl": {"description": "You are given a permutation of the numbers 1,\u20092,\u2009...,\u2009n and m pairs of positions (aj,\u2009bj).At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?Let p and q be two permutations of the numbers 1,\u20092,\u2009...,\u2009n. p is lexicographically smaller than the q if a number 1\u2009\u2264\u2009i\u2009\u2264\u2009n exists, so pk\u2009=\u2009qk for 1\u2009\u2264\u2009k\u2009<\u2009i and pi\u2009<\u2009qi.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009106) \u2014 the length of the permutation p and the number of pairs of positions. The second line contains n distinct integers pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009n) \u2014 the elements of the permutation p. Each of the last m lines contains two integers (aj,\u2009bj) (1\u2009\u2264\u2009aj,\u2009bj\u2009\u2264\u2009n) \u2014 the pairs of positions to swap. Note that you are given a positions, not the values to swap.", "output_spec": "Print the only line with n distinct integers p'i (1\u2009\u2264\u2009p'i\u2009\u2264\u2009n) \u2014 the lexicographically maximal permutation one can get.", "sample_inputs": ["9 6\n1 2 3 4 5 6 7 8 9\n1 4\n4 7\n2 5\n5 8\n3 6\n6 9"], "sample_outputs": ["7 8 9 4 5 6 1 2 3"], "notes": null}, "positive_code": [{"source_code": "let getnum =\n let l = 512000 in\n let buf = String.make l ' ' in\n let s = ref 0 in\n let pos = ref 0 in\n let getc () =\n if !pos >= !s then (\n let new_s = input stdin buf 0 l in\n\t(*if new_s = 0 then raise End_of_file;*)\n\ts := new_s;\n\tif new_s = 0 then (\n\t buf.[0] <- '\\000';\n\t s := 1;\n\t);\n\tpos := 0;\n );\n let c = buf.[!pos] in\n incr pos;\n c\n in\n let aux () =\n let n = ref 0 in\n let k = ref 1 in\n if !s - !pos < 50 then (\n\tlet c = ref (getc ()) in\n\t while !c <= ' ' do\n\t c := getc ()\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := getc ();\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := getc ()\n\t done;\n\t !n * !k\n ) else (\n\tlet c = ref (buf.[!pos]) in\n\t incr pos;\n\t while !c <= ' ' do\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t if !c = '-' then (\n\t k := -1;\n\t c := buf.[!pos];\n\t incr pos;\n\t );\n\t while !c > ' ' do\n\t n := !n * 10 + (Char.code !c - Char.code '0');\n\t c := buf.[!pos];\n\t incr pos;\n\t done;\n\t !n * !k\n )\n in\n aux\n\n\ntype t = {p : int array;\n\t rank : int array}\n\nlet makeset set x =\n set.p.(x) <- x;\n set.rank.(x) <- 0\n\nlet rec find set x =\n if x <> set.p.(x) then set.p.(x) <- find set set.p.(x);\n set.p.(x)\n\nlet link set x y =\n if set.rank.(x) > set.rank.(y) then (\n set.p.(y) <- x;\n x\n ) else (\n if set.rank.(x) = set.rank.(y) then set.rank.(y) <- set.rank.(y) + 1;\n set.p.(x) <- y;\n y\n )\n\nlet newsets size =\n let set =\n {p = Array.make size (-1);\n rank = Array.make size 0\n }\n in\n for i = 0 to size-1 do\n makeset set i\n done;\n set\n\n\nlet _ =\n let n = getnum () in\n let m = getnum () in\n let a = Array.make n 0 in\n let ds = newsets n in\n let _ =\n for i = 0 to n - 1 do\n a.(i) <- getnum ()\n done;\n for i = 0 to m - 1 do\n let u = getnum () - 1 in\n let v = getnum () - 1 in\n let u = find ds u in\n let v = find ds v in\n\tignore (link ds u v)\n done;\n in\n let res = Array.make n 0 in\n let b = Array.make n [] in\n let _ =\n for i = 0 to n - 1 do\n let j = find ds i in\n\tb.(j) <- i :: b.(j)\n done;\n in\n let b = Array.map Array.of_list b in\n let cmp (x : int) y =\n if x < y\n then -1\n else if x = y\n then 0\n else 1\n in\n let get i = a.(i) in\n for i = 0 to n - 1 do\n let c = Array.map get b.(i) in\n\tArray.sort cmp c;\n\tfor j = 0 to Array.length b.(i) - 1 do\n\t res.(b.(i).(j)) <- c.(j)\n\tdone;\n done;\n for i = 0 to n - 1 do\n Printf.printf \"%d \" res.(i)\n done;\n Printf.printf \"\\n\"\n"}], "negative_code": [], "src_uid": "32077a3111c3f28ad56eab0c085a882d"} {"nl": {"description": "Vova plans to go to the conference by train. Initially, the train is at the point $$$1$$$ and the destination point of the path is the point $$$L$$$. The speed of the train is $$$1$$$ length unit per minute (i.e. at the first minute the train is at the point $$$1$$$, at the second minute \u2014 at the point $$$2$$$ and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by $$$v$$$ (i.e. the first lantern is at the point $$$v$$$, the second is at the point $$$2v$$$ and so on).There is also exactly one standing train which occupies all the points from $$$l$$$ to $$$r$$$ inclusive.Vova can see the lantern at the point $$$p$$$ if $$$p$$$ is divisible by $$$v$$$ and there is no standing train at this position ($$$p \\not\\in [l; r]$$$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $$$t$$$ different conferences, so you should answer $$$t$$$ independent queries.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of queries. Then $$$t$$$ lines follow. The $$$i$$$-th line contains four integers $$$L_i, v_i, l_i, r_i$$$ ($$$1 \\le L, v \\le 10^9$$$, $$$1 \\le l \\le r \\le L$$$) \u2014 destination point of the $$$i$$$-th path, the period of the lantern appearance and the segment occupied by the standing train.", "output_spec": "Print $$$t$$$ lines. The $$$i$$$-th line should contain one integer \u2014 the answer for the $$$i$$$-th query.", "sample_inputs": ["4\n10 2 3 7\n100 51 51 51\n1234 1 100 199\n1000000000 1 1 1000000000"], "sample_outputs": ["3\n0\n1134\n0"], "notes": "NoteFor the first example query, the answer is $$$3$$$. There are lanterns at positions $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$ and $$$10$$$, but Vova didn't see the lanterns at positions $$$4$$$ and $$$6$$$ because of the standing train.For the second example query, the answer is $$$0$$$ because the only lantern is at the point $$$51$$$ and there is also a standing train at this point.For the third example query, the answer is $$$1134$$$ because there are $$$1234$$$ lanterns, but Vova didn't see the lanterns from the position $$$100$$$ to the position $$$199$$$ inclusive.For the fourth example query, the answer is $$$0$$$ because the standing train covers the whole path."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\n\tlet dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf \" %d\" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf \" %d %d\" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf \" %d %d %d\" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf \" %d %d %d %d\" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf \" %d %d %d %d %d\" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done\nend open MyInt64\n\nlet () =\n\tlet t = get_i64 0 in\n\trep 1L t (fun _ -> \n\t\tlet ll,v,l,r = get_4_i64 0 in\n\t\tlet k_left =\n\t\t\tif l mod v = 0L then l/v-1L\n\t\t\telse l/v\n\t\tin\n\t\tlet v_r = if r mod v = 0L then (r/v+1L)*v else (r/v+1L)*v in\n\t\tlet k_right = ((ll/v)*v - v_r)/v + 1L in\n\t\tprintf \"%Ld\\n\" (k_left + k_right);\n\t\t(* printf \"%Ld %Ld\\n\" k_left k_right *)\n\t\t(* let n = ll / v in \n\t\tprintf \"%Ld\\n\" (ll/v - r/v + l/v) *)\n\t\t; `Ok\n\t)\n"}], "negative_code": [], "src_uid": "5194846a503c2087fcd299eaf3c20b2b"} {"nl": {"description": "Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n\u2009\u00d7\u2009n matrix \u0410: there is a number on the intersection of the \u0456-th row and j-th column that describes the result of the collision of the \u0456-th and the j-th car: \u2009-\u20091: if this pair of cars never collided. \u2009-\u20091 occurs only on the main diagonal of the matrix. 0: if no car turned over during the collision. 1: if only the i-th car turned over during the collision. 2: if only the j-th car turned over during the collision. 3: if both cars turned over during the collision. Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009100) \u2014 the number of cars. Each of the next n lines contains n space-separated integers that determine matrix A. It is guaranteed that on the main diagonal there are \u2009-\u20091, and \u2009-\u20091 doesn't appear anywhere else in the matrix. It is guaranteed that the input is correct, that is, if Aij\u2009=\u20091, then Aji\u2009=\u20092, if Aij\u2009=\u20093, then Aji\u2009=\u20093, and if Aij\u2009=\u20090, then Aji\u2009=\u20090.", "output_spec": "Print the number of good cars and in the next line print their space-separated indices in the increasing order.", "sample_inputs": ["3\n-1 0 0\n0 -1 1\n0 2 -1", "4\n-1 3 3 3\n3 -1 3 3\n3 3 -1 3\n3 3 3 -1"], "sample_outputs": ["2\n1 3", "0"], "notes": null}, "positive_code": [{"source_code": "let _ =\n\tlet n = Scanf.scanf \"%d \" (fun i -> i) and l = ref [] in\n\tfor i=1 to n do\n\t\tlet flg = ref true in\n\t\tfor j=1 to i-1 do\n\t\t\tScanf.scanf \"%d \" (fun a -> flg := !flg && (a mod 2 = 0)); \n\t\tdone;\n\t\tScanf.scanf \"%d \" (fun a -> ());\n\t\tfor j=i+1 to n do\n\t\t\tScanf.scanf \"%d \" (fun a -> flg := !flg && (a mod 2 = 0));\n\t\tdone;\n\t\tif !flg then l := i::!l;\n\tdone;\n\tPrintf.printf \"%d\\n\" (List.length !l);\n\tList.iter (fun i -> Printf.printf \"%d \" i) (List.rev !l)\n"}], "negative_code": [], "src_uid": "3fc0ac711b113fa98f41740536dad44f"} {"nl": {"description": "You are given an integer m.Let M\u2009=\u20092m\u2009-\u20091.You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.A set of integers S is called \"good\" if the following hold. If , then . If , then All elements of S are less than or equal to M. Here, and refer to the bitwise XOR and bitwise AND operators, respectively.Count the number of good sets S, modulo 109\u2009+\u20097.", "input_spec": "The first line will contain two integers m and n (1\u2009\u2264\u2009m\u2009\u2264\u20091\u2009000, 1\u2009\u2264\u2009n\u2009\u2264\u2009min(2m,\u200950)). The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.", "output_spec": "Print a single integer, the number of good sets modulo 109\u2009+\u20097. ", "sample_inputs": ["5 3\n11010\n00101\n11000", "30 2\n010101010101010010101010101010\n110110110110110011011011011011"], "sample_outputs": ["4", "860616440"], "notes": "NoteAn example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}."}, "positive_code": [{"source_code": "(* Write the input numbers as a matrix. Each number forms a row of\n bits. Now let's say you want to construct the set S = closure(T)\n generated by using the described operations. You do this by doing\n row operations on the matrix to construct new rows, and continue to\n do this until no operation adds anything new. The operations are\n (1) complement a row and (2) form the AND of two rows. Note that\n by combining these we can get OR as well.\n\n Suppose no two columns are identical. Then S consists of all m bit\n patterns. Here's why. Take the ith column. By ANDing together\n each row (complented if column i of that row has a 0 in it) we get\n an basis vector that has 1 in position i and 0 everywhere else.\n We can now OR together any subset of these basis vectors to get\n any vector.\n\n Conversely note that if two columns i and j are identical, then\n positions i and j will be identical in any number generated by\n any of the row operations. \n \n So closure(T) is completely characterized by the groups of\n identical columns of T. For example, say m=5, and columns 1, 2,\n and 3 of T are identical and columns 4 and 5 are also identical\n (but different from 1, 2, and 3). Say we add this row: 00100.\n This splits columns 1,2, and 3 into two groups: (1,2) and (3).\n (Alternatively we could have added 01000 which would make the\n groups (1,3) and (2).) Then we could add 10000 which further\n splits the (1,2) group in two. Each way of doing this gives a\n different closure and thus a different S.\n\n So given a set of numbers {1,2,...,n} how many distinct ways are\n there to split it into non-empty groups? You solve this by\n defining S(n,k) to be the numuber of ways to break {1...n} into\n k groups. What we want is then S(n,1) + S(n,2) + ... + S(n,n).\n\n So in the example above with m=5 the number of possible closures is: \n\n (S(3,1) + S(3,2) + S(3,3)) * (S(2,1) + S(2,2))\n\n Of course this is a known combinatorial quantity, the Stirling\n numbers of the 2nd kind. A nice recurrence is\n\n S(n+1,k) = k*S(n,k) + S(n,k-1)\n\n Along with base cases S(0,0) = 1 and S(n,0) = S(0,n) = 0. for n>0.\n https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind\n\n We can just compute these mod 10^9+7 using the obove recurrence\n since m <= 1000, and it's O(m^2). Grouping the columns into\n equivalence classes is easily done using a hash table. voil\u00e0.\n \n*)\n\n\nlet p = 1_000_000_007L\n\nlet long x = Int64.of_int x\nlet short x = Int64.to_int x\nlet ( %% ) a b = Int64.rem a b\nlet ( ** ) a b = (Int64.mul a b) %% p\nlet ( ++ ) a b = (Int64.add a b) %% p\nlet ( -- ) a b = ((Int64.sub a b) ++ p)\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) ++ a) 0L\n\nlet init_stirling nn kk = \n (* compute an array b so that s.(n).(k) = {n stirling k}, \n where 0 <= n <= nn and 0 <= k <= kk. *)\n let s = Array.make_matrix (nn+1) (kk+1) 0L in\n for n=0 to nn do for k=0 to min nn kk do \n s.(n).(k) <-\n\tif n=0 && k=0 then 1L\n\telse if n=0 || k=0 then 0L\n\telse (long k) ** s.(n-1).(k) ++ s.(n-1).(k-1)\n done done;\n s\n\nlet init_bell nn =\n let s = init_stirling nn nn in\n let bell = Array.make (nn+1) 0L in\n for n=0 to nn do\n bell.(n) <- sum 0 n (fun k -> s.(n).(k))\n done;\n bell\n \nopen Printf\nopen Scanf\n\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet () = \n let (m,n) = read_pair () in\n let t = Array.init n read_string in\n\n let h = Hashtbl.create 10 in\n let increment t = \n let c = try Hashtbl.find h t with Not_found -> 0 in\n Hashtbl.replace h t (c+1)\n in\n\n let column i = Array.init n (fun r -> t.(r).[i]) in\n for i=0 to m-1 do increment (column i) done;\n\n let bell = init_bell m in\n\n let answer = Hashtbl.fold (fun _ c ac -> bell.(c) ** ac) h 1L in\n\n printf \"%Ld\\n\" answer\n"}], "negative_code": [], "src_uid": "c602545676f6388a5c5107a5d83fc2c6"} {"nl": {"description": "Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n\u2009-\u2009i\u2009+\u20091)-th. He does this while i\u2009\u2264\u2009n\u2009-\u2009i\u2009+\u20091.After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday\u00a0\u2014 restore the initial order of the cubes using information of their current location.", "input_spec": "The first line contains single integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092\u00b7105)\u00a0\u2014 the number of cubes. The second line contains n integers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009109\u2009\u2264\u2009ai\u2009\u2264\u2009109), where ai is the number written on the i-th cube after Dima has changed their order.", "output_spec": "Print n integers, separated by spaces\u00a0\u2014 the numbers written on the cubes in their initial order. It can be shown that the answer is unique.", "sample_inputs": ["7\n4 3 7 6 9 1 2", "8\n6 1 4 2 5 6 9 2"], "sample_outputs": ["2 3 9 6 7 1 4", "2 1 6 2 5 4 9 6"], "notes": "NoteConsider the first sample. At the begining row was [2, 3, 9, 6, 7, 1, 4]. After first operation row was [4, 1, 7, 6, 9, 3, 2]. After second operation row was [4, 3, 9, 6, 7, 1, 2]. After third operation row was [4, 3, 7, 6, 9, 1, 2]. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. "}, "positive_code": [{"source_code": "let () =\n let n = read_int () in\n (* values *)\n let a = Array.init n (fun _ -> Scanf.scanf \"%d%_c\" (fun x -> x)) in\n (* permutation *)\n let p = Array.init n (fun i ->\n if i mod 2 = (if n mod 2 = 0 && i >= n / 2 then 1 else 0)\n then a.(n - i - 1)\n else a.(i)) in\n (* output *)\n print_endline (String.concat \" \" (Array.to_list (Array.map string_of_int p)))\n"}, {"source_code": "let rd_int = (fun () -> Scanf.scanf \" %d\" (fun n -> n)) in\nlet pri i = print_string ((string_of_int i) ^ \" \") in\nlet n = rd_int () in\nlet rec make_list n = \n if n == 0 then \n [] \n else \n let num = rd_int () in\n num :: make_list (n - 1) \nin\nlet a = make_list n in \nlet rec pr_list k l rl = \n if k >= n then\n ()\n else \n \n match l with\n | [] -> ()\n | hd :: tl -> \n match rl with\n | [] -> ()\n | hdr :: tlr ->\n let _ = pri hdr in \n let _ = pr_list (k + 2) tlr tl in\n if k + 1 == n then () else pri hd\nin\npr_list 0 a (List.rev a);;\n"}, {"source_code": "let print_array a = \n for k = 0 to (Array.length a) - 1 do\n print_int a.(k);\n print_char ' ';\n done;\n\n print_newline (); \n;;\n\nlet rearrange_blocks a = \n let n = Array.length a in\n let n_2 = n / 2 in\n let n_4 = (n_2 + 1) / 2 in\n for j = 0 to (n_4 - 1) do\n let k = j * 2 in\n let tmp = a.(k) in\n begin\n a.( k ) <- a.( n - k - 1 );\n a.( n - k - 1 ) <- tmp;\n end \n done;\n print_array a;\n;;\n\nlet rec read_block a k = \n if k < (Array.length a) then\n Scanf.bscanf Scanf.Scanning.stdin \"%i \" (add_block a k)\n else\n rearrange_blocks a\nand add_block a k v = \n begin\n a.(k) <- v;\n read_block a (k + 1)\n end \n;;\n\nlet read_blocks n = \n let blocks = Array.make n 0 in\n read_block blocks 0\n;;\n \nread_blocks (read_int ());;\n"}], "negative_code": [], "src_uid": "7d2f22fc06d4f0b8ff8be6c6862046e7"} {"nl": {"description": "Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.Amr has n different types of chemicals. Each chemical i has an initial volume of ai liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.To do this, Amr can do two different kind of operations. Choose some chemical i and double its current volume so the new volume will be 2ai Choose some chemical i and divide its volume by two (integer division) so the new volume will be Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?", "input_spec": "The first line contains one number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105), the number of chemicals. The second line contains n space separated integers ai (1\u2009\u2264\u2009ai\u2009\u2264\u2009105), representing the initial volume of the i-th chemical in liters.", "output_spec": "Output one integer the minimum number of operations required to make all the chemicals volumes equal.", "sample_inputs": ["3\n4 8 2", "3\n3 5 6"], "sample_outputs": ["2", "5"], "notes": "NoteIn the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 1."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)\nlet sum i j f = fold i j (fun i a -> (f i) + a) 0\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let a = Array.init n (fun _ -> read_int()) in\n\n let ma = maxf 0 (n-1) (fun i -> a.(i)) in\n\n let inf_cost = 100 in\n let gen_cost = Array.make (ma+1) inf_cost in\n\n let count = Array.make (ma+1) 0 in (* how many of the input number gen this number *)\n let gen_me = Array.make (ma+1) 0 in (* total over all input of the cost to generate this *)\n\n for i = 0 to n-1 do\n let glist = ref [] in\n let x = a.(i) in\n let rec outer_loop r =\n let x = x lsr r in\n if x > 0 then (\n\tlet rec inner_loop l =\n\t let x = x lsl l in\n\t if x <= ma then (\n\t if gen_cost.(x) = inf_cost then glist := x:: !glist;\n\t gen_cost.(x) <- min gen_cost.(x) (r+l);\n\t inner_loop (l+1)\n\t )\n\tin\n\tinner_loop 0;\n\touter_loop (r+1)\n )\n in\n outer_loop 0;\n List.iter (fun x -> count.(x) <- count.(x) + 1) !glist;\n List.iter (fun x -> gen_me.(x) <- gen_me.(x) + gen_cost.(x)) !glist;\n List.iter (fun x -> gen_cost.(x) <- inf_cost) !glist\n done;\n \n let answer = minf 1 ma (\n fun g -> \n if count.(g) = n then gen_me.(g) else inf_cost * n\n ) in\n\n printf \"%d\\n\" answer\n"}], "negative_code": [], "src_uid": "bc1e2d9dba07b2ac6b0a118bdbdd063b"} {"nl": {"description": "Let's call an array $$$a$$$ consisting of $$$n$$$ positive (greater than $$$0$$$) integers beautiful if the following condition is held for every $$$i$$$ from $$$1$$$ to $$$n$$$: either $$$a_i = 1$$$, or at least one of the numbers $$$a_i - 1$$$ and $$$a_i - 2$$$ exists in the array as well.For example: the array $$$[5, 3, 1]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 2 = 3$$$ exists in the array; for $$$a_2$$$, the number $$$a_2 - 2 = 1$$$ exists in the array; for $$$a_3$$$, the condition $$$a_3 = 1$$$ holds; the array $$$[1, 2, 2, 2, 2]$$$ is beautiful: for $$$a_1$$$, the condition $$$a_1 = 1$$$ holds; for every other number $$$a_i$$$, the number $$$a_i - 1 = 1$$$ exists in the array; the array $$$[1, 4]$$$ is not beautiful: for $$$a_2$$$, neither $$$a_2 - 2 = 2$$$ nor $$$a_2 - 1 = 3$$$ exists in the array, and $$$a_2 \\ne 1$$$; the array $$$[2]$$$ is not beautiful: for $$$a_1$$$, neither $$$a_1 - 1 = 1$$$ nor $$$a_1 - 2 = 0$$$ exists in the array, and $$$a_1 \\ne 1$$$; the array $$$[2, 1, 3]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 1 = 1$$$ exists in the array; for $$$a_2$$$, the condition $$$a_2 = 1$$$ holds; for $$$a_3$$$, the number $$$a_3 - 2 = 1$$$ exists in the array. You are given a positive integer $$$s$$$. Find the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.", "input_spec": "The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 5000$$$) \u2014 the number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$s$$$ ($$$1 \\le s \\le 5000$$$) for the $$$i$$$-th test case.", "output_spec": "Print $$$t$$$ integers, the $$$i$$$-th integer should be the answer for the $$$i$$$-th testcase: the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.", "sample_inputs": ["4\n1\n8\n7\n42"], "sample_outputs": ["1\n3\n3\n7"], "notes": "NoteConsider the example test: in the first test case, the array $$$[1]$$$ meets all conditions; in the second test case, the array $$$[3, 4, 1]$$$ meets all conditions; in the third test case, the array $$$[1, 2, 4]$$$ meets all conditions; in the fourth test case, the array $$$[1, 4, 6, 8, 10, 2, 11]$$$ meets all conditions. "}, "positive_code": [{"source_code": "open Scanf\nopen Printf\n\nlet scan_int _ = scanf \" %d\" (fun x -> x)\n\nlet () =\n for _ = 1 to scan_int () do\n let s = scan_int () in\n printf \"%d\\n\" @@ int_of_float @@ ceil @@ sqrt @@ float_of_int s\n done\n"}], "negative_code": [], "src_uid": "322792a11d3eb1df6b54e8f89c9a0490"} {"nl": {"description": "Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom \"Graph Theory\". In total, the season has n episodes, numbered with integers from 1 to n.Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which episode has Polycaprus forgotten to watch?", "input_spec": "The first line of the input contains integer n (2\u2009\u2264\u2009n\u2009\u2264\u2009100000)\u00a0\u2014 the number of episodes in a season. Assume that the episodes are numbered by integers from 1 to n. The second line contains n\u2009-\u20091 integer a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009n)\u00a0\u2014 the numbers of episodes that Polycarpus has watched. All values of ai are distinct.", "output_spec": "Print the number of the episode that Polycarpus hasn't watched.", "sample_inputs": ["10\n3 8 10 1 7 9 6 5 2"], "sample_outputs": ["4"], "notes": null}, "positive_code": [{"source_code": "let read_int()=Scanf.scanf \"%d \" (fun x->x);;\nlet n=read_int();;\nlet tab=Array.make (n+1) true;;\nfor i=1 to n-1 do\n let x=read_int() in\n tab.(x)<-false\ndone;;\nfor i=1 to n do\n if tab.(i) then print_int i\ndone;;"}], "negative_code": [], "src_uid": "0e4ff955c1e653fbeb003987fa701729"} {"nl": {"description": "In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k\u2009-\u20091)m,\u2009(k\u2009-\u20091)m\u2009+\u2009l], and l\u2009<\u2009m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.", "input_spec": "The first input line contains 4 integer numbers n, d, m, l (1\u2009\u2264\u2009n,\u2009d,\u2009m,\u2009l\u2009\u2264\u2009106,\u2009l\u2009<\u2009m) \u2014 respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k\u2009-\u20091)m,\u2009(k\u2009-\u20091)m\u2009+\u2009l].", "output_spec": "Output the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.", "sample_inputs": ["2 2 5 3", "5 4 11 8"], "sample_outputs": ["4", "20"], "notes": null}, "positive_code": [{"source_code": "let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib \" %Ld\" (fun x -> x)\n\nopen Int64\nlet ( ++ ) = add\nlet ( -- ) = sub\nlet ( ** ) = mul\nlet ( // ) = div\n\nlet () =\n let n = read_int64 0 in\n let d = read_int64 0 in\n let m = read_int64 0 in\n let l = read_int64 0 in\n let rec go i =\n let x = ((i**m++l)//d++1L)**d in\n if i = n--1L || x < (i++1L)**m then\n Printf.printf \"%Ld\\n\" x\n else\n go (i++1L)\n in\n go 0L\n"}], "negative_code": [], "src_uid": "ecbc339ad8064681789075f9234c269a"} {"nl": {"description": "A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre \u2014 an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1,\u2009a2,\u2009...,\u2009an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1\u2009\u2264\u2009x\u2009\u2264\u2009k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.", "input_spec": "The first line of the input contains two integers n and k (2\u2009\u2264\u2009k\u2009\u2264\u2009n\u2009\u2264\u2009105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1\u2009\u2264\u2009ai\u2009\u2264\u2009k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.", "output_spec": "Print a single number \u2014 the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.", "sample_inputs": ["10 3\n1 1 2 3 2 3 3 1 1 3", "7 3\n3 1 3 2 3 1 2"], "sample_outputs": ["3", "1"], "notes": "NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2,\u20093,\u20092,\u20093,\u20093,\u20093 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1,\u20091,\u20093,\u20093,\u20093,\u20091,\u20091,\u20093 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1,\u20091,\u20092,\u20092,\u20091,\u20091 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses."}, "positive_code": [{"source_code": "(* Codeforces 250C done *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet rdln() = input_line stdin;;\nlet spli s = Str.split (Str.regexp \" \") s;;\nlet printlisti li = List.iter (fun i -> (print_string \" \"; print_int i)) li;;\nlet printarri ai = Array.iter (fun i -> (print_string \" \"; print_int i)) ai;;\nlet debug = false;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec removedoubles l = match l with\n\t| [] -> []\n\t| h :: [] -> h :: []\n\t| a :: b :: t ->\n\t\t\tlet tl = removedoubles (b :: t) in\n\t\t\tif a = b then tl\n\t\t\telse a :: tl;;\n\nlet rec countStress l cnts = match l with\n\t| [] -> ()\n\t| h :: [] -> ()\n\t| a :: b :: [] -> cnts.(b) <- cnts.(b) + 1\n\t| a :: b :: c :: t ->\n\t\t\tbegin\n\t\t\t\tif a <> c then\n\t\t\t\t\tcnts.(b) <- cnts.(b) + 1\n\t\t\t\telse cnts.(b) <- cnts.(b) + 2;\n\t\t\t\tcountStress (b :: c :: t) cnts\n\t\t\tend;;\n\nlet countStressF l cnts =\n\tlet a = List.hd l in begin\n\t\tcnts.(a) <- cnts.(a) + 1;\n\t\tcountStress l cnts\n\tend;;\n\nlet rec findBest cnts i k imx mx =\n\tif i > k then imx\n\telse if cnts.(i) > mx then findBest cnts (i +1) k i cnts.(i)\n\telse findBest cnts (i +1) k imx mx;;\n\nlet main () =\n\tlet n = gr() in\n\tlet k = gr() in\n\tlet a = readlist n [] in\n\tlet rva = List.rev a in\n\tbegin\n\t\tif debug then begin\n\t\t\tprint_int n;\n\t\t\tprint_int k;\n\t\t\tprintlisti rva\n\t\tend;\n\t\tlet cnts = Array.make (k +1) 0 in\n\t\tlet anodub = removedoubles rva in\n\t\tbegin\n\t\t\tif debug then begin\t\t\t\t\n\t\t\t\tprint_string \"anodub:\\n\";\n\t\t\t\tprintlisti anodub\n\t\t\tend;\n\t\t\tcountStressF anodub cnts;\n\t\t\tif debug then begin\n\t\t\t\tprint_string \" countStress passed\\n\";\n\t\t\t\tprintarri cnts;\n\t\t\t\tprint_string \"counting and print best\\n\"\n\t\t\tend;\n\t\t\tlet best = findBest cnts 0 k 0 0 in\n\t\t\tprint_int best\n\t\tend end;;\n\nmain();;\n"}], "negative_code": [{"source_code": "(* Codeforces 250C done *)\n\n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet rdln() = input_line stdin;;\nlet spli s = Str.split (Str.regexp \" \") s;;\nlet printlisti li = List.iter (fun i -> (print_string \" \"; print_int i)) li;;\nlet printarri ai = Array.iter (fun i -> (print_string \" \"; print_int i)) ai;;\n\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\n\nlet rec removedoubles l = match l with\n\t| [] -> []\n\t| h :: [] -> h :: []\n\t| a :: b :: t ->\n\t\t\tlet tl = removedoubles (b :: t) in\n\t\t\tif a = b then tl\n\t\t\telse a :: tl;;\n\nlet rec countStress l cnts first = match l with\n\t| [] -> ()\n\t| h :: [] -> ()\n\t| a :: b :: [] -> cnts.(b) <- cnts.(b) + 1\n\t| a :: b :: c :: t ->\n\t\t\tbegin\n\t\t\t\tif first then cnts.(a) <- cnts.(a) + 1;\n\t\t\t\tif a <> c then\n\t\t\t\t\tcnts.(b) <- cnts.(b) + 1\n\t\t\t\t\telse cnts.(b) <- cnts.(b) + 2;\n\t\t\t\tcountStress (b :: c :: t) cnts false\n\t\t\tend;;\n\nlet rec findBest cnts i k imx mx = \n\tif i > k then imx\n\telse if cnts.(i) > mx then findBest cnts (i +1) k i cnts.(i)\n\t\t\t else findBest cnts (i +1) k imx mx;;\n\nlet main () =\n\tlet n = gr() in\n\tlet k = gr() in\n\tlet a = readlist n [] in\n\tlet rva = List.rev a in \n\tbegin\n\t\t(* print_int n; *)\n\t\t(* print_int k; *)\n\t\t(* printlisti rva; *)\n\tlet cnts = Array.make (k+1) 0 in\n\tlet anodub = removedoubles rva in\n\tbegin\n\t\t(* print_string \"anodub:\\n\"; *)\n\t\t(* printlisti anodub; *)\n\t\tcountStress anodub cnts true;\n\t\t(* print_string \" countStress passed\\n\"; *)\n\t\t(* printarri cnts; *)\n\t\t(* print_string \"counting and print best\\n\"; *)\n\t\tlet best = findBest cnts 0 k 0 0 in\n\t\tprint_int best\n\tend end;;\n\nmain();;\n"}], "src_uid": "6ef8200d05dd5eb729edceb62e393c50"} {"nl": {"description": "Alice and Bob play a game. They have a binary string $$$s$$$ (a string such that each character in it is either $$$0$$$ or $$$1$$$). Alice moves first, then Bob, then Alice again, and so on.During their move, the player can choose any number (not less than one) of consecutive equal characters in $$$s$$$ and delete them.For example, if the string is $$$10110$$$, there are $$$6$$$ possible moves (deleted characters are bold): $$$\\textbf{1}0110 \\to 0110$$$; $$$1\\textbf{0}110 \\to 1110$$$; $$$10\\textbf{1}10 \\to 1010$$$; $$$101\\textbf{1}0 \\to 1010$$$; $$$10\\textbf{11}0 \\to 100$$$; $$$1011\\textbf{0} \\to 1011$$$. After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I.\u2009e. the following sequence of moves is valid: $$$10\\textbf{11}0 \\to 1\\textbf{00} \\to 1$$$.The game ends when the string becomes empty, and the score of each player is the number of $$$1$$$-characters deleted by them.Each player wants to maximize their score. Calculate the resulting score of Alice.", "input_spec": "The first line contains one integer $$$T$$$ ($$$1 \\le T \\le 500$$$) \u2014 the number of test cases. Each test case contains exactly one line containing a binary string $$$s$$$ ($$$1 \\le |s| \\le 100$$$).", "output_spec": "For each test case, print one integer \u2014 the resulting score of Alice (the number of $$$1$$$-characters deleted by her).", "sample_inputs": ["5\n01111001\n0000\n111111\n101010101\n011011110111"], "sample_outputs": ["4\n0\n6\n3\n6"], "notes": "NoteQuestions about the optimal strategy will be ignored."}, "positive_code": [{"source_code": "(* \u7ed9\u5b9a\u4e00\u4e2a 0\u30011 \u6784\u6210\u7684\u4e32\uff0c\u6bcf\u4e2a\u73a9\u5bb6\u6bcf\u6b21\u53ef\u5220\u9664\u4efb\u610f\u957f\u5ea6\u7684\u4e00\u4e2a\u8fde\u7eed\u5b57\u4e32 *)\n(* \u6bcf\u5220\u9664\u4e00\u4e2a 1\uff0c\u83b7\u5f97\u4e00\u5206\uff0c\u6c42\u5148\u624b\u80fd\u83b7\u5f97\u7684\u6700\u5927\u5206\u6570 *)\n\nlet rec compress =\n let f accu c =\n match accu with\n | [] -> [ (c, 1) ]\n | (prev, count) :: rest ->\n if prev = c then (prev, count + 1) :: rest else (c, 1) :: accu\n in\n List.fold_left f []\n\nlet explode str =\n let len = String.length str in\n let rec f accu i = if i = len then accu else f (str.[i] :: accu) (i + 1) in\n f [] 0 |> List.rev\n\nlet take =\n let f accu = function '1', c -> c :: accu | _ -> accu in\n List.fold_left f []\n\nlet rec sum = function [] -> 0 | [ x ] -> x | x :: y :: rest -> x + sum rest\n\nlet main =\n let test_cases = Scanf.scanf \" %d\" (fun x -> x) in\n\n for i = 0 to test_cases - 1 do\n let elements = Scanf.scanf \" %s\" explode |> compress in\n\n let r = take elements |> List.sort (fun a b -> b - a) |> sum in\n print_endline (string_of_int r)\n done\n"}], "negative_code": [], "src_uid": "ebf0bf949a29eeaba3bcc35091487199"} {"nl": {"description": "Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC. For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci \u2014 the receiving time (the second) and the number of the text messages, correspondingly.Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows: If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue. Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.", "input_spec": "The first line contains a single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009103) \u2014 the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1\u2009\u2264\u2009ti,\u2009ci\u2009\u2264\u2009106) \u2014 the time (the second) when the i-th task was received and the number of messages to send, correspondingly. It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti\u2009<\u2009ti\u2009+\u20091 for all integer i (1\u2009\u2264\u2009i\u2009<\u2009n).", "output_spec": "In a single line print two space-separated integers \u2014 the time when the last text message was sent and the maximum queue size at a certain moment of time.", "sample_inputs": ["2\n1 1\n2 1", "1\n1000000 10", "3\n3 3\n4 3\n5 3"], "sample_outputs": ["3 1", "1000010 10", "12 7"], "notes": "NoteIn the first test sample: second 1: the first message has appeared in the queue, the queue's size is 1; second 2: the first message is sent, the second message has been received, the queue's size is 1; second 3: the second message is sent, the queue's size is 0, Thus, the maximum size of the queue is 1, the last message was sent at the second 3."}, "positive_code": [{"source_code": "(* Codeforces contest 292 A - SMS Center *)\n\nopen Filename;;\n\n(* you can use either gr or rdln but not both *)\nlet use_input_txt = false;;\nlet fn = (Filename.dirname Filename.current_dir_name);;\nlet filename = Filename.concat \".\" \"input.txt\";;\nlet cin = if use_input_txt then Scanf.Scanning.open_in filename\n\telse Scanf.Scanning.stdin;;\n\nlet cout = open_out \"output.txt\";;\nlet gr () = Scanf.bscanf cin \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line Pervasives.stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet rec readlist n acc = match n with | 0 -> List.rev acc | _ -> readlist (n -1) (gr() :: acc);;\nlet debug = false;;\n\nlet n = gr();; (* size of permutation *)\n\nlet rec readpairs n acc = match n with \n | 0 -> List.rev acc \n | _ -> \n\t\tlet a = gr() in\n\t\tlet b = gr() in\n\t\treadpairs (n -1) ((a,b) :: acc);;\n\nlet rec get_maxlen_maxt lprs maxl maxt = \n\tmatch lprs with\n\t| [] -> (maxl, maxt)\n\t| hd :: tl ->\n\t\tlet (t,n) = hd in\n\t\tlet inq = max 0 (maxt - t) in\n\t\tlet nmaxl = max maxl (inq + n) in\n\t\tlet nmaxt = t + (inq + n) in\n\t\tget_maxlen_maxt tl nmaxl nmaxt;;\n\n\nlet main() =\n\tlet prs = readpairs n [] in\n\tlet (maxl, maxt) = get_maxlen_maxt prs 0 0 in\n\t(\n\t\tprint_int maxt;\n\t\tprint_string \" \";\n\t\tprint_int maxl\n\t\t);;\n\t\n\tmain();;\n"}], "negative_code": [], "src_uid": "608f8246bc6067e259898e8ed94db4c4"} {"nl": {"description": "Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm.His farm is presented by a rectangle grid with $$$r$$$ rows and $$$c$$$ columns. Some of these cells contain rice, others are empty. $$$k$$$ chickens are living on his farm. The number of chickens is not greater than the number of cells with rice on the farm.Long wants to give his chicken playgrounds by assigning these farm cells to his chickens. He would like to satisfy the following requirements: Each cell of the farm is assigned to exactly one chicken. Each chicken is assigned at least one cell. The set of cells assigned to every chicken forms a connected area. More precisely, if two cells $$$(x, y)$$$ and $$$(u, v)$$$ are assigned to the same chicken, this chicken is able to walk from $$$(x, y)$$$ to $$$(u, v)$$$ by passing only its cells and moving from each cell to another cell sharing a side. Long also wants to prevent his chickens from fighting for food. Hence he wants the difference between the maximum and the minimum number of cells with rice assigned to a chicken to be as small as possible. Please help him.", "input_spec": "Each test contains multiple test cases. The first line contains the number of test cases $$$T$$$ ($$$1 \\le T \\le 2 \\cdot 10^4$$$). Description of the test cases follows. The first line of each test case contains three integers $$$r$$$, $$$c$$$ and $$$k$$$ ($$$1 \\leq r, c \\leq 100, 1 \\leq k \\leq 62$$$), representing the size of Long's farm and the number of chickens Long has. Each of the next $$$r$$$ lines contains $$$c$$$ characters, each is either \".\" or \"R\", representing an empty cell or a cell with rice. It is guaranteed that the number of chickens is not greater than the number of cells with rice on the farm. It is guaranteed that the sum of $$$r \\cdot c$$$ over all test cases does not exceed $$$2 \\cdot 10^4$$$.", "output_spec": "For each test case, print $$$r$$$ lines with $$$c$$$ characters on each line. Each character should be either a lowercase English character, an uppercase English character, or a digit. Two characters should be equal if and only if the two corresponding cells are assigned to the same chicken. Uppercase and lowercase characters are considered different, so \"A\" and \"a\" belong to two different chickens. If there are multiple optimal answers, print any.", "sample_inputs": ["4\n3 5 3\n..R..\n...R.\n....R\n6 4 6\nR..R\nR..R\nRRRR\nRRRR\nR..R\nR..R\n5 5 4\nRRR..\nR.R..\nRRR..\nR..R.\nR...R\n2 31 62\nRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR\nRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR"], "sample_outputs": ["11122\n22223\n33333\naacc\naBBc\naBBc\nCbbA\nCbbA\nCCAA\n11114\n22244\n32444\n33344\n33334\nabcdefghijklmnopqrstuvwxyzABCDE\nFGHIJKLMNOPQRSTUVWXYZ0123456789"], "notes": "NoteThese pictures explain the sample output. Each color represents one chicken. Cells filled with patterns (not solid colors) contain rice.In the first test case, each chicken has one cell with rice. Hence, the difference between the maximum and the minimum number of cells with rice assigned to a chicken is $$$0$$$.In the second test case, there are $$$4$$$ chickens with $$$3$$$ cells of rice, and $$$2$$$ chickens with $$$2$$$ cells of rice. Hence, the difference between the maximum and the minimum number of cells with rice assigned to a chicken is $$$3 - 2 = 1$$$.In the third test case, each chicken has $$$3$$$ cells with rice. In the last test case, since there are $$$62$$$ chicken with exactly $$$62$$$ cells of rice, each chicken must be assigned to exactly one cell. The sample output is one of the possible way."}, "positive_code": [{"source_code": "(* Feeding Chicken\n * https://codeforces.com/contest/1254/problem/A *)\n\n(* I shouldn't need explicitly named record fields. But I wanted to\n * practice the notation. *)\ntype cell = {coords: int * int; has_rice: bool}\ntype assignment = {coords: int * int; chicken: int}\n\n(* Converts a board into a list of cells, in snake order. *)\nlet cells_of_board n m (board: string array) =\n let next (i, j) = match (i mod 2, j) with\n | (0, k) when k = m - 1 -> (i + 1, j)\n | (0, _) -> (i, j + 1)\n | (_, 0) -> (i + 1, j)\n | _ -> (i, j - 1) in\n let rec iter i j acc =\n if i >= n then\n acc\n else\n let (ni, nj) = next (i, j) in\n iter ni nj ({coords = (i, j); has_rice = String.get board.(i) j = 'R'} :: acc)\n in iter 0 0 []\n\n(* Converts a bunch of chicken assignments to an array of 'bytes' arrays representing\n * the result. *)\nlet result_of_assns n m (assns : assignment list) =\n let chicken_labels =\n \"0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\" in\n (* The following didn't work! It created n references to the same array.\n It's like doing \"arr = [[0] * m] * n\" in Python.\n let res = Array.make n (Bytes.make m '0') in *)\n let res = Array.init n (fun _ -> Bytes.make m '0') in\n (* Ugh, imperative updates... but this is probably more efficient. *)\n let rec iter ls = match ls with\n | [] -> ()\n | {coords=(i, j); chicken = c} :: lss ->\n (Bytes.set res.(i) j (String.get chicken_labels c);\n iter lss)\n in (iter assns; res)\n\n(* Takes a 'board' (2D array showing where the rice is) and\n * converts it to a board of chicken assignments. *)\nlet solve n m chicks (board: string array) =\n let cells = cells_of_board n m board in\n (* There's probably a function to do this in one go. *)\n let rice_total = List.fold_left\n (fun acc cl -> if cl.has_rice then acc + 1 else acc)\n 0 cells\n in\n (* The amount of rice each chicken should have. *)\n let amt = rice_total / chicks in\n (* These are hungry chickens! They will eat amt+1 rice. *)\n let hungry = rice_total - amt * chicks in\n (* Iterate through cells and assign them chickens in order.\n * Assign the hungry chickens first, then the rest. *)\n let rec iter cls prev_chick k acc =\n match cls with\n | [] -> acc\n | {coords=crd; has_rice=hr} :: clss ->\n let mx = if prev_chick < hungry then amt + 1 else amt in\n let nk' = if hr then k + 1 else k in\n let (cur_chick, nk) = if nk' > mx then\n (prev_chick + 1, 1)\n else\n (prev_chick, nk') in\n iter clss cur_chick nk ({coords=crd; chicken=cur_chick} :: acc)\n in result_of_assns n m (iter cells 0 0 [])\n\nlet rec rep n f = if n = 0 then () else (f (); rep (n-1) f)\n\nlet main () =\n let tt = read_int () in\n rep tt (fun () ->\n (* Scanf.scanf caused Codeforces to give a runtime error for some reason *)\n let [n; m; k] =\n read_line ()\n |> Str.split (Str.regexp \" \")\n |> List.map int_of_string in\n let board = Array.init n (fun _ -> read_line ()) in\n Array.iter (fun s -> (print_bytes s; print_newline ())) (solve n m k board)\n )\n\nlet _ = main ()\n"}, {"source_code": "(* Feeding Chicken\n * https://codeforces.com/contest/1254/problem/A *)\n\n(* I shouldn't need explicitly named record fields. But I wanted to\n * practice the notation. *)\ntype cell = {coords: int * int; has_rice: bool}\ntype assignment = {coords: int * int; chicken: int}\n\n(* Converts a board into a list of cells, in snake order. *)\nlet cells_of_board n m (board: string array) =\n let next (i, j) = match (i mod 2, j) with\n | (0, k) when k = m - 1 -> (i + 1, j)\n | (0, _) -> (i, j + 1)\n | (_, 0) -> (i + 1, j)\n | _ -> (i, j - 1) in\n let rec iter i j acc =\n if i >= n then\n acc\n else\n let (ni, nj) = next (i, j) in\n iter ni nj ({coords = (i, j); has_rice = String.get board.(i) j = 'R'} :: acc)\n in iter 0 0 []\n\n(* Converts a bunch of chicken assignments to an array of 'bytes' arrays representing\n * the result. *)\nlet result_of_assns n m (assns : assignment list) =\n let chicken_labels =\n \"0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\" in\n (* The following didn't work! It created n references to the same array.\n It's like doing \"arr = [[0] * m] * n\" in Python.\n let res = Array.make n (Bytes.make m '0') in *)\n let res = Array.init n (fun _ -> Bytes.make m '0') in\n (* Ugh, imperative updates... but this is probably more efficient. *)\n let rec iter ls = match ls with\n | [] -> ()\n | {coords=(i, j); chicken = c} :: lss ->\n (Bytes.set res.(i) j (String.get chicken_labels c);\n iter lss)\n in (iter assns; res)\n\n(* Takes a 'board' (2D array showing where the rice is) and\n * converts it to a board of chicken assignments. *)\nlet solve n m chicks (board: string array) =\n let cells = cells_of_board n m board in\n (* There's probably a function to do this in one go. *)\n let rice_total = List.fold_left\n (fun acc cl -> if cl.has_rice then acc + 1 else acc)\n 0 cells\n in\n (* The amount of rice each chicken should have. *)\n let amt = rice_total / chicks in\n (* These are hungry chickens! They will eat amt+1 rice. *)\n let hungry = rice_total - amt * chicks in\n (* Iterate through cells and assign them chickens in order.\n * Assign the hungry chickens first, then the rest. *)\n let rec iter cls prev_chick k acc =\n match cls with\n | [] -> acc\n | {coords=crd; has_rice=hr} :: clss ->\n let mx = if prev_chick < hungry then amt + 1 else amt in\n let nk' = if hr then k + 1 else k in\n let (cur_chick, nk) = if nk' > mx then\n (prev_chick + 1, 1)\n else\n (prev_chick, nk') in\n iter clss cur_chick nk ({coords=crd; chicken=cur_chick} :: acc)\n in result_of_assns n m (iter cells 0 0 [])\n\nlet rec rep n f = if n = 0 then () else (f (); rep (n-1) f)\n\nlet main () =\n let tt = read_int () in\n rep tt (fun () ->\n (* Scanf.scanf caused Codeforces to give a runtime error for some reason *)\n let (n, m, k) = Scanf.sscanf (read_line ()) \"%d %d %d\" (fun x y z -> (x, y, z)) in\n let board = Array.init n (fun _ -> read_line ()) in\n Array.iter (fun s -> (print_bytes s; print_newline ())) (solve n m k board)\n )\n\nlet _ = main ()\n"}], "negative_code": [{"source_code": "print_string \"asdf\""}, {"source_code": "(* Feeding Chicken\n * https://codeforces.com/contest/1254/problem/A *)\n\n(* I shouldn't need explicitly named record fields. But I wanted to\n * practice the notation. *)\ntype cell = {coords: int * int; has_rice: bool}\ntype assignment = {coords: int * int; chicken: int}\n\n(* Converts a board into a list of cells, in snake order. *)\nlet cells_of_board n m (board: string array) =\n let next (i, j) = match (i mod 2, j) with\n | (0, k) when k = m - 1 -> (i + 1, j)\n | (0, _) -> (i, j + 1)\n | (_, 0) -> (i + 1, j)\n | _ -> (i, j - 1) in\n let rec iter i j acc =\n if i >= n then\n acc\n else\n let (ni, nj) = next (i, j) in\n iter ni nj ({coords = (i, j); has_rice = String.get board.(i) j = 'R'} :: acc)\n in iter 0 0 []\n\n(* Converts a bunch of chicken assignments to an array of 'bytes' arrays representing\n * the result. *)\nlet result_of_assns n m (assns : assignment list) =\n let chicken_labels =\n \"0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKKLZXCVBNM\" in\n (* The following didn't work! It created n references to the same array.\n It's like doing \"arr = [[0] * m] * n\" in Python.\n let res = Array.make n (Bytes.make m '0') in *)\n let res = Array.init n (fun _ -> Bytes.make m '0') in\n (* Ugh, imperative updates... but this is probably more efficient. *)\n let rec iter ls = match ls with\n | [] -> ()\n | {coords=(i, j); chicken = c} :: lss ->\n (Bytes.set res.(i) j (String.get chicken_labels c);\n iter lss)\n in (iter assns; res)\n\n(* Takes a 'board' (2D array showing where the rice is) and\n * converts it to a board of chicken assignments. *)\nlet solve n m chicks (board: string array) =\n let cells = cells_of_board n m board in\n (* There's probably a function to do this in one go. *)\n let rice_total = List.fold_left\n (fun acc cl -> if cl.has_rice then acc + 1 else acc)\n 0 cells\n in\n (* The amount of rice each chicken should have. *)\n let amt = rice_total / chicks in\n (* These are hungry chickens! They will eat amt+1 rice. *)\n let hungry = rice_total - amt * chicks in\n (* Iterate through cells and assign them chickens in order.\n * Assign the hungry chickens first, then the rest. *)\n let rec iter cls prev_chick k acc =\n match cls with\n | [] -> acc\n | {coords=crd; has_rice=hr} :: clss ->\n let mx = if prev_chick < hungry then amt + 1 else amt in\n let nk' = if hr then k + 1 else k in\n let (cur_chick, nk) = if nk' > mx then\n (prev_chick + 1, 1)\n else\n (prev_chick, nk') in\n iter clss cur_chick nk ({coords=crd; chicken=cur_chick} :: acc)\n in result_of_assns n m (iter cells 0 0 [])\n\nlet rec rep n f = if n = 0 then () else (f (); rep (n-1) f)\n\nlet main () =\n let tt = read_int () in\n rep tt (fun () ->\n (* Scanf.scanf caused Codeforces to give a runtime error for some reason *)\n let (n, m, k) = Scanf.sscanf (read_line ()) \"%d %d %d\" (fun x y z -> (x, y, z)) in\n let board = Array.init n (fun _ -> read_line ()) in\n Array.iter (fun s -> (print_bytes s; print_newline ())) (solve n m k board)\n )\n\nlet _ = main ()\n"}, {"source_code": "(* Feeding Chicken\n * https://codeforces.com/contest/1254/problem/A *)\n\n(* I shouldn't need explicitly named record fields. But I wanted to\n * practice the notation. *)\ntype cell = {coords: int * int; has_rice: bool}\ntype assignment = {coords: int * int; chicken: int}\n\n(* Converts a board into a list of cells, in snake order. *)\nlet cells_of_board n m (board: string array) =\n let next (i, j) = match (i mod 2, j) with\n | (0, k) when k = m - 1 -> (i + 1, j)\n | (0, _) -> (i, j + 1)\n | (_, 0) -> (i + 1, j)\n | _ -> (i, j - 1) in\n let rec iter i j acc =\n if i >= n then\n acc\n else\n let (ni, nj) = next (i, j) in\n iter ni nj ({coords = (i, j); has_rice = String.get board.(i) j = 'R'} :: acc)\n in iter 0 0 []\n\n(* Converts a bunch of chicken assignments to an array of 'bytes' arrays representing\n * the result. *)\nlet result_of_assns n m (assns : assignment list) =\n let chicken_labels =\n \"0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKKLZXCVBNM\" in\n (* The following didn't work! It created n references to the same array.\n It's like doing \"arr = [[0] * m] * n\" in Python.\n let res = Array.make n (Bytes.make m '0') in *)\n let res = Array.init n (fun _ -> Bytes.make m '0') in\n (* Ugh, imperative updates... but this is probably more efficient. *)\n let rec iter ls = match ls with\n | [] -> ()\n | {coords=(i, j); chicken = c} :: lss ->\n (Bytes.set res.(i) j (String.get chicken_labels c);\n iter lss)\n in (iter assns; res)\n\n(* Takes a 'board' (2D array showing where the rice is) and\n * converts it to a board of chicken assignments. *)\nlet solve n m chicks (board: string array) =\n let cells = cells_of_board n m board in\n (* There's probably a function to do this in one go. *)\n let rice_total = List.fold_left\n (fun acc cl -> if cl.has_rice then acc + 1 else acc)\n 0 cells\n in\n (* The amount of rice each chicken should have. *)\n let amt = rice_total / chicks in\n (* These are hungry chickens! They will eat amt+1 rice. *)\n let hungry = rice_total - amt * chicks in\n (* Iterate through cells and assign them chickens in order.\n * Assign the hungry chickens first, then the rest. *)\n let rec iter cls prev_chick k acc =\n match cls with\n | [] -> acc\n | {coords=crd; has_rice=hr} :: clss ->\n let mx = if prev_chick < hungry then amt + 1 else amt in\n let nk' = if hr then k + 1 else k in\n let (cur_chick, nk) = if nk' > mx then\n (prev_chick + 1, 1)\n else\n (prev_chick, nk') in\n iter clss cur_chick nk ({coords=crd; chicken=cur_chick} :: acc)\n in result_of_assns n m (iter cells 0 0 [])\n\nlet rec rep n f = if n = 0 then () else (f (); rep (n-1) f)\n\nlet main () =\n print_string \"asdf\"\n\nlet _ = main ()\n"}], "src_uid": "dc0acf5347fba3c211ebaca7c9475bf5"} {"nl": {"description": "$$$n$$$ people live on the coordinate line, the $$$i$$$-th one lives at the point $$$x_i$$$ ($$$1 \\le i \\le n$$$). They want to choose a position $$$x_0$$$ to meet. The $$$i$$$-th person will spend $$$|x_i - x_0|$$$ minutes to get to the meeting place. Also, the $$$i$$$-th person needs $$$t_i$$$ minutes to get dressed, so in total he or she needs $$$t_i + |x_i - x_0|$$$ minutes. Here $$$|y|$$$ denotes the absolute value of $$$y$$$.These people ask you to find a position $$$x_0$$$ that minimizes the time in which all $$$n$$$ people can gather at the meeting place. ", "input_spec": "The first line contains a single integer $$$t$$$ ($$$1 \\le t \\le 10^3$$$) \u2014 the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of people. The second line contains $$$n$$$ integers $$$x_1, x_2, \\dots, x_n$$$ ($$$0 \\le x_i \\le 10^{8}$$$) \u2014 the positions of the people. The third line contains $$$n$$$ integers $$$t_1, t_2, \\dots, t_n$$$ ($$$0 \\le t_i \\le 10^{8}$$$), where $$$t_i$$$ is the time $$$i$$$-th person needs to get dressed. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$.", "output_spec": "For each test case, print a single real number\u00a0\u2014 the optimum position $$$x_0$$$. It can be shown that the optimal position $$$x_0$$$ is unique. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{\u22126}$$$. Formally, let your answer be $$$a$$$, the jury's answer be $$$b$$$. Your answer will be considered correct if $$$\\frac{|a\u2212b|}{max(1,|b|)} \\le 10^{\u22126}$$$.", "sample_inputs": ["7\n\n1\n\n0\n\n3\n\n2\n\n3 1\n\n0 0\n\n2\n\n1 4\n\n0 0\n\n3\n\n1 2 3\n\n0 0 0\n\n3\n\n1 2 3\n\n4 1 2\n\n3\n\n3 3 3\n\n5 3 3\n\n6\n\n5 4 7 2 10 4\n\n3 2 5 1 4 6"], "sample_outputs": ["0\n2\n2.5\n2\n1\n3\n6"], "notes": "Note In the $$$1$$$-st test case there is one person, so it is efficient to choose his or her position for the meeting place. Then he or she will get to it in $$$3$$$ minutes, that he or she need to get dressed. In the $$$2$$$-nd test case there are $$$2$$$ people who don't need time to get dressed. Each of them needs one minute to get to position $$$2$$$. In the $$$5$$$-th test case the $$$1$$$-st person needs $$$4$$$ minutes to get to position $$$1$$$ ($$$4$$$ minutes to get dressed and $$$0$$$ minutes on the way); the $$$2$$$-nd person needs $$$2$$$ minutes to get to position $$$1$$$ ($$$1$$$ minute to get dressed and $$$1$$$ minute on the way); the $$$3$$$-rd person needs $$$4$$$ minutes to get to position $$$1$$$ ($$$2$$$ minutes to get dressed and $$$2$$$ minutes on the way). "}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)\nlet sum i j f = fold i j (fun i a -> (f i) +. a) 0.0\nlet minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i) \nlet maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)\n\nlet read_int _ = bscanf Scanning.stdin \" %d \" (fun x -> x)\nlet read_float _ = bscanf Scanning.stdin \" %f \" (fun x -> x) \nlet () =\n let cases = read_int() in\n for case = 1 to cases do\n let n = read_int () in\n let x = Array.init n read_float in\n let t = Array.init n read_float in\n\n let p = Array.init n (fun i -> (x.(i), t.(i))) in\n Array.sort compare p;\n let x = Array.init n (fun i -> fst p.(i)) in\n let t = Array.init n (fun i -> snd p.(i)) in\n\n let rec ternary a1 a4 f count =\n if count = 0 then (a1 +. a4) /. 2.0 else\n\tlet a2 = 0.6 *. a1 +. 0.4 *. a4 in\n\tlet a3 = 0.4 *. a1 +. 0.6 *. a4 in\n\tlet v2 = f a2 in\n\tlet v3 = f a3 in\n\tif v2 < v3 then ternary a1 a3 f (count-1)\n\telse ternary a2 a4 f (count-1)\n in\n\n let score x0 =\n maxf 0 (n-1) (fun i -> t.(i) +. (abs_float (x0 -. x.(i))))\n in\n\n let answer = ternary x.(0) x.(n-1) score 100 in\n\n printf \"%f\\n\" answer\n done\n"}], "negative_code": [], "src_uid": "9336bfed41e9b277bdfa157467066078"} {"nl": {"description": "You've got an array, consisting of n integers a1,\u2009a2,\u2009...,\u2009an. Also, you've got m queries, the i-th query is described by two integers li,\u2009ri. Numbers li,\u2009ri define a subsegment of the original array, that is, the sequence of numbers ali,\u2009ali\u2009+\u20091,\u2009ali\u2009+\u20092,\u2009...,\u2009ari. For each query you should check whether the corresponding segment is a ladder. A ladder is a sequence of integers b1,\u2009b2,\u2009...,\u2009bk, such that it first doesn't decrease, then doesn't increase. In other words, there is such integer x (1\u2009\u2264\u2009x\u2009\u2264\u2009k), that the following inequation fulfills: b1\u2009\u2264\u2009b2\u2009\u2264\u2009...\u2009\u2264\u2009bx\u2009\u2265\u2009bx\u2009+\u20091\u2009\u2265\u2009bx\u2009+\u20092...\u2009\u2265\u2009bk. Note that the non-decreasing and the non-increasing sequences are also considered ladders.", "input_spec": "The first line contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009105) \u2014 the number of array elements and the number of queries. The second line contains the sequence of integers a1,\u2009a2,\u2009...,\u2009an (1\u2009\u2264\u2009ai\u2009\u2264\u2009109), where number ai stands for the i-th array element. The following m lines contain the description of the queries. The i-th line contains the description of the i-th query, consisting of two integers li, ri (1\u2009\u2264\u2009li\u2009\u2264\u2009ri\u2009\u2264\u2009n) \u2014 the boundaries of the subsegment of the initial array. The numbers in the lines are separated by single spaces.", "output_spec": "Print m lines, in the i-th line print word \"Yes\" (without the quotes), if the subsegment that corresponds to the i-th query is the ladder, or word \"No\" (without the quotes) otherwise. ", "sample_inputs": ["8 6\n1 2 1 3 3 5 2 1\n1 3\n2 3\n2 4\n8 8\n1 4\n5 8"], "sample_outputs": ["Yes\nYes\nNo\nYes\nNo\nYes"], "notes": null}, "positive_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = -1+read_int() in (u,-1+read_int())\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n let a = Array.init n (fun _ -> read_int()) in\n let q = Array.init m (fun _ -> read_pair()) in\n\n let amap = Array.make n 0 in\n let a1 = Array.copy a in\n\n let rec fill_amap i j = if i=n then j else\n if a.(i-1) <> a.(i) then (\n amap.(i) <- j;\n a1.(j) <- a.(i);\n fill_amap (i+1) (j+1)\n ) else (\n amap.(i) <- amap.(i-1);\n fill_amap (i+1) j\n )\n in\n\n let n1 = fill_amap 1 1 in\n\n(* now a1.(amap.(i)) = a.(i) *)\n(*\n for i=0 to n-1 do\n Printf.printf \"amap.(%d) = %d\\n\" i amap.(i)\n done;\n\n for i=0 to n1-1 do\n Printf.printf \"a1.(%d) = %d\\n\" i a1.(i)\n done;\n*)\n\n let nc = n1-1 in\n\n if nc = 0 then (\n for i = 0 to m-1 do Printf.printf \"Yes\\n\" done\n ) else\n let c = Array.init nc (fun i-> if a1.(i) < a1.(i+1) then 0 else 1) in\n\n let cmap = Array.make nc 0 in\n let c1 = Array.copy c in\n\n let rec fill_cmap i j = if i=nc then j else\n if c.(i-1) <> c.(i) then (\n cmap.(i) <- j;\n c1.(j) <- c.(i);\n fill_cmap (i+1) (j+1)\n ) else (\n cmap.(i) <- cmap.(i-1);\n fill_cmap (i+1) j\n )\n in\n\n let _ = fill_cmap 1 1 in\n\n(*\n for i=0 to nc-1 do\n Printf.printf \"cmap.(%d) = %d\\n\" i cmap.(i)\n done;\n\n for i=0 to n2-1 do\n Printf.printf \"c1.(%d) = %d\\n\" i c1.(i)\n done;\n*)\n for i = 0 to m-1 do\n let answer = \n\tlet (l,r) = q.(i) in\n\tlet (l,r) = (amap.(l), amap.(r)) in\n(*\t Printf.printf \"1: (l,r) = (%d,%d)\\n\" l r; *)\n\t if l=r || l=r-1 then \"Yes\" else (\n\t let r = r-1 in\n\t let (l,r) = (cmap.(l), cmap.(r)) in\n(*\t Printf.printf \"2: (l,r) = (%d,%d)\\n\" l r; *)\n\t if (l=r) || (l=r-1 && c1.(l) = 0) then \"Yes\" else \"No\"\n\t )\n in\n\tPrintf.printf \"%s\\n\" answer\n done\n"}], "negative_code": [{"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = -1+read_int() in (u,-1+read_int())\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n let a = Array.init n (fun _ -> read_int()) in\n let q = Array.init m (fun _ -> read_pair()) in\n\n let amap = Array.make n 0 in\n let a1 = Array.copy a in\n\n let rec fill_amap i j = if i=n then j else\n if a.(i-1) <> a.(i) then (\n amap.(i) <- j;\n a1.(j) <- a.(i);\n fill_amap (i+1) (j+1)\n ) else (\n amap.(i) <- amap.(i-1);\n fill_amap (i+1) j\n )\n in\n\n let n1 = fill_amap 1 1 in\n\n(* now a1.(amap.(i)) = a.(i) *)\n(*\n for i=0 to n-1 do\n Printf.printf \"amap.(%d) = %d\\n\" i amap.(i)\n done;\n\n for i=0 to n1-1 do\n Printf.printf \"a1.(%d) = %d\\n\" i a1.(i)\n done;\n*)\n\n let nc = n1-1 in\n\n if nc = 0 then (\n Printf.printf \"Yes\\n\"; \n ) else\n let c = Array.init nc (fun i-> if a1.(i) < a1.(i+1) then 0 else 1) in\n\n let cmap = Array.make nc 0 in\n let c1 = Array.copy c in\n\n let rec fill_cmap i j = if i=nc then j else\n if c.(i-1) <> c.(i) then (\n cmap.(i) <- j;\n c1.(j) <- c.(i);\n fill_cmap (i+1) (j+1)\n ) else (\n cmap.(i) <- cmap.(i-1);\n fill_cmap (i+1) j\n )\n in\n\n let _ = fill_cmap 1 1 in\n\n(*\n for i=0 to nc-1 do\n Printf.printf \"cmap.(%d) = %d\\n\" i cmap.(i)\n done;\n\n for i=0 to n2-1 do\n Printf.printf \"c1.(%d) = %d\\n\" i c1.(i)\n done;\n*)\n for i = 0 to m-1 do\n let answer = \n\tlet (l,r) = q.(i) in\n\tlet (l,r) = (amap.(l), amap.(r)) in\n(*\t Printf.printf \"1: (l,r) = (%d,%d)\\n\" l r; *)\n\t if l=r || l=r-1 then \"Yes\" else (\n\t let r = r-1 in\n\t let (l,r) = (cmap.(l), cmap.(r)) in\n(*\t Printf.printf \"2: (l,r) = (%d,%d)\\n\" l r; *)\n\t if (l=r) || (l=r-1 && c1.(l) = 0) then \"Yes\" else \"No\"\n\t )\n in\n\tPrintf.printf \"%s\\n\" answer\n done\n"}, {"source_code": "let read_int () = Scanf.bscanf Scanf.Scanning.stdib \" %d \" (fun x -> x)\nlet read_pair () = let u = -1+read_int() in (u,-1+read_int())\n\nlet () = \n let n = read_int() in\n let m = read_int() in\n let a = Array.init n (fun _ -> read_int()) in\n let q = Array.init m (fun _ -> read_pair()) in\n\n let amap = Array.make n 0 in\n let a1 = Array.copy a in\n\n let rec fill_amap i j = if i=n then j else\n if a.(i-1) <> a.(i) then (\n amap.(i) <- j;\n a1.(j) <- a.(i);\n fill_amap (i+1) (j+1)\n ) else (\n amap.(i) <- amap.(i-1);\n fill_amap (i+1) j\n )\n in\n\n let n1 = fill_amap 1 1 in\n\n(* now a1.(amap.(i)) = a.(i) *)\n(*\n for i=0 to n-1 do\n Printf.printf \"amap.(%d) = %d\\n\" i amap.(i)\n done;\n\n for i=0 to n1-1 do\n Printf.printf \"a1.(%d) = %d\\n\" i a1.(i)\n done;\n*)\n\n let nc = n1-1 in\n\n if nc = 0 then (\n Printf.printf \"Yes\\n\"; \n ) else\n let c = Array.init nc (fun i-> if a1.(i) < a1.(i+1) then 0 else 1) in\n\n let cmap = Array.make nc 0 in\n let c1 = Array.copy c in\n\n let rec fill_cmap i j = if i=nc then j else\n if c.(i-1) <> c.(i) then (\n cmap.(i) <- j;\n c1.(j) <- c.(i);\n fill_cmap (i+1) (j+1)\n ) else (\n cmap.(i) <- cmap.(i-1);\n fill_cmap (i+1) j\n )\n in\n\n let _ = fill_cmap 1 1 in\n\n(*\n for i=0 to nc-1 do\n Printf.printf \"cmap.(%d) = %d\\n\" i cmap.(i)\n done;\n\n for i=0 to n2-1 do\n Printf.printf \"c1.(%d) = %d\\n\" i c1.(i)\n done;\n*)\n for i = 0 to m-1 do\n let answer = \n\tlet (l,r) = q.(i) in\n\tlet (l,r) = (amap.(l), amap.(r)) in\n(*\t Printf.printf \"1: (l,r) = (%d,%d)\\n\" l r; *)\n\t if l=r || l=r-1 then \"Yes\" else (\n\t let r = r-1 in\n\t let (l,r) = (cmap.(l), cmap.(r)) in\n(*\t Printf.printf \"2: (l,r) = (%d,%d)\\n\" l r; *)\n\t if (l=r) || (l=r-1 && c1.(l) = 0) then \"Yes\" else \"No\"\n\t )\n in\n\tPrintf.printf \"%s\\n\" answer\n done\n"}], "src_uid": "c39db222c42d8e85dee5686088dc3dac"} {"nl": {"description": "Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n\u2009>\u20091) is an n\u2009\u00d7\u2009n matrix with a diamond inscribed into it.You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character \"D\". All other cells of the matrix should be represented by character \"*\". Look at the examples to understand what you need to draw.", "input_spec": "The only line contains an integer n (3\u2009\u2264\u2009n\u2009\u2264\u2009101; n is odd). ", "output_spec": "Output a crystal of size n.", "sample_inputs": ["3", "5", "7"], "sample_outputs": ["*D*\nDDD\n*D*", "**D**\n*DDD*\nDDDDD\n*DDD*\n**D**", "***D***\n**DDD**\n*DDDDD*\nDDDDDDD\n*DDDDD*\n**DDD**\n***D***"], "notes": null}, "positive_code": [{"source_code": "let pf = Printf.printf ;;\nlet epf = Printf.eprintf ;;\nlet sf = Scanf.scanf ;;\n\nlet (|>) x f = f x ;;\n\nmodule Array = ArrayLabels ;;\nmodule List = ListLabels ;;\n\nlet () =\n sf \"%d \" (fun n ->\n for i = 0 to n / 2 do\n for j = 0 to n - 1 do\n pf (if n / 2 - i <= j && j <= n / 2 + i then \"D\" else \"*\");\n done;\n pf \"\\n\";\n done;\n for i = 1 to n / 2 do\n for j = 0 to n - 1 do\n pf (if i <= j && j <= n - 1 - i then \"D\" else \"*\");\n done;\n pf \"\\n\";\n done)\n;;\n"}], "negative_code": [], "src_uid": "a003d645999934c255f7b05d8494fa40"} {"nl": {"description": "Vasya came up with a password to register for EatForces \u2014 a string $$$s$$$. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin letter and at least one lowercase Latin letter. For example, the passwords \"abaCABA12\", \"Z7q\" and \"3R24m\" are valid, and the passwords \"qwerty\", \"qwerty12345\" and \"Password\" are not. A substring of string $$$s$$$ is a string $$$x = s_l s_{l + 1} \\dots s_{l + len - 1} (1 \\le l \\le |s|, 0 \\le len \\le |s| - l + 1)$$$. $$$len$$$ is the length of the substring. Note that the empty string is also considered a substring of $$$s$$$, it has the length $$$0$$$.Vasya's password, however, may come too weak for the security settings of EatForces. He likes his password, so he wants to replace some its substring with another string of the same length in order to satisfy the above conditions. This operation should be performed exactly once, and the chosen string should have the minimal possible length.Note that the length of $$$s$$$ should not change after the replacement of the substring, and the string itself should contain only lowercase and uppercase Latin letters and digits.", "input_spec": "The first line contains a single integer $$$T$$$ ($$$1 \\le T \\le 100$$$) \u2014 the number of testcases. Each of the next $$$T$$$ lines contains the initial password $$$s~(3 \\le |s| \\le 100)$$$, consisting of lowercase and uppercase Latin letters and digits. Only $$$T = 1$$$ is allowed for hacks.", "output_spec": "For each testcase print a renewed password, which corresponds to given conditions. The length of the replaced substring is calculated as following: write down all the changed positions. If there are none, then the length is $$$0$$$. Otherwise the length is the difference between the first and the last changed position plus one. For example, the length of the changed substring between the passwords \"abcdef\" $$$\\rightarrow$$$ \"a7cdEf\" is $$$4$$$, because the changed positions are $$$2$$$ and $$$5$$$, thus $$$(5 - 2) + 1 = 4$$$. It is guaranteed that such a password always exists. If there are several suitable passwords \u2014 output any of them.", "sample_inputs": ["2\nabcDCE\nhtQw27"], "sample_outputs": ["abcD4E\nhtQw27"], "notes": "NoteIn the first example Vasya's password lacks a digit, he replaces substring \"C\" with \"4\" and gets password \"abcD4E\". That means, he changed the substring of length 1.In the second example Vasya's password is ok from the beginning, and nothing has to be changed. That is the same as replacing the empty substring with another empty substring (length 0)."}, "positive_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\n\nlet llen l = List.length l\nlet () =\n\tlet t = get_i64 0 in \n\trep 1L t (fun _ -> \n\t\tlet s = scanf \" %s\" (fun v -> v) in\n\t\tlet a = s |> char_list_of_string |> Array.of_list in \n\t\tlet b = s |> char_list_of_string |> List.mapi (fun i v -> (i,v)) |> Array.of_list in\n\t\tlet ld,lu,ln = Array.fold_left (fun (d,u,n) (i,v) ->\n\t\t\tif '0' <= v && v <= '9' then (d,u,(i,v)::n)\n\t\t\telse if 'a' <= v && v <= 'z' then ((i,v)::d,u,n)\n\t\t\telse if 'A' <= v && v <= 'Z' then (d,(i,v)::u,n)\n\t\t\telse (d,u,n)\n\t\t)\t([],[],[]) b\n\t\tin\n\t\t\t(* let (i,p),(j,q),(k,r) = List.hd ld,List.hd lu,List.hd ln in *)\n\t\t\tlet i,j,k = llen ld,llen lu,llen ln in \n\t\t\tlet ld,lu,ln = ref ld,ref lu,ref ln in\n\t\t\t(* printf \"%d %d %d\\n\" i j k; *)\n\t\t\tlet i,j,k = ref i,ref j,ref k in\n\t\t\tif !i = 0 then (\n\t\t\t\tif !j >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !lu in\n\t\t\t\t\ta.(w) <- 'a'; j:=!j-$1; lu := List.tl !lu\n\t\t\t\t) else if !k >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !ln in\n\t\t\t\t\ta.(w) <- 'a'; k:=!k-$1; ln := List.tl !ln\n\t\t\t\t)\n\t\t\t);\n\t\t\t(* printf \"%d %d %d\\n\" !i !j !k; *)\n\t\t\tif !j = 0 then (\n\t\t\t\tif !k >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !ln in\n\t\t\t\t\ta.(w) <- 'A'; k:=!k-$1; ln := List.tl !ln\n\t\t\t\t) else if !i >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !ld in\n\t\t\t\t\ta.(w) <- 'A'; i:=!i-$1; ld := List.tl !ld\n\t\t\t\t)\n\t\t\t);\n\t\t\t(* printf \"%d %d %d\\n\" !i !j !k; *)\n\t\t\tif !k = 0 then (\n\t\t\t\tif !i >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !ld in\n\t\t\t\t\ta.(w) <- '3'; i:=!i-$1; ld := List.tl !ld\n\t\t\t\t) else if !j >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !lu in\n\t\t\t\t\ta.(w) <- '3'; j:=!j-$1; lu := List.tl !lu\n\t\t\t\t)\n\t\t\t);\n\t\t\t(* printf \"%d %d %d\\n\" !i !j !k; *)\n\t\t\ta |> Array.to_list |> string_of_list ~separator:\"\" (String.make 1) |> print_endline; `Ok\n\t)"}], "negative_code": [{"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\n\nlet llen l = List.length l\nlet () =\n\tlet t = get_i64 0 in \n\trep 1L t (fun _ -> \n\t\tlet s = scanf \" %s\" (fun v -> v) in\n\t\tlet a = s |> char_list_of_string |> Array.of_list in \n\t\tlet b = s |> char_list_of_string |> List.mapi (fun i v -> (i,v)) |> Array.of_list in\n\t\tlet ld,lu,ln = Array.fold_left (fun (d,u,n) (i,v) ->\n\t\t\tif '0' <= v && v <= '9' then (d,u,(i,v)::n)\n\t\t\telse if 'a' <= v && v <= 'z' then ((i,v)::d,u,n)\n\t\t\telse if 'A' <= v && v <= 'Z' then (d,(i,v)::u,n)\n\t\t\telse (d,u,n)\n\t\t)\t([],[],[]) b\n\t\tin\n\t\t\t(* let (i,p),(j,q),(k,r) = List.hd ld,List.hd lu,List.hd ln in *)\n\t\t\tlet i,j,k = llen ld,llen lu,llen ln in \n\t\t\tlet ld,lu,ln = ref ld,ref lu,ref ln in\n\t\t\tprintf \"%d %d %d\\n\" i j k;\n\t\t\tlet i,j,k = ref i,ref j,ref k in\n\t\t\tif !i = 0 then (\n\t\t\t\tif !j >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !lu in\n\t\t\t\t\ta.(w) <- 'a'; j:=!j-$1; lu := List.tl !lu\n\t\t\t\t) else if !k >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !ln in\n\t\t\t\t\ta.(w) <- 'a'; k:=!k-$1; ln := List.tl !ln\n\t\t\t\t)\n\t\t\t);\n\t\t\tprintf \"%d %d %d\\n\" !i !j !k;\n\t\t\tif !j = 0 then (\n\t\t\t\tif !k >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !ln in\n\t\t\t\t\ta.(w) <- 'A'; k:=!k-$1; ln := List.tl !ln\n\t\t\t\t) else if !i >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !ld in\n\t\t\t\t\ta.(w) <- 'A'; i:=!i-$1; ld := List.tl !ld\n\t\t\t\t)\n\t\t\t);\n\t\t\tprintf \"%d %d %d\\n\" !i !j !k;\n\t\t\tif !k = 0 then (\n\t\t\t\tif !i >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !ld in\n\t\t\t\t\ta.(w) <- '3'; i:=!i-$1; ld := List.tl !ld\n\t\t\t\t) else if !j >= 2 then (\n\t\t\t\t\tlet w,_ = List.hd !lu in\n\t\t\t\t\ta.(w) <- '3'; j:=!j-$1; lu := List.tl !lu\n\t\t\t\t)\n\t\t\t);\n\t\t\tprintf \"%d %d %d\\n\" !i !j !k;\n\t\t\ta |> Array.to_list |> string_of_list ~separator:\"\" (String.make 1) |> print_endline; `Ok\n\t)"}, {"source_code": "open Printf open Scanf\nmodule MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end\nmodule MyInt64 = struct\n\tlet (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf \" %Ld\" (fun v -> v)) let get_i64 _ = Scanf.scanf \" %Ld\" (fun v -> v) let get_2_i64 _ = Scanf.scanf \" %Ld %Ld\" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf \" %Ld %Ld %Ld\" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld\" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf \" %Ld %Ld %Ld %Ld %Ld\" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=\" \") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls \"\" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) \"\" ls\n\tlet (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v\n\tlet ceildiv m n = (m+n-1L) / n\n\tlet abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf \" %s\" (fun v -> v)\n\tlet i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a\nend open MyInt64\n\nlet llen l = List.length l\nlet () =\n\tlet t = get_i64 0 in \n\trep 1L t (fun _ -> \n\t\tlet s = scanf \" %s\" (fun v -> v) in\n\t\tlet a = s |> char_list_of_string |> Array.of_list in \n\t\tlet b = s |> char_list_of_string |> List.mapi (fun i v -> (i,v)) |> Array.of_list in\n\t\tlet ld,lu,ln = Array.fold_left (fun (d,u,n) (i,v) ->\n\t\t\tif '0' <= v && v <= '9' then (d,u,(i,v)::n)\n\t\t\telse if 'a' <= v && v <= 'z' then ((i,v)::d,u,n)\n\t\t\telse if 'A' <= v && v <= 'Z' then (d,(i,v)::u,n)\n\t\t\telse (d,u,n)\n\t\t)\t([],[],[]) b\n\t\tin\n\t\t\t(* let (i,p),(j,q),(k,r) = List.hd ld,List.hd lu,List.hd ln in *)\n\t\t\tlet i,j,k = llen ld,llen lu,llen ln in \n\t\t\t(* printf \"%d %d %d\\n\" i j k; *)\n\t\t\tlet i,j,k = ref i,ref j,ref k in\n\t\t\tif !i = 0 then (\n\t\t\t\tif !j >= 2 then (\n\t\t\t\t\ta.(!i) <- 'a'; j:=!j-$1;\n\t\t\t\t) else if !k >= 2 then (\n\t\t\t\t\ta.(!i) <- 'a'; k:=!k-$1;\n\t\t\t\t)\n\t\t\t);\n\t\t\tif !j = 0 then (\n\t\t\t\tif !k >= 2 then (\n\t\t\t\t\ta.(!j) <- 'A'; k:=!k-$1;\n\t\t\t\t) else if !i >= 2 then (\n\t\t\t\t\ta.(!j) <- 'A'; i:=!i-$1;\n\t\t\t\t)\n\t\t\t);\n\t\t\tif !k = 0 then (\n\t\t\t\tif !i >= 2 then (\n\t\t\t\t\ta.(!k) <- '0'; i:=!i-$1;\n\t\t\t\t) else if !j >= 2 then (\n\t\t\t\t\ta.(!k) <- '0'; j:=!j-$1;\n\t\t\t\t)\n\t\t\t);\n\t\ta |> Array.to_list |> string_of_list ~separator:\"\" (String.make 1) |> print_endline; `Ok\n\t)"}], "src_uid": "81faa525ded9b209fb7d5d8fec95f38b"} {"nl": {"description": "You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.", "input_spec": "The first line contains string a, and the second line\u00a0\u2014 string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.", "output_spec": "On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters. If the answer consists of zero characters, output \u00ab-\u00bb (a minus sign).", "sample_inputs": ["hi\nbob", "abca\naccepted", "abacaba\nabcdcba"], "sample_outputs": ["-", "ac", "abcba"], "notes": "NoteIn the first example strings a and b don't share any symbols, so the longest string that you can get is empty.In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b."}, "positive_code": [{"source_code": "let print_result s = \n\tmatch s with\n\t| \"\" ->\n\t\tPrintf.printf \"-\\n\";\n\t| _ ->\n\t\tPrintf.printf \"%s\\n\" s;\n;;\n\n\nlet left_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make (ns+1) 0 in\n\tlet kp = ref 0 in\n\tlet js = ref 0 in\n\tbegin\n\t\t(*\n\t\tInvariant: \n\t\t\t1. forall j' < js, arr[j'] is amount of matches between strings p and s[0..j'-1]\n\t\t\t2. kp - amount of matches between strings p[0..kp-1] and s[0..js-1] \n\t\tBase case: 1,2. vacuous truth\n\t\tTermination: js == ns, array range of indices j=[0..ns-1] contains amount of matches between p and corresponding substrings s[0..j-1]\n\t\t\t\tkp - maximal amount of matches between s[0..ns-1] (i.e. the whole string s) and p\n\t\t*)\n\t\twhile !js < ns do\n\n\t\t\tarr.(!js) <- !kp; (* now arr[!js] contains amount of matches between p and s[0..js-1] *)\n\n\t\t\tif (!kp < np) && (String.get p !kp) == (String.get s !js) then\n\t\t\tbegin\n\t\t\t\tkp := !kp + 1;\n\t\t\tend;\n\n\t\t\tjs := !js + 1;\n\n\t\tdone;\n\n\t\t(* the last value just duplicates amount if matches between the whole strings p and s *)\n\t\tarr.(!js) <- !kp;\n\n\t\tarr\n\tend\n;;\n\nlet right_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make (ns+1) 0 in\n\tlet kp = ref np in\n\tlet js = ref ns in\n\tbegin\n\n\t\t(*\n\t\tInvariant: \n\t\t\t1. forall j' > js, arr[j'] is amount of matches between strings p and s[j'..ns-1]\n\t\t\t2. kp - position of the last match (if any) in string p or np otherwise. \n\t\tBase case: 1,2. vacuous truth\n\t\tTermination: js == 0, array range of indices j=[1..ns-1] contains amount of matches between p and corresponding substrings s[j..ns-1]\n\t\t\t\t\tarr[ns] contains 0 as there is no matches beyond string length\n\t\t\t\tkp - maximal amount of matches between s[1..ns-1] and p\n\t\t*)\n\t\twhile !js > 0 do\n\n\t\t\tarr.(!js) <- (np - !kp);\n\n\t\t\tif (!kp > 0) && (String.get p (!kp-1) ) == (String.get s (!js-1) ) then\n\t\t\tbegin\n\t\t\t\tkp := !kp - 1;\n\t\t\tend;\n\n\t\t\tjs := !js - 1;\n\n\t\tdone;\n\n\t\t(* amount of matches between the whole strings p and s *)\n\t\tarr.(!js) <- (np - !kp);\n\n\t\tarr;\n\tend\n;;\n\nlet process_strings s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet l = left_arrangements s p in\n\tlet r = right_arrangements s p in\n\tlet best_ks = ref 0 in\n\tlet best_sum = ref 0 in\n\tbegin\n\t\tfor ks = 0 to ns do\n\t\t\tlet sum = l.(ks) + r.(ks) in\n\t\t\tif sum > !best_sum then\n\t\t\t\tbegin\n\t\t\t\t\tbest_sum := sum;\n\t\t\t\t\tbest_ks := ks;\n\t\t\t\tend;\n\t\tdone;\n\n\t\tlet res = if !best_sum <= np \n\t\t\t\tthen (String.sub p 0 l.(!best_ks)) ^ (String.sub p (np - r.(!best_ks)) r.(!best_ks))\n\t\t\t\telse p in\n\t\tprint_result res;\n\tend\n;;\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %s %s \" process_strings\n;;\n\nread_input ()\n"}, {"source_code": "let print_result s = \n\tmatch s with\n\t| \"\" ->\n\t\tPrintf.printf \"-\\n\";\n\t| _ ->\n\t\tPrintf.printf \"%s\\n\" s;\n;;\n\n\nlet left_subsequence_lengths a b =\n\n\tlet n = String.length a in\n\tlet m = String.length b in\n\tlet l = Array.make (n+1) 0 in\n\tlet j = ref 0 in\n\tbegin\n\n\tl.(0) <- !j;\n\n\tfor k=0 to (n-1) do\n\n\t\tif (!j < m) && ((String.get a k) == (String.get b !j)) then\n\t\t\tbegin\n\t\t\tj := !j + 1;\n\t\t\tend;\n\n\t\tl.(k+1) <- !j; (* now l[!js] contains amount of matches between b and a[0..js-1] *)\n\n\tdone;\n\n\tl\n\tend\n;;\n\nlet right_subsequence_lengths a b =\n\tlet n = String.length a in\n\tlet m = String.length b in\n\tlet r = Array.make (n+1) 0 in\n\tlet j = ref m in\n\tbegin\n\n\tr.(n) <- (m - !j);\n\n\tfor k = (n-1) downto 0 do\n\n\t\tif (!j > 0) && ((String.get a k ) == (String.get b (!j-1))) then\n\t\t\tbegin\n\t\t\tj := !j - 1;\n\t\t\tend;\n\n\t\tr.(k) <- (m - !j);\n\n\tdone;\n\n\tr;\n\tend\n;;\n\nlet longest_subsequence a b =\n\tlet n = String.length a in\n\tlet m = String.length b in\n\tlet l = left_subsequence_lengths a b in\n\tlet r = right_subsequence_lengths a b in\n\tlet s_best = ref (l.(0) + r.(0)) in\n\tlet k_best = ref 0 in\n\tbegin\n\tfor k = 1 to n do\n\t\tlet s = l.(k) + r.(k) in\n\t\tif s > !s_best then\n\t\t\tbegin\n\t\t\ts_best := s;\n\t\t\tk_best := k;\n\t\t\tend;\n\tdone;\n\n\tif !s_best >= m\n\t\tthen b\n\t\telse (String.sub b 0 l.(!k_best)) ^ (String.sub b (m - r.(!k_best)) r.(!k_best))\n\tend\n;;\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %s %s \" (fun a b -> print_result (longest_subsequence a b))\n;;\n\nread_input ()\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let a = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let c2i c = Char.code c - Char.code 'a' in\n let n = String.length a\n and m = String.length b in\n let inf = 1000000000 in\n let prev = Array.make_matrix 26 n 0 in\n let next = Array.make_matrix 26 n 0 in\n let p = Array.make 26 inf in\n let p' = Array.make 26 (-1) in\n let _ =\n for i = 0 to n - 1 do\n let c = c2i a.[i] in\n\tfor j = 0 to 25 do\n\t prev.(j).(i) <- p'.(j)\n\tdone;\n\tp'.(c) <- i;\n done;\n for i = n - 1 downto 0 do\n let c = c2i a.[i] in\n\tfor j = 0 to 25 do\n\t next.(j).(i) <- p.(j)\n\tdone;\n\tp.(c) <- i;\n done;\n in\n let d = Array.make m (-1) in\n let pos = ref p.(c2i b.[0]) in\n let _ =\n d.(0) <- !pos;\n for i = 1 to m - 1 do\n if !pos < inf then (\n\tlet c = c2i b.[i] in\n\t pos := next.(c).(!pos);\n );\n d.(i) <- !pos;\n done;\n in\n let d' = Array.make m (-1) in\n let _ =\n pos := p'.(c2i b.[m - 1]);\n d'.(m - 1) <- !pos;\n for i = m - 2 downto 0 do\n if !pos >= 0 then (\n\tlet c = c2i b.[i] in\n\t pos := prev.(c).(!pos);\n );\n d'.(i) <- !pos;\n done;\n in\n (*for i = 0 to m - 1 do\n Printf.printf \"asd %d %d\\n\" d.(i) d'.(i)\n done;*)\n let bl = ref (-1) in\n let br = ref m in\n let r = ref 0 in\n while !r < m && d'.(!r) < 0 do\n incr r;\n done;\n if !br - !bl > !r - (-1) then (\n br := !r;\n bl := -1;\n );\n for l = 0 to m - 1 do\n while !r < m && (!r <= l || d'.(!r) <= d.(l)) do\n\tincr r;\n done;\n if d.(l) < inf && !br - !bl > !r - l then (\n\tbr := !r;\n\tbl := l;\n )\n done;\n (*Printf.printf \"qwe %d %d\\n\" !bl !br;*)\n let res = String.sub b 0 (!bl + 1) ^ String.sub b !br (m - !br) in\n if res = \"\"\n then Printf.printf \"-\\n\"\n else Printf.printf \"%s\\n\" res\n"}], "negative_code": [{"source_code": "let print_result s = \n\tmatch s with\n\t| \"\" ->\n\t\tPrintf.printf \"-\\n\";\n\t| _ ->\n\t\tPrintf.printf \"%s\\n\" s;\n;;\n\nlet left_mismatch s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet kp = ref 0 in\n\tlet js = ref 0 in\n\tlet jl = ref 0 in (* index in s after last match with p *)\n\tbegin\n\t\twhile (!kp < np) && (!js < ns) \n\t\tdo\n\t\t\tif (String.get p !kp) == (String.get s !js) then\n\t\t\tbegin\n\t\t\t\tkp := !kp + 1;\n\t\t\t\tjl := !js + 1;\n\t\t\tend;\n\t\t\tjs := !js + 1;\n\t\tdone; (* for k : (p_b..p_e) *)\n\t\t(!kp, !jl)\n\tend\n;;\n\nlet right_mismatch s p s_b p_b =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet kp = ref np in\n\tlet js = ref ns in\n\tbegin\n\t\twhile (!kp > p_b) && (!js > s_b) \n\t\tdo\n\t\t\tif (String.get p (!kp - 1) ) == (String.get s (!js - 1) ) then\n\t\t\tbegin\n\t\t\t\tkp := !kp - 1;\n\t\t\tend;\n\t\t\tjs := !js - 1;\n\t\tdone; (* for k : (p_b..p_e) *)\n\t\t!kp\n\tend\n;;\n\nlet process_strings s p =\n\tbegin\n\t\tlet m = String.length p in\n\t\tlet (lp, ls) = left_mismatch s p in\n\t\tlet rp = right_mismatch s p ls lp in\n\t\tlet nr = m - rp in\n\t\tlet res = (String.sub p 0 lp) ^ (String.sub p rp nr) in\n\t\tprint_result res;\n\tend\n;;\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %s %s \" process_strings\n;;\n\nread_input ()\n"}, {"source_code": "let print_result s = \n\tmatch s with\n\t| \"\" ->\n\t\tPrintf.printf \"-\\n\";\n\t| _ ->\n\t\tPrintf.printf \"%s\\n\" s;\n;;\n\n\nlet left_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make ns 0 in\n\tlet kp = ref 0 in\n\tlet js = ref 0 in\n\tbegin\n\t\twhile (!kp < np) && (!js < ns) do\n\n\t\t\tarr.(!js) <- !kp;\n\n\t\t\tif (String.get p !kp) == (String.get s !js) then\n\t\t\tbegin\n\t\t\t\tkp := !kp + 1;\n\t\t\tend;\n\n\t\t\tjs := !js + 1;\n\t\tdone;\n\n\t\twhile !js < ns do\n\t\t\tarr.(!js) <- np;\n\t\t\tjs := !js + 1;\n\t\tdone;\n\n\t\tarr\n\tend\n;;\n\nlet right_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make ns 0 in\n\tlet kp = ref np in\n\tlet js = ref ns in\n\tbegin\n\t\twhile (!kp > 0) && (!js > 0) do\n\n\t\t\tif (String.get p (!kp-1) ) == (String.get s (!js-1) ) then\n\t\t\tbegin\n\t\t\t\tkp := !kp - 1;\n\t\t\tend;\n\n\t\t\tjs := !js - 1;\n\n\t\t\tarr.(!js) <- (np - !kp);\n\t\tdone;\n\n\t\twhile (!js > 0) do\n\t\t\tjs := !js - 1;\n\t\t\tarr.(!js) <- np;\n\t\tdone;\n\n\t\tarr;\n\tend\n;;\n\nlet process_strings s p =\n\tlet n = String.length s in\n\tlet m = String.length p in\n\tlet l = left_arrangements s p in\n\tlet r = right_arrangements s p in\n\tlet best_k = ref 0 in\n\tlet best_sum = ref 0 in\n\tbegin\n\t\tfor k = 0 to (n-1) do\n\t\t\tlet sum = l.(k) + r.(k) in\n\t\t\tif sum > !best_sum then\n\t\t\t\tbegin\n\t\t\t\t\tbest_sum := sum;\n\t\t\t\t\tbest_k := k;\n\t\t\t\tend;\n\t\tdone;\n\n\t\tlet res = if !best_sum <= m\n\t\t\t\tthen (String.sub p 0 l.(!best_k)) ^ (String.sub p (m - r.(!best_k)) r.(!best_k))\n\t\t\t\telse p in\n\t\tprint_result res;\n\tend\n;;\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %s %s \" process_strings\n;;\n\nread_input ()\n"}, {"source_code": "let print_result s = \n\tmatch s with\n\t| \"\" ->\n\t\tPrintf.printf \"-\\n\";\n\t| _ ->\n\t\tPrintf.printf \"%s\\n\" s;\n;;\n\n\nlet left_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make ns 0 in\n\tlet kp = ref 0 in\n\tlet js = ref 0 in\n\tbegin\n\t\twhile (!kp < np) && (!js < ns) do\n\n\t\t\tarr.(!js) <- !kp;\n\n\t\t\tif (String.get p !kp) == (String.get s !js) then\n\t\t\tbegin\n\t\t\t\tkp := !kp + 1;\n\t\t\tend;\n\n\t\t\tjs := !js + 1;\n\t\tdone;\n\n\t\twhile !js < ns do\n\t\t\tarr.(!js) <- np;\n\t\t\tjs := !js + 1;\n\t\tdone;\n\n\t\tarr\n\tend\n;;\n\nlet right_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make ns 0 in\n\tlet kp = ref np in\n\tlet js = ref ns in\n\tbegin\n\t\twhile (!kp > 0) && (!js > 0) do\n\n\t\t\tif (String.get p (!kp-1) ) == (String.get s (!js-1) ) then\n\t\t\tbegin\n\t\t\t\tkp := !kp - 1;\n\t\t\tend;\n\n\t\t\tjs := !js - 1;\n\n\t\t\tarr.(!js) <- (np - !kp);\n\t\tdone;\n\n\t\twhile (!js > 0) do\n\t\t\tarr.(!js) <- np;\n\t\t\tjs := !js - 1;\n\t\tdone;\n\n\t\tarr;\n\tend\n;;\n\nlet process_strings s p =\n\tlet n = String.length s in\n\tlet m = String.length p in\n\tlet l = left_arrangements s p in\n\tlet r = right_arrangements s p in\n\tlet best_k = ref 0 in\n\tlet best_sum = ref 0 in\n\tbegin\n\t\tfor k = 0 to (n-1) do\n\t\t\tlet sum = l.(k) + r.(k) in\n\t\t\tif sum > !best_sum then\n\t\t\t\tbegin\n\t\t\t\t\tbest_sum := sum;\n\t\t\t\t\tbest_k := k;\n\t\t\t\tend;\n\t\tdone;\n\n\t\tlet res = (String.sub p 0 l.(!best_k)) ^ (String.sub p (m - r.(!best_k)) r.(!best_k)) in\n\t\tprint_result res;\n\tend\n;;\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %s %s \" process_strings\n;;\n\nread_input ()\n"}, {"source_code": "let print_result s = \n\tmatch s with\n\t| \"\" ->\n\t\tPrintf.printf \"-\\n\";\n\t| _ ->\n\t\tPrintf.printf \"%s\\n\" s;\n;;\n\n\nlet left_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make ns 0 in\n\tlet kp = ref 0 in\n\tlet js = ref 0 in\n\tbegin\n\t\twhile (!kp < np) && (!js < ns) do\n\n\t\t\tarr.(!js) <- !kp;\n\n\t\t\tif (String.get p !kp) == (String.get s !js) then\n\t\t\tbegin\n\t\t\t\tkp := !kp + 1;\n\t\t\tend;\n\n\t\t\tjs := !js + 1;\n\n\t\tdone;\n\n\t\tarr\n\tend\n;;\n\nlet right_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make ns 0 in\n\tlet kp = ref np in\n\tlet js = ref ns in\n\tbegin\n\t\twhile (!kp > 0) && (!js > 0) do\n\n\t\t\tif (String.get p (!kp-1) ) == (String.get s (!js-1) ) then\n\t\t\tbegin\n\t\t\t\tkp := !kp - 1;\n\t\t\tend;\n\n\t\t\tjs := !js - 1;\n\n\t\t\tarr.(!js) <- (np - !kp);\n\n\t\tdone;\n\n\t\tarr;\n\tend\n;;\n\nlet process_strings s p =\n\tlet n = String.length s in\n\tlet m = String.length p in\n\tlet l = left_arrangements s p in\n\tlet r = right_arrangements s p in\n\tlet best_k = ref 0 in\n\tlet best_sum = ref 0 in\n\tbegin\n\t\tfor k = 0 to (n-1) do\n\t\t\tlet sum = l.(k) + r.(k) in\n\t\t\tif sum > !best_sum then\n\t\t\t\tbegin\n\t\t\t\t\tbest_sum := sum;\n\t\t\t\t\tbest_k := k;\n\t\t\t\tend;\n\t\tdone;\n\n\t\tlet res = (String.sub p 0 l.(!best_k)) ^ (String.sub p (m - r.(!best_k)) r.(!best_k)) in\n\t\tprint_result res;\n\tend\n;;\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %s %s \" process_strings\n;;\n\nread_input ()\n"}, {"source_code": "let print_result s = \n\tmatch s with\n\t| \"\" ->\n\t\tPrintf.printf \"-\\n\";\n\t| _ ->\n\t\tPrintf.printf \"%s\\n\" s;\n;;\n\n\nlet left_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make ns 0 in\n\tlet kp = ref 0 in\n\tlet js = ref 0 in\n\tbegin\n\t\twhile (!kp < np) && (!js < ns) do\n\n\t\t\tarr.(!js) <- !kp;\n\n\t\t\tif (String.get p !kp) == (String.get s !js) then\n\t\t\tbegin\n\t\t\t\tkp := !kp + 1;\n\t\t\tend;\n\n\t\t\tjs := !js + 1;\n\t\tdone;\n\n\t\twhile !js < ns do\n\t\t\tarr.(!js) <- np;\n\t\t\tjs := !js + 1;\n\t\tdone;\n\n\t\tarr\n\tend\n;;\n\nlet right_arrangements s p =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet arr = Array.make ns 0 in\n\tlet kp = ref np in\n\tlet js = ref ns in\n\tbegin\n\t\twhile (!kp > 0) && (!js > 0) do\n\n\t\t\tif (String.get p (!kp-1) ) == (String.get s (!js-1) ) then\n\t\t\tbegin\n\t\t\t\tkp := !kp - 1;\n\t\t\tend;\n\n\t\t\tjs := !js - 1;\n\n\t\t\tarr.(!js) <- (np - !kp);\n\t\tdone;\n\n\t\twhile (!js > 0) do\n\t\t\tjs := !js - 1;\n\t\t\tarr.(!js) <- np;\n\t\tdone;\n\n\t\tarr;\n\tend\n;;\n\nlet process_strings s p =\n\tlet n = String.length s in\n\tlet m = String.length p in\n\tlet l = left_arrangements s p in\n\tlet r = right_arrangements s p in\n\tlet best_k = ref 0 in\n\tlet best_sum = ref 0 in\n\tbegin\n\t\tfor k = 0 to (n-1) do\n\t\t\tlet sum = l.(k) + r.(k) in\n\t\t\tif sum > !best_sum then\n\t\t\t\tbegin\n\t\t\t\t\tbest_sum := sum;\n\t\t\t\t\tbest_k := k;\n\t\t\t\tend;\n\t\tdone;\n\n\t\tlet res = (String.sub p 0 l.(!best_k)) ^ (String.sub p (m - r.(!best_k)) r.(!best_k)) in\n\t\tprint_result res;\n\tend\n;;\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %s %s \" process_strings\n;;\n\nread_input ()\n"}, {"source_code": "let print_result s = \n\tmatch s with\n\t| \"\" ->\n\t\tPrintf.printf \"-\\n\";\n\t| _ ->\n\t\tPrintf.printf \"%s\\n\" s;\n;;\n\nlet left_mismatch s p s_e p_e =\n\tlet kp = ref 0 in\n\tlet js = ref 0 in\n\tlet jl = ref 0 in (* index in s after last match with p *)\n\tbegin\n\t\twhile (!kp < p_e) && (!js < s_e) \n\t\tdo\n\t\t\tif (String.get p !kp) == (String.get s !js) then\n\t\t\tbegin\n\t\t\t\tkp := !kp + 1;\n\t\t\t\tjl := !js + 1;\n\t\t\tend;\n\t\t\tjs := !js + 1;\n\t\tdone; (* for k : (p_b..p_e) *)\n\t\t(!kp, !jl)\n\tend\n;;\n\nlet right_mismatch s p s_b p_b =\n\tlet ns = String.length s in\n\tlet np = String.length p in\n\tlet kp = ref np in\n\tlet js = ref ns in\n\tlet jl = ref ns in\n\tbegin\n\t\twhile (!kp > p_b) && (!js > s_b) \n\t\tdo\n\t\t\tif (String.get p (!kp - 1) ) == (String.get s (!js - 1) ) then\n\t\t\tbegin\n\t\t\t\tkp := !kp - 1;\n\t\t\t\tjl := !js - 1;\n\t\t\tend;\n\t\t\tjs := !js - 1;\n\t\tdone; (* for k : (p_b..p_e) *)\n\t\t(!kp, !jl)\n\tend\n;;\n\nlet process_strings s p =\n\tbegin\n\t\tlet n = String.length s in\n\t\tlet m = String.length p in\n\t\tlet (lp1, ls1) = left_mismatch s p n m in\n\t\tlet (rp1, _) = right_mismatch s p ls1 lp1 in\n\t\tlet (rp2, rs2) = right_mismatch s p 0 0 in\n\t\tlet (lp2, _) = left_mismatch s p rs2 rp2 in\n\t\tlet nr1 = m - rp1 in\n\t\tlet nr2 = m - rp2 in\n\t\tlet n1 = lp1 + nr1 in\n\t\tlet n2 = lp2 + nr2 in\n\t\tlet res = if (n1 > n2) \n\t\t\tthen (String.sub p 0 lp1) ^ (String.sub p rp1 nr1)\n\t\t\telse (String.sub p 0 lp2) ^ (String.sub p rp2 nr2) in\n\t\tprint_result res;\n\tend\n;;\n\nlet read_input () = \n\tScanf.bscanf Scanf.Scanning.stdin \" %s %s \" process_strings\n;;\n\nread_input ()\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let a = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let c2i c = Char.code c - Char.code 'a' in\n let n = String.length a\n and m = String.length b in\n let inf = 1000000000 in\n let prev = Array.make_matrix 26 n 0 in\n let next = Array.make_matrix 26 n 0 in\n let p = Array.make 26 inf in\n let p' = Array.make 26 (-1) in\n let _ =\n for i = 0 to n - 1 do\n let c = c2i a.[i] in\n\tfor j = 0 to 25 do\n\t prev.(j).(i) <- p'.(j)\n\tdone;\n\tp'.(c) <- i;\n done;\n for i = n - 1 downto 0 do\n let c = c2i a.[i] in\n\tfor j = 0 to 25 do\n\t next.(j).(i) <- p.(j)\n\tdone;\n\tp.(c) <- i;\n done;\n in\n let d = Array.make m (-1) in\n let pos = ref p.(c2i b.[0]) in\n let _ =\n d.(0) <- !pos;\n for i = 1 to m - 1 do\n if !pos < inf then (\n\tlet c = c2i b.[i] in\n\t pos := next.(c).(!pos);\n );\n d.(i) <- !pos;\n done;\n in\n let d' = Array.make m (-1) in\n let _ =\n pos := p'.(c2i b.[m - 1]);\n d'.(m - 1) <- !pos;\n for i = m - 2 downto 0 do\n if !pos >= 0 then (\n\tlet c = c2i b.[i] in\n\t pos := prev.(c).(!pos);\n );\n d'.(i) <- !pos;\n done;\n in\n for i = 0 to m - 1 do\n Printf.printf \"asd %d %d\\n\" d.(i) d'.(i)\n done;\n let bl = ref (-1) in\n let br = ref m in\n let r = ref 0 in\n (*while !r < m && d'.(!r) < 0 do\n incr r;\n done;*)\n if !br - !bl > !r - (-1) then (\n br := !r;\n bl := -1;\n );\n for l = 0 to m - 1 do\n while !r < m && (!r <= l || d'.(!r) <= d.(l)) do\n\tincr r;\n done;\n if d.(l) < inf && !br - !bl > !r - l then (\n\tbr := !r;\n\tbl := l;\n )\n done;\n (*Printf.printf \"qwe %d %d\\n\" !bl !br;*)\n let res = String.sub b 0 (!bl + 1) ^ String.sub b !br (m - !br) in\n if res = \"\"\n then Printf.printf \"-\\n\"\n else Printf.printf \"%s\\n\" res\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let a = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let c2i c = Char.code c - Char.code 'a' in\n let n = String.length a\n and m = String.length b in\n let inf = 1000000000 in\n let prev = Array.make_matrix 26 n 0 in\n let next = Array.make_matrix 26 n 0 in\n let p = Array.make 26 inf in\n let p' = Array.make 26 (-1) in\n let _ =\n for i = 0 to n - 1 do\n let c = c2i a.[i] in\n\tfor j = 0 to 25 do\n\t prev.(j).(i) <- p'.(j)\n\tdone;\n\tp'.(c) <- i;\n done;\n for i = n - 1 downto 0 do\n let c = c2i a.[i] in\n\tfor j = 0 to 25 do\n\t next.(j).(i) <- p.(j)\n\tdone;\n\tp.(c) <- i;\n done;\n in\n let d = Array.make m (-1) in\n let pos = ref p.(c2i b.[0]) in\n let _ =\n d.(0) <- !pos;\n for i = 1 to m - 1 do\n if !pos < inf then (\n\tlet c = c2i b.[i] in\n\t pos := next.(c).(!pos);\n );\n d.(i) <- !pos;\n done;\n in\n let d' = Array.make m (-1) in\n let _ =\n pos := p'.(c2i b.[m - 1]);\n d'.(m - 1) <- !pos;\n for i = m - 2 downto 0 do\n if !pos >= 0 then (\n\tlet c = c2i b.[i] in\n\t pos := prev.(c).(!pos);\n );\n d'.(i) <- !pos;\n done;\n in\n (*for i = 0 to m - 1 do\n Printf.printf \"asd %d %d\\n\" d.(i) d'.(i)\n done;*)\n let bl = ref (-1) in\n let br = ref m in\n let r = ref 0 in\n for l = 0 to m - 1 do\n while !r < m && d'.(!r) <= d.(l) do\n\tincr r;\n done;\n if d.(l) < inf && !br - !bl > !r - l then (\n\tbr := !r;\n\tbl := l;\n )\n done;\n (*Printf.printf \"qwe %d %d\\n\" !bl !br;*)\n let res = String.sub b 0 (!bl + 1) ^ String.sub b !br (m - !br) in\n if res = \"\"\n then Printf.printf \"-\\n\"\n else Printf.printf \"%s\\n\" res\n"}, {"source_code": "let _ =\n let sb = Scanf.Scanning.stdib in\n let a = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let b = Scanf.bscanf sb \"%s \" (fun s -> s) in\n let c2i c = Char.code c - Char.code 'a' in\n let n = String.length a\n and m = String.length b in\n let inf = 1000000000 in\n let prev = Array.make_matrix 26 n 0 in\n let next = Array.make_matrix 26 n 0 in\n let p = Array.make 26 inf in\n let p' = Array.make 26 (-1) in\n let _ =\n for i = 0 to n - 1 do\n let c = c2i a.[i] in\n\tfor j = 0 to 25 do\n\t prev.(j).(i) <- p'.(j)\n\tdone;\n\tp'.(c) <- i;\n done;\n for i = n - 1 downto 0 do\n let c = c2i a.[i] in\n\tfor j = 0 to 25 do\n\t next.(j).(i) <- p.(j)\n\tdone;\n\tp.(c) <- i;\n done;\n in\n let d = Array.make m (-1) in\n let pos = ref p.(c2i b.[0]) in\n let _ =\n d.(0) <- !pos;\n for i = 1 to m - 1 do\n if !pos < inf then (\n\tlet c = c2i b.[i] in\n\t pos := next.(c).(!pos);\n );\n d.(i) <- !pos;\n done;\n in\n let d' = Array.make m (-1) in\n let _ =\n pos := p'.(c2i b.[m - 1]);\n d'.(m - 1) <- !pos;\n for i = m - 2 downto 0 do\n if !pos >= 0 then (\n\tlet c = c2i b.[i] in\n\t pos := prev.(c).(!pos);\n );\n d'.(i) <- !pos;\n done;\n in\n (*for i = 0 to m - 1 do\n Printf.printf \"asd %d %d\\n\" d.(i) d'.(i)\n done;*)\n let bl = ref (-1) in\n let br = ref m in\n let r = ref 0 in\n for l = 0 to m - 1 do\n while !r < m && d'.(!r) <= d.(l) do\n\tincr r;\n done;\n if d.(l) < m && !br - !bl > !r - l then (\n\tbr := !r;\n\tbl := l;\n )\n done;\n (*Printf.printf \"asd %d %d\\n\" !bl !br;*)\n let res = String.sub b 0 (!bl + 1) ^ String.sub b !br (m - !br) in\n if res = \"\"\n then Printf.printf \"-\\n\"\n else Printf.printf \"%s\\n\" res\n"}], "src_uid": "89aef6720eac7376ce0a657d46c3c5b7"} {"nl": {"description": "Andryusha is an orderly boy and likes to keep things in their place.Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time? ", "input_spec": "The first line contains the single integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009105)\u00a0\u2014 the number of sock pairs. The second line contains 2n integers x1,\u2009x2,\u2009...,\u2009x2n (1\u2009\u2264\u2009xi\u2009\u2264\u2009n), which describe the order in which Andryusha took the socks from the bag. More precisely, xi means that the i-th sock Andryusha took out was from pair xi. It is guaranteed that Andryusha took exactly two socks of each pair.", "output_spec": "Print single integer\u00a0\u2014 the maximum number of socks that were on the table at the same time.", "sample_inputs": ["1\n1 1", "3\n2 1 1 3 2 3"], "sample_outputs": ["1", "2"], "notes": "NoteIn the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.In the second example Andryusha behaved as follows: Initially the table was empty, he took out a sock from pair 2 and put it on the table. Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table. Socks (1,\u20092) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe. Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table. Socks (2,\u20093) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe. Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe. Thus, at most two socks were on the table at the same time."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = Array.init (2*n) read_int in\n\n let out = Array.make (2*n) false in\n\n let rec loop i nout maxout = if i=2*n then maxout else (\n let sock = x.(i)-1 in\n if out.(sock) then (\n out.(sock) <- false;\n loop (i+1) (nout-1) maxout\n ) else (\n out.(sock) <- true;\n loop (i+1) (nout+1) (max maxout (nout+1))\n )\n ) in\n\n printf \"%d\\n\" (loop 0 0 0)\n"}, {"source_code": "type state = Unseen | One | Both\n\nlet () =\n let n = Scanf.scanf \"%d\" (fun x -> x) in\n let pairs = Array.make (n + 1) Unseen in\n let on_table = ref 0 in\n let m = ref 0 in\n for i = 1 to 2*n do\n let k = Scanf.scanf \" %d\" (fun x -> x) in\n match pairs.(k) with\n | Unseen -> begin\n pairs.(k) <- One;\n incr on_table;\n m := max !m !on_table\n end\n | One -> begin\n pairs.(k) <- Both;\n decr on_table\n end\n | Both -> ()\n done;\n Printf.printf \"%d\\n\" !m\n"}], "negative_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet () = \n let n = read_int () in\n let x = Array.init n read_int in\n\n let out = Array.make n false in\n\n let rec loop i nout maxout = if i=n then maxout else (\n let sock = x.(i)-1 in\n if out.(sock) then (\n out.(sock) <- false;\n loop (i+1) (nout-1) maxout\n ) else (\n out.(sock) <- true;\n loop (i+1) (nout+1) (max maxout (nout+1))\n )\n ) in\n\n printf \"%d\\n\" (loop 0 0 0)\n"}], "src_uid": "7f98c9258f3e127a782041c421d6317b"} {"nl": {"description": "Petya has a string of length n consisting of small and large English letters and digits.He performs m operations. Each operation is described with two integers l and r and a character c: Petya removes from the string all characters c on positions between l and r, inclusive. It's obvious that the length of the string remains the same or decreases after each operation.Find how the string will look like after Petya performs all m operations.", "input_spec": "The first string contains two integers n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u20092\u00b7105) \u2014 the length of the string and the number of operations. The second line contains the string of length n, consisting of small and large English letters and digits. Positions in the string are enumerated from 1. Each of the next m lines contains two integers l and r (1\u2009\u2264\u2009l\u2009\u2264\u2009r), followed by a character c, which is a small or large English letter or a digit. This line describes one operation. It is guaranteed that r doesn't exceed the length of the string s before current operation.", "output_spec": "Print the string Petya will obtain after performing all m operations. If the strings becomes empty after all operations, print an empty line.", "sample_inputs": ["4 2\nabac\n1 3 a\n2 2 c", "3 2\nA0z\n1 3 0\n1 1 z", "10 4\nagtFrgF4aF\n2 5 g\n4 9 F\n1 5 4\n1 7 a", "9 5\naAAaBBccD\n1 4 a\n5 6 c\n2 3 B\n4 4 D\n2 3 A"], "sample_outputs": ["b", "Az", "tFrg4", "AB"], "notes": "NoteIn the first example during the first operation both letters 'a' are removed, so the string becomes \"bc\". During the second operation the letter 'c' (on the second position) is removed, and the string becomes \"b\".In the second example during the first operation Petya removes '0' from the second position. After that the string becomes \"Az\". During the second operations the string doesn't change."}, "positive_code": [{"source_code": "(* 6:40 *)\n\nlet parent v = v/2\nlet lc v = 2*v\nlet rc v = 2*v+1\n \nlet superceil n =\n let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in\n 1 + (loop (n-1) 0)\n\n(* segtree for computing the modified indices *)\n(* It's a set of variables for each position in the original\n string. 0 if it has been deleted, 1 otherwise *)\n \nlet make_indextree n =\n let nn = superceil n in\n let a = Array.make (2*nn) 0 in\n (nn,a)\n\nlet assign_index (nn,a) v x =\n (* do a(v) <- x *)\n let x = x - a.(nn+v) in\n let rec loop j = if j > 0 then (\n a.(j) <- a.(j) + x;\n loop (parent j)\n ) in\n loop (nn+v)\n\nlet get_index_var (nn,a) i = a.(nn+i)\n \n(* we don't need sum\nlet sum (nn,a) i j =\n let rec f v l r ql qr =\n let m = (l+r)/2 in\n if l=ql && r=qr then a.(v) else\n let t1 = if ql<=m then f (lc v) l m ql (min m qr) else 0 in\n let t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else 0 in\n t1 + t2\n in\n f 1 0 (nn-1) i j\n*)\n\nlet get_ith (nn,a) i =\n (* return the position of the ith non deleted char *)\n (* zero-based indexing is used throughout *)\n let rec loop k i = (* at node k looking for the ith *)\n if k >= nn then k-nn\n else if a.(lc k) > i\n then loop (lc k) i else loop (rc k) (i-a.(lc k))\n in\n loop 1 i\n\nlet ( ** ) a b = Int64.mul a b\nlet ( ++ ) a b = Int64.add a b\nlet ( -- ) a b = Int64.sub a b\nlet ( // ) a b = Int64.div a b\nlet ( %% ) a b = Int64.rem a b\nlet ( land ) a b = Int64.logand a b\nlet ( lor ) a b = Int64.logor a b\nlet ( lsl) a b = Int64.shift_left a b\nlet long x = Int64.of_int x\n\nlet make_findtree n =\n let nn = superceil n in\n let a = Array.make (2*nn) 0L in\n (nn,a)\n\nlet assign_find (nn,a) v ci add =\n(* v is an index, ci [0,63] is a char index we want to put into\n place v in the segtree This puts it there and propagates\n it up the tree. If add=true, then add it else remove it *)\n let rec loop j = if j > 0 then (\n a.(j) <- a.(lc j) lor a.(rc j);\n loop (parent j)\n ) in\n a.(nn+v) <- if add then 1L lsl ci else 0L;\n loop (parent (nn+v))\n\nlet make_index_list (nn,a) ci ql qr =\n(* return the index list of places where the char ci is stored\n restricted to the range [ql,qr] *)\n let mask = 1L lsl ci in\n let rec scan v l r ac =\n let m = (l+r)/2 in\n if a.(v) land mask = 0L then ac\n else if r < ql || l > qr then ac\n else if v >= nn then (v-nn)::ac\n else scan (lc v) l m (scan (rc v) (m+1) r ac)\n in\n scan 1 0 (nn-1) []\n\nlet char_index c =\n if '0' <= c && c <= '9' then (int_of_char c) - (int_of_char '0')\n else if 'a' <= c && c <= 'z' then 10 + (int_of_char c) - (int_of_char 'a')\n else if 'A' <= c && c <= 'Z' then 36 + (int_of_char c) - (int_of_char 'A')\n else failwith \"bad char\"\n\nopen Printf\nopen Scanf\n\nlet read_pair _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\nlet read_string _ = bscanf Scanning.stdib \" %s \" (fun x -> x)\nlet () =\n let (n,m) = read_pair() in\n let s = read_string() in\n let len = String.length s in\n\n let ft = make_findtree len in\n let it = make_indextree len in\n\n for i=0 to len-1 do\n assign_find ft i (char_index s.[i]) true;\n assign_index it i 1\n done;\n\n for q = 1 to m do\n let (l,r) = read_pair() in\n let c = (read_string()).[0] in\n let ci = char_index c in\n let l = get_ith it (l-1) in\n let r = get_ith it (r-1) in\n let il = make_index_list ft ci l r in\n List.iter (fun i -> assign_index it i 0) il;\n List.iter (fun i -> assign_find ft i 0 false) il;\n done;\n\n for i=0 to len-1 do\n if get_index_var it i = 1 then printf \"%c\" s.[i]\n done;\n print_newline()\n"}], "negative_code": [], "src_uid": "bb6e2f728e1c7e24d86c9352740dea38"} {"nl": {"description": "You have $$$n$$$ students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the $$$i$$$-th student skill is denoted by an integer $$$a_i$$$ (different students can have the same skills).So, about the teams. Firstly, these two teams should have the same size. Two more constraints: The first team should consist of students with distinct skills (i.e. all skills in the first team are unique). The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team.Consider some examples (skills are given): $$$[1, 2, 3]$$$, $$$[4, 4]$$$ is not a good pair of teams because sizes should be the same; $$$[1, 1, 2]$$$, $$$[3, 3, 3]$$$ is not a good pair of teams because the first team should not contain students with the same skills; $$$[1, 2, 3]$$$, $$$[3, 4, 4]$$$ is not a good pair of teams because the second team should contain students with the same skills; $$$[1, 2, 3]$$$, $$$[3, 3, 3]$$$ is a good pair of teams; $$$[5]$$$, $$$[6]$$$ is a good pair of teams. Your task is to find the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$ (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.You have to answer $$$t$$$ independent test cases.", "input_spec": "The first line of the input contains one integer $$$t$$$ ($$$1 \\le t \\le 10^4$$$) \u2014 the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) \u2014 the number of students. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le n$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th student. Different students can have the same skills. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \\cdot 10^5$$$ ($$$\\sum n \\le 2 \\cdot 10^5$$$).", "output_spec": "For each test case, print the answer \u2014 the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$.", "sample_inputs": ["4\n7\n4 2 4 1 4 3 4\n5\n2 1 5 4 3\n1\n1\n4\n1 1 1 3"], "sample_outputs": ["3\n1\n0\n2"], "notes": "NoteIn the first test case of the example, it is possible to construct two teams of size $$$3$$$: the first team is $$$[1, 2, 4]$$$ and the second team is $$$[4, 4, 4]$$$. Note, that there are some other ways to construct two valid teams of size $$$3$$$."}, "positive_code": [{"source_code": "(* Codeforces 1335 CTwo Teams Composing train *)\n \n(* you can use either gr or rdln but not both *)\nlet gr () = Scanf.scanf \" %d\" (fun i -> i);;\nlet grf () = Scanf.scanf \" %f\" (fun i -> i);;\nlet grl () = Scanf.scanf \" %Ld\" (fun i -> i);;\nlet rdln() = input_line stdin;;\n(* let spli s = Str.split (Str.regexp \" \") s;; *)\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printarri ai = Array.iter (fun i -> (print_int i; print_string \" \")) ai;;\nlet debug = false;;\n \n(* reading reversed list *)\nlet rec readlist n acc = match n with\n\t| 0 -> acc\n\t| _ -> readlist (n -1) (gr() :: acc);;\nlet printlisti li = List.iter (fun i -> (print_int i; print_string \" \")) li;;\nlet printlists ls = List.iter (fun s -> (print_string s; print_string \" \")) ls;;\n\nlet rec num_same cursm mxsm last l = match l with\n | [] -> mxsm\n | h :: t ->\n let n_cursm = if h==last then (cursm+1) else 1 in\n let n_mxsm = if n_cursm > mxsm then n_cursm else mxsm in\n num_same n_cursm n_mxsm h t;; \n\nlet rec num_diff dif last l = match l with\n | [] -> dif\n | h :: t ->\n let n_dif = if h != last then (dif + 1) else dif in\n num_diff n_dif h t;;\n \nlet do_one () = \n\tlet n = gr () in\n let a = readlist n [] in\n let a = List.sort compare a in\n let nsame = num_same 0 0 (-1) a in\n let ndiff = num_diff 0 (-1) a in\n (* let _ = Printf.printf \"same,dif = %d %d\\n\" nsame ndiff in *)\n let cmd = if nsame > ndiff then ndiff\n else if nsame < ndiff then nsame\n else nsame - 1 in\n Printf.printf \"%d\\n\" cmd;;\n \nlet do_all t = \n for i = 1 to t do\n do_one ()\n done;;\n \nlet main() =\n\tlet t = gr () in\n\tdo_all t;;\n \nmain();;"}], "negative_code": [], "src_uid": "a1951e7d11b504273765fc9fb2f18a5e"} {"nl": {"description": "On the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi,\u2009j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!", "input_spec": "The first line of input contains two integers, n and m (1\u2009\u2264\u2009n,\u2009m\u2009\u2264\u2009100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi,\u2009j (0\u2009\u2264\u2009gi,\u2009j\u2009\u2264\u2009500).", "output_spec": "If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1\u2009\u2264\u2009x\u2009\u2264\u2009n) describing a move of the form \"choose the x-th row\". col x, (1\u2009\u2264\u2009x\u2009\u2264\u2009m) describing a move of the form \"choose the x-th column\". If there are multiple optimal solutions, output any one of them.", "sample_inputs": ["3 5\n2 2 2 3 2\n0 0 0 1 0\n1 1 1 2 1", "3 3\n0 0 0\n0 1 0\n0 0 0", "3 3\n1 1 1\n1 1 1\n1 1 1"], "sample_outputs": ["4\nrow 1\nrow 1\ncol 4\nrow 3", "-1", "3\nrow 1\nrow 2\nrow 3"], "notes": "NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3."}, "positive_code": [{"source_code": "open Scanf;;\nscanf \"%d %d\\n\" (fun n m ->\n let mat=Array.make_matrix n m 0 in\n let set i j x= mat.(i).(j) <- x in\n for i=0 to n-1 do\n for j=0 to m-2 do\n scanf \"%d \" (set i j) \n done;\n scanf \"%d\\n\" (set i (m-1))\n done;\n let all_N' = List.fold_left (fun f x->f&&x>0) true in\n let rec r_to_list x j=\n if j=m then [] else mat.(x).(j) :: r_to_list x (j+1) in\n let rec c_to_list y i=\n if i=n then [] else mat.(i).(y) :: c_to_list y (i+1) in\n let test_r r=r_to_list r 0 |> all_N' in\n let test_c c=c_to_list c 0 |> all_N' in\n let do_r r=\n for j=0 to m-1 do\n mat.(r).(j)<-mat.(r).(j)-1\n done; \"row \"^(string_of_int (r+1)) in\n let do_c c=\n for i=0 to n-1 do\n mat.(i).(c)<-mat.(i).(c)-1\n done; \"col \"^(string_of_int (c+1)) in\n let solve() = \n let rec solve_r r acc=match test_r r with\n | true -> solve_r r (do_r r ::acc)\n | false -> if r=n-1 then acc else solve_r (r+1) acc in\n let rec solve_c c acc=match test_c c with\n | true -> solve_c c (do_c c ::acc)\n | false -> if c=m-1 then acc else solve_c (c+1) acc in\n if n>m then solve_r 0 [] @ solve_c 0 [] else solve_c 0 [] @ solve_r 0 [] in\n let flag_N'=ref false in\n let test_N'() = \n for i=0 to n-1 do\n for j=0 to m-1 do\n if mat.(i).(j)>0 then flag_N':=true\n done\n done in\n let write l=\n let rec print_list =function\n | [] -> ()\n | h :: t -> print_endline h;print_list t in\n print_int (List.length l);\n print_newline();\n print_list l in\n let ans=solve() in\n test_N'();\n if !flag_N' then print_endline \"-1\" else write ans\n)"}, {"source_code": "open Scanf;;\nscanf \"%d %d\" (fun n m ->\n let mat=Array.make_matrix n m 0 in\n for i=0 to n-1 do\n for j=0 to m-1 do\n scanf \" %d\" (fun x->mat.(i).(j) <- x)\n done;\n done;\n let all_N' =List.for_all (fun x->x>0) in \n let rec r_to_list x j=\n if j=m then [] else mat.(x).(j) :: r_to_list x (j+1) in\n let rec c_to_list y i=\n if i=n then [] else mat.(i).(y) :: c_to_list y (i+1) in\n let test_r r=r_to_list r 0 |> all_N' and test_c c=c_to_list c 0 |> all_N' in\n let dec i j = mat.(i).(j)<-mat.(i).(j)-1 in\n let do_r r=\n for j=0 to m-1 do\n dec r j\n done; \"row \"^(string_of_int (r+1))\n and do_c c=\n for i=0 to n-1 do\n dec i c\n done; \"col \"^(string_of_int (c+1)) in\n let solve() = \n let rec solve_r r acc=match test_r r with\n | true -> solve_r r (do_r r ::acc)\n | false -> if r=n-1 then acc else solve_r (r+1) acc\n and solve_c c acc=match test_c c with\n | true -> solve_c c (do_c c ::acc)\n | false -> if c=m-1 then acc else solve_c (c+1) acc in\n if n0 then flag_N':=true\n done\n done in\n let write l=\n let rec print_list =function\n | [] -> ()\n | h :: t -> print_endline h;print_list t in\n print_int (List.length l);\n print_newline();\n print_list l in\n let ans=solve() in\n test_N'();\n if !flag_N' then print_endline \"-1\" else write ans\n)"}], "negative_code": [{"source_code": "open Scanf;;\nscanf \"%d %d\\n\" (fun n m ->\n let mat=Array.make_matrix n m 0 in\n let set i j x= mat.(i).(j) <- x in\n for i=0 to n-1 do\n for j=0 to m-2 do\n scanf \"%d \" (set i j) \n done;\n scanf \"%d\\n\" (set i (m-1))\n done;\n let has_N' = List.fold_left (fun f x->f&&x>0) true in\n let rec r_to_list x j=\n if j=m-1 then [] else mat.(x).(j) :: r_to_list x (j+1) in\n let rec c_to_list y i=\n if i=n-1 then [] else mat.(i).(y) :: c_to_list y (i+1) in\n let test_r r=r_to_list r 0 |> has_N' in\n let test_c c=c_to_list c 0 |> has_N' in\n let do_r r=\n for j=0 to m-1 do\n mat.(r).(j)<-mat.(r).(j)-1\n done; \"row \"^(string_of_int (r+1)) in\n let do_c c=\n for i=0 to n-1 do\n mat.(i).(c)<-mat.(i).(c)-1\n done; \"col \"^(string_of_int (c+1)) in\n let do_point_rf r c =match test_r r, test_c c with\n | true ,_ -> do_r r\n | _ , true -> do_c c\n | _ ->raise Not_found in\n let do_point_cf r c =match test_r r, test_c c with\n | _ , true -> do_c c\n | true ,_ -> do_r r\n | _ ->raise Not_found in\n let do_point r c = if r (-1,-1)\n |r,c when c=m-1 -> (r+1,0)\n |r,c -> (r,c+1) in\n let test_point r c = mat.(r).(c)>0 in\n let solve() = \n let rec solve_inn r c acc=match test_point r c with\n | true -> solve_inn r c (do_point r c ::acc)\n | false -> \n match next (r,c) with\n | -1,-1 ->acc\n | nr,nc ->solve_inn nr nc acc in solve_inn 0 0 [] in\n let write l=\n let rec print_list =function\n | [] -> ()\n | h :: t -> print_endline h;print_list t in\n print_int (List.length l);\n print_newline();\n print_list l in\n try write (solve()) with\n Not_found -> print_endline \"-1\"\n)"}, {"source_code": "open Scanf;;\nscanf \"%d %d\\n\" (fun n m ->\n let mat=Array.make_matrix n m 0 in\n let set i j x= mat.(i).(j) <- x in\n for i=0 to n-1 do\n for j=0 to m-2 do\n scanf \"%d \" (set i j) \n done;\n scanf \"%d\\n\" (set i (m-1))\n done;\n let all_N' = List.fold_left (fun f x->f&&x>0) true in\n let rec r_to_list x j=\n if j=m then [] else mat.(x).(j) :: r_to_list x (j+1) in\n let rec c_to_list y i=\n if i=n then [] else mat.(i).(y) :: c_to_list y (i+1) in\n let test_r r=r_to_list r 0 |> all_N' in\n let test_c c=c_to_list c 0 |> all_N' in\n let do_r r=\n for j=0 to m-1 do\n mat.(r).(j)<-mat.(r).(j)-1\n done; \"row \"^(string_of_int (r+1)) in\n let do_c c=\n for i=0 to n-1 do\n mat.(i).(c)<-mat.(i).(c)-1\n done; \"col \"^(string_of_int (c+1)) in\n let solve() = \n let rec solve_r r acc=match test_r r with\n | true -> solve_r r (do_r r ::acc)\n | false -> if r=n-1 then acc else solve_r (r+1) acc in\n let rec solve_c c acc=match test_c c with\n | true -> solve_c c (do_c c ::acc)\n | false -> if c=m-1 then acc else solve_c (c+1) acc in\n if n0 then flag_N':=true\n done\n done in\n let write l=\n let rec print_list =function\n | [] -> ()\n | h :: t -> print_endline h;print_list t in\n print_int (List.length l);\n print_newline();\n print_list l in\n let ans=solve() in\n test_N'();\n if !flag_N' then print_endline \"-1\" else write ans\n)"}, {"source_code": "open Scanf;;\nscanf \"%d %d\\n\" (fun n m ->\n let mat=Array.make_matrix n m 0 in\n let set i j x= mat.(i).(j) <- x in\n for i=0 to n-1 do\n for j=0 to m-2 do\n scanf \"%d \" (set i j) \n done;\n scanf \"%d\\n\" (set i (m-1))\n done;\n let has_N' = List.fold_left (fun f x->f&&x>0) true in\n let rec r_to_list x j=\n if j=m-1 then [] else mat.(x).(j) :: r_to_list x (j+1) in\n let rec c_to_list y i=\n if i=n-1 then [] else mat.(i).(y) :: c_to_list y (i+1) in\n let test_r r=r_to_list r 0 |> has_N' in\n let test_c c=c_to_list c 0 |> has_N' in\n let do_r r=\n for j=0 to m-1 do\n mat.(r).(j)<-mat.(r).(j)-1\n done; \"row \"^(string_of_int (r+1)) in\n let do_c c=\n for i=0 to n-1 do\n mat.(i).(c)<-mat.(i).(c)-1\n done; \"col \"^(string_of_int (c+1)) in\n let do_point r c =match test_r r, test_c c with\n | true ,_ -> do_r r\n | _ , true -> do_c c\n | _ ->raise Not_found in\n let next =function\n |r,c when r=n-1 && c=m-1 -> (-1,-1)\n |r,c when c=m-1 -> (r+1,0)\n |r,c -> (r,c+1) in\n let test_point r c = mat.(r).(c)>0 in\n let solve() = \n let rec solve_inn r c acc=match test_point r c with\n | true -> solve_inn r c (do_point r c ::acc)\n | false -> \n match next (r,c) with\n | -1,-1 ->acc\n | nr,nc ->solve_inn nr nc acc in solve_inn 0 0 [] in\n let write l=\n let rec print_list =function\n | [] -> ()\n | h :: t -> print_endline h;print_list t in\n print_int (List.length l);\n print_newline();\n print_list l in\n try write (solve()) with\n Not_found -> print_endline \"-1\"\n)"}], "src_uid": "b19ab2db46484f0c9b49cf261502bf64"} {"nl": {"description": "User ainta has a permutation p1,\u2009p2,\u2009...,\u2009pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1,\u2009a2,\u2009...,\u2009an is prettier than permutation b1,\u2009b2,\u2009...,\u2009bn, if and only if there exists an integer k (1\u2009\u2264\u2009k\u2009\u2264\u2009n) where a1\u2009=\u2009b1,\u2009a2\u2009=\u2009b2,\u2009...,\u2009ak\u2009-\u20091\u2009=\u2009bk\u2009-\u20091 and ak\u2009<\u2009bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n\u2009\u00d7\u2009n binary matrix A, user ainta can swap the values of pi and pj (1\u2009\u2264\u2009i,\u2009j\u2009\u2264\u2009n, i\u2009\u2260\u2009j) if and only if Ai,\u2009j\u2009=\u20091.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.", "input_spec": "The first line contains an integer n (1\u2009\u2264\u2009n\u2009\u2264\u2009300) \u2014 the size of the permutation p. The second line contains n space-separated integers p1,\u2009p2,\u2009...,\u2009pn \u2014 the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai,\u2009j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i,\u2009j where 1\u2009\u2264\u2009i\u2009<\u2009j\u2009\u2264\u2009n, Ai,\u2009j\u2009=\u2009Aj,\u2009i holds. Also, for all integers i where 1\u2009\u2264\u2009i\u2009\u2264\u2009n, Ai,\u2009i\u2009=\u20090 holds.", "output_spec": "In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.", "sample_inputs": ["7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010"], "sample_outputs": ["1 2 4 3 6 7 5", "1 2 3 4 5"], "notes": "NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1,\u2009p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1,\u2009p3),\u2009(p4,\u2009p5),\u2009(p3,\u2009p4). A permutation p is a sequence of integers p1,\u2009p2,\u2009...,\u2009pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int () = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_string () = bscanf Scanning.stdib \" %s \" (fun x -> x)\n\nlet () = \n let n = read_int () in\n let p = Array.init n (fun _ -> read_int()) in\n let a = Array.make n \"\" in\n\n for i=0 to n-1 do\n a.(i) <- read_string()\n done;\n\n let s = Array.make n (-1) in (* the sets *)\n let size = Array.make n 1 in (* sizes of the sets *)\n\n let rec find i = if s.(i) < 0 then i else \n let r = find s.(i) in\n s.(i) <- r;\n r\n in\n\n let union i j = \n let (i,j) = ((find i), (find j)) in\n if i <> j then (\n\tlet (i,j) = if size.(i) < size.(j) then (i,j) else (j,i) in\n\ts.(i) <- j; (* union by rank *)\n\tsize.(j) <- size.(i) + size.(j);\n )\n in\n \n for i=0 to n-1 do\n for j=0 to n-1 do\n if a.(i).[j] = '1' then union i j\n done\n done;\n\n let sets = Array.make n [] in\n\n for i=0 to n-1 do\n let j = find i in\n sets.(j) <- p.(i)::sets.(j)\n done;\n\n for j=0 to n-1 do\n sets.(j) <- List.sort compare sets.(j)\n done;\n\n for i=0 to n-1 do\n let j = find i in\n printf \"%d \" (List.hd sets.(j));\n sets.(j) <- List.tl sets.(j)\n done;\n\n print_newline()\n"}], "negative_code": [], "src_uid": "a67ea891cd6084ceeaace8894cf18e60"} {"nl": {"description": "A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?", "input_spec": "The first line contains integer n (1\u2009\u2264\u2009n\u2009\u2264\u20092000) \u2014 the number of employees. The next n lines contain the integers pi (1\u2009\u2264\u2009pi\u2009\u2264\u2009n or pi\u2009=\u2009-1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi\u2009\u2260\u2009i). Also, there will be no managerial cycles.", "output_spec": "Print a single integer denoting the minimum number of groups that will be formed in the party.", "sample_inputs": ["5\n-1\n1\n2\n1\n-1"], "sample_outputs": ["3"], "notes": "NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5 "}, "positive_code": [{"source_code": "type tree = Leaf of int\n | Node of tree list\n\nlet rec makeList numList num =\n match numList with\n | h :: t -> (num, h) :: (makeList t (num+1))\n | _ -> []\n\nlet rec findOrigin numList =\n match numList with\n | (h, n) :: t -> if (n == -1) then h :: (findOrigin t)\n else findOrigin t\n | _ -> []\n\nlet rec findNum numList num = \n match numList with\n | (h, n) :: t -> if (n == num) then h :: (findNum t num)\n else findNum t num\n | _ -> []\n\n\nlet makeTree numList =\n let originList = findOrigin numList in\n let rec makeList nList =\n match nList with\n | h :: t ->\n let newList = findNum numList h in\n Node(Leaf(h) :: makeList newList) :: (makeList t)\n | _ -> [] in\n makeList originList\n\nlet nodeCount tree =\n let rec node tree count =\n match tree with\n | Node(h::t) :: tail ->\n let c = node (h::t) (count+1) in\n c @ (node tail count)\n | Leaf(h) :: t ->\n node t count\n | _ -> count ::[] in\n let countList = node tree 1 in\n let rec maxCount cList max =\n match cList with\n | h :: t -> if (max > h) then maxCount t max\n else maxCount t h\n | _ -> max in\n maxCount countList 1\n\nlet printLeaf leaf =\n match leaf with\n | Leaf(h) -> let _ = print_string (\"Leaf \") in\n let _ = print_int h in\n print_string \" \"\n | _ -> print_string \" \"\n\nlet rec printNode node =\n match node with\n | Node(h :: t) :: tail -> let _ = print_string (\"[Node \") in\n let _ = printLeaf h in\n let _ = printNode t in\n let _ = print_string \"] \" in\n printNode tail\n | Leaf(h) :: tail -> let _ = printLeaf (Leaf(h)) in\n printNode tail\n | _ -> print_string \" \"\n\nlet num = read_int()\n\nlet rec inputList num =\n if (num != 0) then \n let k = read_int() in\n k :: (inputList (num-1))\n else\n []\nlet numList = makeList (inputList num) 1\nlet k = makeTree numList\n(*let numList = makeList (-1::1::2::3::2::5::1::[]) 1\n\nlet k = makeTree numList\n\nlet _ = printNode k\n\nlet _ = print_string\"\\n\\n\"\n*)\nlet _ = print_int((nodeCount k)-1)\n\n\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\ntype 'a employee = 'a * 'a list (*int is employee's immediate manager; int list are her subordinates*)\n\nlet a = Array.make (n+1) (0,[]);;\n\nlet manager (z:int employee) =\n match z with\n | (i,_) -> i\n\nlet subo (z:int employee) = \n match z with\n | (_,il) -> il\n\nlet adds (t:int employee) x = \n match t with\n (_,z) -> x::z\n\nfor i = 1 to n do\n let j = Scanf.scanf \"%d \" ( fun x -> x ) in\n if j = -1 then\n begin\n let il = subo a.(i) in\n let i2 = adds a.(0) i in\n a.(i) <- (manager a.(i),il); a.(0) <- (manager a.(0),i2)\n end\n else\n begin\n a.(i) <- (j,subo a.(i)); a.(j) <- (manager a.(j), adds a.(j) i)\n end\ndone\n\n(*\nlet printe (z:int employee) =\n match z with \n | (i,il) -> printf \"%d \" i; List.iter (fun x -> printf \"%d \" x) il\n\nlet () = printe a.(11)\n\nlet () = print_endline \"\"\n*)\n\nlet rec height (z:int employee) =\n match z with\n |(_,[]) -> 1\n |(_,il) -> \n List.fold_right (fun x y -> max x y) \n ( List.map (fun i -> 1 + (height a.(i))) il) (-1)\nin\nlet m = height a.(0) in\nprintf \"%d\\n\" (m-1)\n\n\n"}], "negative_code": [{"source_code": "type tree = Leaf of int\n | Node of tree list\n\nlet rec makeList numList num =\n match numList with\n | h :: t -> (num, h) :: (makeList t (num+1))\n | _ -> []\n\nlet rec findOrigin numList =\n match numList with\n | (h, n) :: t -> if (n == -1) then h :: (findOrigin t)\n else findOrigin t\n | _ -> []\n\nlet rec findNum numList num = \n match numList with\n | (h, n) :: t -> if (n == num) then h :: (findNum t num)\n else findNum t num\n | _ -> []\n\n\nlet makeTree numList =\n let originList = findOrigin numList in\n let rec makeList nList =\n match nList with\n | h :: t ->\n let newList = findNum numList h in\n Node(Leaf(h) :: makeList newList) :: (makeList t)\n | _ -> [] in\n makeList originList\n\nlet nodeCount tree =\n let rec node tree count =\n match tree with\n | Node(h::t) :: tail ->\n let c = node (h::t) (count+1) in\n c @ (node tail count)\n | Leaf(h) :: t ->\n node t count\n | _ -> count ::[] in\n let countList = node tree 1 in\n let rec maxCount cList max =\n match cList with\n | h :: t -> if (max > h) then maxCount t max\n else maxCount t h\n | _ -> max in\n let rec printList m =\n match m with\n | h :: t -> let _ = print_int h in\n let _ = print_string \" \" in\n printList t\n | _ -> print_string \" \\n\\n\" in\n let _ = printList countList in\n maxCount countList 1\n\nlet printLeaf leaf =\n match leaf with\n | Leaf(h) -> let _ = print_string (\"Leaf \") in\n let _ = print_int h in\n print_string \" \"\n | _ -> print_string \" \"\n\nlet rec printNode node =\n match node with\n | Node(h :: t) :: tail -> let _ = print_string (\"[Node \") in\n let _ = printLeaf h in\n let _ = printNode t in\n let _ = print_string \"] \" in\n printNode tail\n | Leaf(h) :: tail -> let _ = printLeaf (Leaf(h)) in\n printNode tail\n | _ -> print_string \" \"\n\nlet num = read_int()\n\nlet rec inputList num =\n if (num != 0) then \n let k = read_int() in\n k :: (inputList (num-1))\n else\n []\nlet numList = makeList (inputList num) 1\nlet k = makeTree numList\n(*let numList = makeList (-1::1::2::3::2::5::1::[]) 1\n\nlet k = makeTree numList\n\nlet _ = printNode k\n\nlet _ = print_string\"\\n\\n\"\n*)\nlet _ = print_int((nodeCount k)-1)\n\n\n"}, {"source_code": "type tree = Leaf of int\n | Node of tree list\n\nlet rec makeList numList num =\n match numList with\n | h :: t -> (num, h) :: (makeList t (num+1))\n | _ -> []\n\nlet rec findOrigin numList =\n match numList with\n | (h, n) :: t -> if (n == -1) then h :: (findOrigin t)\n else findOrigin t\n | _ -> []\n\nlet rec findNum numList num = \n match numList with\n | (h, n) :: t -> if (n == num) then h :: (findNum t num)\n else findNum t num\n | _ -> []\n\n\nlet makeTree numList =\n let originList = findOrigin numList in\n let rec makeList nList =\n match nList with\n | h :: t ->\n let newList = findNum numList h in\n Node(Leaf(h) :: makeList newList) :: (makeList t)\n | _ -> [] in\n makeList originList\n\nlet nodeCount tree =\n let rec node tree count =\n match tree with\n | Node(h::t) :: tail ->\n let c = node t count in\n c @ (node t (count+1))\n | _ -> count ::[] in\n let countList = node tree 1 in\n let rec maxCount cList max =\n match cList with\n | h :: t -> if (max > h) then maxCount t max\n else maxCount t h\n | _ -> max in\n maxCount countList 1\n\nlet printLeaf leaf =\n match leaf with\n | Leaf(h) -> let _ = print_string (\"Leaf \") in\n let _ = print_int h in\n print_string \" \"\n | _ -> print_string \" \"\n\nlet rec printNode node =\n match node with\n | Node(h :: t) :: tail -> let _ = print_string (\"[Node \") in\n let _ = printLeaf h in\n let _ = printNode t in\n let _ = print_string \"] \" in\n printNode tail\n | Leaf(h) :: tail -> let _ = printLeaf (Leaf(h)) in\n printNode tail\n | _ -> print_string \" \"\n\nlet num = read_int()\n\nlet rec inputList num =\n if (num != 0) then \n let k = read_int() in\n k :: (inputList (num-1))\n else\n []\nlet numList = makeList (inputList num) 1\nlet k = makeTree numList\n\n(*let numList = makeList (-1::1::2::3::2::5::1::[]) 1\n\nlet k = makeTree numList\n\nlet _ = printNode k\n\nlet _ = print_string\"\\n\\n\"\n*)\nlet _ = print_int((nodeCount k)-1)\n\n\n"}, {"source_code": "open Scanf\nopen Printf\n\nlet n = Scanf.scanf \"%d \" ( fun x -> x )\n\ntype 'a employee = 'a * 'a list (*int is employee's immediate manager; int list are her subordinates*)\n\nlet a = Array.make (n+1) (0,[]);;\n\nlet manager (z:int employee) =\n match z with\n | (i,_) -> i\n\nlet subo (z:int employee) = \n match z with\n | (_,il) -> il\n\nlet adds (t:int employee) x = \n match t with\n (_,z) -> x::z\n\nfor i = 1 to n do\n let j = Scanf.scanf \"%d \" ( fun x -> x ) in\n if j = -1 then\n begin\n let il = subo a.(i) in\n let i2 = adds a.(0) i in\n a.(i) <- (0,il); a.(0) <- (0,i2)\n end\n else\n begin\n a.(i) <- (j,[]); a.(j) <- (manager a.(j), adds a.(j) i)\n end\ndone\n\n(*\nlet printe (z:int employee) =\n match z with \n | (i,il) -> printf \"%d \" i; List.iter (fun x -> printf \"%d \" x) il\n\nlet () = printe a.(0)\n*)\n\nlet rec height (z:int employee) =\n match z with\n |(_,[]) -> 1\n |(_,il) -> \n List.fold_right (fun x y -> max x y) \n ( List.map (fun i -> 1 + (height a.(i))) il) (-1)\nin\nlet m = height a.(0) in\nprintf \"%d\\n\" (m-1)\n\n\n"}], "src_uid": "8d911f79dde31f2c6f62e73b925e6996"} {"nl": {"description": "For a vector $$$\\vec{v} = (x, y)$$$, define $$$|v| = \\sqrt{x^2 + y^2}$$$.Allen had a bit too much to drink at the bar, which is at the origin. There are $$$n$$$ vectors $$$\\vec{v_1}, \\vec{v_2}, \\cdots, \\vec{v_n}$$$. Allen will make $$$n$$$ moves. As Allen's sense of direction is impaired, during the $$$i$$$-th move he will either move in the direction $$$\\vec{v_i}$$$ or $$$-\\vec{v_i}$$$. In other words, if his position is currently $$$p = (x, y)$$$, he will either move to $$$p + \\vec{v_i}$$$ or $$$p - \\vec{v_i}$$$.Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position $$$p$$$ satisfies $$$|p| \\le 1.5 \\cdot 10^6$$$ so that he can stay safe.", "input_spec": "The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 10^5$$$)\u00a0\u2014 the number of moves. Each of the following lines contains two space-separated integers $$$x_i$$$ and $$$y_i$$$, meaning that $$$\\vec{v_i} = (x_i, y_i)$$$. We have that $$$|v_i| \\le 10^6$$$ for all $$$i$$$.", "output_spec": "Output a single line containing $$$n$$$ integers $$$c_1, c_2, \\cdots, c_n$$$, each of which is either $$$1$$$ or $$$-1$$$. Your solution is correct if the value of $$$p = \\sum_{i = 1}^n c_i \\vec{v_i}$$$, satisfies $$$|p| \\le 1.5 \\cdot 10^6$$$. It can be shown that a solution always exists under the given constraints.", "sample_inputs": ["3\n999999 0\n0 999999\n999999 0", "1\n-824590 246031", "8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899"], "sample_outputs": ["1 1 -1", "1", "1 1 1 1 1 1 1 -1"], "notes": null}, "positive_code": [{"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = Scanf.scanf \"%d\" (fun x -> x);;\ntype sgn = POS | NEG;;\nlet mul x y = match (x, y) with\n\t| (POS, x) -> x\n\t| (NEG, POS) -> NEG\n\t| (NEG, NEG) -> POS\n;;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * (sgn * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tlet x = scan_int() in\n\t\tlet y = scan_int() in\n\t\tLeaf((x, y), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), (POS, (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), (NEG, (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tif (r (plus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((plus x y), (POS, (a, b)))::c::l)\n\t\telse if (r (plus x z)) <= 1000000000000L then\n\t\t\tfix (Combine((plus x z), (POS, (a, c)))::b::l)\n\t\telse if (r (plus y z)) <= 1000000000000L then\n\t\t\tfix (Combine((plus y z), (POS, (b, c)))::a::l)\n\t\telse if (r (minus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((minus x y), (NEG, (a, b)))::c::l)\n\t\telse if (r (minus x z)) <= 1000000000000L then\n\t\t\tfix (Combine((minus x z), (NEG, (a, c)))::b::l)\n\t\telse if (r (minus y z)) <= 1000000000000L then\n\t\t\tfix (Combine((minus y z), (NEG, (b, c)))::a::l)\n\t\telse\n\t\t\tfailwith \"lochas\"\n\t)\n;;\nlet ret = Array.make n NEG;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (match w with POS -> (ret.(i) <- POS) | NEG -> ())\n\t| Combine(_, (w2, (l1, l2))) -> find w l1;find (mul w w2) l2\n;;\nlet c = fix (read 0);;\nlet (x, y) = xy c;;\nfind POS c;;\nArray.iter (fun x -> match x with POS -> puts \"1 \" | NEG -> puts \"-1 \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = Scanf.scanf \"%d\" (fun x -> x);;\ntype sgn = POS | NEG;;\nlet mul x y = match (x, y) with\n\t| (POS, x) -> x\n\t| (NEG, POS) -> NEG\n\t| (NEG, NEG) -> POS\n;;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * (sgn * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tlet x = scan_int() in\n\t\tlet y = scan_int() in\n\t\tLeaf((x, y), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), (POS, (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), (NEG, (a, b)))\n\t| a::b::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tif (r (plus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((plus x y), (POS, (a, b)))::l)\n\t\telse if (r (minus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((minus x y), (NEG, (a, b)))::l)\n\t\telse (\n\t\t\tlet c::l = l in\n\t\t\tlet z = xy c in\n\t\t\tif (r (plus x z)) <= 1000000000000L then\n\t\t\t\tfix (Combine((plus x z), (POS, (a, c)))::b::l)\n\t\t\telse if (r (minus x z)) <= 1000000000000L then\n\t\t\t\tfix (Combine((minus x z), (NEG, (a, c)))::b::l)\n\t\t\telse \n\t\t\t\tfix ((\n\t\t\t\t\tif (r (plus y z)) <= 1000000000000L then \n\t\t\t\t\t\tCombine((plus y z), (POS, (b, c)))\n\t\t\t\t\telse\n\t\t\t\t\t\tCombine((minus y z), (NEG, (b, c)))\n\t\t\t\t)::a::l)\n\t\t)\n\t)\n;;\nlet ret = Array.make n NEG;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (match w with POS -> (ret.(i) <- POS) | NEG -> ())\n\t| Combine(_, (w2, (l1, l2))) -> find w l1;find (mul w w2) l2\n;;\nfind POS (fix (read 0));;\nArray.iter (fun x -> match x with POS -> puts \"1 \" | NEG -> puts \"-1 \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = Scanf.scanf \"%d\" (fun x -> x);;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * (int * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tlet x = scan_int() in\n\t\tlet y = scan_int() in\n\t\tLeaf((x, y), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), (1, (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), (-1, (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tif (r (plus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((plus x y), (1, (a, b)))::c::l)\n\t\telse if (r (plus x z)) <= 1000000000000L then\n\t\t\tfix (Combine((plus x z), (1, (a, c)))::b::l)\n\t\telse if (r (plus y z)) <= 1000000000000L then\n\t\t\tfix (Combine((plus y z), (1, (b, c)))::a::l)\n\t\telse if (r (minus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((minus x y), (-1, (a, b)))::c::l)\n\t\telse if (r (minus x z)) <= 1000000000000L then\n\t\t\tfix (Combine((minus x z), (-1, (a, c)))::b::l)\n\t\telse if (r (minus y z)) <= 1000000000000L then\n\t\t\tfix (Combine((minus y z), (-1, (b, c)))::a::l)\n\t\telse\n\t\t\tfailwith \"lochas\"\n\t)\n;;\nlet ret = Array.make n 0;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, (w2, (l1, l2))) -> find w l1;find (w * w2) l2\n;;\nlet c = fix (read 0);;\nlet (x, y) = xy c;;\nfind 1 c;;\nArray.iter (fun x -> print_int x;puts \" \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = Scanf.scanf \"%d\" (fun x -> x);;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * (int * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tlet x = scan_int() in\n\t\tlet y = scan_int() in\n\t\tLeaf((x, y), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), (1, (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), (-1, (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tlet rxyp = r (plus x y) in\n\t\tlet rxzp = r (plus x z) in\n\t\tlet ryzp = r (plus y z) in\n\t\tlet rxym = r (minus x y) in\n\t\tlet rxzm = r (minus x z) in\n\t\tlet ryzm = r (minus y z) in\n\t\tlet rmin = min [rxyp; rxzp; ryzp; rxym; rxzm; ryzm] in\n\t\tif rxyp = rmin then\n\t\t\tfix (Combine((plus x y), (1, (a, b)))::c::l)\n\t\telse if rxzp = rmin then\n\t\t\tfix (Combine((plus x z), (1, (a, c)))::b::l)\n\t\telse if ryzp = rmin then\n\t\t\tfix (Combine((plus y z), (1, (b, c)))::a::l)\n\t\telse if rxym = rmin then\n\t\t\tfix (Combine((minus x y), (-1, (a, b)))::c::l)\n\t\telse if rxzm = rmin then\n\t\t\tfix (Combine((minus x z), (-1, (a, c)))::b::l)\n\t\telse if ryzm = rmin then\n\t\t\tfix (Combine((minus y z), (-1, (b, c)))::a::l)\n\t\telse\n\t\t\tfailwith \"lochas\"\n\t)\n;;\nlet ret = Array.make n 0;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, (w2, (l1, l2))) -> find w l1;find (w * w2) l2\n;;\nlet c = fix (read 0);;\nlet (x, y) = xy c;;\nfind 1 c;;\nArray.iter (fun x -> print_int x;puts \" \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = Scanf.scanf \"%d\" (fun x -> x);;\ntype sgn = POS | NEG;;\nlet mul x y = match (x, y) with\n\t| (POS, x) -> x\n\t| (NEG, POS) -> NEG\n\t| (NEG, NEG) -> POS\n;;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * (sgn * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tlet x = scan_int() in\n\t\tlet y = scan_int() in\n\t\tLeaf((x, y), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), (POS, (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), (NEG, (a, b)))\n\t| a::b::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tif (r (plus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((plus x y), (POS, (a, b)))::l)\n\t\telse if (r (minus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((minus x y), (NEG, (a, b)))::l)\n\t\telse (\n\t\t\tlet c::l = l in\n\t\t\tlet z = xy c in\n\t\t\tif (r (plus x z)) <= 1000000000000L then\n\t\t\t\tfix (Combine((plus x z), (POS, (a, c)))::b::l)\n\t\t\telse if (r (minus x z)) <= 1000000000000L then\n\t\t\t\tfix (Combine((minus x z), (NEG, (a, c)))::b::l)\n\t\t\telse if (r (plus y z)) <= 1000000000000L then\n\t\t\t\tfix (Combine((plus y z), (POS, (b, c)))::a::l)\n\t\t\telse if (r (minus y z)) <= 1000000000000L then\n\t\t\t\tfix (Combine((minus y z), (NEG, (b, c)))::a::l)\n\t\t\telse\n\t\t\t\tfailwith \"lochas\"\n\t\t)\n\t)\n;;\nlet ret = Array.make n NEG;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (match w with POS -> (ret.(i) <- POS) | NEG -> ())\n\t| Combine(_, (w2, (l1, l2))) -> find w l1;find (mul w w2) l2\n;;\nfind POS (fix (read 0));;\nArray.iter (fun x -> match x with POS -> puts \"1 \" | NEG -> puts \"-1 \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = Scanf.scanf \"%d\" (fun x -> x);;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * (int * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tlet x = scan_int() in\n\t\tlet y = scan_int() in\n\t\tLeaf((x, y), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), (1, (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), (-1, (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tif (r (plus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((plus x y), (1, (a, b)))::c::l)\n\t\telse if (r (plus x z)) <= 1000000000000L then\n\t\t\tfix (Combine((plus x z), (1, (a, c)))::b::l)\n\t\telse if (r (plus y z)) <= 1000000000000L then\n\t\t\tfix (Combine((plus y z), (1, (b, c)))::a::l)\n\t\telse if (r (minus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((minus x y), (-1, (a, b)))::c::l)\n\t\telse if (r (minus x z)) <= 1000000000000L then\n\t\t\tfix (Combine((minus x z), (-1, (a, c)))::b::l)\n\t\telse if (r (minus y z)) <= 1000000000000L then\n\t\t\tfix (Combine((minus y z), (-1, (b, c)))::a::l)\n\t\telse\n\t\t\tfailwith \"lochas\"\n\t)\n;;\nlet ret = Array.make n 0;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, (w2, (l1, l2))) -> find w l1;find (w * w2) l2\n;;\nlet c = fix (read 0);;\nlet (x, y) = xy c;;\nfind 1 c;;\nArray.iter (fun x -> if x = 1 then puts \"1 \" else puts \"-1 \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nopen Printf\nopen Scanf\nlet scan_int() = bscanf Scanning.stdib \" %d \" (fun x -> x);;\nlet print_int x = printf \"%d\" x;;\nlet puts s = printf s;;\nlet n = scanf \"%d\" (fun x -> x);;\ntype sgn = POS | NEG;;\nlet mul x y = match (x, y) with\n\t| (POS, x) -> x\n\t| (NEG, POS) -> NEG\n\t| (NEG, NEG) -> POS\n;;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * (sgn * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tlet x = scan_int() in\n\t\tlet y = scan_int() in\n\t\tLeaf((x, y), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), (POS, (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), (NEG, (a, b)))\n\t| a::b::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tif (r (plus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((plus x y), (POS, (a, b)))::l)\n\t\telse if (r (minus x y)) <= 1000000000000L then\n\t\t\tfix (Combine((minus x y), (NEG, (a, b)))::l)\n\t\telse (\n\t\t\tlet c::l = l in\n\t\t\tlet z = xy c in\n\t\t\tif (r (plus x z)) <= 1000000000000L then\n\t\t\t\tfix (Combine((plus x z), (POS, (a, c)))::b::l)\n\t\t\telse if (r (minus x z)) <= 1000000000000L then\n\t\t\t\tfix (Combine((minus x z), (NEG, (a, c)))::b::l)\n\t\t\telse \n\t\t\t\tfix ((\n\t\t\t\t\tif (r (plus y z)) <= 1000000000000L then \n\t\t\t\t\t\tCombine((plus y z), (POS, (b, c)))\n\t\t\t\t\telse\n\t\t\t\t\t\tCombine((minus y z), (NEG, (b, c)))\n\t\t\t\t)::a::l)\n\t\t)\n\t)\n;;\nlet ret = Array.make n NEG;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (match w with POS -> (ret.(i) <- POS) | NEG -> ())\n\t| Combine(_, (w2, (l1, l2))) -> find w l1;find (mul w w2) l2\n;;\nfind POS (fix (read 0));;\nArray.iter (fun x -> match x with POS -> puts \"1 \" | NEG -> puts \"-1 \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = Scanf.scanf \"%d\" (fun x -> x);;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * ((int * int) * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tlet x = scan_int() in\n\t\tlet y = scan_int() in\n\t\tLeaf((x, y), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> Leaf((-1, -1), -1)\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), ((1, 1), (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), ((1, -1), (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tlet rxyp = r (plus x y) in\n\t\tlet rxzp = r (plus x z) in\n\t\tlet ryzp = r (plus y z) in\n\t\tlet rxym = r (minus x y) in\n\t\tlet rxzm = r (minus x z) in\n\t\tlet ryzm = r (minus y z) in\n\t\tlet rmin = min [rxyp; rxzp; ryzp; rxym; rxzm; ryzm] in\n\t\tif rxyp = rmin then\n\t\t\tfix (Combine((plus x y), ((1, 1), (a, b)))::c::l)\n\t\telse if rxzp = rmin then\n\t\t\tfix (Combine((plus x z), ((1, 1), (a, c)))::b::l)\n\t\telse if ryzp = rmin then\n\t\t\tfix (Combine((plus y z), ((1, 1), (b, c)))::a::l)\n\t\telse if rxym = rmin then\n\t\t\tfix (Combine((minus x y), ((1, -1), (a, b)))::c::l)\n\t\telse if rxzm = rmin then\n\t\t\tfix (Combine((minus x z), ((1, -1), (a, c)))::b::l)\n\t\telse if ryzm = rmin then\n\t\t\tfix (Combine((minus y z), ((1, -1), (b, c)))::a::l)\n\t\telse\n\t\t\tfailwith \"lochas\"\n\t)\n;;\nlet ret = Array.make n 0;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, ((w1, w2), (l1, l2))) -> find (w * w1) l1;find (w * w2) l2\n;;\nlet rec check l = match l with\n\t| Leaf((x,y), i) -> puts \"(\";print_int y;puts \")\";\n\t| Combine((x, y), ((w1, w2), (l1, l2)))-> \n\tputs \"(\";\n\tcheck l1;\n\tputs (if(w2==1) then \"+\" else \"-\");\n\tcheck l2;\n\tputs \")\";\n;;\nlet c = fix (read 0);;\nif r (xy c) > (Int64.mul 1500000L 1500000L)\n\tthen failwith \"Oh shit\";;\nlet (x, y) = xy c;;\n(*Printf.printf \"%d %d\\n\" x y;;\nputs \"\\n\";\ncheck c;;*)\nfind 1 c;;\nArray.iter (fun x -> print_int x;puts \" \") ret;;"}], "negative_code": [{"source_code": "(*input\n8\n1000000 0\n0 1000000\n1000000 0\n0 1000000\n1000000 0\n0 1000000\n1000000 0\n0 1000000\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = scan_int();;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * ((int * int) * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tLeaf((scan_int(), scan_int()), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a < c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> Leaf((-1, -1), -1)\n\t| [Leaf(x, y)] -> Leaf(x, y)\n\t| [Combine(x, y)] -> Combine(x, y)\n\t| a::b::[] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), ((1, 1), (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), ((1, -1), (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tlet rxyp = r (plus x y) in\n\t\tlet rxzp = r (plus x z) in\n\t\tlet ryzp = r (plus y z) in\n\t\tlet rxym = r (minus x y) in\n\t\tlet rxzm = r (minus x z) in\n\t\tlet ryzm = r (minus y z) in\n\t\tlet rmin = min [rxyp; rxzp; ryzp; rxym; rxzm; ryzm] in\n\t\tif rxyp = rmin then\n\t\t\tfix (Combine((plus x y), ((1, 1), (a, b)))::c::l)\n\t\telse if rxzp = rmin then\n\t\t\tfix (Combine((plus x z), ((1, 1), (a, c)))::b::l)\n\t\telse if ryzp = rmin then\n\t\t\tfix (Combine((plus y z), ((1, 1), (b, c)))::a::l)\n\t\telse if rxym = rmin then\n\t\t\tfix (Combine((minus x y), ((1, -1), (a, b)))::c::l)\n\t\telse if rxzm = rmin then\n\t\t\tfix (Combine((minus x z), ((1, -1), (a, c)))::b::l)\n\t\telse\n\t\t\tfix (Combine((minus y z), ((1, -1), (b, c)))::a::l)\n\t)\n;;\nlet ret = Array.make n 1;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, ((w1, w2), (l1, l2))) -> find (w * w1) l1;find (w * w2) l2 \n;;\nlet c = fix (read 0);;\nif r (xy c) > (Int64.mul 1500000L 1500000L)\n\tthen failwith \"Oh shit\";;\nfind 1 c;;\nArray.iter (fun x -> print_int x;puts \" \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = scan_int();;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * ((int * int) * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tLeaf((scan_int(), scan_int()), i)::(read (i + 1));;\nlet r (x, y) = x * x + y * y;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list minimum\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a < c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> Leaf((-1, -1), -1)\n\t| [Leaf(x, y)] -> Leaf(x, y)\n\t| [Combine(x, y)] -> Combine(x, y)\n\t| a::b::[] -> \n\t\tif (r (plus (xy a) (xy b))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), ((1, 1), (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), ((1, -1), (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tlet rxyp = r (plus x y) in\n\t\tlet rxzp = r (plus x z) in\n\t\tlet ryzp = r (plus y z) in\n\t\tlet rxym = r (minus x y) in\n\t\tlet rxzm = r (minus x z) in\n\t\tlet ryzm = r (minus y z) in\n\t\tlet rmin = min [rxyp; rxzp; ryzp; rxym; rxzm; ryzm] in\n\t\tif rxyp = rmin then\n\t\t\tfix (Combine((plus x y), ((1, 1), (a, b)))::c::l)\n\t\telse if rxzp = rmin then\n\t\t\tfix (Combine((plus x z), ((1, 1), (a, c)))::b::l)\n\t\telse if ryzp = rmin then\n\t\t\tfix (Combine((plus y z), ((1, 1), (b, c)))::a::l)\n\t\telse if rxym = rmin then\n\t\t\tfix (Combine((minus x y), ((1, -1), (a, b)))::c::l)\n\t\telse if rxzm = rmin then\n\t\t\tfix (Combine((minus x z), ((1, -1), (a, c)))::b::l)\n\t\telse\n\t\t\tfix (Combine((minus y z), ((1, -1), (b, c)))::a::l)\n\t)\n;;\nlet ret = Array.make n 1;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, ((w1, w2), (l1, l2))) -> find (w * w1) l1;find (w * w2) l2 \n;;\nfind 1 (fix (read 0));;\nArray.iter (fun x -> print_int x;puts \" \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = scan_int();;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * ((int * int) * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tLeaf((scan_int(), scan_int()), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a < c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> Leaf((-1, -1), -1)\n\t| [Leaf(x, y)] -> Leaf(x, y)\n\t| [Combine(x, y)] -> Combine(x, y)\n\t| a::b::[] -> \n\t\tif (r (plus (xy a) (xy b))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), ((1, 1), (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), ((1, -1), (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tlet rxyp = r (plus x y) in\n\t\tlet rxzp = r (plus x z) in\n\t\tlet ryzp = r (plus y z) in\n\t\tlet rxym = r (minus x y) in\n\t\tlet rxzm = r (minus x z) in\n\t\tlet ryzm = r (minus y z) in\n\t\tlet rmin = min [rxyp; rxzp; ryzp; rxym; rxzm; ryzm] in\n\t\tif rxyp = rmin then\n\t\t\tfix (Combine((plus x y), ((1, 1), (a, b)))::c::l)\n\t\telse if rxzp = rmin then\n\t\t\tfix (Combine((plus x z), ((1, 1), (a, c)))::b::l)\n\t\telse if ryzp = rmin then\n\t\t\tfix (Combine((plus y z), ((1, 1), (b, c)))::a::l)\n\t\telse if rxym = rmin then\n\t\t\tfix (Combine((minus x y), ((1, -1), (a, b)))::c::l)\n\t\telse if rxzm = rmin then\n\t\t\tfix (Combine((minus x z), ((1, -1), (a, c)))::b::l)\n\t\telse\n\t\t\tfix (Combine((minus y z), ((1, -1), (b, c)))::a::l)\n\t)\n;;\nlet ret = Array.make n 1;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, ((w1, w2), (l1, l2))) -> find (w * w1) l1;find (w * w2) l2 \n;;\nlet c = fix (read 0);;\nlet (x, y) = xy c;;\nPrintf.eprintf \"%d %d\\n\" x y;;\nfind 1 c;;\nArray.iter (fun x -> print_int x;puts \" \") ret;;"}, {"source_code": "(*input\n29\n-613226 -227707\n792237 219301\n-751961 -552208\n-735407 -381381\n650764 -404462\n413131 907455\n-262161 -747347\n-428939 470614\n664354 659984\n-290291 1532\n92915 -821135\n-30613 -930254\n260114 958879\n463417 -576361\n-262253 400445\n-789867 129047\n47749 -851008\n-584972 -453671\n-737269 -24930\n807411 -34487\n-213137 347345\n848053 -522014\n460897 -28204\n-466335 -264003\n293691 -180751\n808540 -399397\n-221574 869266\n253114 264291\n25466 377868\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = scan_int();;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * ((int * int) * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tLeaf((scan_int(), scan_int()), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> Leaf((-1, -1), -1)\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), ((1, 1), (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), ((1, -1), (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tlet rxyp = r (plus x y) in\n\t\tlet rxzp = r (plus x z) in\n\t\tlet ryzp = r (plus y z) in\n\t\tlet rxym = r (minus x y) in\n\t\tlet rxzm = r (minus x z) in\n\t\tlet ryzm = r (minus y z) in\n\t\tlet rmin = min [rxyp; rxzp; ryzp; rxym; rxzm; ryzm] in\n\t\tif rxyp = rmin then\n\t\t\tfix (Combine((plus x y), ((1, 1), (a, b)))::c::l)\n\t\telse if rxzp = rmin then\n\t\t\tfix (Combine((plus x z), ((1, 1), (a, c)))::b::l)\n\t\telse if ryzp = rmin then\n\t\t\tfix (Combine((plus y z), ((1, 1), (b, c)))::a::l)\n\t\telse if rxym = rmin then\n\t\t\tfix (Combine((minus x y), ((1, -1), (a, b)))::c::l)\n\t\telse if rxzm = rmin then\n\t\t\tfix (Combine((minus x z), ((1, -1), (a, c)))::b::l)\n\t\telse if ryzm = rmin then\n\t\t\tfix (Combine((minus y z), ((1, -1), (b, c)))::a::l)\n\t\telse\n\t\t\tfailwith \"lochas\"\n\t)\n;;\nlet ret = Array.make n 1;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, ((w1, w2), (l1, l2))) -> find (w * w1) l1;find (w * w2) l2\n;;\nlet shuffle d =\n let nd = List.map (fun c -> (Random.bits (), c)) d in\n let sond = List.sort compare nd in\n List.map snd sond\nlet c = fix (shuffle (read 0));;\nif r (xy c) > (Int64.mul 1500000L 1500000L)\n\tthen failwith \"Oh shit\";;\nfind 1 c;;\nArray.iter (fun x -> print_int x;puts \" \") ret;;"}, {"source_code": "(*input\n29\n-613226 -227707\n792237 219301\n-751961 -552208\n-735407 -381381\n650764 -404462\n413131 907455\n-262161 -747347\n-428939 470614\n664354 659984\n-290291 1532\n92915 -821135\n-30613 -930254\n260114 958879\n463417 -576361\n-262253 400445\n-789867 129047\n47749 -851008\n-584972 -453671\n-737269 -24930\n807411 -34487\n-213137 347345\n848053 -522014\n460897 -28204\n-466335 -264003\n293691 -180751\n808540 -399397\n-221574 869266\n253114 264291\n25466 377868\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = scan_int();;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * ((int * int) * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tLeaf((scan_int(), scan_int()), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a <= c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> Leaf((-1, -1), -1)\n\t| [a] -> a\n\t| [a; b] -> \n\t\tif ((r (plus (xy a) (xy b)))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), ((1, 1), (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), ((1, -1), (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tlet rxyp = r (plus x y) in\n\t\tlet rxzp = r (plus x z) in\n\t\tlet ryzp = r (plus y z) in\n\t\tlet rxym = r (minus x y) in\n\t\tlet rxzm = r (minus x z) in\n\t\tlet ryzm = r (minus y z) in\n\t\tlet rmin = min [rxyp; rxzp; ryzp; rxym; rxzm; ryzm] in\n\t\tif rxyp = rmin then\n\t\t\tfix (Combine((plus x y), ((1, 1), (a, b)))::c::l)\n\t\telse if rxzp = rmin then\n\t\t\tfix (Combine((plus x z), ((1, 1), (a, c)))::b::l)\n\t\telse if ryzp = rmin then\n\t\t\tfix (Combine((plus y z), ((1, 1), (b, c)))::a::l)\n\t\telse if rxym = rmin then\n\t\t\tfix (Combine((minus x y), ((1, -1), (a, b)))::c::l)\n\t\telse if rxzm = rmin then\n\t\t\tfix (Combine((minus x z), ((1, -1), (a, c)))::b::l)\n\t\telse if ryzm = rmin then\n\t\t\tfix (Combine((minus y z), ((1, -1), (b, c)))::a::l)\n\t\telse\n\t\t\tfailwith \"lochas\"\n\t)\n;;\nlet ret = Array.make n 1;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, ((w1, w2), (l1, l2))) -> find (w * w1) l1;find (w * w2) l2\n;;\nlet c = fix (read 0);;\nif r (xy c) > (Int64.mul 1500000L 1500000L)\n\tthen failwith \"Oh shit\";;\nfind 1 c;;\nArray.iter (fun x -> print_int x;puts \" \") ret;;"}, {"source_code": "(*input\n8\n-67761 603277\n640586 -396671\n46147 -122580\n569609 -2112\n400 914208\n131792 309779\n-850150 -486293\n5272 721899\n*)\nlet scan_int() = Scanf.scanf \" %d\" (fun x -> x);;\nlet print_int x = Printf.printf \"%d\" x;;\nlet puts s = Printf.printf s;;\nlet n = scan_int();;\ntype vect = \n\t| Leaf of (int * int) * int \n\t| Combine of (int * int) * ((int * int) * (vect * vect))\n;;\nlet xy l = match l with\n\t| Leaf((x, y), _) -> (x, y)\n\t| Combine((x, y), _) -> (x, y)\n;;\nlet plus (a, b) (x, y) = (a + x, b + y);;\nlet minus (a, b) (x, y) = (a - x, b - y);;\nlet rec read i = \n\tif i >= n then \n\t\t[]\n\telse \n\t\tLeaf((scan_int(), scan_int()), i)::(read (i + 1));;\nlet r (x, y) = \n\tlet a = Int64.of_int x in\n\tlet b = Int64.of_int y in\n\tInt64.add (Int64.mul a a) (Int64.mul b b)\n;;\nlet rec min l = match l with\n\t| [] -> failwith \"empty list minimum\"\n\t| [x] -> x\n\t| a::b -> let c = (min b) in if a < c then a else c\n;;\nlet rec fix l = match l with\n\t| [] -> Leaf((-1, -1), -1)\n\t| [Leaf(x, y)] -> Leaf(x, y)\n\t| [Combine(x, y)] -> Combine(x, y)\n\t| a::b::[] -> \n\t\tif (r (plus (xy a) (xy b))) < (r (minus (xy a) (xy b))) then\n\t\t\tCombine((plus (xy a) (xy b)), ((1, 1), (a, b)))\n\t\telse \n\t\t\tCombine((minus (xy a) (xy b)), ((1, -1), (a, b)))\n\t| a::b::c::l -> (\n\t\tlet x = xy a in\n\t\tlet y = xy b in\n\t\tlet z = xy c in\n\t\tlet rxyp = r (plus x y) in\n\t\tlet rxzp = r (plus x z) in\n\t\tlet ryzp = r (plus y z) in\n\t\tlet rxym = r (minus x y) in\n\t\tlet rxzm = r (minus x z) in\n\t\tlet ryzm = r (minus y z) in\n\t\tlet rmin = min [rxyp; rxzp; ryzp; rxym; rxzm; ryzm] in\n\t\tif rxyp = rmin then\n\t\t\tfix (Combine((plus x y), ((1, 1), (a, b)))::c::l)\n\t\telse if rxzp = rmin then\n\t\t\tfix (Combine((plus x z), ((1, 1), (a, c)))::b::l)\n\t\telse if ryzp = rmin then\n\t\t\tfix (Combine((plus y z), ((1, 1), (b, c)))::a::l)\n\t\telse if rxym = rmin then\n\t\t\tfix (Combine((minus x y), ((1, -1), (a, b)))::c::l)\n\t\telse if rxzm = rmin then\n\t\t\tfix (Combine((minus x z), ((1, -1), (a, c)))::b::l)\n\t\telse\n\t\t\tfix (Combine((minus y z), ((1, -1), (b, c)))::a::l)\n\t)\n;;\nlet ret = Array.make n 1;;\nlet rec find w l = match l with\n\t| Leaf(_, i) -> (ret.(i) <- w)\n\t| Combine(_, ((w1, w2), (l1, l2))) -> find (w * w1) l1;find (w * w2) l2 \n;;\nfind 1 (fix (read 0));;\nArray.iter (fun x -> print_int x;puts \" \") ret;;"}], "src_uid": "a37a92db3626b46c7af79e3eb991983a"} {"nl": {"description": "A piece of paper contains an array of n integers a1,\u2009a2,\u2009...,\u2009an. Your task is to find a number that occurs the maximum number of times in this array.However, before looking for such number, you are allowed to perform not more than k following operations \u2014 choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one.", "input_spec": "The first line contains two integers n and k (1\u2009\u2264\u2009n\u2009\u2264\u2009105; 0\u2009\u2264\u2009k\u2009\u2264\u2009109) \u2014 the number of elements in the array and the number of operations you are allowed to perform, correspondingly. The third line contains a sequence of n integers a1,\u2009a2,\u2009...,\u2009an (|ai|\u2009\u2264\u2009109) \u2014 the initial array. The numbers in the lines are separated by single spaces.", "output_spec": "In a single line print two numbers \u2014 the maximum number of occurrences of some number in the array after at most k allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.", "sample_inputs": ["5 3\n6 3 4 0 2", "3 4\n5 5 5", "5 3\n3 1 2 2 1"], "sample_outputs": ["3 4", "3 5", "4 2"], "notes": "NoteIn the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6,\u20094,\u20094,\u20090,\u20094, where number 4 occurs 3 times.In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5,\u20095,\u20095, if we increase each by one, we get 6,\u20096,\u20096. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6.In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3,\u20092,\u20092,\u20092,\u20092, where number 2 occurs 4 times."}, "positive_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet _ = \n let (n, k) = read2() in\n let tab = Array.init n ( fun x -> read (n-x-1) )\n and max = ref 0\n and gdzie = ref 0\n and kol = Queue.create ()\n and dodaj = ref 0 in\n Array.sort compare tab;\n for i=0 to (n-1) do\n let x = tab.(i)\n and ost = if i=0 then tab.(i) else tab.(i-1) in\n while !dodaj +$ ( (x-ost) *$ (Queue.length kol) ) > k do\n let y = Queue.take kol in\n dodaj := !dodaj - (ost-y)\n done;\n dodaj := !dodaj +$ ( (x-ost) *$ (Queue.length kol) );\n Queue.add x kol;\n if Queue.length kol > !max then begin\n max := Queue.length kol;\n gdzie := x;\n end\n done;\n Printf.printf \"%d %d\\n\" !max !gdzie;;\n\n\n"}], "negative_code": [{"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\n\nlet _ = \n let (n, k) = read2() in\n let tab = Array.init n ( fun x -> read (n-x-1) )\n and max = ref 0\n and gdzie = ref 0\n and kol = Queue.create ()\n and dodaj = ref 0 in\n Array.sort compare tab;\n for i=0 to (n-1) do\n let x = tab.(i)\n and ost = if i=0 then 0 else tab.(i-1) in\n dodaj := !dodaj + (x-ost)*(Queue.length kol);\n while !dodaj > k do\n let y = Queue.take kol in\n dodaj := !dodaj - (x-y)\n done;\n Queue.add x kol;\n if Queue.length kol > !max then begin\n max := Queue.length kol;\n gdzie := x;\n end\n done;\n Printf.printf \"%d %d\\n\" !max !gdzie;;\n\n\n"}, {"source_code": "let read1 () = Scanf.scanf \"%d\\n\" ( fun x -> x );;\nlet read2 () = Scanf.scanf \"%d %d\\n\" ( fun x y -> x, y );;\nlet read3 () = Scanf.scanf \"%d %d %d\\n\" ( fun x y z -> x, y, z);;\nlet read x = (if x = 0 then Scanf.scanf \"%d\\n\" else Scanf.scanf \"%d \") ( fun x -> x );;\n\nlet (+$) x y =\n if x > max_int - y then max_int\n else x + y;;\n\nlet rec ( *$ ) x y =\n if y = 0 then 0 else\n if y mod 2 = 1 then x *$ (y-1) +$ x\n else let a = x *$ (y/2) in a +$ a;;\n\nlet _ = \n let (n, k) = read2() in\n let tab = Array.init n ( fun x -> read (n-x-1) )\n and max = ref 0\n and gdzie = ref 0\n and kol = Queue.create ()\n and dodaj = ref 0 in\n Array.sort compare tab;\n for i=0 to (n-1) do\n let x = tab.(i)\n and ost = if i=0 then tab.(i) else tab.(i-1) in\n dodaj := !dodaj +$ ( (x-ost) *$ (Queue.length kol) );\n while !dodaj > k do\n let y = Queue.take kol in\n dodaj := !dodaj - (x-y)\n done;\n Queue.add x kol;\n if Queue.length kol > !max then begin\n max := Queue.length kol;\n gdzie := x;\n end\n done;\n Printf.printf \"%d %d\\n\" !max !gdzie;;\n\n\n"}], "src_uid": "3791d1a504b39eb2e72472bcfd9a7e22"} {"nl": {"description": "You are given sequence a1,\u2009a2,\u2009...,\u2009an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You should write a program which finds sum of the best subsequence.", "input_spec": "The first line contains integer number n (1\u2009\u2264\u2009n\u2009\u2264\u2009105). The second line contains n integer numbers a1,\u2009a2,\u2009...,\u2009an (\u2009-\u2009104\u2009\u2264\u2009ai\u2009\u2264\u2009104). The sequence contains at least one subsequence with odd sum.", "output_spec": "Print sum of resulting subseqeuence.", "sample_inputs": ["4\n-2 2 -3 1", "3\n2 -5 -3"], "sample_outputs": ["3", "-1"], "notes": "NoteIn the first example sum of the second and the fourth elements is 3."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () = \n\tlet n = read_int ()\n\tand suma = ref 0\n\tand mini = ref 10007 \n\tand maxi = ref (-10007) in\n\n\tfor i = 1 to n do \n\t\tlet a = read_int () in\n\t\tif a > 0 then begin\n\t\t\tsuma := !suma + a;\n\t\t\tif a mod 2 = 1 then\n\t\t\t\tmini := min !mini a\n\t\tend else if abs (a mod 2) = 1 then\n\t\t\tmaxi := max !maxi a;\n\tdone;\n\n\tif !suma mod 2 = 1 then\n\t\tprintf \"%d\\n\" !suma\n\telse\n\t\tprintf \"%d\\n\" (max (!suma - !mini) (!suma + !maxi))\n\n"}, {"source_code": "open Printf\nopen Scanf\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\n\nlet () =\n let n = read_int () in\n let a = Array.init n read_int in\n let sum = Array.fold_left (fun acc x -> if x > 0 then acc + x else acc) 0 a in\n let max_neg = Array.fold_left (fun acc x -> if x < 0 && abs x mod 2 = 1 then max acc x else acc) (-1000000000) a in\n let min_pos = Array.fold_left (fun acc x -> if x > 0 && abs x mod 2 = 1 then min acc x else acc) (1000000000) a in\n let ans =\n if sum mod 2 = 1 then sum\n else max (sum - min_pos) (sum + max_neg) in\n printf \"%d\\n\" ans"}], "negative_code": [], "src_uid": "76dd49c5545770a1dfbb2da4140199c1"} {"nl": {"description": "For a connected undirected weighted graph G, MST (minimum spanning tree) is a subgraph of G that contains all of G's vertices, is a tree, and sum of its edges is minimum possible.You are given a graph G. If you run a MST algorithm on graph it would give you only one MST and it causes other edges to become jealous. You are given some queries, each query contains a set of edges of graph G, and you should determine whether there is a MST containing all these edges or not.", "input_spec": "The first line contains two integers n, m (2\u2009\u2009\u2264\u2009n,\u2009m\u2009\u2009\u2264\u20095\u00b7105, n\u2009-\u20091\u2009\u2264\u2009m)\u00a0\u2014 the number of vertices and edges in the graph and the number of queries. The i-th of the next m lines contains three integers ui, vi, wi (ui\u2009\u2260\u2009vi, 1\u2009\u2264\u2009wi\u2009\u2264\u20095\u00b7105)\u00a0\u2014 the endpoints and weight of the i-th edge. There can be more than one edges between two vertices. It's guaranteed that the given graph is connected. The next line contains a single integer q (1\u2009\u2264\u2009q\u2009\u2264\u20095\u00b7105)\u00a0\u2014 the number of queries. q lines follow, the i-th of them contains the i-th query. It starts with an integer ki (1\u2009\u2264\u2009ki\u2009\u2264\u2009n\u2009-\u20091)\u00a0\u2014 the size of edges subset and continues with ki distinct space-separated integers from 1 to m\u00a0\u2014 the indices of the edges. It is guaranteed that the sum of ki for 1\u2009\u2264\u2009i\u2009\u2264\u2009q does not exceed 5\u00b7105.", "output_spec": "For each query you should print \"YES\" (without quotes) if there's a MST containing these edges and \"NO\" (of course without quotes again) otherwise.", "sample_inputs": ["5 7\n1 2 2\n1 3 2\n2 3 1\n2 4 1\n3 4 1\n3 5 2\n4 5 2\n4\n2 3 4\n3 3 4 5\n2 1 7\n2 1 2"], "sample_outputs": ["YES\nNO\nYES\nNO"], "notes": "NoteThis is the graph of sample: Weight of minimum spanning tree on this graph is 6.MST with edges (1,\u20093,\u20094,\u20096), contains all of edges from the first query, so answer on the first query is \"YES\".Edges from the second query form a cycle of length 3, so there is no spanning tree including these three edges. Thus, answer is \"NO\"."}, "positive_code": [{"source_code": "open Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_2 _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet graph_cyclic edge_list =\n let map = Hashtbl.create 5 in\n let vn = ref 0 in\n let set_map u =\n if not (Hashtbl.mem map u) then (\n Hashtbl.add map u !vn;\n vn := !vn+1\n )\n in\n let get_map u = Hashtbl.find map u in\n List.iter (fun (u,v) -> set_map u; set_map v) edge_list;\n\n let parent = Array.make !vn (-1) in\n let rec find i = if parent.(i) < 0 then i else (\n parent.(i) <- find (parent.(i));\n parent.(i)\n ) in\n let union u v = parent.(u) <- v in\n\n let rec find_cycle li =\n match li with\n |\t[] -> false\n | (u,v)::tail ->\n\tlet cu = find (get_map u) in\n\tlet cv = find (get_map v) in\n\tif cu = cv then true else (\n\t union cu cv;\n\t find_cycle tail\n\t)\n in\n find_cycle edge_list\n \nlet () = \n let (n,m) = read_2 () in\n\n let v1 = Array.make m 0 in\n let v2 = Array.make m 0 in\n let w = Array.make m 0 in \n\n for i=0 to m-1 do\n v1.(i) <- read_int() -1;\n v2.(i) <- read_int() -1;\n w.(i) <- read_int(); \n done;\n\n let q = read_int() in\n let query = Array.make q ([],[[]]) in\n\n for i=0 to q-1 do\n let k = read_int() in\n let rec loop j ac = if j=k then ac else loop (j+1) ((read_int()-1) :: ac) in\n let qlist = loop 0 [] in\n\n let h = Hashtbl.create 5 in\n List.iter (fun e ->\n let li = try Hashtbl.find h w.(e) with Not_found -> [] in\n Hashtbl.replace h w.(e) (e :: li)\n ) qlist;\n \n query.(i) <- (qlist, Hashtbl.fold (fun _ v ac -> v::ac) h [])\n (* it's a list of lists of edges of the same weight *)\n done;\n\n let parent = Array.make n (-1) in\n let size = Array.make n 1 in\n let edge_no = Array.make n (-1) in\n\n let union a b edge =\n (* assume a and b are canonoical elements *)\n let (a,b) = if size.(a) <= size.(b) then (a,b) else (b,a) in\n parent.(a) <- b;\n size.(b) <- size.(b) + size.(a);\n edge_no.(a) <- edge\n in\n let rec find i = if parent.(i) < 0 then i else find parent.(i) in\n\n let perm = Array.init m (fun i -> i) in\n\n Array.sort (fun a b -> compare w.(a) w.(b)) perm;\n\n for i=0 to m-1 do\n let i = perm.(i) in\n let (a,b) = (find v1.(i), find v2.(i)) in\n if a<>b then union a b i\n done;\n\n for i=0 to q-1 do\n let (qlist, qlistlist) = query.(i) in\n (* first determine if the queries form a cycle *)\n let graph = List.map (fun e -> (v1.(e), v2.(e))) qlist in\n if graph_cyclic graph then printf \"NO\\n\" else (\n let edge_set_valid es =\n\tlet rec find_canon j ew =\n\t if parent.(j) >= 0 && w.(edge_no.(j)) < ew then find_canon parent.(j) ew\n\t else j\n\tin\n\n\tlet graph = List.map (fun e -> (find_canon v1.(e) w.(e), find_canon v2.(e) w.(e))) es in\n\tnot (graph_cyclic graph)\n in\n\n if List.for_all edge_set_valid qlistlist then printf \"YES\\n\" else printf \"NO\\n\"\n )\n done\n"}, {"source_code": "(* keywords: union-find, MST\n Really nice problem involving understainding the MST algorithm, and\n how to use the union/find data structure without path compression.\n*)\n\nopen Printf\nopen Scanf\n\nlet read_int _ = bscanf Scanning.stdib \" %d \" (fun x -> x)\nlet read_2 _ = bscanf Scanning.stdib \" %d %d \" (fun x y -> (x,y))\n\nlet graph_cyclic edge_list =\n let map = Hashtbl.create 5 in\n let vn = ref 0 in\n let set_map u =\n if not (Hashtbl.mem map u) then (\n Hashtbl.add map u !vn;\n vn := !vn+1\n )\n in\n let get_map u = Hashtbl.find map u in\n List.iter (fun (u,v) -> set_map u; set_map v) edge_list;\n\n let parent = Array.make !vn (-1) in\n let rec find i = if parent.(i) < 0 then i else (\n parent.(i) <- find (parent.(i));\n parent.(i)\n ) in\n let union u v = parent.(u) <- v in\n\n let rec find_cycle li =\n match li with\n |\t[] -> false\n | (u,v)::tail ->\n\tlet cu = find (get_map u) in\n\tlet cv = find (get_map v) in\n\tif cu = cv then true else (\n\t union cu cv;\n\t find_cycle tail\n\t)\n in\n find_cycle edge_list\n \nlet () = \n let (n,m) = read_2 () in\n\n let v1 = Array.make m 0 in\n let v2 = Array.make m 0 in\n let w = Array.make m 0 in \n\n for i=0 to m-1 do\n v1.(i) <- read_int() -1;\n v2.(i) <- read_int() -1;\n w.(i) <- read_int(); \n done;\n\n let q = read_int() in\n let query = Array.make q [] in\n\n for i=0 to q-1 do\n let k = read_int() in\n let rec loop j ac = if j=k then ac else loop (j+1) ((read_int()-1) :: ac) in\n query.(i) <- loop 0 []\n done;\n\n let parent = Array.make n (-1) in\n let size = Array.make n 1 in\n let edge_no = Array.make n (-1) in\n\n let union a b edge =\n (* assume a and b are canonoical elements *)\n let (a,b) = if size.(a) <= size.(b) then (a,b) else (b,a) in\n parent.(a) <- b;\n size.(b) <- size.(b) + size.(a);\n edge_no.(a) <- edge\n in\n let rec find i = if parent.(i) < 0 then i else find parent.(i) in\n\n let perm = Array.init m (fun i -> i) in\n\n Array.sort (fun a b -> compare w.(a) w.(b)) perm;\n\n for i=0 to m-1 do\n let i = perm.(i) in\n let (a,b) = (find v1.(i), find v2.(i)) in\n if a<>b then union a b i\n done;\n\n for i=0 to q-1 do\n (* first determine if the queries form a cycle *)\n let graph = List.map (fun e -> (v1.(e), v2.(e))) query.(i) in\n if graph_cyclic graph then printf \"NO\\n\" else (\n let rec find_canon j ew =\n\tif parent.(j) >= 0 && w.(edge_no.(j)) < ew then find_canon parent.(j) ew\n\telse j\n in\n \n let graph = List.map (fun e -> (find_canon v1.(e) w.(e), find_canon v2.(e) w.(e))) query.(i) in\n if graph_cyclic graph then printf \"NO\\n\" else printf \"YES\\n\"\n )\n done\n"}], "negative_code": [], "src_uid": "21a1aada3570f42093c7ed4e06f0766d"}